context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//Copyright (C) 2006 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the IsAResolver.java source file found in the //original java implementation of OpenNLP. That source file contains the following header: //Copyright (C) 2003 Thomas Morton // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; using System.Text.RegularExpressions; using System.Collections.Generic; using DiscourseEntity = OpenNLP.Tools.Coreference.DiscourseEntity; using MentionContext = OpenNLP.Tools.Coreference.Mention.MentionContext; namespace OpenNLP.Tools.Coreference.Resolver { /// <summary> Resolves coreference between appositives. </summary> public class IsAResolver:MaximumEntropyResolver { internal Regex predicativePattern; public IsAResolver(string projectName, ResolverMode mode):base(projectName, "/imodel", mode, 20) { ShowExclusions = false; //predicativePattern = Pattern.compile("^(,|am|are|is|was|were|--)$"); predicativePattern = new Regex("^(,|--)$", RegexOptions.Compiled); } public IsAResolver(string projectName, ResolverMode mode, INonReferentialResolver nonReferentialResolver) : base(projectName, "/imodel", mode, 20, nonReferentialResolver) { ShowExclusions = false; //predicativePattern = Pattern.compile("^(,|am|are|is|was|were|--)$"); predicativePattern = new Regex("^(,|--)$", RegexOptions.Compiled); } public override bool CanResolve(MentionContext context) { if (PartsOfSpeech.IsNoun(context.HeadTokenTag)) { return (context.PreviousToken != null && predicativePattern.IsMatch(context.PreviousToken.ToString())); } return false; } protected internal override bool IsExcluded(MentionContext context, DiscourseEntity discourseEntity) { MentionContext currentContext = discourseEntity.LastExtent; if (context.SentenceNumber != currentContext.SentenceNumber) { return true; } //shallow parse appositives if (currentContext.IndexSpan.End == context.IndexSpan.Start - 2) { return false; } //full parse w/o trailing comma if (currentContext.IndexSpan.End == context.IndexSpan.End) { return false; } //full parse w/ trailing comma or period if (currentContext.IndexSpan.End <= context.IndexSpan.End + 2 && (context.NextToken != null && (context.NextToken.ToString() == PartsOfSpeech.Comma || context.NextToken.ToString() == PartsOfSpeech.SentenceFinalPunctuation))) { return false; } return true; } protected internal override bool IsOutOfRange(MentionContext context, DiscourseEntity discourseEntity) { MentionContext currentContext = discourseEntity.LastExtent; return (currentContext.SentenceNumber != context.SentenceNumber); } protected internal override bool defaultReferent(DiscourseEntity discourseEntity) { return true; } protected internal override List<string> GetFeatures(MentionContext mention, DiscourseEntity entity) { List<string> features = base.GetFeatures(mention, entity); if (entity != null) { MentionContext ant = entity.LastExtent; List<string> leftContexts = GetContextFeatures(ant); for (int ci = 0, cn = leftContexts.Count; ci < cn; ci++) { features.Add("l" + leftContexts[ci]); } List<string> rightContexts = GetContextFeatures(mention); for (int ci = 0, cn = rightContexts.Count; ci < cn; ci++) { features.Add("r" + rightContexts[ci]); } features.Add("hts" + ant.HeadTokenTag + "," + mention.HeadTokenTag); } /* if (entity != null) { //previous word and tag if (ant.prevToken != null) { features.add("pw=" + ant.prevToken); features.add("pt=" + ant.prevToken.getSyntacticType()); } else { features.add("pw=<none>"); features.add("pt=<none>"); } //next word and tag if (mention.nextToken != null) { features.add("nw=" + mention.nextToken); features.add("nt=" + mention.nextToken.getSyntacticType()); } else { features.add("nw=<none>"); features.add("nt=<none>"); } //modifier word and tag for c1 int i = 0; List c1toks = ant.tokens; for (; i < ant.headTokenIndex; i++) { features.add("mw=" + c1toks.get(i)); features.add("mt=" + ((Parse) c1toks.get(i)).getSyntacticType()); } //head word and tag for c1 features.add("mh=" + c1toks.get(i)); features.add("mt=" + ((Parse) c1toks.get(i)).getSyntacticType()); //modifier word and tag for c2 i = 0; List c2toks = mention.tokens; for (; i < mention.headTokenIndex; i++) { features.add("mw=" + c2toks.get(i)); features.add("mt=" + ((Parse) c2toks.get(i)).getSyntacticType()); } //head word and tag for n2 features.add("mh=" + c2toks.get(i)); features.add("mt=" + ((Parse) c2toks.get(i)).getSyntacticType()); //word/tag pairs for (i = 0; i < ant.headTokenIndex; i++) { for (int j = 0; j < mention.headTokenIndex; j++) { features.add("w=" + c1toks.get(i) + "|" + "w=" + c2toks.get(j)); features.add("w=" + c1toks.get(i) + "|" + "t=" + ((Parse) c2toks.get(j)).getSyntacticType()); features.add("t=" + ((Parse) c1toks.get(i)).getSyntacticType() + "|" + "w=" + c2toks.get(j)); features.add("t=" + ((Parse) c1toks.get(i)).getSyntacticType() + "|" + "t=" + ((Parse) c2toks.get(j)).getSyntacticType()); } } features.add("ht=" + ant.headTokenTag + "|" + "ht=" + mention.headTokenTag); features.add("ht1=" + ant.headTokenTag); features.add("ht2=" + mention.headTokenTag); */ //semantic categories /* if (ant.neType != null) { if (re.neType != null) { features.add("sc="+ant.neType+","+re.neType); } else if (!PartsOfSpeech.IsProperNoun(re.headTokenTag) && PartsOfSpeech.IsNoun(re.headTokenTag)) { Set synsets = re.synsets; for (Iterator si=synsets.iterator();si.hasNext();) { features.add("sc="+ant.neType+","+si.next()); } } } else if (!PartsOfSpeech.IsProperNoun(ant.headTokenTag) && PartsOfSpeech.IsNoun(ant.headTokenTag)) { if (re.neType != null) { Set synsets = ant.synsets; for (Iterator si=synsets.iterator();si.hasNext();) { features.add("sc="+re.neType+","+si.next()); } } else if (!PartsOfSpeech.IsProperNoun(re.headTokenTag) && PartsOfSpeech.IsNoun(re.headTokenTag)) { Set synsets1 = ant.synsets; Set synsets2 = re.synsets; for (Iterator si=synsets1.iterator();si.hasNext();) { Object synset = si.next(); if (synsets2.contains(synset)) { features.add("sc="+synset); } } } } } */ return features; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Hopnscotch.Portal.Web.Areas.HelpPage.Models; namespace Hopnscotch.Portal.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified 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 SetActualName(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 SetActualName(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 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) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System.Security; using System; public struct TestStruct { public int IntValue; public string StringValue; } public class DisposableClass : IDisposable { public void Dispose() { } } /// <summary> /// Target /// </summary> [SecuritySafeCritical] public class WeakReferenceTarget { #region Private Fields private const int c_MIN_STRING_LENGTH = 8; private const int c_MAX_STRING_LENGTH = 1024; private WeakReference[] m_References; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call Target on short weak reference to instance of an object"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); retVal = GenerateUnusedData1("001.1") && retVal; // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < m_References.Length; ++i) { if (m_References[i].Target != null) { TestLibrary.TestFramework.LogError("001.2", "Target is not null after GC collecting memory"); TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = " + m_References[i].Target.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call Target on long weak reference to instance of an object"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); retVal = GenerateUnusedData2("002.1") && retVal; // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < m_References.Length; ++i) { if (m_References[i].Target != null) { TestLibrary.TestFramework.LogError("002.2", "Target is not null after GC collecting memory"); TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = " + m_References[i].Target.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call set_Target on short weak reference to instance of an object before GC"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); retVal = GenerateUnusedData1("003.1") && retVal; object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); ; WeakReferenceTarget thisClass = new WeakReferenceTarget(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); Object[] objs = new object[] { obj, str, randBytes, thisClass, dc, ptr, IntPtr.Zero }; for (int i = 0; i < m_References.Length; ++i) { m_References[i].Target = objs[i]; if (!m_References[i].Target.Equals(objs[i])) { TestLibrary.TestFramework.LogError("003.2", "Target is not set correctly"); TestLibrary.TestFramework.LogInformation("WARNING: m_References[i].Target = " + m_References[i].Target.ToString() + ", objs = " + objs[i].ToString() + ", i = " + i.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Call set_Target on long weak reference to instance of an object before GC"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); retVal = GenerateUnusedData2("004.1") && retVal; object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); WeakReferenceTarget thisClass = new WeakReferenceTarget(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); Object[] objs = new object[] { obj, str, randBytes, thisClass, dc, ptr, IntPtr.Zero }; for (int i = 0; i < m_References.Length; ++i) { m_References[i].Target = objs[i]; if (!m_References[i].Target.Equals(objs[i])) { TestLibrary.TestFramework.LogError("004.2", "Target is not set correctly"); TestLibrary.TestFramework.LogInformation("WARNING: m_References[i].Target = " + m_References[i].Target.ToString() + ", objs = " + objs[i].ToString() + ", i = " + i.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } #endregion #endregion public static int Main() { WeakReferenceTarget test = new WeakReferenceTarget(); TestLibrary.TestFramework.BeginTestCase("WeakReferenceTarget"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool GenerateUnusedData1(string errorNo) { bool retVal = true; object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); WeakReferenceTarget thisClass = new WeakReferenceTarget(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); Object[] objs = new object[] { obj, str, randBytes, thisClass, dc, ptr, IntPtr.Zero }; m_References = new WeakReference[objs.Length]; for (int i = 0; i < objs.Length; ++i) { m_References[i] = new WeakReference(objs[i], false); } for (int i = 0; i < m_References.Length; ++i) { if (!m_References[i].Target.Equals(objs[i])) { TestLibrary.TestFramework.LogError(errorNo, "Target returns wrong value for weak references"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] i = " + i.ToString() + ", m_References[i].Target = " + m_References[i].Target.ToString() + ", objs[i] = " + objs[i].ToString()); retVal = false; } } return retVal; } private bool GenerateUnusedData2(string errorNo) { bool retVal = true; object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); TestStruct ts = new TestStruct(); ts.IntValue = TestLibrary.Generator.GetInt32(-55); WeakReferenceTarget thisClass = new WeakReferenceTarget(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); Object[] objs = new object[] { obj, str, randBytes, thisClass, dc, ptr, IntPtr.Zero }; m_References = new WeakReference[objs.Length]; for (int i = 0; i < objs.Length; ++i) { m_References[i] = new WeakReference(objs[i], true); } for (int i = 0; i < m_References.Length; ++i) { if (!m_References[i].Target.Equals(objs[i])) { TestLibrary.TestFramework.LogError(errorNo, "Target returns wrong value for weak references"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] i = " + i.ToString() + ", m_References[i].Target = " + m_References[i].Target.ToString() + ", objs[i] = " + objs[i].ToString()); retVal = false; } } return retVal; } private void GenerateUnusedDisposableData() { DisposableClass dc = null; m_References = new WeakReference[1]; try { dc = new DisposableClass(); m_References[0] = new WeakReference(dc); } finally { if (null != dc) { dc.Dispose(); } } GC.Collect(); } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// Base internal class of all XPathDocument XPathNodeIterator implementations. /// </summary> internal abstract class XPathDocumentBaseIterator : XPathNodeIterator { protected XPathDocumentNavigator ctxt; protected int pos; /// <summary> /// Create a new iterator that is initially positioned on the "ctxt" node. /// </summary> protected XPathDocumentBaseIterator(XPathDocumentNavigator ctxt) { this.ctxt = new XPathDocumentNavigator(ctxt); } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> protected XPathDocumentBaseIterator(XPathDocumentBaseIterator iter) { this.ctxt = new XPathDocumentNavigator(iter.ctxt); this.pos = iter.pos; } /// <summary> /// Return the current navigator. /// </summary> public override XPathNavigator Current { get { return this.ctxt; } } /// <summary> /// Return the iterator's current position. /// </summary> public override int CurrentPosition { get { return this.pos; } } } /// <summary> /// Iterate over all element children with a particular QName. /// </summary> internal class XPathDocumentElementChildIterator : XPathDocumentBaseIterator { private string localName, namespaceUri; /// <summary> /// Create an iterator that ranges over all element children of "parent" having the specified QName. /// </summary> public XPathDocumentElementChildIterator(XPathDocumentNavigator parent, string name, string namespaceURI) : base(parent) { if (namespaceURI == null) throw new ArgumentNullException("namespaceURI"); this.localName = parent.NameTable.Get(name); this.namespaceUri = namespaceURI; } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> public XPathDocumentElementChildIterator(XPathDocumentElementChildIterator iter) : base(iter) { this.localName = iter.localName; this.namespaceUri = iter.namespaceUri; } /// <summary> /// Create a copy of this iterator. /// </summary> public override XPathNodeIterator Clone() { return new XPathDocumentElementChildIterator(this); } /// <summary> /// Position the iterator to the next matching child. /// </summary> public override bool MoveNext() { if (this.pos == 0) { if (!this.ctxt.MoveToChild(this.localName, this.namespaceUri)) return false; } else { if (!this.ctxt.MoveToNext(this.localName, this.namespaceUri)) return false; } this.pos++; return true; } } /// <summary> /// Iterate over all content children with a particular XPathNodeType. /// </summary> internal class XPathDocumentKindChildIterator : XPathDocumentBaseIterator { private XPathNodeType typ; /// <summary> /// Create an iterator that ranges over all content children of "parent" having the specified XPathNodeType. /// </summary> public XPathDocumentKindChildIterator(XPathDocumentNavigator parent, XPathNodeType typ) : base(parent) { this.typ = typ; } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> public XPathDocumentKindChildIterator(XPathDocumentKindChildIterator iter) : base(iter) { this.typ = iter.typ; } /// <summary> /// Create a copy of this iterator. /// </summary> public override XPathNodeIterator Clone() { return new XPathDocumentKindChildIterator(this); } /// <summary> /// Position the iterator to the next descendant. /// </summary> public override bool MoveNext() { if (this.pos == 0) { if (!this.ctxt.MoveToChild(this.typ)) return false; } else { if (!this.ctxt.MoveToNext(this.typ)) return false; } this.pos++; return true; } } /// <summary> /// Iterate over all element descendants with a particular QName. /// </summary> internal class XPathDocumentElementDescendantIterator : XPathDocumentBaseIterator { private XPathDocumentNavigator end; private string localName, namespaceUri; private bool matchSelf; /// <summary> /// Create an iterator that ranges over all element descendants of "root" having the specified QName. /// </summary> public XPathDocumentElementDescendantIterator(XPathDocumentNavigator root, string name, string namespaceURI, bool matchSelf) : base(root) { if (namespaceURI == null) throw new ArgumentNullException("namespaceURI"); this.localName = root.NameTable.Get(name); this.namespaceUri = namespaceURI; this.matchSelf = matchSelf; // Find the next non-descendant node that follows "root" in document order if (root.NodeType != XPathNodeType.Root) { this.end = new XPathDocumentNavigator(root); this.end.MoveToNonDescendant(); } } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> public XPathDocumentElementDescendantIterator(XPathDocumentElementDescendantIterator iter) : base(iter) { this.end = iter.end; this.localName = iter.localName; this.namespaceUri = iter.namespaceUri; this.matchSelf = iter.matchSelf; } /// <summary> /// Create a copy of this iterator. /// </summary> public override XPathNodeIterator Clone() { return new XPathDocumentElementDescendantIterator(this); } /// <summary> /// Position the iterator to the next descendant. /// </summary> public override bool MoveNext() { if (this.matchSelf) { this.matchSelf = false; if (this.ctxt.IsElementMatch(this.localName, this.namespaceUri)) { this.pos++; return true; } } if (!this.ctxt.MoveToFollowing(this.localName, this.namespaceUri, this.end)) return false; this.pos++; return true; } } /// <summary> /// Iterate over all content descendants with a particular XPathNodeType. /// </summary> internal class XPathDocumentKindDescendantIterator : XPathDocumentBaseIterator { private XPathDocumentNavigator end; private XPathNodeType typ; private bool matchSelf; /// <summary> /// Create an iterator that ranges over all content descendants of "root" having the specified XPathNodeType. /// </summary> public XPathDocumentKindDescendantIterator(XPathDocumentNavigator root, XPathNodeType typ, bool matchSelf) : base(root) { this.typ = typ; this.matchSelf = matchSelf; // Find the next non-descendant node that follows "root" in document order if (root.NodeType != XPathNodeType.Root) { this.end = new XPathDocumentNavigator(root); this.end.MoveToNonDescendant(); } } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> public XPathDocumentKindDescendantIterator(XPathDocumentKindDescendantIterator iter) : base(iter) { this.end = iter.end; this.typ = iter.typ; this.matchSelf = iter.matchSelf; } /// <summary> /// Create a copy of this iterator. /// </summary> public override XPathNodeIterator Clone() { return new XPathDocumentKindDescendantIterator(this); } /// <summary> /// Position the iterator to the next descendant. /// </summary> public override bool MoveNext() { if (this.matchSelf) { this.matchSelf = false; if (this.ctxt.IsKindMatch(this.typ)) { this.pos++; return true; } } if (!this.ctxt.MoveToFollowing(this.typ, this.end)) return false; this.pos++; 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Cryptography { public abstract partial class Aes : System.Security.Cryptography.SymmetricAlgorithm { protected Aes() { } public static new System.Security.Cryptography.Aes Create() { throw null; } public static new System.Security.Cryptography.Aes Create(string algorithmName) { throw null; } } public sealed partial class AesCcm : System.IDisposable { public AesCcm(byte[] key) { } public AesCcm(System.ReadOnlySpan<byte> key) { } public static System.Security.Cryptography.KeySizes NonceByteSizes { get { throw null; } } public static System.Security.Cryptography.KeySizes TagByteSizes { get { throw null; } } public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[] associatedData = null) { } public void Decrypt(System.ReadOnlySpan<byte> nonce, System.ReadOnlySpan<byte> ciphertext, System.ReadOnlySpan<byte> tag, System.Span<byte> plaintext, System.ReadOnlySpan<byte> associatedData = default(System.ReadOnlySpan<byte>)) { } public void Dispose() { } public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData = null) { } public void Encrypt(System.ReadOnlySpan<byte> nonce, System.ReadOnlySpan<byte> plaintext, System.Span<byte> ciphertext, System.Span<byte> tag, System.ReadOnlySpan<byte> associatedData = default(System.ReadOnlySpan<byte>)) { } } public sealed partial class AesGcm : System.IDisposable { public AesGcm(byte[] key) { } public AesGcm(System.ReadOnlySpan<byte> key) { } public static System.Security.Cryptography.KeySizes NonceByteSizes { get { throw null; } } public static System.Security.Cryptography.KeySizes TagByteSizes { get { throw null; } } public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[] associatedData = null) { } public void Decrypt(System.ReadOnlySpan<byte> nonce, System.ReadOnlySpan<byte> ciphertext, System.ReadOnlySpan<byte> tag, System.Span<byte> plaintext, System.ReadOnlySpan<byte> associatedData = default(System.ReadOnlySpan<byte>)) { } public void Dispose() { } public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData = null) { } public void Encrypt(System.ReadOnlySpan<byte> nonce, System.ReadOnlySpan<byte> plaintext, System.Span<byte> ciphertext, System.Span<byte> tag, System.ReadOnlySpan<byte> associatedData = default(System.ReadOnlySpan<byte>)) { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class AesManaged : System.Security.Cryptography.Aes { public AesManaged() { } public override int BlockSize { get { throw null; } set { } } public override int FeedbackSize { get { throw null; } set { } } public override byte[] IV { get { throw null; } set { } } public override byte[] Key { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } } public abstract partial class AsymmetricKeyExchangeDeformatter { protected AsymmetricKeyExchangeDeformatter() { } public abstract string Parameters { get; set; } public abstract byte[] DecryptKeyExchange(byte[] rgb); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public abstract partial class AsymmetricKeyExchangeFormatter { protected AsymmetricKeyExchangeFormatter() { } public abstract string Parameters { get; } public abstract byte[] CreateKeyExchange(byte[] data); public abstract byte[] CreateKeyExchange(byte[] data, System.Type symAlgType); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public abstract partial class AsymmetricSignatureDeformatter { protected AsymmetricSignatureDeformatter() { } public abstract void SetHashAlgorithm(string strName); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature); public virtual bool VerifySignature(System.Security.Cryptography.HashAlgorithm hash, byte[] rgbSignature) { throw null; } } public abstract partial class AsymmetricSignatureFormatter { protected AsymmetricSignatureFormatter() { } public abstract byte[] CreateSignature(byte[] rgbHash); public virtual byte[] CreateSignature(System.Security.Cryptography.HashAlgorithm hash) { throw null; } public abstract void SetHashAlgorithm(string strName); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public partial class CryptoConfig { public CryptoConfig() { } public static bool AllowOnlyFipsAlgorithms { get { throw null; } } public static void AddAlgorithm(System.Type algorithm, params string[] names) { } public static void AddOID(string oid, params string[] names) { } public static object CreateFromName(string name) { throw null; } public static object CreateFromName(string name, params object[] args) { throw null; } public static byte[] EncodeOID(string str) { throw null; } public static string MapNameToOID(string name) { throw null; } } public abstract partial class DeriveBytes : System.IDisposable { protected DeriveBytes() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract byte[] GetBytes(int cb); public abstract void Reset(); } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public abstract partial class DES : System.Security.Cryptography.SymmetricAlgorithm { protected DES() { } public override byte[] Key { get { throw null; } set { } } public static new System.Security.Cryptography.DES Create() { throw null; } public static new System.Security.Cryptography.DES Create(string algName) { throw null; } public static bool IsSemiWeakKey(byte[] rgbKey) { throw null; } public static bool IsWeakKey(byte[] rgbKey) { throw null; } } public abstract partial class DSA : System.Security.Cryptography.AsymmetricAlgorithm { protected DSA() { } public static new System.Security.Cryptography.DSA Create() { throw null; } public static System.Security.Cryptography.DSA Create(int keySizeInBits) { throw null; } public static System.Security.Cryptography.DSA Create(System.Security.Cryptography.DSAParameters parameters) { throw null; } public static new System.Security.Cryptography.DSA Create(string algName) { throw null; } public abstract byte[] CreateSignature(byte[] rgbHash); public abstract System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters); public override void FromXmlString(string xmlString) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract void ImportParameters(System.Security.Cryptography.DSAParameters parameters); public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public override string ToXmlString(bool includePrivateParameters) { throw null; } public virtual bool TryCreateSignature(System.ReadOnlySpan<byte> hash, System.Span<byte> destination, out int bytesWritten) { throw null; } protected virtual bool TryHashData(System.ReadOnlySpan<byte> data, System.Span<byte> destination, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, out int bytesWritten) { throw null; } public virtual bool TrySignData(System.ReadOnlySpan<byte> data, System.Span<byte> destination, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, out int bytesWritten) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(System.ReadOnlySpan<byte> data, System.ReadOnlySpan<byte> signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature); public virtual bool VerifySignature(System.ReadOnlySpan<byte> hash, System.ReadOnlySpan<byte> signature) { throw null; } } public partial struct DSAParameters { public int Counter; public byte[] G; public byte[] J; public byte[] P; public byte[] Q; public byte[] Seed; public byte[] X; public byte[] Y; } public partial class DSASignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter { public DSASignatureDeformatter() { } public DSASignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; } } public partial class DSASignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter { public DSASignatureFormatter() { } public DSASignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override byte[] CreateSignature(byte[] rgbHash) { throw null; } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial struct ECCurve { private object _dummy; public byte[] A; public byte[] B; public byte[] Cofactor; public System.Security.Cryptography.ECCurve.ECCurveType CurveType; public System.Security.Cryptography.ECPoint G; public System.Security.Cryptography.HashAlgorithmName? Hash; public byte[] Order; public byte[] Polynomial; public byte[] Prime; public byte[] Seed; public bool IsCharacteristic2 { get { throw null; } } public bool IsExplicit { get { throw null; } } public bool IsNamed { get { throw null; } } public bool IsPrime { get { throw null; } } public System.Security.Cryptography.Oid Oid { get { throw null; } } public static System.Security.Cryptography.ECCurve CreateFromFriendlyName(string oidFriendlyName) { throw null; } public static System.Security.Cryptography.ECCurve CreateFromOid(System.Security.Cryptography.Oid curveOid) { throw null; } public static System.Security.Cryptography.ECCurve CreateFromValue(string oidValue) { throw null; } public void Validate() { } public enum ECCurveType { Characteristic2 = 4, Implicit = 0, Named = 5, PrimeMontgomery = 3, PrimeShortWeierstrass = 1, PrimeTwistedEdwards = 2, } public static partial class NamedCurves { public static System.Security.Cryptography.ECCurve brainpoolP160r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP160t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP192r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP192t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP224r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP224t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP256r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP256t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP320r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP320t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP384r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP384t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP512r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP512t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP256 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP384 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP521 { get { throw null; } } } } public abstract partial class ECDiffieHellman : System.Security.Cryptography.AsymmetricAlgorithm { protected ECDiffieHellman() { } public override string KeyExchangeAlgorithm { get { throw null; } } public abstract System.Security.Cryptography.ECDiffieHellmanPublicKey PublicKey { get; } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.ECDiffieHellman Create() { throw null; } public static System.Security.Cryptography.ECDiffieHellman Create(System.Security.Cryptography.ECCurve curve) { throw null; } public static System.Security.Cryptography.ECDiffieHellman Create(System.Security.Cryptography.ECParameters parameters) { throw null; } public static new System.Security.Cryptography.ECDiffieHellman Create(string algorithm) { throw null; } public byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] secretPrepend, byte[] secretAppend) { throw null; } public byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey) { throw null; } public virtual byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend) { throw null; } public virtual byte[] DeriveKeyMaterial(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey) { throw null; } public virtual byte[] DeriveKeyTls(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { throw null; } public virtual byte[] ExportECPrivateKey() { throw null; } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; } public override void FromXmlString(string xmlString) { } public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { } public virtual void ImportECPrivateKey(System.ReadOnlySpan<byte> source, out int bytesRead) { throw null; } public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { } public override string ToXmlString(bool includePrivateParameters) { throw null; } public virtual bool TryExportECPrivateKey(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class ECDiffieHellmanPublicKey : System.IDisposable { protected ECDiffieHellmanPublicKey() { } protected ECDiffieHellmanPublicKey(byte[] keyBlob) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters() { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters() { throw null; } public virtual byte[] ToByteArray() { throw null; } public virtual string ToXmlString() { throw null; } } public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm { protected ECDsa() { } public override string KeyExchangeAlgorithm { get { throw null; } } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.ECDsa Create() { throw null; } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECCurve curve) { throw null; } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECParameters parameters) { throw null; } public static new System.Security.Cryptography.ECDsa Create(string algorithm) { throw null; } public virtual byte[] ExportECPrivateKey() { throw null; } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; } public override void FromXmlString(string xmlString) { } public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual void ImportECPrivateKey(System.ReadOnlySpan<byte> source, out int bytesRead) { throw null; } public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { } public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract byte[] SignHash(byte[] hash); public override string ToXmlString(bool includePrivateParameters) { throw null; } public virtual bool TryExportECPrivateKey(System.Span<byte> destination, out int bytesWritten) { throw null; } protected virtual bool TryHashData(System.ReadOnlySpan<byte> data, System.Span<byte> destination, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, out int bytesWritten) { throw null; } public virtual bool TrySignData(System.ReadOnlySpan<byte> data, System.Span<byte> destination, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, out int bytesWritten) { throw null; } public virtual bool TrySignHash(System.ReadOnlySpan<byte> hash, System.Span<byte> destination, out int bytesWritten) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(System.ReadOnlySpan<byte> data, System.ReadOnlySpan<byte> signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract bool VerifyHash(byte[] hash, byte[] signature); public virtual bool VerifyHash(System.ReadOnlySpan<byte> hash, System.ReadOnlySpan<byte> signature) { throw null; } } public partial struct ECParameters { public System.Security.Cryptography.ECCurve Curve; public byte[] D; public System.Security.Cryptography.ECPoint Q; public void Validate() { } } public partial struct ECPoint { public byte[] X; public byte[] Y; } public partial class HMACMD5 : System.Security.Cryptography.HMAC { public HMACMD5() { } public HMACMD5(byte[] key) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA1 : System.Security.Cryptography.HMAC { public HMACSHA1() { } public HMACSHA1(byte[] key) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public HMACSHA1(byte[] key, bool useManagedSha1) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA256 : System.Security.Cryptography.HMAC { public HMACSHA256() { } public HMACSHA256(byte[] key) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA384 : System.Security.Cryptography.HMAC { public HMACSHA384() { } public HMACSHA384(byte[] key) { } public override byte[] Key { get { throw null; } set { } } public bool ProduceLegacyHmacValues { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA512 : System.Security.Cryptography.HMAC { public HMACSHA512() { } public HMACSHA512(byte[] key) { } public override byte[] Key { get { throw null; } set { } } public bool ProduceLegacyHmacValues { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public sealed partial class IncrementalHash : System.IDisposable { internal IncrementalHash() { } public System.Security.Cryptography.HashAlgorithmName AlgorithmName { get { throw null; } } public void AppendData(byte[] data) { } public void AppendData(byte[] data, int offset, int count) { } public void AppendData(System.ReadOnlySpan<byte> data) { } public static System.Security.Cryptography.IncrementalHash CreateHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key) { throw null; } public void Dispose() { } public byte[] GetHashAndReset() { throw null; } public bool TryGetHashAndReset(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class MaskGenerationMethod { protected MaskGenerationMethod() { } public abstract byte[] GenerateMask(byte[] rgbSeed, int cbReturn); } public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm { protected MD5() { } public static new System.Security.Cryptography.MD5 Create() { throw null; } public static new System.Security.Cryptography.MD5 Create(string algName) { throw null; } } public partial class PKCS1MaskGenerationMethod : System.Security.Cryptography.MaskGenerationMethod { public PKCS1MaskGenerationMethod() { } public string HashName { get { throw null; } set { } } public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn) { throw null; } } public abstract partial class RandomNumberGenerator : System.IDisposable { protected RandomNumberGenerator() { } public static System.Security.Cryptography.RandomNumberGenerator Create() { throw null; } public static System.Security.Cryptography.RandomNumberGenerator Create(string rngName) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public static void Fill(System.Span<byte> data) { } public abstract void GetBytes(byte[] data); public virtual void GetBytes(byte[] data, int offset, int count) { } public virtual void GetBytes(System.Span<byte> data) { } public static int GetInt32(int toExclusive) { throw null; } public static int GetInt32(int fromInclusive, int toExclusive) { throw null; } public virtual void GetNonZeroBytes(byte[] data) { } public virtual void GetNonZeroBytes(System.Span<byte> data) { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public abstract partial class RC2 : System.Security.Cryptography.SymmetricAlgorithm { protected int EffectiveKeySizeValue; protected RC2() { } public virtual int EffectiveKeySize { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public static new System.Security.Cryptography.RC2 Create() { throw null; } public static new System.Security.Cryptography.RC2 Create(string AlgName) { throw null; } } public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes { public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public Rfc2898DeriveBytes(string password, byte[] salt) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public Rfc2898DeriveBytes(string password, int saltSize) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public System.Security.Cryptography.HashAlgorithmName HashAlgorithm { get { throw null; } } public int IterationCount { get { throw null; } set { } } public byte[] Salt { get { throw null; } set { } } public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override byte[] GetBytes(int cb) { throw null; } public override void Reset() { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public abstract partial class Rijndael : System.Security.Cryptography.SymmetricAlgorithm { protected Rijndael() { } public static new System.Security.Cryptography.Rijndael Create() { throw null; } public static new System.Security.Cryptography.Rijndael Create(string algName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class RijndaelManaged : System.Security.Cryptography.Rijndael { public RijndaelManaged() { } public override int BlockSize { get { throw null; } set { } } public override byte[] IV { get { throw null; } set { } } public override byte[] Key { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } } public abstract partial class RSA : System.Security.Cryptography.AsymmetricAlgorithm { protected RSA() { } public override string KeyExchangeAlgorithm { get { throw null; } } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.RSA Create() { throw null; } public static System.Security.Cryptography.RSA Create(int keySizeInBits) { throw null; } public static System.Security.Cryptography.RSA Create(System.Security.Cryptography.RSAParameters parameters) { throw null; } public static new System.Security.Cryptography.RSA Create(string algName) { throw null; } public virtual byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; } public virtual byte[] DecryptValue(byte[] rgb) { throw null; } public virtual byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; } public virtual byte[] EncryptValue(byte[] rgb) { throw null; } public abstract System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters); public virtual byte[] ExportRSAPrivateKey() { throw null; } public virtual byte[] ExportRSAPublicKey() { throw null; } public override void FromXmlString(string xmlString) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract void ImportParameters(System.Security.Cryptography.RSAParameters parameters); public virtual void ImportRSAPrivateKey(System.ReadOnlySpan<byte> source, out int bytesRead) { throw null; } public virtual void ImportRSAPublicKey(System.ReadOnlySpan<byte> source, out int bytesRead) { throw null; } public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public override string ToXmlString(bool includePrivateParameters) { throw null; } public virtual bool TryDecrypt(System.ReadOnlySpan<byte> data, System.Span<byte> destination, System.Security.Cryptography.RSAEncryptionPadding padding, out int bytesWritten) { throw null; } public virtual bool TryEncrypt(System.ReadOnlySpan<byte> data, System.Span<byte> destination, System.Security.Cryptography.RSAEncryptionPadding padding, out int bytesWritten) { throw null; } public virtual bool TryExportRSAPrivateKey(System.Span<byte> destination, out int bytesWritten) { throw null; } public virtual bool TryExportRSAPublicKey(System.Span<byte> destination, out int bytesWritten) { throw null; } protected virtual bool TryHashData(System.ReadOnlySpan<byte> data, System.Span<byte> destination, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, out int bytesWritten) { throw null; } public virtual bool TrySignData(System.ReadOnlySpan<byte> data, System.Span<byte> destination, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding, out int bytesWritten) { throw null; } public virtual bool TrySignHash(System.ReadOnlySpan<byte> hash, System.Span<byte> destination, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding, out int bytesWritten) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual bool VerifyData(System.ReadOnlySpan<byte> data, System.ReadOnlySpan<byte> signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual bool VerifyHash(System.ReadOnlySpan<byte> hash, System.ReadOnlySpan<byte> signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } } public sealed partial class RSAEncryptionPadding : System.IEquatable<System.Security.Cryptography.RSAEncryptionPadding> { internal RSAEncryptionPadding() { } public System.Security.Cryptography.RSAEncryptionPaddingMode Mode { get { throw null; } } public System.Security.Cryptography.HashAlgorithmName OaepHashAlgorithm { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA1 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA256 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA384 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public override bool Equals(object obj) { throw null; } public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; } public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; } public override string ToString() { throw null; } } public enum RSAEncryptionPaddingMode { Oaep = 1, Pkcs1 = 0, } public partial class RSAOAEPKeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter { public RSAOAEPKeyExchangeDeformatter() { } public RSAOAEPKeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } set { } } public override byte[] DecryptKeyExchange(byte[] rgbData) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAOAEPKeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter { public RSAOAEPKeyExchangeFormatter() { } public RSAOAEPKeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public byte[] Parameter { get { throw null; } set { } } public override string Parameters { get { throw null; } } public System.Security.Cryptography.RandomNumberGenerator Rng { get { throw null; } set { } } public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; } public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial struct RSAParameters { public byte[] D; public byte[] DP; public byte[] DQ; public byte[] Exponent; public byte[] InverseQ; public byte[] Modulus; public byte[] P; public byte[] Q; } public partial class RSAPKCS1KeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter { public RSAPKCS1KeyExchangeDeformatter() { } public RSAPKCS1KeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } set { } } public System.Security.Cryptography.RandomNumberGenerator RNG { get { throw null; } set { } } public override byte[] DecryptKeyExchange(byte[] rgbIn) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAPKCS1KeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter { public RSAPKCS1KeyExchangeFormatter() { } public RSAPKCS1KeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } } public System.Security.Cryptography.RandomNumberGenerator Rng { get { throw null; } set { } } public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; } public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAPKCS1SignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter { public RSAPKCS1SignatureDeformatter() { } public RSAPKCS1SignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; } } public partial class RSAPKCS1SignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter { public RSAPKCS1SignatureFormatter() { } public RSAPKCS1SignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override byte[] CreateSignature(byte[] rgbHash) { throw null; } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public sealed partial class RSASignaturePadding : System.IEquatable<System.Security.Cryptography.RSASignaturePadding> { internal RSASignaturePadding() { } public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { throw null; } } public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { throw null; } } public static System.Security.Cryptography.RSASignaturePadding Pss { get { throw null; } } public override bool Equals(object obj) { throw null; } public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; } public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; } public override string ToString() { throw null; } } public enum RSASignaturePaddingMode { Pkcs1 = 0, Pss = 1, } public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm { protected SHA1() { } public static new System.Security.Cryptography.SHA1 Create() { throw null; } public static new System.Security.Cryptography.SHA1 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class SHA1Managed : System.Security.Cryptography.SHA1 { public SHA1Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm { protected SHA256() { } public static new System.Security.Cryptography.SHA256 Create() { throw null; } public static new System.Security.Cryptography.SHA256 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class SHA256Managed : System.Security.Cryptography.SHA256 { public SHA256Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm { protected SHA384() { } public static new System.Security.Cryptography.SHA384 Create() { throw null; } public static new System.Security.Cryptography.SHA384 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class SHA384Managed : System.Security.Cryptography.SHA384 { public SHA384Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm { protected SHA512() { } public static new System.Security.Cryptography.SHA512 Create() { throw null; } public static new System.Security.Cryptography.SHA512 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed partial class SHA512Managed : System.Security.Cryptography.SHA512 { public SHA512Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class SignatureDescription { public SignatureDescription() { } public SignatureDescription(System.Security.SecurityElement el) { } public string DeformatterAlgorithm { get { throw null; } set { } } public string DigestAlgorithm { get { throw null; } set { } } public string FormatterAlgorithm { get { throw null; } set { } } public string KeyAlgorithm { get { throw null; } set { } } public virtual System.Security.Cryptography.AsymmetricSignatureDeformatter CreateDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; } public virtual System.Security.Cryptography.HashAlgorithm CreateDigest() { throw null; } public virtual System.Security.Cryptography.AsymmetricSignatureFormatter CreateFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; } } public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm { protected TripleDES() { } public override byte[] Key { get { throw null; } set { } } public static new System.Security.Cryptography.TripleDES Create() { throw null; } public static new System.Security.Cryptography.TripleDES Create(string str) { throw null; } public static bool IsWeakKey(byte[] rgbKey) { throw null; } } }
using System; using System.Globalization; /// <summary> /// UInt16.Parse(String, NumberStyles) /// </summary> public class UInt16Parse { public static int Main() { UInt16Parse ui32ct2 = new UInt16Parse(); TestLibrary.TestFramework.BeginTestCase("for method: UInt16.Parse(String, NumberStyles)"); if (ui32ct2.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; retVal = NegTest7() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; string errorDesc; UInt16 actualValue; NumberStyles numberStyle; TestLibrary.TestFramework.BeginScenario("PosTest1: UInt16.MaxValue, number style is NumberStyles.Integer."); try { numberStyle = NumberStyles.Integer; string strValue = UInt16.MaxValue.ToString(); strValue = " " + strValue + " "; actualValue = UInt16.Parse(strValue, numberStyle); if (actualValue != UInt16.MaxValue) { errorDesc = "The parse value of " + strValue + " with number styles " + numberStyle + " is not the value " + UInt16.MaxValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("001", errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string errorDesc; UInt16 actualValue; NumberStyles numberStyle; TestLibrary.TestFramework.BeginScenario("PosTest2: UInt16.MinValue, number style is NumberStyles.None."); try { string strValue = UInt16.MinValue.ToString(); numberStyle = NumberStyles.None; actualValue = UInt16.Parse(strValue, numberStyle); if (actualValue != UInt16.MinValue) { errorDesc = "The parse value of " + strValue + " with number styles " + numberStyle + " is not the value " + UInt16.MaxValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("003", errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string errorDesc; UInt16 expectedValue; UInt16 actualValue; NumberStyles numberStyle; TestLibrary.TestFramework.BeginScenario("PosTest3: random hexadecimal UInt16 value between 0 and UInt16.MaxValue"); try { expectedValue = (UInt16)this.GetInt32(0, UInt16.MaxValue); string strValue = expectedValue.ToString("x"); numberStyle = NumberStyles.HexNumber; actualValue = UInt16.Parse(strValue, numberStyle); if (actualValue != expectedValue) { errorDesc = "The parse value of " + strValue + " with number styles " + numberStyle + " is not the value " + UInt16.MaxValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string errorDesc; UInt16 expectedValue; UInt16 actualValue; NumberStyles numberStyle; TestLibrary.TestFramework.BeginScenario("PosTest4: random currency UInt16 value between 0 and UInt16.MaxValue"); try { expectedValue = (UInt16)this.GetInt32(0, UInt16.MaxValue); string strValue = expectedValue.ToString("c"); numberStyle = NumberStyles.Currency; actualValue = UInt16.Parse(strValue, numberStyle); if (actualValue != expectedValue) { errorDesc = "The parse value of " + strValue + " with number styles " + numberStyle + " is not the value " + UInt16.MaxValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string errorDesc; UInt16 expectedValue; UInt16 actualValue; NumberStyles numberStyle; TestLibrary.TestFramework.BeginScenario("PosTest5: random UInt16 value between 0 and UInt16.MaxValue, number styles is NumberStyels.Any"); try { expectedValue = (UInt16)this.GetInt32(0, UInt16.MaxValue); string strValue = expectedValue.ToString("f"); numberStyle = NumberStyles.Any; actualValue = UInt16.Parse(strValue, numberStyle); if (actualValue != expectedValue) { errorDesc = "The parse value of " + strValue + " with number styles " + numberStyle + " is not the value " + UInt16.MaxValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region Negative tests //ArgumentNullException public bool NegTest1() { bool retVal = true; const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: string representation is a null reference"; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { UInt16.Parse(null, NumberStyles.Integer); errorDesc = "ArgumentNullException is not thrown as expected."; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //FormatException public bool NegTest2() { bool retVal = true; const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: String representation is not in the correct format"; string errorDesc; string strValue; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { strValue = "Incorrect"; UInt16.Parse(strValue, NumberStyles.Integer); errorDesc = "FormatException is not thrown as expected."; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (FormatException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_ID = "N003"; const string c_TEST_DESC = "NegTest3: String representation does not match the correct number style"; string errorDesc; string strValue; strValue = this.GetInt32(0, UInt16.MaxValue).ToString("c"); NumberStyles numberStyle = NumberStyles.None; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { UInt16.Parse(strValue, numberStyle); errorDesc = "FormatException is not thrown as expected."; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, numberStyle); TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (FormatException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, numberStyle); TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //OverflowException public bool NegTest4() { bool retVal = true; const string c_TEST_ID = "N004"; const string c_TEST_DESC = "NegTest4: String representation is greater than UInt16.MaxValue"; string errorDesc; string strValue; int i; i = this.GetInt32(UInt16.MaxValue + 1, int.MaxValue); strValue = i.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { UInt16.Parse(strValue, NumberStyles.None); errorDesc = "OverflowException is not thrown as expected."; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, NumberStyles.None); TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (OverflowException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, NumberStyles.None); TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; const string c_TEST_ID = "N005"; const string c_TEST_DESC = "NegTest5: String representation is less than UInt16.MaxValue"; string errorDesc; string strValue; int i; i = -1 * TestLibrary.Generator.GetInt32(-55) - 1; strValue = i.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { UInt16.Parse(strValue, NumberStyles.Integer); errorDesc = "OverflowException is not thrown as expected."; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, NumberStyles.Integer); TestLibrary.TestFramework.LogError("017" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (OverflowException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, NumberStyles.Integer); TestLibrary.TestFramework.LogError("018" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //ArgumentException public bool NegTest6() { bool retVal = true; const string c_TEST_ID = "N006"; const string c_TEST_DESC = "NegTest6: style is not a NumberStyles value."; string errorDesc; string strValue; UInt16 i; i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1)); strValue = i.ToString(); NumberStyles numberStyle = (NumberStyles)(0x204 + TestLibrary.Generator.GetInt16(-55)); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { UInt16.Parse(strValue, numberStyle); errorDesc = "ArgumentException is not thrown as expected."; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, numberStyle); TestLibrary.TestFramework.LogError("019" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, numberStyle); TestLibrary.TestFramework.LogError("020" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool NegTest7() { bool retVal = true; const string c_TEST_ID = "N007"; const string c_TEST_DESC = "NegTest7: style is not a combination of AllowHexSpecifier and HexNumber values."; string errorDesc; string strValue; UInt16 i; i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1)); strValue = i.ToString(); NumberStyles numberStyle = (NumberStyles)(NumberStyles.AllowHexSpecifier | NumberStyles.AllowCurrencySymbol); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { UInt16.Parse(strValue, numberStyle); errorDesc = "ArgumentException is not thrown as expected."; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, numberStyle); TestLibrary.TestFramework.LogError("021" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nString representation is {0}, number styles is {1}", strValue, numberStyle); TestLibrary.TestFramework.LogError("022" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion #region ForTestObject private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
// 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.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListBySubscriptionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates/Updates a service namespace. Once created, this /// namespace's resource manifest is immutable. This operation is /// idempotent. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<NamespaceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates/Updates a service namespace. Once created, this /// namespace's resource manifest is immutable. This operation is /// idempotent. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<NamespaceResource>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the description for the specified namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<NamespaceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Authorization rules for a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates an authorization rule for a namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Namespace Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a namespace authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Authorization rule for a namespace by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Primary and Secondary ConnectionStrings to the namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerats the Primary or Secondary ConnectionStrings to the /// namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateKeysParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Authorization rules for a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace NetGore.Features.NPCChat { /// <summary> /// A TreeView specifically for displaying a NPC chat dialog. /// </summary> public class NPCChatDialogView : TreeView { /// <summary> /// Maps the objects handled by a TreeNode to the TreeNodes that handle it. /// </summary> readonly Dictionary<object, List<NPCChatDialogViewNode>> _objToTreeNode = new Dictionary<object, List<NPCChatDialogViewNode>>(); Color _nodeForeColorBranch = Color.DarkRed; Color _nodeForeColorGoTo = Color.Blue; Color _nodeForeColorNormal = Color.Black; Color _nodeForeColorResponse = Color.Green; EditorNPCChatDialog _npcChatDialog; /// <summary> /// Gets or sets the NPCChatDialog currently being displayed. /// </summary> public EditorNPCChatDialog NPCChatDialog { get { return _npcChatDialog; } set { if (_npcChatDialog == value) return; _npcChatDialog = value; Nodes.Clear(); _objToTreeNode.Clear(); if (_npcChatDialog != null && _npcChatDialog.GetInitialDialogItem() != null) new NPCChatDialogViewNode(this, _npcChatDialog.GetInitialDialogItem()); } } /// <summary> /// Gets or sets the font color of branch chat dialog nodes. /// </summary> [Description("The font color of branch chat dialog nodes.")] public Color NodeForeColorBranch { get { return _nodeForeColorBranch; } set { _nodeForeColorBranch = value; } } /// <summary> /// Gets or sets the font color of GOTO nodes. /// </summary> [Description("The font color of GOTO nodes.")] public Color NodeForeColorGoTo { get { return _nodeForeColorGoTo; } set { _nodeForeColorGoTo = value; } } /// <summary> /// Gets or sets the font color of normal chat dialog nodes. /// </summary> [Description("The font color of normal chat dialog nodes.")] public Color NodeForeColorNormal { get { return _nodeForeColorNormal; } set { _nodeForeColorNormal = value; } } /// <summary> /// Gets or sets the font color of dialog response value nodes. /// </summary> [Description("The font color of dialog response value nodes.")] public Color NodeForeColorResponse { get { return _nodeForeColorResponse; } set { _nodeForeColorResponse = value; } } /// <summary> /// Handles when a <see cref="EditorNPCChatDialogItem"/> changes. /// </summary> /// <param name="sender">The <see cref="EditorNPCChatDialogItem"/> that changed.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void EditorNPCChatDialogItem_Changed(EditorNPCChatDialogItem sender, EventArgs e) { List<NPCChatDialogViewNode> l; if (!_objToTreeNode.TryGetValue(sender, out l)) return; foreach (var node in l) { node.Update(false); } } /// <summary> /// Handles when a <see cref="EditorNPCChatResponse"/> changes. /// </summary> /// <param name="response">The <see cref="EditorNPCChatResponse"/> that changed.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void EditorNPCChatResponse_Changed(EditorNPCChatResponse response, EventArgs e) { List<NPCChatDialogViewNode> l; if (!_objToTreeNode.TryGetValue(response, out l)) return; foreach (var node in l) { node.Update(false); } } /// <summary> /// Gets an IEnumerable of all the TreeNodes from the given <paramref name="root"/>. /// </summary> /// <param name="root">The root collection of TreeNodes.</param> /// <returns>An IEnumerable of all the TreeNodes from the given <paramref name="root"/>.</returns> public static IEnumerable<TreeNode> GetAllNodes(IEnumerable root) { foreach (var node in root.Cast<TreeNode>()) { yield return node; foreach (var r in GetAllNodes(node.Nodes)) { yield return r; } } } /// <summary> /// Gets an IEnumerable of all the TreeNodes in this TreeView. /// </summary> /// <returns>An IEnumerable of all the TreeNodes in this TreeView.</returns> public IEnumerable<TreeNode> GetAllNodes() { return GetAllNodes(Nodes); } /// <summary> /// Gets the NPCChatDialogViewNode for the given NPCChatDialogItemBase. Nodes that redirect to the /// given NPCChatDialogItemBase are not included. /// </summary> /// <param name="dialogItem">The NPCChatDialogItemBase to find the NPCChatDialogViewNode for.</param> /// <returns>The NPCChatDialogViewNode for the given <paramref name="dialogItem"/>, or null if /// no NPCChatDialogViewNode was found that handles the given <paramref name="dialogItem"/>.</returns> public NPCChatDialogViewNode GetNodeForDialogItem(NPCChatDialogItemBase dialogItem) { if (NPCChatDialog == null) return null; List<NPCChatDialogViewNode> ret; if (!_objToTreeNode.TryGetValue(dialogItem, out ret)) return null; // Remove dead nodes foreach (var deadNode in ret.Where(x => x.IsDead)) { NotifyNodeDestroyed(deadNode); } Debug.Assert(ret.Count(x => x.ChatItemType == NPCChatDialogViewNodeItemType.DialogItem) <= 1, "Was only expected 0 or 1 TreeNodes to be directly for this dialogItem."); var r = ret.FirstOrDefault(x => x.ChatItemType == NPCChatDialogViewNodeItemType.DialogItem); Debug.Assert(r.ChatItemAsDialogItem == dialogItem); return r; } /// <summary> /// Gets the NPCChatDialogViewNode for the given NPCChatDialogItemBase. Nodes that redirect to the /// given NPCChatDialogItemBase are not included. /// </summary> /// <param name="dialogItemID">The index of the NPCChatDialogItemBase to find the NPCChatDialogViewNode for.</param> /// <returns>The NPCChatDialogViewNode for the given <paramref name="dialogItemID"/>, or null if /// no NPCChatDialogViewNode was found that handles the given <paramref name="dialogItemID"/> or /// if the <paramref name="dialogItemID"/> was for an invalid NPCChatDialogItemBase.</returns> public NPCChatDialogViewNode GetNodeForDialogItem(NPCChatDialogItemID dialogItemID) { if (NPCChatDialog == null) return null; var dialogItem = NPCChatDialog.GetDialogItem(dialogItemID); if (dialogItem == null) return null; return GetNodeForDialogItem(dialogItem); } /// <summary> /// Gets an IEnumerable of all the NPCChatDialogViewNodes that handle the given <paramref name="dialogItem"/>. /// This includes any NPCChatDialogViewNodes that redirect to the NPCChatDialogItemBase. /// </summary> /// <param name="dialogItem">The NPCChatDialogItemBase to find the NPCChatDialogViewNodes for.</param> /// <returns>An IEnumerable of all the NPCChatDialogViewNodes that handle the given /// <paramref name="dialogItem"/>.</returns> public IEnumerable<NPCChatDialogViewNode> GetNodesForDialogItem(NPCChatDialogItemBase dialogItem) { if (NPCChatDialog == null) return null; List<NPCChatDialogViewNode> ret; if (!_objToTreeNode.TryGetValue(dialogItem, out ret)) return Enumerable.Empty<NPCChatDialogViewNode>(); // Remove dead nodes foreach (var deadNode in ret.Where(x => x.IsDead)) { NotifyNodeDestroyed(deadNode); } Debug.Assert(ret.All(x => x.ChatItemAsDialogItem == dialogItem)); return ret; } /// <summary> /// Notifies the NPCChatDialogView when a NPCChatDialogViewNode was created. /// </summary> /// <param name="node">The NPCChatDialogViewNode that was created.</param> internal void NotifyNodeCreated(NPCChatDialogViewNode node) { List<NPCChatDialogViewNode> l; if (!_objToTreeNode.TryGetValue(node.ChatItem, out l)) { l = new List<NPCChatDialogViewNode>(1); _objToTreeNode.Add(node.ChatItem, l); } if (node.ChatItemType == NPCChatDialogViewNodeItemType.Response) { node.ChatItemAsResponse.Changed -= EditorNPCChatResponse_Changed; node.ChatItemAsResponse.Changed += EditorNPCChatResponse_Changed; } else { node.ChatItemAsDialogItem.Changed -= EditorNPCChatDialogItem_Changed; node.ChatItemAsDialogItem.Changed += EditorNPCChatDialogItem_Changed; } l.Add(node); } /// <summary> /// Notifies the NPCChatDialogView when a NPCChatDialogViewNode was destroyed. /// </summary> /// <param name="node">The NPCChatDialogViewNode that was destroyed.</param> internal void NotifyNodeDestroyed(NPCChatDialogViewNode node) { List<NPCChatDialogViewNode> l; if (!_objToTreeNode.TryGetValue(node.ChatItem, out l)) return; l.Remove(node); } /// <summary> /// Handles when the NPCChatDialogView is double-clicked. /// </summary> /// <param name="e">Event args.</param> protected override void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e) { if (e.Node != null) { var tagAsTreeNode = e.Node.Tag as TreeNode; if (tagAsTreeNode != null) SelectedNode = tagAsTreeNode; } base.OnNodeMouseDoubleClick(e); } /// <summary> /// Updates the whole TreeView to ensure it is properly synchronized. /// </summary> public void UpdateTree() { if (NPCChatDialog == null) return; foreach (var childNode in Nodes.OfType<NPCChatDialogViewNode>()) { childNode.Update(true); } } } }
/* * 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.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; [TestFixture] [Category("group4")] [Category("unicast_only")] [Category("generics")] public class ThinClientStringArrayTests : ThinClientRegionSteps { #region Private members private UnitProcess m_client1; private UnitProcess m_client2; private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2", "Portfolios3" }; private static string QERegionName = "Portfolios"; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); return new ClientBase[] { m_client1, m_client2 }; } [TestFixtureSetUp] public override void InitTests() { base.InitTests(); m_client1.Call(InitClient); m_client2.Call(InitClient); } [TearDown] public override void EndTest() { CacheHelper.StopJavaServers(); base.EndTest(); } public void InitClient() { CacheHelper.Init(); try { CacheHelper.DCache.TypeRegistry.RegisterType(Portfolio.CreateDeserializable, 8); CacheHelper.DCache.TypeRegistry.RegisterType(Position.CreateDeserializable, 7); } catch (IllegalStateException) { // ignore since we run multiple incarnations of client in same process } } public void StepOne(string locators) { CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes; region.CreateSubRegion(QueryRegionNames[1], regattrs); } public void StepTwo() { IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]); IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]); IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]); IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]); QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize, qh.PortfolioNumSets); string[] cnm = { "C#aaa", "C#bbb", "C#ccc", "C#ddd" }; //CacheableStringArray cnm = CacheableStringArray.Create(sta); qh.PopulatePortfolioData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets, 1, cnm); qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets, 1, cnm); qh.PopulatePortfolioData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets, 1, cnm); } public void StepTwoQT() { IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]); QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); string[] /*sta*/ cnm = { "C#aaa", "C#bbb", "C#ccc", "C#ddd" }; //CacheableStringArray cnm = CacheableStringArray.Create(sta); qh.PopulatePortfolioData(region0, 4, 2, 2, cnm); qh.PopulatePositionData(subRegion0, 4, 2); } public void StepOneQE(string locators) { CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName); string[] /*sta*/ cnm = { "C#aaa", "C#bbb", "C#ccc", "C#ddd" }; //CacheableStringArray cnm = CacheableStringArray.Create(sta); Portfolio p1 = new Portfolio(1, 2, cnm); Portfolio p2 = new Portfolio(2, 2, cnm); Portfolio p3 = new Portfolio(3, 2, cnm); Portfolio p4 = new Portfolio(4, 2, cnm); region["1"] = p1; region["2"] = p2; region["3"] = p3; region["4"] = p4; var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); Query<object> qry = qs.NewQuery<object>("select * from /" + QERegionName + " p where p.ID!=3"); ISelectResults<object> results = qry.Execute(); Util.Log("Results size {0}.", results.Size); foreach (var item in results) { Portfolio port = item as Portfolio; if (port == null) { Position pos = item as Position; if (pos == null) { //CacheableString cs = item as CacheableString; string cs = item as string; if (cs == null) { Util.Log("Query got other/unknown object."); } else { Util.Log("Query got string : {0}.", cs); } } else { Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding); } } else { Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid); } } // Bring down the region region.GetLocalView().DestroyRegion(); } void runStringArrayTest() { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(StepOne, CacheHelper.Locators); Util.Log("StepOne complete."); m_client1.Call(StepTwo); Util.Log("StepTwo complete."); m_client1.Call(StepOneQE, CacheHelper.Locators); Util.Log("StepOneQE complete."); m_client1.Call(Close); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearLocators(); CacheHelper.ClearEndpoints(); } [Test] public void StringArrayTest() { runStringArrayTest(); } } }
// <copyright file="FirefoxProfile.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; using Newtonsoft.Json; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Firefox { /// <summary> /// Provides the ability to edit the preferences associated with a Firefox profile. /// </summary> public class FirefoxProfile { private const string UserPreferencesFileName = "user.js"; private string profileDir; private string sourceProfileDir; private bool deleteSource; private bool deleteOnClean = true; private Preferences profilePreferences; private Dictionary<string, FirefoxExtension> extensions = new Dictionary<string, FirefoxExtension>(); /// <summary> /// Initializes a new instance of the <see cref="FirefoxProfile"/> class. /// </summary> public FirefoxProfile() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxProfile"/> class using a /// specific profile directory. /// </summary> /// <param name="profileDirectory">The directory containing the profile.</param> public FirefoxProfile(string profileDirectory) : this(profileDirectory, false) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxProfile"/> class using a /// specific profile directory. /// </summary> /// <param name="profileDirectory">The directory containing the profile.</param> /// <param name="deleteSourceOnClean">Delete the source directory of the profile upon cleaning.</param> public FirefoxProfile(string profileDirectory, bool deleteSourceOnClean) { this.sourceProfileDir = profileDirectory; this.deleteSource = deleteSourceOnClean; this.ReadDefaultPreferences(); this.profilePreferences.AppendPreferences(this.ReadExistingPreferences()); } /// <summary> /// Gets the directory containing the profile. /// </summary> public string ProfileDirectory { get { return this.profileDir; } } /// <summary> /// Gets or sets a value indicating whether to delete this profile after use with /// the <see cref="FirefoxDriver"/>. /// </summary> public bool DeleteAfterUse { get { return this.deleteOnClean; } set { this.deleteOnClean = value; } } /// <summary> /// Converts a base64-encoded string into a <see cref="FirefoxProfile"/>. /// </summary> /// <param name="base64">The base64-encoded string containing the profile contents.</param> /// <returns>The constructed <see cref="FirefoxProfile"/>.</returns> public static FirefoxProfile FromBase64String(string base64) { string destinationDirectory = FileUtilities.GenerateRandomTempDirectoryName("webdriver.{0}.duplicated"); byte[] zipContent = Convert.FromBase64String(base64); using (MemoryStream zipStream = new MemoryStream(zipContent)) { using (ZipArchive profileZipArchive = new ZipArchive(zipStream, ZipArchiveMode.Read)) { profileZipArchive.ExtractToDirectory(destinationDirectory); } } return new FirefoxProfile(destinationDirectory, true); } /// <summary> /// Adds a Firefox Extension to this profile /// </summary> /// <param name="extensionToInstall">The path to the new extension</param> public void AddExtension(string extensionToInstall) { this.extensions.Add(Path.GetFileNameWithoutExtension(extensionToInstall), new FirefoxExtension(extensionToInstall)); } /// <summary> /// Sets a preference in the profile. /// </summary> /// <param name="name">The name of the preference to add.</param> /// <param name="value">A <see cref="string"/> value to add to the profile.</param> public void SetPreference(string name, string value) { this.profilePreferences.SetPreference(name, value); } /// <summary> /// Sets a preference in the profile. /// </summary> /// <param name="name">The name of the preference to add.</param> /// <param name="value">A <see cref="int"/> value to add to the profile.</param> public void SetPreference(string name, int value) { this.profilePreferences.SetPreference(name, value); } /// <summary> /// Sets a preference in the profile. /// </summary> /// <param name="name">The name of the preference to add.</param> /// <param name="value">A <see cref="bool"/> value to add to the profile.</param> public void SetPreference(string name, bool value) { this.profilePreferences.SetPreference(name, value); } /// <summary> /// Writes this in-memory representation of a profile to disk. /// </summary> public void WriteToDisk() { this.profileDir = GenerateProfileDirectoryName(); if (!string.IsNullOrEmpty(this.sourceProfileDir)) { FileUtilities.CopyDirectory(this.sourceProfileDir, this.profileDir); } else { Directory.CreateDirectory(this.profileDir); } this.InstallExtensions(); this.DeleteLockFiles(); this.DeleteExtensionsCache(); this.UpdateUserPreferences(); } /// <summary> /// Cleans this Firefox profile. /// </summary> /// <remarks>If this profile is a named profile that existed prior to /// launching Firefox, the <see cref="Clean"/> method removes the WebDriver /// Firefox extension. If the profile is an anonymous profile, the profile /// is deleted.</remarks> public void Clean() { if (this.deleteOnClean && !string.IsNullOrEmpty(this.profileDir) && Directory.Exists(this.profileDir)) { FileUtilities.DeleteDirectory(this.profileDir); } if (this.deleteSource && !string.IsNullOrEmpty(this.sourceProfileDir) && Directory.Exists(this.sourceProfileDir)) { FileUtilities.DeleteDirectory(this.sourceProfileDir); } } /// <summary> /// Converts the profile into a base64-encoded string. /// </summary> /// <returns>A base64-encoded string containing the contents of the profile.</returns> public string ToBase64String() { string base64zip = string.Empty; this.WriteToDisk(); using (MemoryStream profileMemoryStream = new MemoryStream()) { using (ZipArchive profileZipArchive = new ZipArchive(profileMemoryStream, ZipArchiveMode.Create, true)) { string[] files = Directory.GetFiles(this.profileDir, "*.*", SearchOption.AllDirectories); foreach (string file in files) { string fileNameInZip = file.Substring(this.profileDir.Length + 1).Replace(Path.DirectorySeparatorChar, '/'); profileZipArchive.CreateEntryFromFile(file, fileNameInZip); } } base64zip = Convert.ToBase64String(profileMemoryStream.ToArray()); this.Clean(); } return base64zip; } /// <summary> /// Generates a random directory name for the profile. /// </summary> /// <returns>A random directory name for the profile.</returns> private static string GenerateProfileDirectoryName() { return FileUtilities.GenerateRandomTempDirectoryName("anonymous.{0}.webdriver-profile"); } /// <summary> /// Deletes the lock files for a profile. /// </summary> private void DeleteLockFiles() { File.Delete(Path.Combine(this.profileDir, ".parentlock")); File.Delete(Path.Combine(this.profileDir, "parent.lock")); } /// <summary> /// Installs all extensions in the profile in the directory on disk. /// </summary> private void InstallExtensions() { foreach (string extensionKey in this.extensions.Keys) { this.extensions[extensionKey].Install(this.profileDir); } } /// <summary> /// Deletes the cache of extensions for this profile, if the cache exists. /// </summary> /// <remarks>If the extensions cache does not exist for this profile, the /// <see cref="DeleteExtensionsCache"/> method performs no operations, but /// succeeds.</remarks> private void DeleteExtensionsCache() { DirectoryInfo ex = new DirectoryInfo(Path.Combine(this.profileDir, "extensions")); string cacheFile = Path.Combine(ex.Parent.FullName, "extensions.cache"); if (File.Exists(cacheFile)) { File.Delete(cacheFile); } } /// <summary> /// Writes the user preferences to the profile. /// </summary> private void UpdateUserPreferences() { string userPrefs = Path.Combine(this.profileDir, UserPreferencesFileName); if (File.Exists(userPrefs)) { try { File.Delete(userPrefs); } catch (Exception e) { throw new WebDriverException("Cannot delete existing user preferences", e); } } string homePage = this.profilePreferences.GetPreference("browser.startup.homepage"); if (!string.IsNullOrEmpty(homePage)) { this.profilePreferences.SetPreference("startup.homepage_welcome_url", string.Empty); if (homePage != "about:blank") { this.profilePreferences.SetPreference("browser.startup.page", 1); } } this.profilePreferences.WriteToFile(userPrefs); } private void ReadDefaultPreferences() { using (Stream defaultPrefsStream = ResourceUtilities.GetResourceStream("webdriver.json", "WebDriver.FirefoxPreferences")) { using (StreamReader reader = new StreamReader(defaultPrefsStream)) { string defaultPreferences = reader.ReadToEnd(); Dictionary<string, object> deserializedPreferences = JsonConvert.DeserializeObject<Dictionary<string, object>>(defaultPreferences, new ResponseValueJsonConverter()); Dictionary<string, object> immutableDefaultPreferences = deserializedPreferences["frozen"] as Dictionary<string, object>; Dictionary<string, object> editableDefaultPreferences = deserializedPreferences["mutable"] as Dictionary<string, object>; this.profilePreferences = new Preferences(immutableDefaultPreferences, editableDefaultPreferences); } } } /// <summary> /// Reads the existing preferences from the profile. /// </summary> /// <returns>A <see cref="Dictionary{K, V}"/>containing key-value pairs representing the preferences.</returns> /// <remarks>Assumes that we only really care about the preferences, not the comments</remarks> private Dictionary<string, string> ReadExistingPreferences() { Dictionary<string, string> prefs = new Dictionary<string, string>(); try { if (!string.IsNullOrEmpty(this.sourceProfileDir)) { string userPrefs = Path.Combine(this.sourceProfileDir, UserPreferencesFileName); if (File.Exists(userPrefs)) { string[] fileLines = File.ReadAllLines(userPrefs); foreach (string line in fileLines) { if (line.StartsWith("user_pref(\"", StringComparison.OrdinalIgnoreCase)) { string parsedLine = line.Substring("user_pref(\"".Length); parsedLine = parsedLine.Substring(0, parsedLine.Length - ");".Length); string[] parts = line.Split(new string[] { "," }, StringSplitOptions.None); parts[0] = parts[0].Substring(0, parts[0].Length - 1); prefs.Add(parts[0].Trim(), parts[1].Trim()); } } } } } catch (IOException e) { throw new WebDriverException(string.Empty, e); } return prefs; } } }
using System; using System.Collections; using Fonet.Fo.Flow; using Fonet.Fo.Properties; using Fonet.Layout; namespace Fonet.Fo.Pagination { internal class PageSequence : FObj { new internal class Maker : FObj.Maker { public override FObj Make(FObj parent, PropertyList propertyList) { return new PageSequence(parent, propertyList); } } new public static FObj.Maker GetMaker() { return new Maker(); } private const int EXPLICIT = 0; private const int AUTO = 1; private const int AUTO_EVEN = 2; private const int AUTO_ODD = 3; private Root root; private LayoutMasterSet layoutMasterSet; private Hashtable _flowMap; private string masterName; private bool _isFlowSet = false; private Page currentPage; private string ipnValue; private int currentPageNumber = 0; private PageNumberGenerator pageNumberGenerator; private int forcePageCount = 0; private int pageCount = 0; private bool isForcing = false; private int pageNumberType; private bool thisIsFirstPage; private SubSequenceSpecifier currentSubsequence; private int currentSubsequenceNumber = -1; private string currentPageMasterName; protected PageSequence(FObj parent, PropertyList propertyList) : base(parent, propertyList) { this.name = "fo:page-sequence"; if (parent.GetName().Equals("fo:root")) { this.root = (Root)parent; } else { throw new FonetException("page-sequence must be child of root, not " + parent.GetName()); } layoutMasterSet = root.getLayoutMasterSet(); layoutMasterSet.checkRegionNames(); _flowMap = new Hashtable(); thisIsFirstPage = true; ipnValue = this.properties.GetProperty("initial-page-number").GetString(); if (ipnValue.Equals("auto")) { pageNumberType = AUTO; } else if (ipnValue.Equals("auto-even")) { pageNumberType = AUTO_EVEN; } else if (ipnValue.Equals("auto-odd")) { pageNumberType = AUTO_ODD; } else { pageNumberType = EXPLICIT; try { int pageStart = Int32.Parse(ipnValue); this.currentPageNumber = (pageStart > 0) ? pageStart - 1 : 0; } catch (FormatException) { throw new FonetException("\"" + ipnValue + "\" is not a valid value for initial-page-number"); } } masterName = this.properties.GetProperty("master-reference").GetString(); this.pageNumberGenerator = new PageNumberGenerator(this.properties.GetProperty("format").GetString(), this.properties.GetProperty("grouping-separator").GetCharacter(), this.properties.GetProperty("grouping-size").GetNumber().IntValue(), this.properties.GetProperty("letter-value").GetEnum()); this.forcePageCount = this.properties.GetProperty("force-page-count").GetEnum(); } public void AddFlow(Flow.Flow flow) { if (_flowMap.ContainsKey(flow.GetFlowName())) { throw new FonetException("flow-names must be unique within an fo:page-sequence"); } if (!this.layoutMasterSet.regionNameExists(flow.GetFlowName())) { FonetDriver.ActiveDriver.FireFonetError( "region-name '" + flow.GetFlowName() + "' doesn't exist in the layout-master-set."); } _flowMap.Add(flow.GetFlowName(), flow); IsFlowSet = true; } public void Format(AreaTree areaTree) { Status status = new Status(Status.OK); this.layoutMasterSet.resetPageMasters(); int firstAvailPageNumber = 0; do { firstAvailPageNumber = this.root.getRunningPageNumberCounter(); bool tempIsFirstPage = false; if (thisIsFirstPage) { tempIsFirstPage = thisIsFirstPage; if (pageNumberType == AUTO) { this.currentPageNumber = this.root.getRunningPageNumberCounter(); } else if (pageNumberType == AUTO_ODD) { this.currentPageNumber = this.root.getRunningPageNumberCounter(); if (this.currentPageNumber % 2 == 1) { this.currentPageNumber++; } } else if (pageNumberType == AUTO_EVEN) { this.currentPageNumber = this.root.getRunningPageNumberCounter(); if (this.currentPageNumber % 2 == 0) { this.currentPageNumber++; } } thisIsFirstPage = false; } this.currentPageNumber++; bool isEmptyPage = false; if ((status.getCode() == Status.FORCE_PAGE_BREAK_EVEN) && ((currentPageNumber % 2) == 1)) { isEmptyPage = true; } else if ((status.getCode() == Status.FORCE_PAGE_BREAK_ODD) && ((currentPageNumber % 2) == 0)) { isEmptyPage = true; } else { isEmptyPage = false; } currentPage = MakePage(areaTree, firstAvailPageNumber, tempIsFirstPage, isEmptyPage); currentPage.setNumber(this.currentPageNumber); string formattedPageNumber = pageNumberGenerator.makeFormattedPageNumber(this.currentPageNumber); currentPage.setFormattedNumber(formattedPageNumber); this.root.setRunningPageNumberCounter(this.currentPageNumber); FonetDriver.ActiveDriver.FireFonetInfo( "[" + currentPageNumber + "]"); if ((status.getCode() == Status.FORCE_PAGE_BREAK_EVEN) && ((currentPageNumber % 2) == 1)) { } else if ((status.getCode() == Status.FORCE_PAGE_BREAK_ODD) && ((currentPageNumber % 2) == 0)) { } else { BodyAreaContainer bodyArea = currentPage.getBody(); bodyArea.setIDReferences(areaTree.getIDReferences()); Flow.Flow flow = GetCurrentFlow(RegionBody.REGION_CLASS); if (flow == null) { FonetDriver.ActiveDriver.FireFonetError( "No flow found for region-body in page-master '" + currentPageMasterName + "'"); break; } else { status = flow.Layout(bodyArea); } } currentPage.setPageSequence(this); FormatStaticContent(areaTree); areaTree.addPage(currentPage); this.pageCount++; } while (FlowsAreIncomplete()); ForcePage(areaTree, firstAvailPageNumber); currentPage = null; } private Page MakePage(AreaTree areaTree, int firstAvailPageNumber, bool isFirstPage, bool isEmptyPage) { PageMaster pageMaster = GetNextPageMaster(masterName, firstAvailPageNumber, isFirstPage, isEmptyPage); if (pageMaster == null) { throw new FonetException("page masters exhausted. Cannot recover."); } Page p = pageMaster.makePage(areaTree); if (currentPage != null) { ArrayList foots = currentPage.getPendingFootnotes(); p.setPendingFootnotes(foots); } return p; } private void FormatStaticContent(AreaTree areaTree) { SimplePageMaster simpleMaster = GetCurrentSimplePageMaster(); if (simpleMaster.getRegion(RegionBefore.REGION_CLASS) != null && (currentPage.getBefore() != null)) { Flow.Flow staticFlow = (Flow.Flow)_flowMap[simpleMaster.getRegion(RegionBefore.REGION_CLASS).getRegionName()]; if (staticFlow != null) { AreaContainer beforeArea = currentPage.getBefore(); beforeArea.setIDReferences(areaTree.getIDReferences()); LayoutStaticContent(staticFlow, simpleMaster.getRegion(RegionBefore.REGION_CLASS), beforeArea); } } if (simpleMaster.getRegion(RegionAfter.REGION_CLASS) != null && (currentPage.getAfter() != null)) { Flow.Flow staticFlow = (Flow.Flow)_flowMap[simpleMaster.getRegion(RegionAfter.REGION_CLASS).getRegionName()]; if (staticFlow != null) { AreaContainer afterArea = currentPage.getAfter(); afterArea.setIDReferences(areaTree.getIDReferences()); LayoutStaticContent(staticFlow, simpleMaster.getRegion(RegionAfter.REGION_CLASS), afterArea); } } if (simpleMaster.getRegion(RegionStart.REGION_CLASS) != null && (currentPage.getStart() != null)) { Flow.Flow staticFlow = (Flow.Flow)_flowMap[simpleMaster.getRegion(RegionStart.REGION_CLASS).getRegionName()]; if (staticFlow != null) { AreaContainer startArea = currentPage.getStart(); startArea.setIDReferences(areaTree.getIDReferences()); LayoutStaticContent(staticFlow, simpleMaster.getRegion(RegionStart.REGION_CLASS), startArea); } } if (simpleMaster.getRegion(RegionEnd.REGION_CLASS) != null && (currentPage.getEnd() != null)) { Flow.Flow staticFlow = (Flow.Flow)_flowMap[simpleMaster.getRegion(RegionEnd.REGION_CLASS).getRegionName()]; if (staticFlow != null) { AreaContainer endArea = currentPage.getEnd(); endArea.setIDReferences(areaTree.getIDReferences()); LayoutStaticContent(staticFlow, simpleMaster.getRegion(RegionEnd.REGION_CLASS), endArea); } } } private void LayoutStaticContent(Flow.Flow flow, Region region, AreaContainer area) { if (flow is StaticContent) { ((StaticContent)flow).Layout(area, region); } else { FonetDriver.ActiveDriver.FireFonetError(region.GetName() + " only supports static-content flows currently. " + "Cannot use flow named '" + flow.GetFlowName() + "'"); } } private SubSequenceSpecifier GetNextSubsequence(PageSequenceMaster master) { if (master.GetSubSequenceSpecifierCount() > currentSubsequenceNumber + 1) { currentSubsequence = master.getSubSequenceSpecifier(currentSubsequenceNumber + 1); currentSubsequenceNumber++; return currentSubsequence; } else { return null; } } private SimplePageMaster GetNextSimplePageMaster(PageSequenceMaster sequenceMaster, int currentPageNumber, bool thisIsFirstPage, bool isEmptyPage) { if (isForcing) { return this.layoutMasterSet.getSimplePageMaster( GetNextPageMasterName(sequenceMaster, currentPageNumber, false, true)); } string nextPageMaster = GetNextPageMasterName(sequenceMaster, currentPageNumber, thisIsFirstPage, isEmptyPage); return this.layoutMasterSet.getSimplePageMaster(nextPageMaster); } private string GetNextPageMasterName(PageSequenceMaster sequenceMaster, int currentPageNumber, bool thisIsFirstPage, bool isEmptyPage) { if (null == currentSubsequence) { currentSubsequence = GetNextSubsequence(sequenceMaster); } string nextPageMaster = currentSubsequence.GetNextPageMaster(currentPageNumber, thisIsFirstPage, isEmptyPage); if (null == nextPageMaster || IsFlowForMasterNameDone(currentPageMasterName)) { SubSequenceSpecifier nextSubsequence = GetNextSubsequence(sequenceMaster); if (nextSubsequence == null) { FonetDriver.ActiveDriver.FireFonetError( "Page subsequences exhausted. Using previous subsequence."); thisIsFirstPage = true; currentSubsequence.Reset(); } else { currentSubsequence = nextSubsequence; } nextPageMaster = currentSubsequence.GetNextPageMaster(currentPageNumber, thisIsFirstPage, isEmptyPage); } currentPageMasterName = nextPageMaster; return nextPageMaster; } private SimplePageMaster GetCurrentSimplePageMaster() { return this.layoutMasterSet.getSimplePageMaster(currentPageMasterName); } private string GetCurrentPageMasterName() { return currentPageMasterName; } private PageMaster GetNextPageMaster(string pageSequenceName, int currentPageNumber, bool thisIsFirstPage, bool isEmptyPage) { PageMaster pageMaster = null; PageSequenceMaster sequenceMaster = this.layoutMasterSet.getPageSequenceMaster(pageSequenceName); if (sequenceMaster != null) { pageMaster = GetNextSimplePageMaster(sequenceMaster, currentPageNumber, thisIsFirstPage, isEmptyPage).getPageMaster(); } else { SimplePageMaster simpleMaster = this.layoutMasterSet.getSimplePageMaster(pageSequenceName); if (simpleMaster == null) { throw new FonetException("'master-reference' for 'fo:page-sequence'" + "matches no 'simple-page-master' or 'page-sequence-master'"); } currentPageMasterName = pageSequenceName; pageMaster = simpleMaster.GetNextPageMaster(); } return pageMaster; } private bool FlowsAreIncomplete() { bool isIncomplete = false; foreach (Flow.Flow flow in _flowMap.Values) { if (flow is StaticContent) { continue; } Status status = flow.getStatus(); isIncomplete |= status.isIncomplete(); } return isIncomplete; } private Flow.Flow GetCurrentFlow(string regionClass) { Region region = GetCurrentSimplePageMaster().getRegion(regionClass); if (region != null) { Flow.Flow flow = (Flow.Flow)_flowMap[region.getRegionName()]; return flow; } else { FonetDriver.ActiveDriver.FireFonetInfo( "flow is null. regionClass = '" + regionClass + "' currentSPM = " + GetCurrentSimplePageMaster()); return null; } } private bool IsFlowForMasterNameDone(string masterName) { if (isForcing) { return false; } if (masterName != null) { SimplePageMaster spm = this.layoutMasterSet.getSimplePageMaster(masterName); Region region = spm.getRegion(RegionBody.REGION_CLASS); Flow.Flow flow = (Flow.Flow)_flowMap[region.getRegionName()]; if ((null == flow) || flow.getStatus().isIncomplete()) { return false; } else { return true; } } return false; } public bool IsFlowSet { get { return _isFlowSet; } set { _isFlowSet = value; } } public string IpnValue { get { return ipnValue; } } public int CurrentPageNumber { get { return currentPageNumber; } } public int PageCount { get { return this.pageCount; } } private void ForcePage(AreaTree areaTree, int firstAvailPageNumber) { bool bmakePage = false; if (this.forcePageCount == ForcePageCount.AUTO) { PageSequence nextSequence = this.root.getSucceedingPageSequence(this); if (nextSequence != null) { if (nextSequence.IpnValue.Equals("auto")) { // do nothing } else if (nextSequence.IpnValue.Equals("auto-odd")) { if (firstAvailPageNumber % 2 == 0) { bmakePage = true; } } else if (nextSequence.IpnValue.Equals("auto-even")) { if (firstAvailPageNumber % 2 != 0) { bmakePage = true; } } else { int nextSequenceStartPageNumber = nextSequence.CurrentPageNumber; if ((nextSequenceStartPageNumber % 2 == 0) && (firstAvailPageNumber % 2 == 0)) { bmakePage = true; } else if ((nextSequenceStartPageNumber % 2 != 0) && (firstAvailPageNumber % 2 != 0)) { bmakePage = true; } } } } else if ((this.forcePageCount == ForcePageCount.EVEN) && (this.pageCount % 2 != 0)) { bmakePage = true; } else if ((this.forcePageCount == ForcePageCount.ODD) && (this.pageCount % 2 == 0)) { bmakePage = true; } else if ((this.forcePageCount == ForcePageCount.END_ON_EVEN) && (firstAvailPageNumber % 2 == 0)) { bmakePage = true; } else if ((this.forcePageCount == ForcePageCount.END_ON_ODD) && (firstAvailPageNumber % 2 != 0)) { bmakePage = true; } else if (this.forcePageCount == ForcePageCount.NO_FORCE) { // do nothing } if (bmakePage) { try { this.isForcing = true; this.currentPageNumber++; firstAvailPageNumber = this.currentPageNumber; currentPage = MakePage(areaTree, firstAvailPageNumber, false, true); string formattedPageNumber = pageNumberGenerator.makeFormattedPageNumber(this.currentPageNumber); currentPage.setFormattedNumber(formattedPageNumber); currentPage.setPageSequence(this); FormatStaticContent(areaTree); FonetDriver.ActiveDriver.FireFonetInfo( "[forced-" + firstAvailPageNumber + "]"); areaTree.addPage(currentPage); this.root.setRunningPageNumberCounter(this.currentPageNumber); this.isForcing = false; } catch (FonetException) { FonetDriver.ActiveDriver.FireFonetInfo( "'force-page-count' failure"); } } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id$")] namespace Elmah { #region Imports using System; using ReaderWriterLock = System.Threading.ReaderWriterLock; using Timeout = System.Threading.Timeout; using NameObjectCollectionBase = System.Collections.Specialized.NameObjectCollectionBase; using IDictionary = System.Collections.IDictionary; using CultureInfo = System.Globalization.CultureInfo; using System.Collections.Generic; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses memory as its /// backing store. /// </summary> /// <remarks> /// All <see cref="MemoryErrorLog"/> instances will share the same memory /// store that is bound to the application (not an instance of this class). /// </remarks> public sealed class MemoryErrorLog : ErrorLog { // // The collection that provides the actual storage for this log // implementation and a lock to guarantee concurrency correctness. // private static EntryCollection _entries; private readonly static ReaderWriterLock _lock = new ReaderWriterLock(); // // IMPORTANT! The size must be the same for all instances // for the entires collection to be intialized correctly. // private readonly int _size; /// <summary> /// The maximum number of errors that will ever be allowed to be stored /// in memory. /// </summary> public static readonly int MaximumSize = 500; /// <summary> /// The maximum number of errors that will be held in memory by default /// if no size is specified. /// </summary> public static readonly int DefaultSize = 15; /// <summary> /// Initializes a new instance of the <see cref="MemoryErrorLog"/> class /// with a default size for maximum recordable entries. /// </summary> public MemoryErrorLog() : this(DefaultSize) {} /// <summary> /// Initializes a new instance of the <see cref="MemoryErrorLog"/> class /// with a specific size for maximum recordable entries. /// </summary> public MemoryErrorLog(int size) { if (size < 0 || size > MaximumSize) throw new ArgumentOutOfRangeException("size", size, string.Format("Size must be between 0 and {0}.", MaximumSize)); _size = size; } /// <summary> /// Initializes a new instance of the <see cref="MemoryErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public MemoryErrorLog(IDictionary config) { if (config == null) { _size = DefaultSize; } else { var sizeString = config.Find("size", string.Empty); if (sizeString.Length == 0) { _size = DefaultSize; } else { _size = Convert.ToInt32(sizeString, CultureInfo.InvariantCulture); _size = Math.Max(0, Math.Min(MaximumSize, _size)); } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "In-Memory Error Log"; } } /// <summary> /// Logs an error to the application memory. /// </summary> /// <remarks> /// If the log is full then the oldest error entry is removed. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); // // Make a copy of the error to log since the source is mutable. // Assign a new GUID and create an entry for the error. // error = (Error) ((ICloneable) error).Clone(); error.ApplicationName = this.ApplicationName; Guid newId = Guid.NewGuid(); ErrorLogEntry entry = new ErrorLogEntry(this, newId.ToString(), error); _lock.AcquireWriterLock(Timeout.Infinite); try { if (_entries == null) _entries = new EntryCollection(_size); _entries.Add(entry); } finally { _lock.ReleaseWriterLock(); } return newId.ToString(); } /// <summary> /// Returns the specified error from application memory, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { _lock.AcquireReaderLock(Timeout.Infinite); ErrorLogEntry entry; try { if (_entries == null) return null; entry = _entries[id]; } finally { _lock.ReleaseReaderLock(); } if (entry == null) return null; // // Return a copy that the caller can party on. // Error error = (Error) ((ICloneable) entry.Error).Clone(); return new ErrorLogEntry(this, entry.Id, error); } /// <summary> /// Returns a page of errors from the application memory in /// descending order of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); // // To minimize the time for which we hold the lock, we'll first // grab just references to the entries we need to return. Later, // we'll make copies and return those to the caller. Since Error // is mutable, we don't want to return direct references to our // internal versions since someone could change their state. // ErrorLogEntry[] selectedEntries = null; int totalCount; _lock.AcquireReaderLock(Timeout.Infinite); try { if (_entries == null) return 0; totalCount = _entries.Count; int startIndex = pageIndex * pageSize; int endIndex = Math.Min(startIndex + pageSize, totalCount); int count = Math.Max(0, endIndex - startIndex); if (count > 0) { selectedEntries = new ErrorLogEntry[count]; int sourceIndex = endIndex; int targetIndex = 0; while (sourceIndex > startIndex) selectedEntries[targetIndex++] = _entries[--sourceIndex]; } } finally { _lock.ReleaseReaderLock(); } if (errorEntryList != null && selectedEntries != null) { // // Return copies of fetched entries. If the Error class would // be immutable then this step wouldn't be necessary. // foreach (ErrorLogEntry entry in selectedEntries) { Error error = (Error)((ICloneable)entry.Error).Clone(); errorEntryList.Add(new ErrorLogEntry(this, entry.Id, error)); } } return totalCount; } private class EntryCollection : NameObjectCollectionBase { private readonly int _size; public EntryCollection(int size) : base(size) { _size = size; } public ErrorLogEntry this[int index] { get { return (ErrorLogEntry) BaseGet(index); } } public ErrorLogEntry this[Guid id] { get { return (ErrorLogEntry) BaseGet(id.ToString()); } } public ErrorLogEntry this[string id] { get { return this[new Guid(id)]; } } public void Add(ErrorLogEntry entry) { Debug.Assert(entry != null); Debug.AssertStringNotEmpty(entry.Id); Debug.Assert(this.Count <= _size); if (this.Count == _size) BaseRemoveAt(0); BaseAdd(entry.Id, entry); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Hydra.Data.Model { public partial class Location : AbstractIdNameDescriptionWithPosition { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Location"/> class. /// </summary> public Location() : base() { this.AccessPoint = new HashSet<AccessPoint>(); this.Chokepoint = new HashSet<Chokepoint>(); this.Coverage = new HashSet<Coverage>(); this.Device = new HashSet<Device>(); this.DeviceHistory = new HashSet<DeviceHistory>(); this.GPSMarker = new HashSet<GPSMarker>(); this.Item = new HashSet<Item>(); this.ItemDevice = new HashSet<ItemDevice>(); this.StaticDevices = new HashSet<ItemDevice>(); this.ParentLocations = new HashSet<Location>(); this.TextLocations = new HashSet<Location>(); this.OwnerLocations = new HashSet<Location>(); this.Marker = new HashSet<Marker>(); this.MyItems = new HashSet<MyItems>(); this.Obstacle = new HashSet<Obstacle>(); this.Point = new HashSet<Point>(); this.ReferenceDevice = new HashSet<ReferenceDevice>(); this.Region = new HashSet<Region>(); this.User = new HashSet<Account>(); this.LocationGroup = new HashSet<LocationGroup>(); } #endregion #region Foreign Keys [ForeignKey("ParentLocation")] public Nullable<int> ParentLocationID { get; set; } /// <summary> /// Gets or sets the text location ID. /// </summary> /// <value>The text location ID.</value> [ForeignKey("TextLocation")] public Nullable<int> TextLocationID { get; set; } /// <summary> /// Gets or sets the owner location ID. /// </summary> /// <value>The owner location ID.</value> [ForeignKey("OwnerLocation")] public Nullable<int> OwnerLocationID { get; set; } /// <summary> /// Gets or sets the organisation ID. /// </summary> /// <value>The organisation ID.</value> [ForeignKey("Organisation")] public Nullable<int> OrganisationID { get; set; } /// <summary> /// Gets or sets the image ID. /// </summary> /// <value>The image ID.</value> [ForeignKey("Image")] public Nullable<int> ImageID { get; set; } #endregion #region Attributes /// <summary> /// Gets or sets the name of the alternative. /// </summary> /// <value>The name of the alternative.</value> [Column(TypeName = DataTypeConstants.VARCHAR)] [MaxLength(128)] public string AlternativeName { get; set; } /// <summary> /// Gets or sets the type of the location. /// </summary> /// <value>The type of the location.</value> public int LocationType { get; set; } /// <summary> /// Gets or sets the colour. /// </summary> /// <value>The colour.</value> [Column(TypeName = DataTypeConstants.VARCHAR)] [MaxLength(10)] public string Colour { get; set; } /// <summary> /// Gets or sets the type of the zoom. /// </summary> /// <value>The type of the zoom.</value> public Nullable<int> ZoomType { get; set; } /// <summary> /// Gets or sets the level. /// </summary> /// <value>The level.</value> public Nullable<int> Level { get; set; } /// <summary> /// Gets or sets the sort order. /// </summary> /// <value>The sort order.</value> public Nullable<int> SortOrder { get; set; } /// <summary> /// Gets or sets the point list. /// </summary> /// <value>The point list.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string PointList { get; set; } /// <summary> /// Gets or sets the path. /// </summary> /// <value>The path.</value> [Column(TypeName = DataTypeConstants.VARCHAR)] [MaxLength(256)] public string Path { get; set; } /// <summary> /// Gets or sets the origin X. /// </summary> /// <value>The origin X.</value> public Nullable<float> OriginX { get; set; } /// <summary> /// Gets or sets the origin Y. /// </summary> /// <value>The origin Y.</value> public Nullable<float> OriginY { get; set; } /// <summary> /// Gets or sets the type of the object. /// </summary> /// <value>The type of the object.</value> public Nullable<int> ObjectType { get; set; } /// <summary> /// Gets or sets the object. /// </summary> /// <value>The object.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string Object { get; set; } /// <summary> /// Gets or sets the type of the contact. /// </summary> /// <value>The type of the contact.</value> public Nullable<int> ContactType { get; set; } /// <summary> /// Gets or sets the contact details. /// </summary> /// <value>The contact details.</value> [Column(TypeName = DataTypeConstants.VARCHAR)] [MaxLength(128)] public string ContactDetails { get; set; } /// <summary> /// Gets or sets the type of the measurement. /// </summary> /// <value>The type of the measurement.</value> public Nullable<int> MeasurementType { get; set; } /// <summary> /// Gets or sets the external reference. /// </summary> /// <value>The external reference.</value> public Nullable<int> ExternalReference { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is enabled. /// </summary> /// <value> /// <c>true</c> if this instance is enabled; otherwise, <c>false</c>. /// </value> public bool IsEnabled { get; set; } /// <summary> /// Gets or sets the style. /// </summary> /// <value>The style.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string Style { get; set; } /// <summary> /// Gets or sets the script. /// </summary> /// <value>The script.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string Script { get; set; } /// <summary> /// Gets or sets the URL. /// </summary> /// <value>The URL.</value> [Column(TypeName = DataTypeConstants.VARCHAR)] [MaxLength(1024)] public string Url { get; set; } /// <summary> /// Gets or sets the other notes. /// </summary> /// <value>The other notes.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string OtherNotes { get; set; } /// <summary> /// Gets or sets the calibration model. /// </summary> /// <value>The calibration model.</value> [Column(TypeName = DataTypeConstants.VARCHAR)] [MaxLength(1024)] public string CalibrationModel { get; set; } /// <summary> /// Gets or sets the is ext key. /// </summary> /// <value>The is ext key.</value> public Nullable<bool> IsExtKey { get; set; } /// <summary> /// Gets or sets the number. /// </summary> /// <value>The number.</value> public Nullable<int> Number { get; set; } /// <summary> /// Gets or sets the name of the image. /// </summary> /// <value>The name of the image.</value> [Column(TypeName = DataTypeConstants.VARCHAR)] [MaxLength(128)] public string ImageName { get; set; } /// <summary> /// Gets or sets the is logically deleted flag /// </summary> /// <value>is logically deleted flag.</value> public Nullable<bool> IsDeleted { get; set; } /// <summary> /// Gets or sets the is outdoor. /// </summary> /// <value>The is outdoor.</value> public Nullable<bool> IsOutdoor { get; set; } /// <summary> /// Gets or sets the type of the image. /// </summary> /// <value>The type of the image.</value> public Nullable<int> ImageType { get; set; } /// <summary> /// Gets or sets the width. /// </summary> /// <value>The width.</value> public Nullable<float> Width { get; set; } /// <summary> /// Gets or sets the height. /// </summary> /// <value>The height.</value> public Nullable<float> Height { get; set; } /// <summary> /// Gets or sets the length. /// </summary> /// <value>The length.</value> public Nullable<float> Length { get; set; } /// <summary> /// Gets or sets the X offset. /// </summary> /// <value>The X offset.</value> public Nullable<float> XOffset { get; set; } /// <summary> /// Gets or sets the Y offset. /// </summary> /// <value>The Y offset.</value> public Nullable<float> YOffset { get; set; } /// <summary> /// Gets or sets the unique ID. /// </summary> /// <value>The unique ID.</value> public long UniqueID { get; set; } /// <summary> /// Gets or sets the hierarchy. /// </summary> /// <value>The hierarchy.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string Hierarchy { get; set; } /// <summary> /// Gets or sets the capability. /// </summary> /// <value>The capability.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string Capability { get; set; } /// <summary> /// Gets or sets the constraints. /// </summary> /// <value>The constraints.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string Constraints { get; set; } /// <summary> /// Gets or sets the rules. /// </summary> /// <value>The rules.</value> [Column(TypeName = DataTypeConstants.TEXT)] public string Rules { get; set; } /// <summary> /// Gets or sets the X coordinate. /// </summary> /// <value>The X coordinate.</value> public Nullable<float> XCoordinate { get; set; } /// <summary> /// Gets or sets the Y coordinate. /// </summary> /// <value>The Y coordinate.</value> public Nullable<float> YCoordinate { get; set; } #endregion #region Navigation /// <summary> /// Gets or sets the image. /// </summary> /// <value>The image.</value> public virtual Image Image { get; set; } /// <summary> /// Gets or sets the parent location. /// </summary> /// <value>The parent location.</value> public virtual Location ParentLocation { get; set; } /// <summary> /// Gets or sets the text location. /// </summary> /// <value>The text location.</value> public virtual Location TextLocation { get; set; } /// <summary> /// Gets or sets the owner location. /// </summary> /// <value>The owner location.</value> public virtual Location OwnerLocation { get; set; } /// <summary> /// Gets or sets the organisation. /// </summary> /// <value>The organisation.</value> public virtual Organisation Organisation { get; set; } /// <summary> /// Gets or sets the access point. /// </summary> /// <value>The access point.</value> public virtual ICollection<AccessPoint> AccessPoint { get; set; } /// <summary> /// Gets or sets the chokepoint. /// </summary> /// <value>The chokepoint.</value> public virtual ICollection<Chokepoint> Chokepoint { get; set; } /// <summary> /// Gets or sets the coverage. /// </summary> /// <value>The coverage.</value> public virtual ICollection<Coverage> Coverage { get; set; } /// <summary> /// Gets or sets the device. /// </summary> /// <value>The device.</value> public virtual ICollection<Device> Device { get; set; } /// <summary> /// Gets or sets the device history. /// </summary> /// <value>The device history.</value> public virtual ICollection<DeviceHistory> DeviceHistory { get; set; } /// <summary> /// Gets or sets the GPS marker. /// </summary> /// <value>The GPS marker.</value> public virtual ICollection<GPSMarker> GPSMarker { get; set; } /// <summary> /// Gets or sets the item. /// </summary> /// <value>The item.</value> public virtual ICollection<Item> Item { get; set; } /// <summary> /// Gets or sets the item device. /// </summary> /// <value>The item device.</value> public virtual ICollection<ItemDevice> ItemDevice { get; set; } /// <summary> /// Gets or sets the static devices. /// </summary> /// <value>The static devices.</value> public virtual ICollection<ItemDevice> StaticDevices { get; set; } /// <summary> /// Gets or sets the parent locations. /// </summary> /// <value>The parent locations.</value> public virtual ICollection<Location> ParentLocations { get; set; } /// <summary> /// Gets or sets the text locations. /// </summary> /// <value>The text locations.</value> public virtual ICollection<Location> TextLocations { get; set; } /// <summary> /// Gets or sets the owner locations. /// </summary> /// <value>The owner locations.</value> public virtual ICollection<Location> OwnerLocations { get; set; } /// <summary> /// Gets or sets the marker. /// </summary> /// <value>The marker.</value> public virtual ICollection<Marker> Marker { get; set; } /// <summary> /// Gets or sets my items. /// </summary> /// <value>My items.</value> public virtual ICollection<MyItems> MyItems { get; set; } /// <summary> /// Gets or sets the obstacle. /// </summary> /// <value>The obstacle.</value> public virtual ICollection<Obstacle> Obstacle { get; set; } /// <summary> /// Gets or sets the point. /// </summary> /// <value>The point.</value> public virtual ICollection<Point> Point { get; set; } /// <summary> /// Gets or sets the reference device. /// </summary> /// <value>The reference device.</value> public virtual ICollection<ReferenceDevice> ReferenceDevice { get; set; } /// <summary> /// Gets or sets the region. /// </summary> /// <value>The region.</value> public virtual ICollection<Region> Region { get; set; } /// <summary> /// Gets or sets the user. /// </summary> /// <value>The user.</value> public virtual ICollection<Account> User { get; set; } /// <summary> /// Gets or sets the location group. /// </summary> /// <value>The location group.</value> public virtual ICollection<LocationGroup> LocationGroup { get; set; } #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.ComponentModel; namespace System.Data { public class DataRowView : ICustomTypeDescriptor, IEditableObject, IDataErrorInfo, INotifyPropertyChanged { private readonly DataView _dataView; private readonly DataRow _row; private bool _delayBeginEdit; private static readonly PropertyDescriptorCollection s_zeroPropertyDescriptorCollection = new PropertyDescriptorCollection(null); internal DataRowView(DataView dataView, DataRow row) { _dataView = dataView; _row = row; } /// <remarks> /// Checks for same reference instead of equivalent <see cref="DataView"/> or <see cref="Row"/>. /// /// Necessary for ListChanged event handlers to use data structures that use the default to /// <see cref="object.Equals(object)"/> instead of <see cref="object.ReferenceEquals"/> /// to understand if they need to add a <see cref="PropertyChanged"/> event handler. /// </remarks> /// <returns><see cref="object.ReferenceEquals"/></returns> public override bool Equals(object other) => ReferenceEquals(this, other); /// <returns>Hashcode of <see cref="Row"/></returns> public override int GetHashCode() { // Everett compatability, must return hashcode for DataRow // this does prevent using this object in collections like Hashtable // which use the hashcode as an immutable value to identify this object // user could/should have used the DataRow property instead of the hashcode return Row.GetHashCode(); } public DataView DataView => _dataView; internal int ObjectID => _row._objectID; /// <summary>Gets or sets a value in specified column.</summary> /// <param name="ndx">Specified column index.</param> /// <remarks>Uses either <see cref="DataRowVersion.Default"/> or <see cref="DataRowVersion.Original"/> to access <see cref="Row"/></remarks> /// <exception cref="DataException"><see cref="System.Data.DataView.get_AllowEdit"/> when setting a value.</exception> /// <exception cref="IndexOutOfRangeException"><see cref="DataColumnCollection.get_Item(int)"/></exception> public object this[int ndx] { get { return Row[ndx, RowVersionDefault]; } set { if (!_dataView.AllowEdit && !IsNew) { throw ExceptionBuilder.CanNotEdit(); } SetColumnValue(_dataView.Table.Columns[ndx], value); } } /// <summary>Gets the specified column value or related child view or sets a value in specified column.</summary> /// <param name="property">Specified column or relation name when getting. Specified column name when setting.</param> /// <exception cref="ArgumentException"><see cref="DataColumnCollection.get_Item(string)"/> when <paramref name="property"/> is ambiguous.</exception> /// <exception cref="ArgumentException">Unmatched <paramref name="property"/> when getting a value.</exception> /// <exception cref="DataException">Unmatched <paramref name="property"/> when setting a value.</exception> /// <exception cref="DataException"><see cref="System.Data.DataView.get_AllowEdit"/> when setting a value.</exception> public object this[string property] { get { DataColumn column = _dataView.Table.Columns[property]; if (null != column) { return Row[column, RowVersionDefault]; } else if (_dataView.Table.DataSet != null && _dataView.Table.DataSet.Relations.Contains(property)) { return CreateChildView(property); } throw ExceptionBuilder.PropertyNotFound(property, _dataView.Table.TableName); } set { DataColumn column = _dataView.Table.Columns[property]; if (null == column) { throw ExceptionBuilder.SetFailed(property); } if (!_dataView.AllowEdit && !IsNew) { throw ExceptionBuilder.CanNotEdit(); } SetColumnValue(column, value); } } // IDataErrorInfo stuff string IDataErrorInfo.this[string colName] => Row.GetColumnError(colName); string IDataErrorInfo.Error => Row.RowError; /// <summary> /// Gets the current version description of the <see cref="DataRow"/> /// in relation to <see cref="System.Data.DataView.get_RowStateFilter"/> /// </summary> /// <returns>Either <see cref="DataRowVersion.Current"/> or <see cref="DataRowVersion.Original"/></returns> public DataRowVersion RowVersion => (RowVersionDefault & ~DataRowVersion.Proposed); /// <returns>Either <see cref="DataRowVersion.Default"/> or <see cref="DataRowVersion.Original"/></returns> private DataRowVersion RowVersionDefault => Row.GetDefaultRowVersion(_dataView.RowStateFilter); internal int GetRecord() => Row.GetRecordFromVersion(RowVersionDefault); internal bool HasRecord() => Row.HasVersion(RowVersionDefault); internal object GetColumnValue(DataColumn column) => Row[column, RowVersionDefault]; internal void SetColumnValue(DataColumn column, object value) { if (_delayBeginEdit) { _delayBeginEdit = false; Row.BeginEdit(); } if (DataRowVersion.Original == RowVersionDefault) { throw ExceptionBuilder.SetFailed(column.ColumnName); } Row[column] = value; } /// <summary> /// Returns a <see cref="System.Data.DataView"/> /// for the child <see cref="System.Data.DataTable"/> /// with the specified <see cref="System.Data.DataRelation"/>. /// </summary> /// <param name="relation">Specified <see cref="System.Data.DataRelation"/>.</param> /// <exception cref="ArgumentException">null or mismatch between <paramref name="relation"/> and <see cref="System.Data.DataView.get_Table"/>.</exception> public DataView CreateChildView(DataRelation relation, bool followParent) { if (relation == null || relation.ParentKey.Table != DataView.Table) { throw ExceptionBuilder.CreateChildView(); } RelatedView childView; if (!followParent) { int record = GetRecord(); object[] values = relation.ParentKey.GetKeyValues(record); childView = new RelatedView(relation.ChildColumnsReference, values); } else { childView = new RelatedView(this, relation.ParentKey, relation.ChildColumnsReference); } childView.SetIndex("", DataViewRowState.CurrentRows, null); // finish construction via RelatedView.SetIndex childView.SetDataViewManager(DataView.DataViewManager); return childView; } public DataView CreateChildView(DataRelation relation) => CreateChildView(relation, followParent: false); /// <summary><see cref="CreateChildView(DataRelation)"/></summary> /// <param name="relationName">Specified <see cref="System.Data.DataRelation"/> name.</param> /// <exception cref="ArgumentException">Unmatched <paramref name="relationName"/>.</exception> public DataView CreateChildView(string relationName, bool followParent) => CreateChildView(DataView.Table.ChildRelations[relationName], followParent); public DataView CreateChildView(string relationName) => CreateChildView(relationName, followParent: false); public DataRow Row => _row; public void BeginEdit() => _delayBeginEdit = true; public void CancelEdit() { DataRow tmpRow = Row; if (IsNew) { _dataView.FinishAddNew(false); } else { tmpRow.CancelEdit(); } _delayBeginEdit = false; } public void EndEdit() { if (IsNew) { _dataView.FinishAddNew(true); } else { Row.EndEdit(); } _delayBeginEdit = false; } public bool IsNew => (_row == _dataView._addNewRow); public bool IsEdit => Row.HasVersion(DataRowVersion.Proposed) || // It was edited or _delayBeginEdit; // DataRowView.BegingEdit() was called, but not edited yet. public void Delete() => _dataView.Delete(Row); // When the PropertyChanged event happens, it must happen on the same DataRowView reference. // This is so a generic event handler like Windows Presentation Foundation can redirect as appropriate. // Having DataView.Equals is not sufficient for WPF, because two different instances may be equal but not equivalent. // For DataRowView, if two instances are equal then they are equivalent. public event PropertyChangedEventHandler PropertyChanged; // Do not try catch, we would mask users bugs. if they throw we would catch internal void RaisePropertyChangedEvent(string propName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName)); #region ICustomTypeDescriptor AttributeCollection ICustomTypeDescriptor.GetAttributes() => new AttributeCollection(null); string ICustomTypeDescriptor.GetClassName() => null; string ICustomTypeDescriptor.GetComponentName() => null; TypeConverter ICustomTypeDescriptor.GetConverter() => null; EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() => null; PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() => null; object ICustomTypeDescriptor.GetEditor(Type editorBaseType) => null; EventDescriptorCollection ICustomTypeDescriptor.GetEvents() => new EventDescriptorCollection(null); EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) => new EventDescriptorCollection(null); PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() => ((ICustomTypeDescriptor)this).GetProperties(null); PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) => (_dataView.Table != null ? _dataView.Table.GetPropertyDescriptorCollection(attributes) : s_zeroPropertyDescriptorCollection); object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) => this; #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Threading; namespace Lucene.Net.Util { //using AssumptionViolatedException = org.junit.@internal.AssumptionViolatedException; using Lucene.Net.Randomized.Generators; /* * 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. */ /* import static Lucene.Net.Util.LuceneTestCase.INFOSTREAM; import static Lucene.Net.Util.LuceneTestCase.TEST_CODEC; import static Lucene.Net.Util.LuceneTestCase.TEST_DOCVALUESFORMAT; import static Lucene.Net.Util.LuceneTestCase.TEST_POSTINGSFORMAT; import static Lucene.Net.Util.LuceneTestCase.VERBOSE; import static Lucene.Net.Util.LuceneTestCase.assumeFalse; import static Lucene.Net.Util.LuceneTestCase.localeForName; import static Lucene.Net.Util.LuceneTestCase.random; import static Lucene.Net.Util.LuceneTestCase.randomLocale; import static Lucene.Net.Util.LuceneTestCase.randomTimeZone;*/ using Codec = Lucene.Net.Codecs.Codec; using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat; //using CheapBastardCodec = Lucene.Net.Codecs.cheapbastard.CheapBastardCodec; //using MockRandomPostingsFormat = Lucene.Net.Codecs.mockrandom.MockRandomPostingsFormat; using Lucene46Codec = Lucene.Net.Codecs.Lucene46.Lucene46Codec; using PostingsFormat = Lucene.Net.Codecs.PostingsFormat; //using SimpleTextCodec = Lucene.Net.Codecs.simpletext.SimpleTextCodec; using RandomCodec = Lucene.Net.Index.RandomCodec; using RandomSimilarityProvider = Lucene.Net.Search.RandomSimilarityProvider; using Similarity = Lucene.Net.Search.Similarities.Similarity; //using RandomizedContext = com.carrotsearch.randomizedtesting.RandomizedContext; /// <summary> /// Setup and restore suite-level environment (fine grained junk that /// doesn't fit anywhere else). /// </summary> internal sealed class TestRuleSetupAndRestoreClassEnv// : AbstractBeforeAfterRule { /// <summary> /// Restore these system property values. /// </summary> private Dictionary<string, string> RestoreProperties = new Dictionary<string, string>(); private Codec SavedCodec; private CultureInfo SavedLocale; private TimeZone SavedTimeZone; private InfoStream SavedInfoStream; internal CultureInfo Locale; internal TimeZone TimeZone; internal Similarity Similarity; internal Codec Codec; /// <seealso cref= SuppressCodecs </seealso> internal HashSet<string> AvoidCodecs; public TestRuleSetupAndRestoreClassEnv() { /*// if verbose: print some debugging stuff about which codecs are loaded. if (LuceneTestCase.VERBOSE) { ISet<string> codecs = Codec.AvailableCodecs(); foreach (string codec in codecs) { Console.WriteLine("Loaded codec: '" + codec + "': " + Codec.ForName(codec).GetType().Name); } ISet<string> postingsFormats = PostingsFormat.AvailablePostingsFormats(); foreach (string postingsFormat in postingsFormats) { Console.WriteLine("Loaded postingsFormat: '" + postingsFormat + "': " + PostingsFormat.ForName(postingsFormat).GetType().Name); } } SavedInfoStream = InfoStream.Default; Random random = RandomizedContext.Current.Random; bool v = random.NextBoolean(); if (LuceneTestCase.INFOSTREAM) { InfoStream.Default = new ThreadNameFixingPrintStreamInfoStream(Console.Out); } else if (v) { InfoStream.Default = new NullInfoStream(); } Type targetClass = RandomizedContext.Current.GetTargetType; AvoidCodecs = new HashSet<string>(); // set back to default LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = false; SavedCodec = Codec.Default; int randomVal = random.Next(10); if ("Lucene3x".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 3 && !ShouldAvoidCodec("Lucene3x"))) // preflex-only setup { Codec = Codec.ForName("Lucene3x"); Debug.Assert((Codec is PreFlexRWCodec), "fix your classpath to have tests-framework.jar before lucene-core.jar"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; } else if ("Lucene40".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && randomVal == 0 && !ShouldAvoidCodec("Lucene40"))) // 4.0 setup { Codec = Codec.ForName("Lucene40"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert(Codec is Lucene40RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar"); Debug.Assert((PostingsFormat.ForName("Lucene40") is Lucene40RWPostingsFormat), "fix your classpath to have tests-framework.jar before lucene-core.jar"); } else if ("Lucene41".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 1 && !ShouldAvoidCodec("Lucene41"))) { Codec = Codec.ForName("Lucene41"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert(Codec is Lucene41RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar"); } else if ("Lucene42".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 2 && !ShouldAvoidCodec("Lucene42"))) { Codec = Codec.ForName("Lucene42"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert(Codec is Lucene42RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar"); } else if ("Lucene45".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 5 && !ShouldAvoidCodec("Lucene45"))) { Codec = Codec.ForName("Lucene45"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert(Codec is Lucene45RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar"); } else if (("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) == false) || ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) == false)) { // the user wired postings or DV: this is messy // refactor into RandomCodec.... PostingsFormat format; if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT)) { format = PostingsFormat.ForName("Lucene41"); } else { format = PostingsFormat.ForName(LuceneTestCase.TEST_POSTINGSFORMAT); } DocValuesFormat dvFormat; if ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT)) { dvFormat = DocValuesFormat.ForName("Lucene45"); } else { dvFormat = DocValuesFormat.ForName(LuceneTestCase.TEST_DOCVALUESFORMAT); } Codec = new Lucene46CodecAnonymousInnerClassHelper(this, format, dvFormat); } else if ("Asserting".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && randomVal == 6 && !ShouldAvoidCodec("Asserting"))) { Codec = new AssertingCodec(); } else if ("Compressing".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && randomVal == 5 && !ShouldAvoidCodec("Compressing"))) { Codec = CompressingCodec.RandomInstance(random); } else if (!"random".Equals(LuceneTestCase.TEST_CODEC)) { Codec = Codec.ForName(LuceneTestCase.TEST_CODEC); } else if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT)) { Codec = new RandomCodec(random, AvoidCodecs); } else { Debug.Assert(false); } Codec.Default = Codec; */ Random random = new Random(1); Similarity = random.NextBoolean() ? (Similarity)new DefaultSimilarity() : new RandomSimilarityProvider(new Random(1)); /* // Check codec restrictions once at class level. try { CheckCodecRestrictions(Codec); } catch (Exception e) { Console.Error.WriteLine("NOTE: " + e.Message + " Suppressed codecs: " + Arrays.ToString(AvoidCodecs.ToArray())); throw e; }*/ } /*~TestRuleSetupAndRestoreClassEnv() { foreach (KeyValuePair<string, string> e in RestoreProperties) { if (e.Value == null) { System.ClearProperty(e.Key); } else { System.setProperty(e.Key, e.Value); } } RestoreProperties.Clear(); Codec.Default = SavedCodec; InfoStream.Default = SavedInfoStream; if (SavedLocale != null) { Locale = SavedLocale; } if (SavedTimeZone != null) { TimeZone = SavedTimeZone; } }*/ internal class ThreadNameFixingPrintStreamInfoStream : PrintStreamInfoStream { public ThreadNameFixingPrintStreamInfoStream(TextWriter @out) : base(@out) { } public override void Message(string component, string message) { if ("TP".Equals(component)) { return; // ignore test points! } string name; if (Thread.CurrentThread.Name != null && Thread.CurrentThread.Name.StartsWith("TEST-")) { // The name of the main thread is way too // long when looking at IW verbose output... name = "main"; } else { name = Thread.CurrentThread.Name; } Stream.WriteLine(component + " " + MessageID + " [" + DateTime.Now + "; " + name + "]: " + message); } } /*protected internal override void Before() { // enable this by default, for IDE consistency with ant tests (as its the default from ant) // TODO: really should be in solr base classes, but some extend LTC directly. // we do this in beforeClass, because some tests currently disable it RestoreProperties["solr.directoryFactory"] = System.getProperty("solr.directoryFactory"); if (System.getProperty("solr.directoryFactory") == null) { System.setProperty("solr.directoryFactory", "org.apache.solr.core.MockDirectoryFactory"); } // Restore more Solr properties. RestoreProperties["solr.solr.home"] = System.getProperty("solr.solr.home"); RestoreProperties["solr.data.dir"] = System.getProperty("solr.data.dir"); // if verbose: print some debugging stuff about which codecs are loaded. if (LuceneTestCase.VERBOSE) { ISet<string> codecs = Codec.AvailableCodecs(); foreach (string codec in codecs) { Console.WriteLine("Loaded codec: '" + codec + "': " + Codec.ForName(codec).GetType().Name); } ISet<string> postingsFormats = PostingsFormat.AvailablePostingsFormats(); foreach (string postingsFormat in postingsFormats) { Console.WriteLine("Loaded postingsFormat: '" + postingsFormat + "': " + PostingsFormat.ForName(postingsFormat).GetType().Name); } } SavedInfoStream = InfoStream.Default; Random random = RandomizedContext.Current.Random; bool v = random.NextBoolean(); if (LuceneTestCase.INFOSTREAM) { InfoStream.Default = new ThreadNameFixingPrintStreamInfoStream(Console.Out); } else if (v) { InfoStream.Default = new NullInfoStream(); } Type targetClass = RandomizedContext.Current.GetTargetType; AvoidCodecs = new HashSet<string>(); if (targetClass.isAnnotationPresent(typeof(SuppressCodecs))) { SuppressCodecs a = targetClass.getAnnotation(typeof(SuppressCodecs)); AvoidCodecs.AddAll(Arrays.AsList(a.Value())); } // set back to default LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = false; SavedCodec = Codec.Default; int randomVal = random.Next(10); if ("Lucene3x".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 3 && !ShouldAvoidCodec("Lucene3x"))) // preflex-only setup { Codec = Codec.ForName("Lucene3x"); Debug.Assert((Codec is PreFlexRWCodec), "fix your classpath to have tests-framework.jar before lucene-core.jar"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; } else if ("Lucene40".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && randomVal == 0 && !ShouldAvoidCodec("Lucene40"))) // 4.0 setup { Codec = Codec.ForName("Lucene40"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert(Codec is Lucene40RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar"); Debug.Assert((PostingsFormat.ForName("Lucene40") is Lucene40RWPostingsFormat), "fix your classpath to have tests-framework.jar before lucene-core.jar"); } else if ("Lucene41".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 1 && !ShouldAvoidCodec("Lucene41"))) { Codec = Codec.ForName("Lucene41"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert(Codec is Lucene41RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar"); } else if ("Lucene42".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 2 && !ShouldAvoidCodec("Lucene42"))) { Codec = Codec.ForName("Lucene42"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert(Codec is Lucene42RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar"); } else if ("Lucene45".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) && randomVal == 5 && !ShouldAvoidCodec("Lucene45"))) { Codec = Codec.ForName("Lucene45"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert(Codec is Lucene45RWCodec, "fix your classpath to have tests-framework.jar before lucene-core.jar"); } else if (("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT) == false) || ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT) == false)) { // the user wired postings or DV: this is messy // refactor into RandomCodec.... PostingsFormat format; if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT)) { format = PostingsFormat.ForName("Lucene41"); } else if ("MockRandom".Equals(LuceneTestCase.TEST_POSTINGSFORMAT)) { format = new MockRandomPostingsFormat(new Random(random.Next())); } else { format = PostingsFormat.ForName(LuceneTestCase.TEST_POSTINGSFORMAT); } DocValuesFormat dvFormat; if ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT)) { dvFormat = DocValuesFormat.ForName("Lucene45"); } else { dvFormat = DocValuesFormat.ForName(LuceneTestCase.TEST_DOCVALUESFORMAT); } Codec = new Lucene46CodecAnonymousInnerClassHelper(this, format, dvFormat); } else if ("SimpleText".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && randomVal == 9 && LuceneTestCase.Rarely(random) && !ShouldAvoidCodec("SimpleText"))) { Codec = new SimpleTextCodec(); } else if ("CheapBastard".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && randomVal == 8 && !ShouldAvoidCodec("CheapBastard") && !ShouldAvoidCodec("Lucene41"))) { // we also avoid this codec if Lucene41 is avoided, since thats the postings format it uses. Codec = new CheapBastardCodec(); } else if ("Asserting".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && randomVal == 6 && !ShouldAvoidCodec("Asserting"))) { Codec = new AssertingCodec(); } else if ("Compressing".Equals(LuceneTestCase.TEST_CODEC) || ("random".Equals(LuceneTestCase.TEST_CODEC) && randomVal == 5 && !ShouldAvoidCodec("Compressing"))) { Codec = CompressingCodec.RandomInstance(random); } else if (!"random".Equals(LuceneTestCase.TEST_CODEC)) { Codec = Codec.ForName(LuceneTestCase.TEST_CODEC); } else if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT)) { Codec = new RandomCodec(random, AvoidCodecs); } else { Debug.Assert(false); } Codec.Default = Codec; // Initialize locale/ timezone. string testLocale = System.getProperty("tests.locale", "random"); string testTimeZone = System.getProperty("tests.timezone", "random"); // Always pick a random one for consistency (whether tests.locale was specified or not). SavedLocale = Locale.Default; Locale randomLocale = RandomLocale(random); Locale = testLocale.Equals("random") ? randomLocale : localeForName(testLocale); Locale.Default = Locale; // TimeZone.getDefault will set user.timezone to the default timezone of the user's locale. // So store the original property value and restore it at end. RestoreProperties["user.timezone"] = System.getProperty("user.timezone"); SavedTimeZone = TimeZone.Default; TimeZone randomTimeZone = RandomTimeZone(random); TimeZone = testTimeZone.Equals("random") ? randomTimeZone : TimeZone.getTimeZone(testTimeZone); TimeZone.Default = TimeZone; Similarity = random.NextBoolean() ? (Similarity)new DefaultSimilarity() : new RandomSimilarityProvider(new Random()); // Check codec restrictions once at class level. try { CheckCodecRestrictions(Codec); } catch (Exception e) { Console.Error.WriteLine("NOTE: " + e.Message + " Suppressed codecs: " + Arrays.ToString(AvoidCodecs.ToArray())); throw e; } }*/ private class Lucene46CodecAnonymousInnerClassHelper : Lucene46Codec { private readonly TestRuleSetupAndRestoreClassEnv OuterInstance; private PostingsFormat Format; private DocValuesFormat DvFormat; public Lucene46CodecAnonymousInnerClassHelper(TestRuleSetupAndRestoreClassEnv outerInstance, PostingsFormat format, DocValuesFormat dvFormat) { this.OuterInstance = outerInstance; this.Format = format; this.DvFormat = dvFormat; } public override PostingsFormat GetPostingsFormatForField(string field) { return Format; } public override DocValuesFormat GetDocValuesFormatForField(string field) { return DvFormat; } public override string ToString() { return base.ToString() + ": " + Format.ToString() + ", " + DvFormat.ToString(); } } /// <summary> /// Check codec restrictions. /// </summary> /// <exception cref="AssumptionViolatedException"> if the class does not work with a given codec. </exception> private void CheckCodecRestrictions(Codec codec) { LuceneTestCase.AssumeFalse("Class not allowed to use codec: " + codec.Name + ".", ShouldAvoidCodec(codec.Name)); if (codec is RandomCodec && AvoidCodecs.Count > 0) { foreach (string name in ((RandomCodec)codec).FormatNames) { LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + name + ".", ShouldAvoidCodec(name)); } } PostingsFormat pf = codec.PostingsFormat(); LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + pf.Name + ".", ShouldAvoidCodec(pf.Name)); LuceneTestCase.AssumeFalse("Class not allowed to use postings format: " + LuceneTestCase.TEST_POSTINGSFORMAT + ".", ShouldAvoidCodec(LuceneTestCase.TEST_POSTINGSFORMAT)); } /// <summary> /// After suite cleanup (always invoked). /// </summary> /*protected internal override void After() { foreach (KeyValuePair<string, string> e in RestoreProperties) { if (e.Value == null) { System.ClearProperty(e.Key); } else { System.setProperty(e.Key, e.Value); } } RestoreProperties.Clear(); Codec.Default = SavedCodec; InfoStream.Default = SavedInfoStream; if (SavedLocale != null) { Locale = SavedLocale; } if (SavedTimeZone != null) { TimeZone = SavedTimeZone; } }*/ /// <summary> /// Should a given codec be avoided for the currently executing suite? /// </summary> private bool ShouldAvoidCodec(string codec) { return AvoidCodecs.Count > 0 && AvoidCodecs.Contains(codec); } } }
// 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.namedandoptional.decl.strct.strct01.strct01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01.strct01; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(dynamic x = null, dynamic y = default(dynamic)) { if (x == null && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01a.strct01a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01a.strct01a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? x = 2, int? y = 1) { if (x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 1; return p.Foo(y: d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03.strct03 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03.strct03; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(dynamic x, dynamic y = null) { if (x == 2 && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03a.strct03a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03a.strct03a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? x, int? y = 1) { if (x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 2; return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05.strct05 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05.strct05; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(dynamic z, dynamic x = null, dynamic y = null) { if (z == 1 && x == null && y == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05a.strct05a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05a.strct05a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? z, int? x = 2, int? y = 1) { if (z == 1 && x == 2 && y == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = 1; return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct06a.strct06a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct06a.strct06a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. Expressions ued</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? z = 1 + 1) { if (z == 2) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct07a.strct07a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct07a.strct07a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. Max int</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(int? z = 2147483647) { if (z == 2147483647) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct09a.strct09a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct09a.strct09a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(long? z = (long)1) { if (z == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12.strct12 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12.strct12; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public struct Parent { public int Foo( [Optional] dynamic i) { if (i == System.Type.Missing) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12a.strct12a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12a.strct12a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public struct Parent { public int Foo( [Optional] int ? i) { if (i == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13.strct13 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13.strct13; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public struct Parent { public int Foo( [Optional] dynamic i, [Optional] long j, [Optional] float f, [Optional] dynamic d) { if (d == System.Type.Missing) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13a.strct13a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13a.strct13a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description> // <Expects status=success></Expects> // <Code> using System.Runtime.InteropServices; public struct Parent { public int Foo( [Optional] int ? i, [Optional] long ? j, [Optional] float ? f, [Optional] decimal ? d) { if (d == null) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct14a.strct14a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct14a.strct14a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public struct Parent { private const int x = 1; public int Foo(long? z = x) { if (z == 1) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct18a.strct18a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct18a.strct18a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public struct Parent { private const string x = "test"; public int Foo(string z = x) { if (z == "test") return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct19a.strct19a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct19a.strct19a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public struct Parent { private const bool x = true; public int Foo(bool? z = x) { if ((bool)z) return 0; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct20a.strct20a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct20a.strct20a; // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description> Declaration of OPs with constant values</Description> // <Expects status=success></Expects> // <Code> public struct Parent { public int Foo(string z = "test", int? y = 3) { if (z == "test" && y == 3) return 1; return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); try { p.Foo(3, "test"); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Parent.Foo(string, int?)"); if (ret) return 0; } return 1; } } //</Code> }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using Common.Logging; using Naru.TPL; using Naru.WPF.Command; using Naru.WPF.ContextMenu; using Naru.WPF.Dialog; using Naru.WPF.MVVM; using Naru.WPF.Scheduler; using Naru.WPF.ViewModel; using Nitrogen.Common; using Nitrogen.Common.DataExplorer; namespace Nitrogen.Client.DataExplorer.Data { public class DataViewModel : Workspace { private readonly IDataService _service; private readonly Func<BindableCollection<Dictionary<string, object>>> _itemsCollectionFactory; private readonly Func<BindableCollection<Column>> _columnCollectionFactory; private readonly Subject<Query> _drillDownDimensionRequest = new Subject<Query>(); private readonly Subject<Dictionary<string, object>> _selectedItemChanged = new Subject<Dictionary<string, object>>(); #region Items private BindableCollection<Dictionary<string, object>> _items; public BindableCollection<Dictionary<string, object>> Items { get { return _items; } private set { _items = value; RaisePropertyChanged(() => Items); } } #endregion #region Columns private BindableCollection<Column> _columns; public BindableCollection<Column> Columns { get { return _columns; } private set { _columns = value; RaisePropertyChanged(() => Columns); } } #endregion public BindableCollection<IContextMenuItem> ContextMenu { get; private set; } #region SelectedItem private Dictionary<string, object> _selectedItem; public Dictionary<string, object> SelectedItem { get { return _selectedItem; } set { _selectedItem = value; _selectedItemChanged.OnNext(_selectedItem); } } #endregion public IObservable<Query> DrillDownDimensionRequest { get { return _drillDownDimensionRequest.AsObservable(); } } public BindableCollection<SelectedCell> SelectedCells { get; set; } public DataViewModel(ILog log, IDispatcherSchedulerProvider scheduler, IStandardDialog standardDialog, IDataService service, BindableCollection<IContextMenuItem> contextMenuCollection, Func<BindableCollection<Dictionary<string, object>>> itemsCollectionFactory, Func<BindableCollection<Column>> columnCollectionFactory, BindableCollection<SelectedCell> selectedCellsCollection) : base(log, scheduler, standardDialog) { _service = service; _itemsCollectionFactory = itemsCollectionFactory; _columnCollectionFactory = columnCollectionFactory; Disposables.Add(service); ContextMenu = contextMenuCollection; SelectedCells = selectedCellsCollection; SelectedCells.AddedItemsCollectionChanged .TakeUntil(ClosingStrategy.Closed) .ObserveOn(Scheduler.Dispatcher.RX) .Subscribe(cells => { }); } public Task<Query> Reset(Query query, IEnumerable<Dimension> dimensionsAvailable) { return ContextMenu.ClearAsync() .Then(() => SetupContextMenu(query, dimensionsAvailable), Scheduler.Task.TPL) .Then(() => _service.GetDataAsync(query), Scheduler.Task.TPL) .Then(data => { // TODO : This is not great. Change grid to support CollectionChanges Columns = null; Items = null; if (!data.Any()) { return query; } var records = TransformSerializableDynamicObjectToDictionary(data); var items = _itemsCollectionFactory(); items.AddRange(records); Items = items; var columns = _columnCollectionFactory(); columns.AddRange(GetColumns(records)); Columns = columns; return query; }, Scheduler.Dispatcher.TPL); } private Task SetupContextMenu(Query query, IEnumerable<Dimension> dimensionsAvailable) { // Only show Dimensions that haven't been grouped by. var dimensionContextMenuItems = dimensionsAvailable .Where(x => !query.GroupingDimensions.Contains(x)) .Select(x => new ContextMenuButtonItem(Scheduler) { DisplayName = x.Name, Command = new DelegateCommand( () => { var selectedDimension = dimensionsAvailable .SingleOrDefault(d => d.Name == x.Name); if (selectedDimension == null) { return; } //var selectedItem = Items[SelectedItemIndex]; var newFilter = query.GroupingDimensions .Select(d => new Nitrogen.Common.DataExplorer.Filter { Dimension = d, Operator = FilterOperator.Equals, Value = SelectedItem[d.Name] }) .ToList(); var newQuery = query.DrillDown(new[] {selectedDimension}, newFilter); _drillDownDimensionRequest.OnNext(newQuery); }) }); return ContextMenu.AddRangeAsync(dimensionContextMenuItems); } private static IEnumerable<Column> GetColumns(IEnumerable<Dictionary<string, object>> records) { return records.First().Keys .Select((x, i) => new Column(x, x, i)) .ToList(); } private static List<Dictionary<string, object>> TransformSerializableDynamicObjectToDictionary(IEnumerable<SerializableDynamicObject> data) { return data .AsParallel() .Select(x => x.GetDictionary()) .OrderBy(x => (long)x["RecordIndex"]) .ToList(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; namespace System.Net.Sockets { // The System.Net.Sockets.UdpClient class provides access to UDP services at a higher abstraction // level than the System.Net.Sockets.Socket class. System.Net.Sockets.UdpClient is used to // connect to a remote host and to receive connections from a remote client. public class UdpClient : IDisposable { private const int MaxUDPSize = 0x10000; private Socket _clientSocket; private bool _active; private byte[] _buffer = new byte[MaxUDPSize]; private AddressFamily _family = AddressFamily.InterNetwork; // Initializes a new instance of the System.Net.Sockets.UdpClientclass. public UdpClient() : this(AddressFamily.InterNetwork) { } // Initializes a new instance of the System.Net.Sockets.UdpClientclass. public UdpClient(AddressFamily family) { // Validate the address family. if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "UDP"), "family"); } _family = family; CreateClientSocket(); } // Creates a new instance of the UdpClient class that communicates on the // specified port number. // // NOTE: We should obsolete this. This also breaks IPv6-only scenarios. // But fixing it has many complications that we have decided not // to fix it and instead obsolete it later. public UdpClient(int port) : this(port, AddressFamily.InterNetwork) { } // Creates a new instance of the UdpClient class that communicates on the // specified port number. public UdpClient(int port, AddressFamily family) { // Validate input parameters. if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException("port"); } // Validate the address family. if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) { throw new ArgumentException(SR.net_protocol_invalid_family, "family"); } IPEndPoint localEP; _family = family; if (_family == AddressFamily.InterNetwork) { localEP = new IPEndPoint(IPAddress.Any, port); } else { localEP = new IPEndPoint(IPAddress.IPv6Any, port); } CreateClientSocket(); Client.Bind(localEP); } // Creates a new instance of the UdpClient class that communicates on the // specified end point. public UdpClient(IPEndPoint localEP) { // Validate input parameters. if (localEP == null) { throw new ArgumentNullException("localEP"); } // IPv6 Changes: Set the AddressFamily of this object before // creating the client socket. _family = localEP.AddressFamily; CreateClientSocket(); Client.Bind(localEP); } // Used by the class to provide the underlying network socket. public Socket Client { get { return _clientSocket; } set { _clientSocket = value; } } // Used by the class to indicate that a connection to a remote host has been made. protected bool Active { get { return _active; } set { _active = value; } } public int Available { get { return _clientSocket.Available; } } public short Ttl { get { return _clientSocket.Ttl; } set { _clientSocket.Ttl = value; } } public bool DontFragment { get { return _clientSocket.DontFragment; } set { _clientSocket.DontFragment = value; } } public bool MulticastLoopback { get { return _clientSocket.MulticastLoopback; } set { _clientSocket.MulticastLoopback = value; } } public bool EnableBroadcast { get { return _clientSocket.EnableBroadcast; } set { _clientSocket.EnableBroadcast = value; } } public bool ExclusiveAddressUse { get { return _clientSocket.ExclusiveAddressUse; } set { _clientSocket.ExclusiveAddressUse = value; } } private bool _cleanedUp = false; private void FreeResources() { // The only resource we need to free is the network stream, since this // is based on the client socket, closing the stream will cause us // to flush the data to the network, close the stream and (in the // NetoworkStream code) close the socket as well. if (_cleanedUp) { return; } Socket chkClientSocket = Client; if (chkClientSocket != null) { // If the NetworkStream wasn't retrieved, the Socket might // still be there and needs to be closed to release the effect // of the Bind() call and free the bound IPEndPoint. chkClientSocket.InternalShutdown(SocketShutdown.Both); chkClientSocket.Dispose(); Client = null; } _cleanedUp = true; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { GlobalLog.Print("UdpClient::Dispose()"); FreeResources(); GC.SuppressFinalize(this); } } private bool _isBroadcast; private void CheckForBroadcast(IPAddress ipAddress) { // Here we check to see if the user is trying to use a Broadcast IP address // we only detect IPAddress.Broadcast (which is not the only Broadcast address) // and in that case we set SocketOptionName.Broadcast on the socket to allow its use. // if the user really wants complete control over Broadcast addresses he needs to // inherit from UdpClient and gain control over the Socket and do whatever is appropriate. if (Client != null && !_isBroadcast && IsBroadcast(ipAddress)) { // We need to set the Broadcast socket option. // Note that once we set the option on the Socket we never reset it. _isBroadcast = true; Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); } } private bool IsBroadcast(IPAddress address) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { // No such thing as a broadcast address for IPv6. return false; } else { return address.Equals(IPAddress.Broadcast); } } internal IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state) { // Validate input parameters. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (datagram == null) { throw new ArgumentNullException("datagram"); } if (bytes > datagram.Length || bytes < 0) { throw new ArgumentOutOfRangeException("bytes"); } if (_active && endPoint != null) { // Do not allow sending packets to arbitrary host when connected. throw new InvalidOperationException(SR.net_udpconnected); } if (endPoint == null) { return Client.BeginSend(datagram, 0, bytes, SocketFlags.None, requestCallback, state); } CheckForBroadcast(endPoint.Address); return Client.BeginSendTo(datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state); } internal IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state) { if (_active && ((hostname != null) || (port != 0))) { // Do not allow sending packets to arbitrary host when connected. throw new InvalidOperationException(SR.net_udpconnected); } IPEndPoint ipEndPoint = null; if (hostname != null && port != 0) { IPAddress[] addresses = Dns.GetHostAddressesAsync(hostname).GetAwaiter().GetResult(); int i = 0; for (; i < addresses.Length && addresses[i].AddressFamily != _family; i++) { } if (addresses.Length == 0 || i == addresses.Length) { throw new ArgumentException(SR.net_invalidAddressList, "hostname"); } CheckForBroadcast(addresses[i]); ipEndPoint = new IPEndPoint(addresses[i], port); } return BeginSend(datagram, bytes, ipEndPoint, requestCallback, state); } internal IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state) { return BeginSend(datagram, bytes, null, requestCallback, state); } internal int EndSend(IAsyncResult asyncResult) { if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (_active) { return Client.EndSend(asyncResult); } else { return Client.EndSendTo(asyncResult); } } internal IAsyncResult BeginReceive(AsyncCallback requestCallback, object state) { // Validate input parameters. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Due to the nature of the ReceiveFrom() call and the ref parameter convention, // we need to cast an IPEndPoint to its base class EndPoint and cast it back down // to IPEndPoint. EndPoint tempRemoteEP; if (_family == AddressFamily.InterNetwork) { tempRemoteEP = IPEndPointStatics.Any; } else { tempRemoteEP = IPEndPointStatics.IPv6Any; } return Client.BeginReceiveFrom(_buffer, 0, MaxUDPSize, SocketFlags.None, ref tempRemoteEP, requestCallback, state); } internal byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP) { if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } EndPoint tempRemoteEP; if (_family == AddressFamily.InterNetwork) { tempRemoteEP = IPEndPointStatics.Any; } else { tempRemoteEP = IPEndPointStatics.IPv6Any; } int received = Client.EndReceiveFrom(asyncResult, ref tempRemoteEP); remoteEP = (IPEndPoint)tempRemoteEP; // Because we don't return the actual length, we need to ensure the returned buffer // has the appropriate length. if (received < MaxUDPSize) { byte[] newBuffer = new byte[received]; Buffer.BlockCopy(_buffer, 0, newBuffer, 0, received); return newBuffer; } return _buffer; } // Joins a multicast address group. public void JoinMulticastGroup(IPAddress multicastAddr) { // Validate input parameters. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (multicastAddr == null) { throw new ArgumentNullException("multicastAddr"); } // IPv6 Changes: we need to create the correct MulticastOption and // must also check for address family compatibility. if (multicastAddr.AddressFamily != _family) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr"); } if (_family == AddressFamily.InterNetwork) { MulticastOption mcOpt = new MulticastOption(multicastAddr); Client.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, mcOpt); } else { IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr); Client.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, mcOpt); } } public void JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress) { // Validate input parameters. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (_family != AddressFamily.InterNetwork) { throw new SocketException((int)SocketError.OperationNotSupported); } MulticastOption mcOpt = new MulticastOption(multicastAddr, localAddress); Client.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, mcOpt); } // Joins an IPv6 multicast address group. public void JoinMulticastGroup(int ifindex, IPAddress multicastAddr) { // Validate input parameters. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (multicastAddr == null) { throw new ArgumentNullException("multicastAddr"); } if (ifindex < 0) { throw new ArgumentException(SR.net_value_cannot_be_negative, "ifindex"); } // Ensure that this is an IPv6 client, otherwise throw WinSock // Operation not supported socked exception. if (_family != AddressFamily.InterNetworkV6) { throw new SocketException((int)SocketError.OperationNotSupported); } IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex); Client.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, mcOpt); } // Joins a multicast address group with the specified time to live (TTL). public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive) { // parameter validation; if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (multicastAddr == null) { throw new ArgumentNullException("multicastAddr"); } if (!RangeValidationHelpers.ValidateRange(timeToLive, 0, 255)) { throw new ArgumentOutOfRangeException("timeToLive"); } // Join the Multicast Group. JoinMulticastGroup(multicastAddr); // Set Time To Live (TTL). Client.SetSocketOption( (_family == AddressFamily.InterNetwork) ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, timeToLive); } // Leaves a multicast address group. public void DropMulticastGroup(IPAddress multicastAddr) { // Validate input parameters. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (multicastAddr == null) { throw new ArgumentNullException("multicastAddr"); } // IPv6 Changes: we need to create the correct MulticastOption and // must also check for address family compatibility. if (multicastAddr.AddressFamily != _family) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr"); } if (_family == AddressFamily.InterNetwork) { MulticastOption mcOpt = new MulticastOption(multicastAddr); Client.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.DropMembership, mcOpt); } else { IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr); Client.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.DropMembership, mcOpt); } } // Leaves an IPv6 multicast address group. public void DropMulticastGroup(IPAddress multicastAddr, int ifindex) { // Validate input parameters. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (multicastAddr == null) { throw new ArgumentNullException("multicastAddr"); } if (ifindex < 0) { throw new ArgumentException(SR.net_value_cannot_be_negative, "ifindex"); } // Ensure that this is an IPv6 client, otherwise throw WinSock // Operation not supported socked exception. if (_family != AddressFamily.InterNetworkV6) { throw new SocketException((int)SocketError.OperationNotSupported); } IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex); Client.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.DropMembership, mcOpt); } public Task<int> SendAsync(byte[] datagram, int bytes) { return Task<int>.Factory.FromAsync( (targetDatagram, targetBytes, callback, state) => ((UdpClient)state).BeginSend(targetDatagram, targetBytes, callback, state), asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult), datagram, bytes, state: this); } public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint endPoint) { return Task<int>.Factory.FromAsync( (targetDatagram, targetBytes, targetEndpoint, callback, state) => ((UdpClient)state).BeginSend(targetDatagram, targetBytes, targetEndpoint, callback, state), asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult), datagram, bytes, endPoint, state: this); } public Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port) { Tuple<byte[], string> packedArguments = Tuple.Create(datagram, hostname); return Task<int>.Factory.FromAsync( (targetPackedArguments, targetBytes, targetPort, callback, state) => { byte[] targetDatagram = targetPackedArguments.Item1; string targetHostname = targetPackedArguments.Item2; var client = (UdpClient)state; return client.BeginSend(targetDatagram, targetBytes, targetHostname, targetPort, callback, state); }, asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult), packedArguments, bytes, port, state: this); } public Task<UdpReceiveResult> ReceiveAsync() { return Task<UdpReceiveResult>.Factory.FromAsync( (callback, state) => ((UdpClient)state).BeginReceive(callback, state), asyncResult => { var client = (UdpClient)asyncResult.AsyncState; IPEndPoint remoteEP = null; byte[] buffer = client.EndReceive(asyncResult, ref remoteEP); return new UdpReceiveResult(buffer, remoteEP); }, state: this); } private void CreateClientSocket() { // Common initialization code. // // IPv6 Changes: Use the AddressFamily of this class rather than hardcode. Client = new Socket(_family, SocketType.Dgram, ProtocolType.Udp); } } }
/* * 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 Explanation = Lucene.Net.Search.Explanation; namespace Lucene.Net.Search.Function { /// <summary> Expert: represents field values as different types. /// Normally created via a /// <see cref="Lucene.Net.Search.Function.ValueSource">ValueSuorce</see> /// for a particular field and reader. /// /// <p/><font color="#FF0000"> /// WARNING: The status of the <b>Search.Function</b> package is experimental. /// The APIs introduced here might change in the future and will not be /// supported anymore in such a case.</font> /// /// /// </summary> public abstract class DocValues { /* * DocValues is distinct from ValueSource because * there needs to be an object created at query evaluation time that * is not referenced by the query itself because: * - Query objects should be MT safe * - For caching, Query objects are often used as keys... you don't * want the Query carrying around big objects */ /// <summary> Return doc value as a float. /// <p/>Mandatory: every DocValues implementation must implement at least this method. /// </summary> /// <param name="doc">document whose float value is requested. /// </param> public abstract float FloatVal(int doc); /// <summary> Return doc value as an int. /// <p/>Optional: DocValues implementation can (but don't have to) override this method. /// </summary> /// <param name="doc">document whose int value is requested. /// </param> public virtual int IntVal(int doc) { return (int) FloatVal(doc); } /// <summary> Return doc value as a long. /// <p/>Optional: DocValues implementation can (but don't have to) override this method. /// </summary> /// <param name="doc">document whose long value is requested. /// </param> public virtual long LongVal(int doc) { return (long) FloatVal(doc); } /// <summary> Return doc value as a double. /// <p/>Optional: DocValues implementation can (but don't have to) override this method. /// </summary> /// <param name="doc">document whose double value is requested. /// </param> public virtual double DoubleVal(int doc) { return (double) FloatVal(doc); } /// <summary> Return doc value as a string. /// <p/>Optional: DocValues implementation can (but don't have to) override this method. /// </summary> /// <param name="doc">document whose string value is requested. /// </param> public virtual System.String StrVal(int doc) { return FloatVal(doc).ToString(); } /// <summary> Return a string representation of a doc value, as reuired for Explanations.</summary> public abstract System.String ToString(int doc); /// <summary> Explain the scoring value for the input doc.</summary> public virtual Explanation Explain(int doc) { return new Explanation(FloatVal(doc), ToString(doc)); } /// <summary> Expert: for test purposes only, return the inner array of values, or null if not applicable. /// <p/> /// Allows tests to verify that loaded values are: /// <list type="bullet"> /// <item>indeed cached/reused.</item> /// <item>stored in the expected size/type (byte/short/int/float).</item> /// </list> /// Note: implementations of DocValues must override this method for /// these test elements to be tested, Otherwise the test would not fail, just /// print a warning. /// </summary> protected internal virtual object InnerArray { get { throw new System.NotSupportedException("this optional method is for test purposes only"); } } // --- some simple statistics on values private float minVal = System.Single.NaN; private float maxVal = System.Single.NaN; private float avgVal = System.Single.NaN; private bool computed = false; // compute optional values private void Compute() { if (computed) { return ; } float sum = 0; int n = 0; while (true) { float val; try { val = FloatVal(n); } catch (System.IndexOutOfRangeException) { break; } sum += val; minVal = System.Single.IsNaN(minVal)?val:System.Math.Min(minVal, val); maxVal = System.Single.IsNaN(maxVal)?val:System.Math.Max(maxVal, val); ++n; } avgVal = n == 0?System.Single.NaN:sum / n; computed = true; } /// <summary> Returns the minimum of all values or <c>Float.NaN</c> if this /// DocValues instance does not contain any value. /// <p/> /// This operation is optional /// <p/> /// /// </summary> /// <returns> the minimum of all values or <c>Float.NaN</c> if this /// DocValues instance does not contain any value. /// </returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual float GetMinValue() { Compute(); return minVal; } /// <summary> Returns the maximum of all values or <c>Float.NaN</c> if this /// DocValues instance does not contain any value. /// <p/> /// This operation is optional /// <p/> /// /// </summary> /// <returns> the maximum of all values or <c>Float.NaN</c> if this /// DocValues instance does not contain any value. /// </returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual float GetMaxValue() { Compute(); return maxVal; } /// <summary> Returns the average of all values or <c>Float.NaN</c> if this /// DocValues instance does not contain any value. * /// <p/> /// This operation is optional /// <p/> /// /// </summary> /// <returns> the average of all values or <c>Float.NaN</c> if this /// DocValues instance does not contain any value /// </returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual float GetAverageValue() { Compute(); return avgVal; } } }
using UnityEditor; using UnityEngine; using System.Collections.Generic; [CanEditMultipleObjects] [CustomEditor(typeof(tk2dTextMesh))] class tk2dTextMeshEditor : Editor { tk2dGenericIndexItem[] allFonts = null; // all generators string[] allFontNames = null; Vector2 gradientScroll; // Word wrap on text area - almost impossible to use otherwise GUIStyle _textAreaStyle = null; GUIStyle textAreaStyle { get { if (_textAreaStyle == null) { _textAreaStyle = new GUIStyle(EditorStyles.textField); _textAreaStyle.wordWrap = true; } return _textAreaStyle; } } tk2dTextMesh[] targetTextMeshes = new tk2dTextMesh[0]; #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) Renderer[] renderers = new Renderer[0]; #endif void OnEnable() { targetTextMeshes = new tk2dTextMesh[targets.Length]; for (int i = 0; i < targets.Length; ++i) { targetTextMeshes[i] = targets[i] as tk2dTextMesh; } #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) List<Renderer> rs = new List<Renderer>(); foreach (var v in targetTextMeshes) { if (v != null && v.renderer != null) { rs.Add(v.renderer); } } renderers = rs.ToArray(); #endif } void OnDestroy() { tk2dEditorSkin.Done(); } // Draws the word wrap GUI void DrawWordWrapSceneGUI(tk2dTextMesh textMesh) { tk2dFontData font = textMesh.font.inst; Transform transform = textMesh.transform; int px = textMesh.wordWrapWidth; Vector3 p0 = transform.position; float width = font.texelSize.x * px * transform.localScale.x; bool drawRightHandle = true; bool drawLeftHandle = false; switch (textMesh.anchor) { case TextAnchor.LowerCenter: case TextAnchor.MiddleCenter: case TextAnchor.UpperCenter: drawLeftHandle = true; p0 -= width * 0.5f * transform.right; break; case TextAnchor.LowerRight: case TextAnchor.MiddleRight: case TextAnchor.UpperRight: drawLeftHandle = true; drawRightHandle = false; p0 -= width * transform.right; break; } Vector3 p1 = p0 + width * transform.right; Handles.color = new Color32(255, 255, 255, 24); float subPin = font.texelSize.y * 2048; Handles.DrawLine(p0, p1); Handles.DrawLine(p0 - subPin * transform.up, p0 + subPin * transform.up); Handles.DrawLine(p1 - subPin * transform.up, p1 + subPin * transform.up); Handles.color = Color.white; Vector3 pin = transform.up * font.texelSize.y * 10.0f; Handles.DrawLine(p0 - pin, p0 + pin); Handles.DrawLine(p1 - pin, p1 + pin); if (drawRightHandle) { Vector3 newp1 = Handles.Slider(p1, transform.right, HandleUtility.GetHandleSize(p1), Handles.ArrowCap, 0.0f); if (newp1 != p1) { tk2dUndo.RecordObject(textMesh, "TextMesh Wrap Length"); int newPx = (int)Mathf.Round((newp1 - p0).magnitude / (font.texelSize.x * transform.localScale.x)); newPx = Mathf.Max(newPx, 0); textMesh.wordWrapWidth = newPx; textMesh.Commit(); } } if (drawLeftHandle) { Vector3 newp0 = Handles.Slider(p0, -transform.right, HandleUtility.GetHandleSize(p0), Handles.ArrowCap, 0.0f); if (newp0 != p0) { tk2dUndo.RecordObject(textMesh, "TextMesh Wrap Length"); int newPx = (int)Mathf.Round((p1 - newp0).magnitude / (font.texelSize.x * transform.localScale.x)); newPx = Mathf.Max(newPx, 0); textMesh.wordWrapWidth = newPx; textMesh.Commit(); } } } public void OnSceneGUI() { if (!tk2dEditorUtility.IsEditable(target)) { return; } tk2dTextMesh textMesh = (tk2dTextMesh)target; if (textMesh.formatting && textMesh.wordWrapWidth > 0) { DrawWordWrapSceneGUI(textMesh); } if (tk2dPreferences.inst.enableSpriteHandles == true) { MeshFilter meshFilter = textMesh.GetComponent<MeshFilter>(); if (!meshFilter || meshFilter.sharedMesh == null) { return; } Transform t = textMesh.transform; Bounds b = meshFilter.sharedMesh.bounds; Rect localRect = new Rect(b.min.x, b.min.y, b.size.x, b.size.y); // Draw rect outline Handles.color = new Color(1,1,1,0.5f); tk2dSceneHelper.DrawRect (localRect, t); Handles.BeginGUI (); // Resize handles if (tk2dSceneHelper.RectControlsToggle ()) { EditorGUI.BeginChangeCheck (); Rect resizeRect = tk2dSceneHelper.RectControl (132546, localRect, t); if (EditorGUI.EndChangeCheck ()) { Vector3 newScale = new Vector3 (textMesh.scale.x * (resizeRect.width / localRect.width), textMesh.scale.y * (resizeRect.height / localRect.height)); float scaleMin = 0.001f; if (textMesh.scale.x > 0.0f && newScale.x < scaleMin) newScale.x = scaleMin; if (textMesh.scale.x < 0.0f && newScale.x > -scaleMin) newScale.x = -scaleMin; if (textMesh.scale.y > 0.0f && newScale.y < scaleMin) newScale.y = scaleMin; if (textMesh.scale.y < 0.0f && newScale.y > -scaleMin) newScale.y = -scaleMin; if (newScale != textMesh.scale) { tk2dUndo.RecordObjects (new Object[] {t, textMesh}, "Resize"); float factorX = (Mathf.Abs (textMesh.scale.x) > Mathf.Epsilon) ? (newScale.x / textMesh.scale.x) : 0.0f; float factorY = (Mathf.Abs (textMesh.scale.y) > Mathf.Epsilon) ? (newScale.y / textMesh.scale.y) : 0.0f; Vector3 offset = new Vector3(resizeRect.xMin - localRect.xMin * factorX, resizeRect.yMin - localRect.yMin * factorY, 0.0f); Vector3 newPosition = t.TransformPoint (offset); if (newPosition != t.position) { t.position = newPosition; } textMesh.scale = newScale; textMesh.Commit (); EditorUtility.SetDirty(textMesh); } } } // Rotate handles if (!tk2dSceneHelper.RectControlsToggle ()) { EditorGUI.BeginChangeCheck(); float theta = tk2dSceneHelper.RectRotateControl (645231, localRect, t, new List<int>()); if (EditorGUI.EndChangeCheck()) { if (Mathf.Abs(theta) > Mathf.Epsilon) { tk2dUndo.RecordObject (t, "Rotate"); t.Rotate(t.forward, theta, Space.World); } } } Handles.EndGUI (); // Sprite selecting tk2dSceneHelper.HandleSelectSprites(); // Move targeted sprites tk2dSceneHelper.HandleMoveSprites(t, localRect); } if (GUI.changed) { EditorUtility.SetDirty(target); } } void UndoableAction( System.Action<tk2dTextMesh> action ) { tk2dUndo.RecordObjects (targetTextMeshes, "Inspector"); foreach (tk2dTextMesh tm in targetTextMeshes) { action(tm); } } static bool showInlineStylingHelp = false; public override void OnInspectorGUI() { tk2dTextMesh textMesh = (tk2dTextMesh)target; tk2dGuiUtility.LookLikeControls(80, 50); // maybe cache this if its too slow later if (allFonts == null || allFontNames == null) { tk2dGenericIndexItem[] indexFonts = tk2dEditorUtility.GetOrCreateIndex().GetFonts(); List<tk2dGenericIndexItem> filteredFonts = new List<tk2dGenericIndexItem>(); foreach (var f in indexFonts) if (!f.managed) filteredFonts.Add(f); allFonts = filteredFonts.ToArray(); allFontNames = new string[allFonts.Length]; for (int i = 0; i < allFonts.Length; ++i) allFontNames[i] = allFonts[i].AssetName; } if (allFonts != null && allFonts.Length > 0) { if (textMesh.font == null) { textMesh.font = allFonts[0].GetAsset<tk2dFont>().data; } int currId = -1; string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(textMesh.font)); for (int i = 0; i < allFonts.Length; ++i) { if (allFonts[i].dataGUID == guid) { currId = i; } } int newId = EditorGUILayout.Popup("Font", currId, allFontNames); if (newId != currId) { UndoableAction( tm => tm.font = allFonts[newId].GetAsset<tk2dFont>().data ); GUI.changed = true; } EditorGUILayout.BeginHorizontal(); int newMaxChars = Mathf.Clamp( EditorGUILayout.IntField("Max Chars", textMesh.maxChars), 1, 16000 ); if (newMaxChars != textMesh.maxChars) { UndoableAction( tm => tm.maxChars = newMaxChars ); } if (GUILayout.Button("Fit", GUILayout.MaxWidth(32.0f))) { UndoableAction( tm => tm.maxChars = tm.NumTotalCharacters() ); GUI.changed = true; } EditorGUILayout.EndHorizontal(); bool newFormatting = EditorGUILayout.BeginToggleGroup("Formatting", textMesh.formatting); if (newFormatting != textMesh.formatting) { UndoableAction( tm => tm.formatting = newFormatting ); GUI.changed = true; } GUILayout.BeginHorizontal(); ++EditorGUI.indentLevel; if (textMesh.wordWrapWidth == 0) { EditorGUILayout.PrefixLabel("Word Wrap"); if (GUILayout.Button("Enable", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { UndoableAction( tm => tm.wordWrapWidth = (tm.wordWrapWidth == 0) ? 500 : tm.wordWrapWidth ); GUI.changed = true; } } else { int newWordWrapWidth = EditorGUILayout.IntField("Word Wrap", textMesh.wordWrapWidth); if (newWordWrapWidth != textMesh.wordWrapWidth) { UndoableAction( tm => tm.wordWrapWidth = newWordWrapWidth ); } if (GUILayout.Button("Disable", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { UndoableAction( tm => tm.wordWrapWidth = 0 ); GUI.changed = true; } } --EditorGUI.indentLevel; GUILayout.EndHorizontal(); EditorGUILayout.EndToggleGroup(); GUILayout.BeginHorizontal (); bool newInlineStyling = EditorGUILayout.Toggle("Inline Styling", textMesh.inlineStyling); if (newInlineStyling != textMesh.inlineStyling) { UndoableAction( tm => tm.inlineStyling = newInlineStyling ); } if (textMesh.inlineStyling) { showInlineStylingHelp = GUILayout.Toggle(showInlineStylingHelp, "?", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); } GUILayout.EndHorizontal (); if (textMesh.inlineStyling && showInlineStylingHelp) { Color bg = GUI.backgroundColor; GUI.backgroundColor = new Color32(154, 176, 203, 255); string message = "Inline style commands\n\n" + "^cRGBA - set color\n" + "^gRGBARGBA - set top and bottom colors\n" + " RGBA = single digit hex values (0 - f)\n\n" + "^CRRGGBBAA - set color\n" + "^GRRGGBBAARRGGBBAA - set top and bottom colors\n" + " RRGGBBAA = 2 digit hex values (00 - ff)\n\n" + ((textMesh.font.inst.textureGradients && textMesh.font.inst.gradientCount > 0) ? "^0-9 - select gradient\n" : "") + "^^ - print ^"; tk2dGuiUtility.InfoBox( message, tk2dGuiUtility.WarningLevel.Info ); GUI.backgroundColor = bg; } GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Text"); string newText = EditorGUILayout.TextArea(textMesh.text, textAreaStyle, GUILayout.Height(64)); if (newText != textMesh.text) { UndoableAction( tm => tm.text = newText ); GUI.changed = true; } GUILayout.EndHorizontal(); if (textMesh.NumTotalCharacters() > textMesh.maxChars) { tk2dGuiUtility.InfoBox( "Number of printable characters in text mesh exceeds MaxChars on this text mesh. "+ "The text will be clipped at " + textMesh.maxChars.ToString() + " characters.", tk2dGuiUtility.WarningLevel.Error ); } TextAnchor newTextAnchor = (TextAnchor)EditorGUILayout.EnumPopup("Anchor", textMesh.anchor); if (newTextAnchor != textMesh.anchor) UndoableAction( tm => tm.anchor = newTextAnchor ); bool newKerning = EditorGUILayout.Toggle("Kerning", textMesh.kerning); if (newKerning != textMesh.kerning) UndoableAction( tm => tm.kerning = newKerning ); float newSpacing = EditorGUILayout.FloatField("Spacing", textMesh.Spacing); if (newSpacing != textMesh.Spacing) UndoableAction( tm => tm.Spacing = newSpacing ); float newLineSpacing = EditorGUILayout.FloatField("Line Spacing", textMesh.LineSpacing); if (newLineSpacing != textMesh.LineSpacing) UndoableAction( tm => tm.LineSpacing = newLineSpacing ); #if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 int sortingOrder = EditorGUILayout.IntField("Sorting Order In Layer", targetTextMeshes[0].SortingOrder); if (sortingOrder != targetTextMeshes[0].SortingOrder) { tk2dUndo.RecordObjects(targetTextMeshes, "Sorting Order In Layer"); foreach (tk2dTextMesh s in targetTextMeshes) { s.SortingOrder = sortingOrder; } } #else if (renderers.Length > 0) { string sortingLayerName = tk2dEditorUtility.SortingLayerNamePopup("Sorting Layer", renderers[0].sortingLayerName); if (sortingLayerName != renderers[0].sortingLayerName) { tk2dUndo.RecordObjects(renderers, "Sorting Layer"); foreach (Renderer r in renderers) { r.sortingLayerName = sortingLayerName; EditorUtility.SetDirty(r); } } int sortingOrder = EditorGUILayout.IntField("Order In Layer", targetTextMeshes[0].SortingOrder); if (sortingOrder != targetTextMeshes[0].SortingOrder) { tk2dUndo.RecordObjects(targetTextMeshes, "Order In Layer"); tk2dUndo.RecordObjects(renderers, "Order In Layer"); foreach (tk2dTextMesh s in targetTextMeshes) { s.SortingOrder = sortingOrder; } } } #endif Vector3 newScale = EditorGUILayout.Vector3Field("Scale", textMesh.scale); if (newScale != textMesh.scale) UndoableAction( tm => tm.scale = newScale ); if (textMesh.font.textureGradients && textMesh.font.inst.gradientCount > 0) { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("TextureGradient"); // Draw gradient scroller bool drawGradientScroller = true; if (drawGradientScroller) { textMesh.textureGradient = textMesh.textureGradient % textMesh.font.inst.gradientCount; gradientScroll = EditorGUILayout.BeginScrollView(gradientScroll, GUILayout.ExpandHeight(false)); Rect r = GUILayoutUtility.GetRect(textMesh.font.inst.gradientTexture.width, textMesh.font.inst.gradientTexture.height, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); GUI.DrawTexture(r, textMesh.font.inst.gradientTexture); Rect hr = r; hr.width /= textMesh.font.inst.gradientCount; hr.x += hr.width * textMesh.textureGradient; float ox = hr.width / 8; float oy = hr.height / 8; Vector3[] rectVerts = { new Vector3(hr.x + 0.5f + ox, hr.y + oy, 0), new Vector3(hr.x + hr.width - ox, hr.y + oy, 0), new Vector3(hr.x + hr.width - ox, hr.y + hr.height - 0.5f - oy, 0), new Vector3(hr.x + ox, hr.y + hr.height - 0.5f - oy, 0) }; Handles.DrawSolidRectangleWithOutline(rectVerts, new Color(0,0,0,0.2f), new Color(0,0,0,1)); if (GUIUtility.hotControl == 0 && Event.current.type == EventType.MouseDown && r.Contains(Event.current.mousePosition)) { int newTextureGradient = (int)(Event.current.mousePosition.x / (textMesh.font.inst.gradientTexture.width / textMesh.font.inst.gradientCount)); if (newTextureGradient != textMesh.textureGradient) { UndoableAction( delegate(tk2dTextMesh tm) { if (tm.useGUILayout && tm.font != null && newTextureGradient < tm.font.inst.gradientCount) { tm.textureGradient = newTextureGradient; } } ); } GUI.changed = true; } EditorGUILayout.EndScrollView(); } GUILayout.EndHorizontal(); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("HFlip")) { UndoableAction( delegate(tk2dTextMesh tm) { Vector3 s = tm.scale; s.x *= -1.0f; tm.scale = s; } ); GUI.changed = true; } if (GUILayout.Button("VFlip")) { UndoableAction( delegate(tk2dTextMesh tm) { Vector3 s = tm.scale; s.y *= -1.0f; tm.scale = s; } ); GUI.changed = true; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Bake Scale")) { tk2dScaleUtility.Bake(textMesh.transform); GUI.changed = true; } GUIContent pixelPerfectButton = new GUIContent("1:1", "Make Pixel Perfect"); if ( GUILayout.Button(pixelPerfectButton )) { if (tk2dPixelPerfectHelper.inst) tk2dPixelPerfectHelper.inst.Setup(); UndoableAction( tm => tm.MakePixelPerfect() ); GUI.changed = true; } EditorGUILayout.EndHorizontal(); if (textMesh.font && !textMesh.font.inst.isPacked) { bool newUseGradient = EditorGUILayout.Toggle("Use Gradient", textMesh.useGradient); if (newUseGradient != textMesh.useGradient) { UndoableAction( tm => tm.useGradient = newUseGradient ); } if (textMesh.useGradient) { Color newColor = EditorGUILayout.ColorField("Top Color", textMesh.color); if (newColor != textMesh.color) UndoableAction( tm => tm.color = newColor ); Color newColor2 = EditorGUILayout.ColorField("Bottom Color", textMesh.color2); if (newColor2 != textMesh.color2) UndoableAction( tm => tm.color2 = newColor2 ); } else { Color newColor = EditorGUILayout.ColorField("Color", textMesh.color); if (newColor != textMesh.color) UndoableAction( tm => tm.color = newColor ); } } if (GUI.changed) { foreach (tk2dTextMesh tm in targetTextMeshes) { tm.ForceBuild(); EditorUtility.SetDirty(tm); } } } } [MenuItem("GameObject/Create Other/tk2d/TextMesh", false, 13905)] static void DoCreateTextMesh() { tk2dFontData fontData = null; // Find reference in scene tk2dTextMesh dupeMesh = GameObject.FindObjectOfType(typeof(tk2dTextMesh)) as tk2dTextMesh; if (dupeMesh) fontData = dupeMesh.font; // Find in library if (fontData == null) { tk2dGenericIndexItem[] allFontEntries = tk2dEditorUtility.GetOrCreateIndex().GetFonts(); foreach (var v in allFontEntries) { if (v.managed) continue; tk2dFontData data = v.GetData<tk2dFontData>(); if (data != null) { fontData = data; break; } } } if (fontData == null) { EditorUtility.DisplayDialog("Create TextMesh", "Unable to create text mesh as no Fonts have been found.", "Ok"); return; } GameObject go = tk2dEditorUtility.CreateGameObjectInScene("TextMesh"); tk2dTextMesh textMesh = go.AddComponent<tk2dTextMesh>(); textMesh.font = fontData; textMesh.text = "New TextMesh"; textMesh.Commit(); Selection.activeGameObject = go; Undo.RegisterCreatedObjectUndo(go, "Create TextMesh"); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * 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 AppendingDeltaPackedInt64Buffer = Lucene.Net.Util.Packed.AppendingDeltaPackedInt64Buffer; using AppendingPackedInt64Buffer = Lucene.Net.Util.Packed.AppendingPackedInt64Buffer; using ArrayUtil = Lucene.Net.Util.ArrayUtil; using ByteBlockPool = Lucene.Net.Util.ByteBlockPool; using BytesRef = Lucene.Net.Util.BytesRef; using BytesRefHash = Lucene.Net.Util.BytesRefHash; using Counter = Lucene.Net.Util.Counter; using DirectBytesStartArray = Lucene.Net.Util.BytesRefHash.DirectBytesStartArray; using DocValuesConsumer = Lucene.Net.Codecs.DocValuesConsumer; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; /// <summary> /// Buffers up pending <see cref="T:byte[]"/>s per doc, deref and sorting via /// int ord, then flushes when segment flushes. /// </summary> internal class SortedSetDocValuesWriter : DocValuesWriter { internal readonly BytesRefHash hash; private AppendingPackedInt64Buffer pending; // stream of all termIDs private AppendingDeltaPackedInt64Buffer pendingCounts; // termIDs per doc private readonly Counter iwBytesUsed; private long bytesUsed; // this only tracks differences in 'pending' and 'pendingCounts' private readonly FieldInfo fieldInfo; private int currentDoc; private int[] currentValues = new int[8]; private int currentUpto = 0; private int maxCount = 0; public SortedSetDocValuesWriter(FieldInfo fieldInfo, Counter iwBytesUsed) { this.fieldInfo = fieldInfo; this.iwBytesUsed = iwBytesUsed; hash = new BytesRefHash(new ByteBlockPool(new ByteBlockPool.DirectTrackingAllocator(iwBytesUsed)), BytesRefHash.DEFAULT_CAPACITY, new DirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY, iwBytesUsed)); pending = new AppendingPackedInt64Buffer(PackedInt32s.COMPACT); pendingCounts = new AppendingDeltaPackedInt64Buffer(PackedInt32s.COMPACT); bytesUsed = pending.RamBytesUsed() + pendingCounts.RamBytesUsed(); iwBytesUsed.AddAndGet(bytesUsed); } public virtual void AddValue(int docID, BytesRef value) { if (value == null) { throw new ArgumentException("field \"" + fieldInfo.Name + "\": null value not allowed"); } if (value.Length > (ByteBlockPool.BYTE_BLOCK_SIZE - 2)) { throw new ArgumentException("DocValuesField \"" + fieldInfo.Name + "\" is too large, must be <= " + (ByteBlockPool.BYTE_BLOCK_SIZE - 2)); } if (docID != currentDoc) { FinishCurrentDoc(); } // Fill in any holes: while (currentDoc < docID) { pendingCounts.Add(0); // no values currentDoc++; } AddOneValue(value); UpdateBytesUsed(); } // finalize currentDoc: this deduplicates the current term ids private void FinishCurrentDoc() { Array.Sort(currentValues, 0, currentUpto); int lastValue = -1; int count = 0; for (int i = 0; i < currentUpto; i++) { int termID = currentValues[i]; // if its not a duplicate if (termID != lastValue) { pending.Add(termID); // record the term id count++; } lastValue = termID; } // record the number of unique term ids for this doc pendingCounts.Add(count); maxCount = Math.Max(maxCount, count); currentUpto = 0; currentDoc++; } public override void Finish(int maxDoc) { FinishCurrentDoc(); // fill in any holes for (int i = currentDoc; i < maxDoc; i++) { pendingCounts.Add(0); // no values } } private void AddOneValue(BytesRef value) { int termID = hash.Add(value); if (termID < 0) { termID = -termID - 1; } else { // reserve additional space for each unique value: // 1. when indexing, when hash is 50% full, rehash() suddenly needs 2*size ints. // TODO: can this same OOM happen in THPF? // 2. when flushing, we need 1 int per value (slot in the ordMap). iwBytesUsed.AddAndGet(2 * RamUsageEstimator.NUM_BYTES_INT32); } if (currentUpto == currentValues.Length) { currentValues = ArrayUtil.Grow(currentValues, currentValues.Length + 1); // reserve additional space for max # values per-doc // when flushing, we need an int[] to sort the mapped-ords within the doc iwBytesUsed.AddAndGet((currentValues.Length - currentUpto) * 2 * RamUsageEstimator.NUM_BYTES_INT32); } currentValues[currentUpto] = termID; currentUpto++; } private void UpdateBytesUsed() { long newBytesUsed = pending.RamBytesUsed() + pendingCounts.RamBytesUsed(); iwBytesUsed.AddAndGet(newBytesUsed - bytesUsed); bytesUsed = newBytesUsed; } [MethodImpl(MethodImplOptions.NoInlining)] public override void Flush(SegmentWriteState state, DocValuesConsumer dvConsumer) { int maxDoc = state.SegmentInfo.DocCount; int maxCountPerDoc = maxCount; Debug.Assert(pendingCounts.Count == maxDoc); int valueCount = hash.Count; int[] sortedValues = hash.Sort(BytesRef.UTF8SortedAsUnicodeComparer); int[] ordMap = new int[valueCount]; for (int ord = 0; ord < valueCount; ord++) { ordMap[sortedValues[ord]] = ord; } dvConsumer.AddSortedSetField(fieldInfo, GetBytesRefEnumberable(valueCount, sortedValues), // doc -> ordCount GetOrdsEnumberable(maxDoc), // ords GetOrdCountEnumberable(maxCountPerDoc, ordMap)); } [MethodImpl(MethodImplOptions.NoInlining)] public override void Abort() { } private IEnumerable<BytesRef> GetBytesRefEnumberable(int valueCount, int[] sortedValues) { for (int i = 0; i < valueCount; ++i) { var scratch = new BytesRef(); yield return hash.Get(sortedValues[i], scratch); } } private IEnumerable<long?> GetOrdsEnumberable(int maxDoc) { AppendingDeltaPackedInt64Buffer.Iterator iter = pendingCounts.GetIterator(); Debug.Assert(maxDoc == pendingCounts.Count, "MaxDoc: " + maxDoc + ", pending.Count: " + pending.Count); for (int i = 0; i < maxDoc; ++i) { yield return (int)iter.Next(); } } private IEnumerable<long?> GetOrdCountEnumberable(int maxCountPerDoc, int[] ordMap) { int currentUpTo = 0, currentLength = 0; AppendingPackedInt64Buffer.Iterator iter = pending.GetIterator(); AppendingDeltaPackedInt64Buffer.Iterator counts = pendingCounts.GetIterator(); int[] currentDoc = new int[maxCountPerDoc]; for (long i = 0; i < pending.Count; ++i) { while (currentUpTo == currentLength) { // refill next doc, and sort remapped ords within the doc. currentUpTo = 0; currentLength = (int)counts.Next(); for (int j = 0; j < currentLength; j++) { currentDoc[j] = ordMap[(int)iter.Next()]; } Array.Sort(currentDoc, 0, currentLength); } int ord = currentDoc[currentUpTo]; currentUpTo++; yield return ord; } } } }
/* * f1livetiming - Part of the Live Timing Library for .NET * Copyright (C) 2009 Liam Lowey * * http://livetiming.turnitin.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Common.Patterns.Command { using Impl; namespace Impl { public delegate void CommandProc(); public delegate void CommandProc<T1>(T1 a1); public delegate void CommandProc<T1, T2>(T1 a1, T2 a2); public delegate void CommandProc<T1, T2, T3>(T1 a1, T2 a2, T3 a3); public delegate void CommandProc<T1, T2, T3, T4>(T1 a1, T2 a2, T3 a3, T4 a4); public delegate void CommandProc<T1, T2, T3, T4, T5>(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5); public delegate void CommandProc<T1, T2, T3, T4, T5, T6>(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6); public delegate void CommandProc<T1, T2, T3, T4, T5, T6, T7>(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7); public delegate void CommandProc<T1, T2, T3, T4, T5, T6, T7, T8>(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7, T8 a8); } public interface ICommand : IDisposable { void Execute(); } public static class CommandFactory { public static ICommand MakeCommand(CommandProc proc) { return new Command0(proc); } public static ICommand MakeCommand<T1>(CommandProc<T1> proc, T1 arg1) { return new Command1<T1>(proc, arg1); } public static ICommand MakeCommand<T1, T2>(CommandProc<T1, T2> proc, T1 arg1, T2 arg2) { return new Command2<T1, T2>(proc, arg1, arg2); } public static ICommand MakeCommand<T1, T2, T3>(CommandProc<T1, T2, T3> proc, T1 arg1, T2 arg2, T3 arg3) { return new Command3<T1, T2, T3>(proc, arg1, arg2, arg3); } public static ICommand MakeCommand<T1, T2, T3, T4>(CommandProc<T1, T2, T3, T4> proc, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { return new Command4<T1, T2, T3, T4>(proc, arg1, arg2, arg3, arg4); } public static ICommand MakeCommand<T1, T2, T3, T4, T5>(CommandProc<T1, T2, T3, T4, T5> proc, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { return new Command5<T1, T2, T3, T4, T5>(proc, arg1, arg2, arg3, arg4, arg5); } public static ICommand MakeCommand<T1, T2, T3, T4, T5, T6>(CommandProc<T1, T2, T3, T4, T5, T6> proc, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) { return new Command6<T1, T2, T3, T4, T5, T6>(proc, arg1, arg2, arg3, arg4, arg5, arg6); } public static ICommand MakeCommand<T1, T2, T3, T4, T5, T6, T7>(CommandProc<T1, T2, T3, T4, T5, T6, T7> proc, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) { return new Command7<T1, T2, T3, T4, T5, T6, T7>(proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } } namespace Impl { internal class Command0 : ICommand { private readonly CommandProc _proc; public Command0(CommandProc proc) { _proc = proc; } public void Execute() { _proc.Invoke(); } public void Dispose() { } } internal class Command1<T1> : ICommand { private readonly CommandProc<T1> _proc; private readonly T1 _arg1; public Command1(CommandProc<T1> proc, T1 arg1) { _proc = proc; _arg1 = arg1; } public void Execute() { _proc.Invoke(_arg1); } public void Dispose() { } } internal class Command2<T1, T2> : ICommand { private readonly CommandProc<T1, T2> _proc; private readonly T1 _arg1; private readonly T2 _arg2; public Command2(CommandProc<T1, T2> proc, T1 arg1, T2 arg2) { _proc = proc; _arg1 = arg1; _arg2 = arg2; } public void Execute() { _proc.Invoke(_arg1, _arg2); } public void Dispose() { } } internal class Command3<T1, T2, T3> : ICommand { private readonly CommandProc<T1, T2, T3> _proc; private readonly T1 _arg1; private readonly T2 _arg2; private readonly T3 _arg3; public Command3(CommandProc<T1, T2, T3> proc, T1 arg1, T2 arg2, T3 arg3) { _proc = proc; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } public void Execute() { _proc.Invoke(_arg1, _arg2, _arg3); } public void Dispose() { } } internal class Command4<T1, T2, T3, T4> : ICommand { private readonly CommandProc<T1, T2, T3, T4> _proc; private readonly T1 _arg1; private readonly T2 _arg2; private readonly T3 _arg3; private readonly T4 _arg4; public Command4(CommandProc<T1, T2, T3, T4> proc, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { _proc = proc; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; } public void Execute() { _proc.Invoke(_arg1, _arg2, _arg3, _arg4); } public void Dispose() { } } internal class Command5<T1, T2, T3, T4, T5> : ICommand { private readonly CommandProc<T1, T2, T3, T4, T5> _proc; private readonly T1 _arg1; private readonly T2 _arg2; private readonly T3 _arg3; private readonly T4 _arg4; private readonly T5 _arg5; public Command5(CommandProc<T1, T2, T3, T4, T5> proc, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { _proc = proc; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; _arg5 = arg5; } public void Execute() { _proc.Invoke(_arg1, _arg2, _arg3, _arg4, _arg5); } public void Dispose() { } } internal class Command6<T1, T2, T3, T4, T5, T6> : ICommand { private readonly CommandProc<T1, T2, T3, T4, T5, T6> _proc; private readonly T1 _arg1; private readonly T2 _arg2; private readonly T3 _arg3; private readonly T4 _arg4; private readonly T5 _arg5; private readonly T6 _arg6; public Command6(CommandProc<T1, T2, T3, T4, T5, T6> proc, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) { _proc = proc; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; _arg5 = arg5; _arg6 = arg6; } public void Execute() { _proc.Invoke(_arg1, _arg2, _arg3, _arg4, _arg5, _arg6); } public void Dispose() { } } internal class Command7<T1, T2, T3, T4, T5, T6, T7> : ICommand { private readonly CommandProc<T1, T2, T3, T4, T5, T6, T7> _proc; private readonly T1 _arg1; private readonly T2 _arg2; private readonly T3 _arg3; private readonly T4 _arg4; private readonly T5 _arg5; private readonly T6 _arg6; private readonly T7 _arg7; public Command7(CommandProc<T1, T2, T3, T4, T5, T6, T7> proc, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) { _proc = proc; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; _arg5 = arg5; _arg6 = arg6; _arg7 = arg7; } public void Execute() { _proc.Invoke(_arg1, _arg2, _arg3, _arg4, _arg5, _arg6, _arg7); } public void Dispose() { } } } }
// Copyright (c) Converter Systems LLC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Expression = System.Linq.Expressions.Expression; namespace RobotHmi.Controls { public class Trendline : Control { public static readonly DependencyProperty ItemsSourceProperty; public static readonly DependencyProperty ValuePathProperty; public static readonly DependencyProperty TimePathProperty; public static readonly DependencyProperty MinValueProperty; public static readonly DependencyProperty MaxValueProperty; public static readonly DependencyProperty StrokeProperty; public static readonly DependencyProperty StrokeThicknessProperty; public static readonly DependencyProperty TimeSpanProperty; public static readonly DependencyProperty StartTimeProperty; public static readonly DependencyProperty EndTimeProperty; public static readonly DependencyProperty GeometryProperty; public static readonly DependencyProperty ShowAxisProperty; public static readonly DependencyProperty AutoRangeProperty; private readonly ScaleTransform renderScale; private readonly TranslateTransform renderTranslate; private readonly ScaleTransform scale; private readonly TranslateTransform translate; private readonly TimeSpan frameDuration = TimeSpan.FromMilliseconds(1000.0 / 24.0); // 24 fps private FrameworkElement chartArea; private bool isAnimationRunning; private DateTime previousUpdateTime; private Func<object, DateTime> timeGetter; private Func<object, IConvertible> valueGetter; static Trendline() { DefaultStyleKeyProperty.OverrideMetadata(typeof(Trendline), new FrameworkPropertyMetadata(typeof(Trendline))); ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(Trendline), new FrameworkPropertyMetadata(null, OnItemsSourceChanged)); ValuePathProperty = DependencyProperty.Register("ValuePath", typeof(string), typeof(Trendline), new FrameworkPropertyMetadata("Value"), IsPathValid); TimePathProperty = DependencyProperty.Register("TimePath", typeof(string), typeof(Trendline), new FrameworkPropertyMetadata("SourceTimestamp"), IsPathValid); MinValueProperty = DependencyProperty.Register("MinValue", typeof(double), typeof(Trendline), new FrameworkPropertyMetadata(0.0, OnMinMaxChanged), IsMinMaxValid); MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(double), typeof(Trendline), new FrameworkPropertyMetadata(100.0, OnMinMaxChanged), IsMinMaxValid); StartTimeProperty = DependencyProperty.Register("StartTime", typeof(DateTime), typeof(Trendline), new FrameworkPropertyMetadata(DateTime.MinValue)); EndTimeProperty = DependencyProperty.Register("EndTime", typeof(DateTime), typeof(Trendline), new FrameworkPropertyMetadata(DateTime.MaxValue)); StrokeProperty = DependencyProperty.Register("Stroke", typeof(Brush), typeof(Trendline), new FrameworkPropertyMetadata(null)); StrokeThicknessProperty = DependencyProperty.Register("StrokeThickness", typeof(double), typeof(Trendline), new FrameworkPropertyMetadata(1.0)); TimeSpanProperty = DependencyProperty.Register("TimeSpan", typeof(TimeSpan), typeof(Trendline), new FrameworkPropertyMetadata(new TimeSpan(0, 0, 60))); GeometryProperty = DependencyProperty.Register("Geometry", typeof(StreamGeometry), typeof(Trendline)); ShowAxisProperty = DependencyProperty.Register("ShowAxis", typeof(bool), typeof(Trendline), new FrameworkPropertyMetadata(false)); AutoRangeProperty = DependencyProperty.Register("AutoRange", typeof(bool), typeof(Trendline), new FrameworkPropertyMetadata(true)); } public Trendline() { this.translate = new TranslateTransform(); this.scale = new ScaleTransform(); this.renderTranslate = new TranslateTransform(); this.renderScale = new ScaleTransform(); this.Geometry = new StreamGeometry { Transform = new TransformGroup { Children = new TransformCollection { this.translate, this.scale, this.renderScale, this.renderTranslate } } }; this.Loaded += this.OnLoaded; this.Unloaded += this.OnUnloaded; } [Category("Common")] public IEnumerable ItemsSource { get { return (IEnumerable)this.GetValue(ItemsSourceProperty); } set { this.SetValue(ItemsSourceProperty, value); } } [Category("Common")] public double MinValue { get { return (double)this.GetValue(MinValueProperty); } set { this.SetValue(MinValueProperty, value); } } [Category("Common")] public double MaxValue { get { return (double)this.GetValue(MaxValueProperty); } set { this.SetValue(MaxValueProperty, value); } } [Category("Common")] public TimeSpan TimeSpan { get { return (TimeSpan)this.GetValue(TimeSpanProperty); } set { this.SetValue(TimeSpanProperty, value); } } [Category("Common")] public string TimePath { get { return (string)this.GetValue(TimePathProperty); } set { this.SetValue(TimePathProperty, value); } } [Category("Common")] public string ValuePath { get { return (string)this.GetValue(ValuePathProperty); } set { this.SetValue(ValuePathProperty, value); } } [Category("Brush")] public Brush Stroke { get { return (Brush)this.GetValue(StrokeProperty); } set { this.SetValue(StrokeProperty, value); } } [Category("Appearance")] [TypeConverter(typeof(LengthConverter))] public double StrokeThickness { get { return (double)this.GetValue(StrokeThicknessProperty); } set { this.SetValue(StrokeThicknessProperty, value); } } public bool AutoRange { get { return (bool)this.GetValue(AutoRangeProperty); } set { this.SetValue(AutoRangeProperty, value); } } public bool ShowAxis { get { return (bool)this.GetValue(ShowAxisProperty); } set { this.SetValue(ShowAxisProperty, value); } } public DateTime StartTime { get { return (DateTime)this.GetValue(StartTimeProperty); } private set { this.SetValue(StartTimeProperty, value); } } public DateTime EndTime { get { return (DateTime)this.GetValue(EndTimeProperty); } private set { this.SetValue(EndTimeProperty, value); } } public StreamGeometry Geometry { get { return (StreamGeometry)this.GetValue(GeometryProperty); } private set { this.SetValue(GeometryProperty, value); } } private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((Trendline)d).OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue); } private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue) { this.valueGetter = null; this.timeGetter = null; if (newValue != null) { var elementType = newValue.AsQueryable().ElementType; this.valueGetter = TryMakePropertyGetFromObjectDelegate<IConvertible>(elementType, this.ValuePath); this.timeGetter = TryMakePropertyGetFromObjectDelegate<DateTime>(elementType, this.TimePath); } } /// <summary> /// Builds a delegate that casts an object to a target type and then gets the value a property or field. /// </summary> /// <typeparam name="T">The expected return type of the property or field.</typeparam> /// <param name="targetType">The expected target instance type.</param> /// <param name="propertyOrField">The name of the target property or field.</param> /// <returns>A delegate.</returns> private static Func<object, T> TryMakePropertyGetFromObjectDelegate<T>(Type targetType, string propertyOrField) { try { var target = Expression.Parameter(typeof(object), "target"); var expr = Expression.Lambda<Func<object, T>>(Expression.Convert(Expression.PropertyOrField(Expression.Convert(target, targetType), propertyOrField), typeof(T)), target); return expr.Compile(); } catch { return null; } } private static bool IsPathValid(object value) { var path = (string)value; return path.IndexOfAny(new[] { '.' }) == -1; } private static void OnMinMaxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((Trendline)d).OnMinMaxChanged(e); } private void OnMinMaxChanged(DependencyPropertyChangedEventArgs e) { if ((this.MaxValue - this.MinValue) < 1.53E-06) { this.translate.Y = -this.MaxValue - 0.5; // as if max/min = value +/- 0.5 this.scale.ScaleY = -1.0; } else { this.translate.Y = -this.MaxValue; this.scale.ScaleY = -1.0 / (this.MaxValue - this.MinValue); } } private static bool IsMinMaxValid(object value) { var num = (double)value; return !double.IsNaN(num) && !double.IsInfinity(num); } private void UpdateGeometry() { try { this.previousUpdateTime = DateTime.UtcNow; this.EndTime = this.previousUpdateTime; this.StartTime = this.previousUpdateTime - this.TimeSpan; var isEmpty = true; var minValue = double.MaxValue; var maxValue = double.MinValue; using (var context = this.Geometry.Open()) { if (this.ItemsSource == null || this.valueGetter == null || this.timeGetter == null) { return; } var startTicks = this.StartTime.Ticks; var endTicks = this.EndTime.Ticks; var rangeTicks = endTicks - startTicks; var startDrawingTicks = startTicks - (rangeTicks / 10); var endDrawingTicks = endTicks + (rangeTicks / 10); foreach (var item in this.ItemsSource) { if (item == null) { continue; } var time = this.timeGetter(item); var tick = time.Ticks; if (tick >= startDrawingTicks) { if (tick > endDrawingTicks) { break; } var value = this.valueGetter(item).ToDouble(null); if (isEmpty) { context.BeginFigure(new Point((double)(tick - startTicks) / rangeTicks, value), false, false); isEmpty = false; } else { context.LineTo(new Point((double)(tick - startTicks) / rangeTicks, value), true, true); } if (maxValue < value) { maxValue = value; } if (minValue > value) { minValue = value; } } } } if (this.AutoRange && !isEmpty) { this.MaxValue = maxValue; this.MinValue = minValue; } } catch { } } private void OnLoaded(object sender, RoutedEventArgs routedEventArgs) { if (!this.isAnimationRunning && !DesignerProperties.GetIsInDesignMode(this)) { this.isAnimationRunning = true; CompositionTarget.Rendering += this.OnRendering; } } private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs) { if (this.isAnimationRunning) { this.isAnimationRunning = false; CompositionTarget.Rendering -= this.OnRendering; } } private void OnRendering(object sender, EventArgs eventArgs) { if (DateTime.UtcNow.Subtract(this.previousUpdateTime) > this.frameDuration) { this.UpdateGeometry(); } } public override void OnApplyTemplate() { base.OnApplyTemplate(); this.chartArea = (this.GetTemplateChild("PART_ChartArea") as FrameworkElement) ?? this; this.chartArea.SizeChanged += this.OnSizeChanged; } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { this.renderScale.ScaleX = Math.Max(e.NewSize.Width - this.StrokeThickness, 0.0); this.renderScale.ScaleY = Math.Max(e.NewSize.Height - this.StrokeThickness, 0.0); this.renderTranslate.X = this.StrokeThickness / 2.0; this.renderTranslate.Y = this.StrokeThickness / 2.0; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Editor; using Microsoft.PythonTools.Editor.Core; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Navigation; using Microsoft.PythonTools.Refactoring; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Navigation; using IServiceProvider = System.IServiceProvider; using Task = System.Threading.Tasks.Task; namespace Microsoft.PythonTools.Language { /// <summary> /// IOleCommandTarget implementation for interacting with various editor commands. This enables /// wiring up most of our features to the VisualStudio editor. We currently support: /// Goto Definition /// Find All References /// Show Member List /// Complete Word /// Enable/Disable Outlining /// Comment/Uncomment block /// /// We also support Python specific commands via this class. Currently these commands are /// added by updating our CommandTable class to contain a new command. These commands also need /// to be registered in our .vsct file so that VS knows about them. /// </summary> internal sealed class EditFilter : IOleCommandTarget { private readonly PythonEditorServices _editorServices; private readonly IVsTextView _vsTextView; private readonly ITextView _textView; private readonly IOleCommandTarget _next; private EditFilter( PythonEditorServices editorServices, IVsTextView vsTextView, ITextView textView, IOleCommandTarget next ) { _editorServices = editorServices; _vsTextView = vsTextView; _textView = textView; _next = next; BraceMatcher.WatchBraceHighlights(_editorServices, textView); if (_next == null && vsTextView != null) { ErrorHandler.ThrowOnFailure(vsTextView.AddCommandFilter(this, out _next)); } } public static EditFilter GetOrCreate( PythonEditorServices editorServices, ITextView textView, IOleCommandTarget next = null ) { var vsTextView = editorServices.EditorAdaptersFactoryService.GetViewAdapter(textView); return textView.Properties.GetOrCreateSingletonProperty(() => new EditFilter( editorServices, vsTextView, textView, next )); } public static EditFilter GetOrCreate( PythonEditorServices editorServices, IVsTextView vsTextView, IOleCommandTarget next = null ) { var textView = editorServices.EditorAdaptersFactoryService.GetWpfTextView(vsTextView); return textView.Properties.GetOrCreateSingletonProperty(() => new EditFilter( editorServices, vsTextView, textView, next )); } /// <summary> /// Implements Goto Definition. Called when the user selects Goto Definition from the /// context menu or hits the hotkey associated with Goto Definition. /// /// If there is 1 and only one definition immediately navigates to it. If there are /// no references displays a dialog box to the user. Otherwise it opens the find /// symbols dialog with the list of results. /// </summary> private async void GotoDefinition() { UpdateStatusForIncompleteAnalysis(); var caret = _textView.GetPythonCaret(); var analysis = _textView.GetAnalysisAtCaret(_editorServices.Site); if (analysis != null && caret != null) { var defs = await analysis.Analyzer.AnalyzeExpressionAsync(analysis, caret.Value, ExpressionAtPointPurpose.FindDefinition); if (defs == null) { return; } Dictionary<LocationInfo, SimpleLocationInfo> references, definitions, values; GetDefsRefsAndValues(analysis.Analyzer, _editorServices.Site, defs.Expression, defs.Variables, out definitions, out references, out values); if ((values.Count + definitions.Count) == 1) { if (values.Count != 0) { foreach (var location in values.Keys) { GotoLocation(location); break; } } else { foreach (var location in definitions.Keys) { GotoLocation(location); break; } } } else if (values.Count + definitions.Count == 0) { if (String.IsNullOrWhiteSpace(defs.Expression)) { MessageBox.Show(Strings.CannotGoToDefn, Strings.ProductTitle); } else { MessageBox.Show(Strings.CannotGoToDefn_Name.FormatUI(defs.Expression), Strings.ProductTitle); } } else if (definitions.Count == 0) { ShowFindSymbolsDialog(defs.Expression, new SymbolList(Strings.SymbolListValues, StandardGlyphGroup.GlyphForwardType, values.Values)); } else if (values.Count == 0) { ShowFindSymbolsDialog(defs.Expression, new SymbolList(Strings.SymbolListDefinitions, StandardGlyphGroup.GlyphLibrary, definitions.Values)); } else { ShowFindSymbolsDialog(defs.Expression, new LocationCategory( new SymbolList(Strings.SymbolListDefinitions, StandardGlyphGroup.GlyphLibrary, definitions.Values), new SymbolList(Strings.SymbolListValues, StandardGlyphGroup.GlyphForwardType, values.Values) ) ); } } } /// <summary> /// Moves the caret to the specified location, staying in the current text view /// if possible. /// /// https://pytools.codeplex.com/workitem/1649 /// </summary> private void GotoLocation(LocationInfo location) { Debug.Assert(location != null); Debug.Assert(location.StartLine > 0); Debug.Assert(location.StartColumn > 0); if (PathUtils.IsSamePath(location.FilePath, _textView.GetFilePath())) { var viewAdapter = _vsTextView; viewAdapter.SetCaretPos(location.StartLine - 1, location.StartColumn - 1); viewAdapter.CenterLines(location.StartLine - 1, 1); } else { PythonToolsPackage.NavigateTo( _editorServices.Site, location.FilePath, Guid.Empty, location.StartLine - 1, location.StartColumn - 1 ); } } /// <summary> /// Implements Find All References. Called when the user selects Find All References from /// the context menu or hits the hotkey associated with find all references. /// /// Always opens the Find Symbol Results box to display the results. /// </summary> private async void FindAllReferences() { UpdateStatusForIncompleteAnalysis(); var caret = _textView.GetPythonCaret(); var analysis = _textView.GetAnalysisAtCaret(_editorServices.Site); if (analysis != null && caret != null) { var references = await analysis.Analyzer.AnalyzeExpressionAsync(analysis, caret.Value, ExpressionAtPointPurpose.FindDefinition); if (references == null) { return; } var locations = GetFindRefLocations(analysis.Analyzer, _editorServices.Site, references.Expression, references.Variables); ShowFindSymbolsDialog(references.Expression, locations); } } internal static LocationCategory GetFindRefLocations(VsProjectAnalyzer analyzer, IServiceProvider serviceProvider, string expr, IReadOnlyList<AnalysisVariable> analysis) { Dictionary<LocationInfo, SimpleLocationInfo> references, definitions, values; GetDefsRefsAndValues(analyzer, serviceProvider, expr, analysis, out definitions, out references, out values); var locations = new LocationCategory( new SymbolList(Strings.SymbolListDefinitions, StandardGlyphGroup.GlyphLibrary, definitions.Values), new SymbolList(Strings.SymbolListValues, StandardGlyphGroup.GlyphForwardType, values.Values), new SymbolList(Strings.SymbolListReferences, StandardGlyphGroup.GlyphReference, references.Values) ); return locations; } private static void GetDefsRefsAndValues(VsProjectAnalyzer analyzer, IServiceProvider serviceProvider, string expr, IReadOnlyList<AnalysisVariable> variables, out Dictionary<LocationInfo, SimpleLocationInfo> definitions, out Dictionary<LocationInfo, SimpleLocationInfo> references, out Dictionary<LocationInfo, SimpleLocationInfo> values) { references = new Dictionary<LocationInfo, SimpleLocationInfo>(); definitions = new Dictionary<LocationInfo, SimpleLocationInfo>(); values = new Dictionary<LocationInfo, SimpleLocationInfo>(); if (variables == null) { Debug.Fail("unexpected null variables"); return; } foreach (var v in variables) { if (v?.Location == null) { Debug.Fail("unexpected null variable or location"); continue; } if (v.Location.FilePath == null) { // ignore references in the REPL continue; } switch (v.Type) { case VariableType.Definition: values.Remove(v.Location); definitions[v.Location] = new SimpleLocationInfo(analyzer, serviceProvider, expr, v.Location, StandardGlyphGroup.GlyphGroupField); break; case VariableType.Reference: references[v.Location] = new SimpleLocationInfo(analyzer, serviceProvider, expr, v.Location, StandardGlyphGroup.GlyphGroupField); break; case VariableType.Value: if (!definitions.ContainsKey(v.Location)) { values[v.Location] = new SimpleLocationInfo(analyzer, serviceProvider, expr, v.Location, StandardGlyphGroup.GlyphGroupField); } break; } } } /// <summary> /// Opens the find symbols dialog with a list of results. This is done by requesting /// that VS does a search against our library GUID. Our library then responds to /// that request by extracting the prvoided symbol list out and using that for the /// search results. /// </summary> private void ShowFindSymbolsDialog(string expr, IVsNavInfo symbols) { // ensure our library is loaded so find all references will go to our library _editorServices.Site.GetService(typeof(IPythonLibraryManager)); if (!string.IsNullOrEmpty(expr)) { var findSym = (IVsFindSymbol)_editorServices.Site.GetService(typeof(SVsObjectSearch)); VSOBSEARCHCRITERIA2 searchCriteria = new VSOBSEARCHCRITERIA2(); searchCriteria.eSrchType = VSOBSEARCHTYPE.SO_ENTIREWORD; searchCriteria.pIVsNavInfo = symbols; searchCriteria.grfOptions = (uint)_VSOBSEARCHOPTIONS2.VSOBSO_LISTREFERENCES; searchCriteria.szName = expr; Guid guid = Guid.Empty; // new Guid("{a5a527ea-cf0a-4abf-b501-eafe6b3ba5c6}") ErrorHandler.ThrowOnFailure(findSym.DoSearch(new Guid(CommonConstants.LibraryGuid), new VSOBSEARCHCRITERIA2[] { searchCriteria })); } else { var statusBar = (IVsStatusbar)_editorServices.Site.GetService(typeof(SVsStatusbar)); statusBar.SetText(Strings.FindReferencesCaretMustBeOnValidExpression); } } internal class LocationCategory : SimpleObjectList<SymbolList>, IVsNavInfo, ICustomSearchListProvider { internal LocationCategory(params SymbolList[] locations) { foreach (var location in locations) { if (location.Children.Count > 0) { Children.Add(location); } } } public override uint CategoryField(LIB_CATEGORY lIB_CATEGORY) { return (uint)(_LIB_LISTTYPE.LLT_HIERARCHY | _LIB_LISTTYPE.LLT_MEMBERS | _LIB_LISTTYPE.LLT_PACKAGE); } #region IVsNavInfo Members public int EnumCanonicalNodes(out IVsEnumNavInfoNodes ppEnum) { ppEnum = new NodeEnumerator<SymbolList>(Children); return VSConstants.S_OK; } public int EnumPresentationNodes(uint dwFlags, out IVsEnumNavInfoNodes ppEnum) { ppEnum = new NodeEnumerator<SymbolList>(Children); return VSConstants.S_OK; } public int GetLibGuid(out Guid pGuid) { pGuid = Guid.Empty; return VSConstants.S_OK; } public int GetSymbolType(out uint pdwType) { pdwType = (uint)_LIB_LISTTYPE2.LLT_MEMBERHIERARCHY; return VSConstants.S_OK; } #endregion #region ICustomSearchListProvider Members public IVsSimpleObjectList2 GetSearchList() { return this; } #endregion } internal class SimpleLocationInfo : SimpleObject, IVsNavInfoNode { private readonly IServiceProvider _serviceProvider; private readonly LocationInfo _locationInfo; private readonly StandardGlyphGroup _glyphType; private readonly string _pathText, _lineText; public SimpleLocationInfo(VsProjectAnalyzer analyzer, IServiceProvider serviceProvider, string searchText, LocationInfo locInfo, StandardGlyphGroup glyphType) { _serviceProvider = serviceProvider; _locationInfo = locInfo; _glyphType = glyphType; _pathText = GetSearchDisplayText(); AnalysisEntry entry = analyzer.GetAnalysisEntryFromPath(_locationInfo.FilePath); if (entry != null) { _lineText = entry.GetLine(_locationInfo.StartLine) ?? ""; } else { _lineText = ""; } } public override string Name { get { return _locationInfo.FilePath; } } public override string GetTextRepresentation(VSTREETEXTOPTIONS options) { if (options == VSTREETEXTOPTIONS.TTO_DEFAULT) { return _pathText + _lineText.Trim(); } return String.Empty; } private string GetSearchDisplayText() { return $"{_locationInfo.FilePath} - {_locationInfo.Span.Start}: "; } public override string UniqueName { get { return _locationInfo.FilePath; } } public override bool CanGoToSource { get { return true; } } public override VSTREEDISPLAYDATA DisplayData { get { var res = new VSTREEDISPLAYDATA(); res.Image = res.SelectedImage = (ushort)_glyphType; res.State = (uint)_VSTREEDISPLAYSTATE.TDS_FORCESELECT; // This code highlights the text but it gets the wrong region. This should be re-enabled // and highlight the correct region. //res.ForceSelectStart = (ushort)(_pathText.Length + _locationInfo.Column - 1); //res.ForceSelectLength = (ushort)_locationInfo.Length; return res; } } public override void GotoSource(VSOBJGOTOSRCTYPE SrcType) { PythonToolsPackage.NavigateTo( _serviceProvider, _locationInfo.FilePath, Guid.Empty, _locationInfo.StartLine - 1, _locationInfo.StartColumn - 1 ); } #region IVsNavInfoNode Members public int get_Name(out string pbstrName) { pbstrName = _locationInfo.FilePath; return VSConstants.S_OK; } public int get_Type(out uint pllt) { pllt = 16; // (uint)_LIB_LISTTYPE2.LLT_MEMBERHIERARCHY; return VSConstants.S_OK; } #endregion } internal class SymbolList : SimpleObjectList<SimpleLocationInfo>, IVsNavInfo, IVsNavInfoNode, ICustomSearchListProvider, ISimpleObject { private readonly string _name; private readonly StandardGlyphGroup _glyphGroup; internal SymbolList(string description, StandardGlyphGroup glyphGroup, IEnumerable<SimpleLocationInfo> locations) { _name = description; _glyphGroup = glyphGroup; foreach (var location in locations) { Children.Add(location); } } public override uint CategoryField(LIB_CATEGORY lIB_CATEGORY) { return (uint)(_LIB_LISTTYPE.LLT_MEMBERS | _LIB_LISTTYPE.LLT_PACKAGE); } #region ISimpleObject Members public bool CanDelete { get { return false; } } public bool CanGoToSource { get { return false; } } public bool CanRename { get { return false; } } public string Name { get { return _name; } } public string UniqueName { get { return _name; } } public string FullName { get { return _name; } } public string GetTextRepresentation(VSTREETEXTOPTIONS options) { switch(options) { case VSTREETEXTOPTIONS.TTO_DISPLAYTEXT: return _name; } return null; } public string TooltipText { get { return null; } } public object BrowseObject { get { return null; } } public System.ComponentModel.Design.CommandID ContextMenuID { get { return null; } } public VSTREEDISPLAYDATA DisplayData { get { var res = new VSTREEDISPLAYDATA(); res.Image = res.SelectedImage = (ushort)_glyphGroup; return res; } } public void Delete() { } public void DoDragDrop(OleDataObject dataObject, uint grfKeyState, uint pdwEffect) { } public void Rename(string pszNewName, uint grfFlags) { } public void GotoSource(VSOBJGOTOSRCTYPE SrcType) { } public void SourceItems(out IVsHierarchy ppHier, out uint pItemid, out uint pcItems) { ppHier = null; pItemid = 0; pcItems = 0; } public uint EnumClipboardFormats(_VSOBJCFFLAGS _VSOBJCFFLAGS, VSOBJCLIPFORMAT[] rgcfFormats) { return VSConstants.S_OK; } public void FillDescription(_VSOBJDESCOPTIONS _VSOBJDESCOPTIONS, IVsObjectBrowserDescription3 pobDesc) { } public IVsSimpleObjectList2 FilterView(uint ListType) { return this; } #endregion #region IVsNavInfo Members public int EnumCanonicalNodes(out IVsEnumNavInfoNodes ppEnum) { ppEnum = new NodeEnumerator<SimpleLocationInfo>(Children); return VSConstants.S_OK; } public int EnumPresentationNodes(uint dwFlags, out IVsEnumNavInfoNodes ppEnum) { ppEnum = new NodeEnumerator<SimpleLocationInfo>(Children); return VSConstants.S_OK; } public int GetLibGuid(out Guid pGuid) { pGuid = Guid.Empty; return VSConstants.S_OK; } public int GetSymbolType(out uint pdwType) { pdwType = (uint)_LIB_LISTTYPE2.LLT_MEMBERHIERARCHY; return VSConstants.S_OK; } #endregion #region ICustomSearchListProvider Members public IVsSimpleObjectList2 GetSearchList() { return this; } #endregion #region IVsNavInfoNode Members public int get_Name(out string pbstrName) { pbstrName = "name"; return VSConstants.S_OK; } public int get_Type(out uint pllt) { pllt = 16; // (uint)_LIB_LISTTYPE2.LLT_MEMBERHIERARCHY; return VSConstants.S_OK; } #endregion } class NodeEnumerator<T> : IVsEnumNavInfoNodes where T : IVsNavInfoNode { private readonly IList<T> _locations; private IEnumerator<T> _locationEnum; public NodeEnumerator(IList<T> locations) { _locations = locations; Reset(); } #region IVsEnumNavInfoNodes Members public int Clone(out IVsEnumNavInfoNodes ppEnum) { ppEnum = new NodeEnumerator<T>(_locations); return VSConstants.S_OK; } public int Next(uint celt, IVsNavInfoNode[] rgelt, out uint pceltFetched) { pceltFetched = 0; while (celt-- != 0 && _locationEnum.MoveNext()) { rgelt[pceltFetched++] = _locationEnum.Current; } return VSConstants.S_OK; } public int Reset() { _locationEnum = _locations.GetEnumerator(); return VSConstants.S_OK; } public int Skip(uint celt) { while (celt-- != 0) { _locationEnum.MoveNext(); } return VSConstants.S_OK; } #endregion } private void UpdateStatusForIncompleteAnalysis() { var statusBar = (IVsStatusbar)_editorServices.Site.GetService(typeof(SVsStatusbar)); var analyzer = _textView.GetAnalyzerAtCaret(_editorServices.Site); if (analyzer != null && analyzer.IsAnalyzing) { statusBar.SetText(Strings.SourceAnalysisNotUpToDate); } } #region IOleCommandTarget Members /// <summary> /// Called from VS when we should handle a command or pass it on. /// </summary> public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { try { return ExecWorker(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } catch (Exception ex) { ex.ReportUnhandledException(_editorServices.Site, GetType()); return VSConstants.E_FAIL; } } private int ExecWorker(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { // preprocessing if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { switch ((VSConstants.VSStd97CmdID)nCmdID) { case VSConstants.VSStd97CmdID.Paste: if (!_editorServices.Python.AdvancedOptions.PasteRemovesReplPrompts) { // Not stripping prompts, so don't use our logic break; } var beforePaste = _textView.TextSnapshot; if (_editorServices.EditOperationsFactory.GetEditorOperations(_textView).Paste()) { var afterPaste = _textView.TextSnapshot; var um = _editorServices.UndoManagerFactory.GetTextBufferUndoManager(afterPaste.TextBuffer); using (var undo = um.TextBufferUndoHistory.CreateTransaction(Strings.RemoveReplPrompts)) { if (ReplPromptHelpers.RemovePastedPrompts(beforePaste, afterPaste)) { undo.Complete(); } } return VSConstants.S_OK; } break; case VSConstants.VSStd97CmdID.GotoDefn: GotoDefinition(); return VSConstants.S_OK; case VSConstants.VSStd97CmdID.FindReferences: FindAllReferences(); return VSConstants.S_OK; } } else if (pguidCmdGroup == VSConstants.VsStd12) { switch ((VSConstants.VSStd12CmdID)nCmdID) { case VSConstants.VSStd12CmdID.PeekDefinition: if (_editorServices.PeekBroker != null && !_textView.Roles.Contains(PredefinedTextViewRoles.EmbeddedPeekTextView) && !_textView.Roles.Contains(PredefinedTextViewRoles.CodeDefinitionView)) { _editorServices.PeekBroker.TriggerPeekSession(_textView, PredefinedPeekRelationships.Definitions.Name); return VSConstants.S_OK; } break; } } else if (pguidCmdGroup == CommonConstants.Std2KCmdGroupGuid) { SnapshotPoint? pyPoint; IntellisenseController controller; switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.RETURN: pyPoint = _textView.GetPythonCaret(); if (pyPoint != null) { // https://github.com/Microsoft/PTVS/issues/241 // If the current line is a full line comment and we // are splitting the text, automatically insert the // comment marker on the new line. var line = pyPoint.Value.GetContainingLine(); var lineText = pyPoint.Value.Snapshot.GetText(line.Start, pyPoint.Value - line.Start); int comment = lineText.IndexOf('#'); if (comment >= 0 && pyPoint.Value < line.End && line.Start + comment < pyPoint.Value && string.IsNullOrWhiteSpace(lineText.Remove(comment)) ) { int extra = lineText.Skip(comment + 1).TakeWhile(char.IsWhiteSpace).Count() + 1; using (var edit = line.Snapshot.TextBuffer.CreateEdit()) { edit.Insert( pyPoint.Value.Position, _textView.Options.GetNewLineCharacter() + lineText.Substring(0, comment + extra) ); edit.Apply(); } return VSConstants.S_OK; } } break; case VSConstants.VSStd2KCmdID.FORMATDOCUMENT: FormatDocumentAsync().DoNotWait(); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.FORMATSELECTION: FormatSelectionAsync().DoNotWait(); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.SHOWMEMBERLIST: case VSConstants.VSStd2KCmdID.COMPLETEWORD: if (_textView.Properties.TryGetProperty(typeof(IntellisenseController), out controller)) { controller.TriggerCompletionSession( (VSConstants.VSStd2KCmdID)nCmdID == VSConstants.VSStd2KCmdID.COMPLETEWORD, '\0', true ).DoNotWait(); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.QUICKINFO: if (_textView.Properties.TryGetProperty(typeof(IntellisenseController), out controller)) { controller.TriggerQuickInfoAsync().DoNotWait(); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.PARAMINFO: if (_textView.Properties.TryGetProperty(typeof(IntellisenseController), out controller)) { controller.TriggerSignatureHelp(); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.OUTLN_STOP_HIDING_ALL: _textView.GetOutliningTagger()?.Disable(_textView.TextSnapshot); // let VS get the event as well break; case VSConstants.VSStd2KCmdID.OUTLN_START_AUTOHIDING: _textView.GetOutliningTagger()?.Enable(_textView.TextSnapshot); // let VS get the event as well break; case VSConstants.VSStd2KCmdID.COMMENT_BLOCK: case VSConstants.VSStd2KCmdID.COMMENTBLOCK: if (_textView.CommentOrUncommentBlock(comment: true)) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.UNCOMMENT_BLOCK: case VSConstants.VSStd2KCmdID.UNCOMMENTBLOCK: if (_textView.CommentOrUncommentBlock(comment: false)) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.EXTRACTMETHOD: ExtractMethod(); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.RENAME: RefactorRename(); return VSConstants.S_OK; } } else if (pguidCmdGroup == GuidList.guidPythonToolsCmdSet) { switch (nCmdID) { case PkgCmdIDList.cmdidRefactorRenameIntegratedShell: RefactorRename(); return VSConstants.S_OK; case PkgCmdIDList.cmdidExtractMethodIntegratedShell: ExtractMethod(); return VSConstants.S_OK; case CommonConstants.StartDebuggingCmdId: case CommonConstants.StartWithoutDebuggingCmdId: PythonToolsPackage.LaunchFile(_editorServices.Site, _textView.GetFilePath(), nCmdID == CommonConstants.StartDebuggingCmdId, true); return VSConstants.S_OK; } } return _next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } private void ExtractMethod() { new Refactoring.MethodExtractor(_editorServices, _textView).ExtractMethod(new ExtractMethodUserInput(_editorServices.Site)).DoNotWait(); } internal async Task FormatDocumentAsync() { var pyPoint = _textView.GetPythonCaret(); if (pyPoint != null) { await FormatCodeAsync(new SnapshotSpan(pyPoint.Value.Snapshot, 0, pyPoint.Value.Snapshot.Length), false); } } internal async Task FormatSelectionAsync() { var snapshotSpan = _textView.Selection.StreamSelectionSpan.SnapshotSpan; foreach (var span in _textView.BufferGraph.MapDownToFirstMatch(snapshotSpan, SpanTrackingMode.EdgeInclusive, EditorExtensions.IsPythonContent)) { await FormatCodeAsync(span, true); } } private async Task FormatCodeAsync(SnapshotSpan span, bool selectResult) { var entry = span.Snapshot.TextBuffer.TryGetAnalysisEntry(); if (entry == null) { return; } var options = _editorServices.Python.GetCodeFormattingOptions(); options.NewLineFormat = _textView.Options.GetNewLineCharacter(); await entry.Analyzer.FormatCodeAsync(span, _textView, options, selectResult); } internal void RefactorRename() { var analyzer = _textView.GetAnalyzerAtCaret(_editorServices.Site); if (analyzer.IsAnalyzing) { var dialog = new WaitForCompleteAnalysisDialog(analyzer); var res = dialog.ShowModal(); if (res != true) { // user cancelled dialog before analysis completed... return; } } new VariableRenamer(_textView, _editorServices.Site).RenameVariable( new RenameVariableUserInput(_editorServices.Site), (IVsPreviewChangesService)_editorServices.Site.GetService(typeof(SVsPreviewChangesService)) ).DoNotWait(); } private const uint CommandDisabledAndHidden = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_DEFHIDEONCTXTMENU); /// <summary> /// Called from VS to see what commands we support. /// </summary> public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { for (int i = 0; i < cCmds; i++) { switch ((VSConstants.VSStd97CmdID)prgCmds[i].cmdID) { case VSConstants.VSStd97CmdID.GotoDefn: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); return VSConstants.S_OK; case VSConstants.VSStd97CmdID.FindReferences: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == VSConstants.VsStd12) { for (int i = 0; i < cCmds; i++) { switch ((VSConstants.VSStd12CmdID)prgCmds[i].cmdID) { case VSConstants.VSStd12CmdID.PeekDefinition: // Since our provider supports standalone files, // the predicate isn't invoked but it needs to be non null. var canPeek = _editorServices.PeekBroker?.CanTriggerPeekSession( _textView, PredefinedPeekRelationships.Definitions.Name, isStandaloneFilePredicate: (string filename) => false ); prgCmds[i].cmdf = (uint)OLECMDF.OLECMDF_SUPPORTED; prgCmds[0].cmdf |= (uint)(canPeek == true ? OLECMDF.OLECMDF_ENABLED : OLECMDF.OLECMDF_INVISIBLE); return VSConstants.S_OK; } } } else if (pguidCmdGroup == GuidList.guidPythonToolsCmdSet) { for (int i = 0; i < cCmds; i++) { switch (prgCmds[i].cmdID) { case PkgCmdIDList.cmdidRefactorRenameIntegratedShell: // C# provides the refactor context menu for the main VS command outside // of the integrated shell. In the integrated shell we provide our own // command for it so these still show up. prgCmds[i].cmdf = CommandDisabledAndHidden; return VSConstants.S_OK; case PkgCmdIDList.cmdidExtractMethodIntegratedShell: // C# provides the refactor context menu for the main VS command outside // of the integrated shell. In the integrated shell we provide our own // command for it so these still show up. prgCmds[i].cmdf = CommandDisabledAndHidden; return VSConstants.S_OK; case CommonConstants.StartDebuggingCmdId: case CommonConstants.StartWithoutDebuggingCmdId: // Don't enable the command when the file is null or doesn't exist, // which can happen in the diff window. if (File.Exists(_textView.GetFilePath())) { prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); } else { prgCmds[i].cmdf = CommandDisabledAndHidden; } return VSConstants.S_OK; default: lock (CommonPackage.CommandsLock) { foreach (var command in CommonPackage.Commands.Keys) { if (command.CommandId == prgCmds[i].cmdID) { int? res = command.EditFilterQueryStatus(ref prgCmds[i], pCmdText); if (res != null) { return res.Value; } } } } break; } } } else if (pguidCmdGroup == CommonConstants.Std2KCmdGroupGuid) { for (int i = 0; i < cCmds; i++) { switch ((VSConstants.VSStd2KCmdID)prgCmds[i].cmdID) { case VSConstants.VSStd2KCmdID.FORMATDOCUMENT: case VSConstants.VSStd2KCmdID.FORMATSELECTION: case VSConstants.VSStd2KCmdID.SHOWMEMBERLIST: case VSConstants.VSStd2KCmdID.COMPLETEWORD: case VSConstants.VSStd2KCmdID.QUICKINFO: case VSConstants.VSStd2KCmdID.PARAMINFO: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.OUTLN_STOP_HIDING_ALL: if (_textView.GetOutliningTagger()?.Enabled == true) { prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.OUTLN_START_AUTOHIDING: if (_textView.GetOutliningTagger()?.Enabled == false) { prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.COMMENT_BLOCK: case VSConstants.VSStd2KCmdID.COMMENTBLOCK: case VSConstants.VSStd2KCmdID.UNCOMMENT_BLOCK: case VSConstants.VSStd2KCmdID.UNCOMMENTBLOCK: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.EXTRACTMETHOD: QueryStatusExtractMethod(prgCmds, i); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.RENAME: QueryStatusRename(prgCmds, i); return VSConstants.S_OK; } } } return _next.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } private void QueryStatusExtractMethod(OLECMD[] prgCmds, int i) { switch (Refactoring.MethodExtractor.CanExtract(_textView)) { case true: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); break; case false: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED); break; case null: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE); break; } } private void QueryStatusRename(OLECMD[] prgCmds, int i) { var analyzer = _textView.GetAnalyzerAtCaret(_editorServices.Site); if (analyzer != null && _textView.GetPythonBufferAtCaret() != null) { prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); } else { prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE); } } #endregion internal void DoIdle(IOleComponentManager compMgr) { } } }
// // 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.Azure.Commands.Compute.Automation { public abstract class ComputeAutomationBaseCmdlet : Microsoft.Azure.Commands.Compute.ComputeClientBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ComputeAutomationAutoMapperProfile.Initialize(); } protected static PSArgument[] ConvertFromObjectsToArguments(string[] names, object[] objects) { var arguments = new PSArgument[objects.Length]; for (int index = 0; index < objects.Length; index++) { arguments[index] = new PSArgument { Name = names[index], Type = objects[index].GetType(), Value = objects[index] }; } return arguments; } protected static object[] ConvertFromArgumentsToObjects(object[] arguments) { if (arguments == null) { return null; } var objects = new object[arguments.Length]; for (int index = 0; index < arguments.Length; index++) { if (arguments[index] is PSArgument) { objects[index] = ((PSArgument)arguments[index]).Value; } else { objects[index] = arguments[index]; } } return objects; } public IAvailabilitySetsOperations AvailabilitySetsClient { get { return ComputeClient.ComputeManagementClient.AvailabilitySets; } } public IContainerServicesOperations ContainerServicesClient { get { return ComputeClient.ComputeManagementClient.ContainerServices; } } public IDisksOperations DisksClient { get { return ComputeClient.ComputeManagementClient.Disks; } } public IImagesOperations ImagesClient { get { return ComputeClient.ComputeManagementClient.Images; } } public ISnapshotsOperations SnapshotsClient { get { return ComputeClient.ComputeManagementClient.Snapshots; } } public IVirtualMachineScaleSetsOperations VirtualMachineScaleSetsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSets; } } public IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSetVMs; } } public IVirtualMachinesOperations VirtualMachinesClient { get { return ComputeClient.ComputeManagementClient.VirtualMachines; } } public static string FormatObject(Object obj) { var objType = obj.GetType(); System.Reflection.PropertyInfo[] pros = objType.GetProperties(); string result = "\n"; var resultTuples = new List<Tuple<string, string, int>>(); var totalTab = GetTabLength(obj, 0, 0, resultTuples) + 1; foreach (var t in resultTuples) { string preTab = new string(' ', t.Item3 * 2); string postTab = new string(' ', totalTab - t.Item3 * 2 - t.Item1.Length); result += preTab + t.Item1 + postTab + ": " + t.Item2 + "\n"; } return result; } private static int GetTabLength(Object obj, int max, int depth, List<Tuple<string, string, int>> tupleList) { var objType = obj.GetType(); var propertySet = new List<PropertyInfo>(); if (objType.BaseType != null) { foreach (var property in objType.BaseType.GetProperties()) { propertySet.Add(property); } } foreach (var property in objType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)) { propertySet.Add(property); } foreach (var property in propertySet) { Object childObject = property.GetValue(obj, null); var isJObject = childObject as Newtonsoft.Json.Linq.JObject; if (isJObject != null) { var objStringValue = Newtonsoft.Json.JsonConvert.SerializeObject(childObject); int i = objStringValue.IndexOf("xmlCfg"); if (i >= 0) { var xmlCfgString = objStringValue.Substring(i + 7); int start = xmlCfgString.IndexOf('"'); int end = xmlCfgString.IndexOf('"', start + 1); xmlCfgString = xmlCfgString.Substring(start + 1, end - start - 1); objStringValue = objStringValue.Replace(xmlCfgString, "..."); } tupleList.Add(MakeTuple(property.Name, objStringValue, depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else { var elem = childObject as IList; if (elem != null) { if (elem.Count != 0) { max = Math.Max(max, depth * 2 + property.Name.Length + 4); for (int i = 0; i < elem.Count; i++) { Type propType = elem[i].GetType(); if (propType.IsSerializable) { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", elem[i].ToString(), depth)); } else { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", "", depth)); max = Math.Max(max, GetTabLength((Object)elem[i], max, depth + 1, tupleList)); } } } } else { if (property.PropertyType.IsSerializable) { if (childObject != null) { tupleList.Add(MakeTuple(property.Name, childObject.ToString(), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } } else { var isDictionary = childObject as IDictionary; if (isDictionary != null) { tupleList.Add(MakeTuple(property.Name, Newtonsoft.Json.JsonConvert.SerializeObject(childObject), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else if (childObject != null) { tupleList.Add(MakeTuple(property.Name, "", depth)); max = Math.Max(max, GetTabLength(childObject, max, depth + 1, tupleList)); } } } } } return max; } private static Tuple<string, string, int> MakeTuple(string key, string value, int depth) { return new Tuple<string, string, int>(key, value, depth); } } }
// 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: This class will encapsulate a short and provide an ** Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Int16 : IComparable, IFormattable, IConvertible , IComparable<Int16>, IEquatable<Int16> { internal short m_value; public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked((short)0x8000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int16, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Int16) { return m_value - ((Int16)value).m_value; } throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt16")); } public int CompareTo(Int16 value) { return m_value - value; } public override bool Equals(Object obj) { if (!(obj is Int16)) { return false; } return m_value == ((Int16)obj).m_value; } [System.Runtime.Versioning.NonVersionable] public bool Equals(Int16 obj) { return m_value == obj; } // Returns a HashCode for the Int16 public override int GetHashCode() { return ((int)((ushort)m_value) | (((int)m_value) << 16)); } [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return ToString(format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return ToString(format, NumberFormatInfo.GetInstance(provider)); } [System.Security.SecuritySafeCritical] // auto-generated private String ToString(String format, NumberFormatInfo info) { Contract.Ensures(Contract.Result<String>() != null); if (m_value<0 && format!=null && format.Length>0 && (format[0]=='X' || format[0]=='x')) { uint temp = (uint)(m_value & 0x0000FFFF); return Number.FormatUInt32(temp,format, info); } return Number.FormatInt32(m_value, format, info); } public static short Parse(String s) { return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static short Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.CurrentInfo); } public static short Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static short Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static short Parse(String s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch(OverflowException e) { throw new OverflowException(Environment.GetResourceString("Overflow_Int16"), e); } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || (i > UInt16.MaxValue)) { throw new OverflowException(Environment.GetResourceString("Overflow_Int16")); } return (short)i; } if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Int16")); return (short)i; } public static bool TryParse(String s, out Int16 result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int16 result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out Int16 result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || i > UInt16.MaxValue) { return false; } result = (Int16) i; return true; } if (i < MinValue || i > MaxValue) { return false; } result = (Int16) i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int16; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return m_value; } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int16", "DateTime")); } /// <internalonly/> 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. namespace System.Xml.Serialization { using System.Reflection; using System.Collections; using System.IO; using System.Xml.Schema; using System; using System.Text; using System.Threading; using System.Globalization; using System.Security; using System.Diagnostics; using System.CodeDom.Compiler; using System.Collections.Generic; using Hashtable = System.Collections.IDictionary; using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants; using XmlDeserializationEvents = System.Object; ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract class XmlSerializerImplementation { public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } } public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } } public virtual IDictionary ReadMethods { get { throw new NotSupportedException(); } } public virtual IDictionary WriteMethods { get { throw new NotSupportedException(); } } public virtual IDictionary TypedSerializers { get { throw new NotSupportedException(); } } public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); } public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSerializer { private TempAssembly _tempAssembly; private bool _typedSerializer; private Type _primitiveType; private XmlMapping _mapping; private XmlDeserializationEvents _events = new XmlDeserializationEvents(); #if NET_NATIVE public string DefaultNamespace = null; private XmlSerializer innerSerializer; private readonly Type rootType; #endif private static TempAssemblyCache s_cache = new TempAssemblyCache(); private static volatile XmlSerializerNamespaces s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get { if (s_defaultNamespaces == null) { XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.AddInternal("xsi", XmlSchema.InstanceNamespace); nss.AddInternal("xsd", XmlSchema.Namespace); if (s_defaultNamespaces == null) { s_defaultNamespaces = nss; } } return s_defaultNamespaces; } } private static readonly Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>>(); ///<internalonly/> protected XmlSerializer() { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null, null) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null, null) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if !NET_NATIVE public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null, null) #else public XmlSerializer(Type type, Type[] extraTypes) : this(type) #endif // NET_NATIVE { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null, null) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(XmlTypeMapping xmlTypeMapping) { _tempAssembly = GenerateTempAssembly(xmlTypeMapping); _mapping = xmlTypeMapping; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type) : this(type, (string)null) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, string defaultNamespace) { if (type == null) throw new ArgumentNullException(nameof(type)); #if NET_NATIVE this.DefaultNamespace = defaultNamespace; rootType = type; #endif _mapping = GetKnownMapping(type, defaultNamespace); if (_mapping != null) { _primitiveType = type; return; } #if !NET_NATIVE _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { { // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } #else XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly(); if (contract != null) { this.innerSerializer = contract.GetSerializer(type); } #endif } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence) { #if NET_NATIVE throw new PlatformNotSupportedException(); #else if (type == null) throw new ArgumentNullException(nameof(type)); XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) importer.IncludeType(extraTypes[i]); } _mapping = importer.ImportTypeMapping(type, root, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); #endif } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace) { if (xmlMapping == null) throw new ArgumentNullException(nameof(xmlMapping)); return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, null, null); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o) { Serialize(textWriter, o, null); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings); Serialize(xmlWriter, o, namespaces); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o) { Serialize(stream, o, null); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; XmlWriter xmlWriter = XmlWriter.Create(stream, settings); Serialize(xmlWriter, o, namespaces); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o) { Serialize(xmlWriter, o, null); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { Serialize(xmlWriter, o, namespaces, null); } internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { try { if (_primitiveType != null) { SerializePrimitive(xmlWriter, o, namespaces); } #if !NET_NATIVE else if (_tempAssembly == null || _typedSerializer) { XmlSerializationWriter writer = CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly); try { Serialize(o, writer); } finally { writer.Dispose(); } } else _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); #else else { if (this.innerSerializer == null) { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name)); } if (!string.IsNullOrEmpty(this.DefaultNamespace)) { this.innerSerializer.DefaultNamespace = this.DefaultNamespace; } XmlSerializationWriter writer = this.innerSerializer.CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); try { this.innerSerializer.Serialize(o, writer); } finally { writer.Dispose(); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; throw new InvalidOperationException(SR.XmlGenError, e); } xmlWriter.Flush(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(Stream stream) { XmlReaderSettings settings = new XmlReaderSettings(); // WhitespaceHandling.Significant means that you only want events for *significant* whitespace // resulting from elements marked with xml:space="preserve". All other whitespace // (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not // reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true. settings.IgnoreWhitespace = true; settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */ // Normalization = true, that's the default for the readers created with XmlReader.Create(). // The XmlTextReader has as default a non-conformant mode according to the XML spec // which skips some of the required processing for new lines, hence the need for the explicit // Normalization = true. The mode is no-longer exposed on XmlReader.Create() XmlReader xmlReader = XmlReader.Create(stream, settings); return Deserialize(xmlReader, null); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(TextReader textReader) { XmlReaderSettings settings = new XmlReaderSettings(); // WhitespaceHandling.Significant means that you only want events for *significant* whitespace // resulting from elements marked with xml:space="preserve". All other whitespace // (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not // reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true. settings.IgnoreWhitespace = true; settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */ // Normalization = true, that's the default for the readers created with XmlReader.Create(). // The XmlTextReader has as default a non-conformant mode according to the XML spec // which skips some of the required processing for new lines, hence the need for the explicit // Normalization = true. The mode is no-longer exposed on XmlReader.Create() XmlReader xmlReader = XmlReader.Create(textReader, settings); return Deserialize(xmlReader, null); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } internal object Deserialize(XmlReader xmlReader, string encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } internal object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) { try { if (_primitiveType != null) { return DeserializePrimitive(xmlReader, events); } #if !NET_NATIVE else if (_tempAssembly == null || _typedSerializer) { XmlSerializationReader reader = CreateReader(); reader.Init(xmlReader, events, encodingStyle, _tempAssembly); try { return Deserialize(reader); } finally { reader.Dispose(); } } else { return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } #else else { if (this.innerSerializer == null) { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name)); } if (!string.IsNullOrEmpty(this.DefaultNamespace)) { this.innerSerializer.DefaultNamespace = this.DefaultNamespace; } XmlSerializationReader reader = this.innerSerializer.CreateReader(); reader.Init(xmlReader, encodingStyle); try { return this.innerSerializer.Deserialize(reader); } finally { reader.Dispose(); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; if (xmlReader is IXmlLineInfo) { IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e); } else { throw new InvalidOperationException(SR.XmlSerializeError, e); } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]; return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty); } #if !NET_NATIVE else if (_tempAssembly != null) { return _tempAssembly.CanRead(_mapping, xmlReader); } else { return false; } #else if (this.innerSerializer == null) { return false; } return this.innerSerializer.CanDeserialize(xmlReader); #endif } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings) { return FromMappings(mappings, (Type)null); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>(); XmlSerializerImplementation contract = null; TempAssembly tempAssembly = null; { if (XmlMapping.IsShallow(mappings)) { return Array.Empty<XmlSerializer>(); } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } return serializers; } else { // Use XmlSerializer cache when the type is not null. return GetSerializersFromCache(mappings, type); } } } } private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; Dictionary<XmlSerializerMappingKey, XmlSerializer> typedMappingTable = null; lock (s_xmlSerializerTable) { if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable)) { typedMappingTable = new Dictionary<XmlSerializerMappingKey, XmlSerializer>(); s_xmlSerializerTable[type] = typedMappingTable; } } lock (typedMappingTable) { var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>(); for (int i = 0; i < mappings.Length; i++) { XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]); if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i])) { pendingKeys.Add(mappingKey, i); } } if (pendingKeys.Count > 0) { XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count]; int index = 0; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { pendingMappings[index++] = mappingKey.Mapping; } TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null, null); XmlSerializerImplementation contract = tempAssembly.Contract; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = pendingKeys[mappingKey]; serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key]; serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping); typedMappingTable[mappingKey] = serializers[index]; } } } return serializers; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromTypes(Type[] types) { if (types == null) return Array.Empty<XmlSerializer>(); #if NET_NATIVE var serializers = new XmlSerializer[types.Length]; for (int i = 0; i < types.Length; i++) { serializers[i] = new XmlSerializer(types[i]); } return serializers; #else XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } return FromMappings(mappings); #endif } #if NET_NATIVE // this the global XML serializer contract introduced for multi-file private static XmlSerializerImplementation xmlSerializerContract; internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly() { // hack to pull in SetXmlSerializerContract which is only referenced from the // code injected by MainMethodInjector transform // there's probably also a way to do this via [DependencyReductionRoot], // but I can't get the compiler to find that... if (xmlSerializerContract == null) SetXmlSerializerContract(null); // this method body used to be rewritten by an IL transform // with the restructuring for multi-file, it has become a regular method return xmlSerializerContract; } public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation) { xmlSerializerContract = xmlSerializerImplementation; } #endif ///<internalonly/> protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); } ///<internalonly/> protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); } ///<internalonly/> protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); } ///<internalonly/> protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { _tempAssembly = tempAssembly; _mapping = mapping; _typedSerializer = true; } private static XmlTypeMapping GetKnownMapping(Type type, string ns) { if (ns != null && ns != string.Empty) return null; TypeDesc typeDesc; if (!TypeScope.PrimtiveTypes.TryGetValue(type, out typeDesc)) return null; ElementAccessor element = new ElementAccessor(); element.Name = typeDesc.DataType.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); switch (_primitiveType.GetTypeCode()) { case TypeCode.String: writer.Write_string(o); break; case TypeCode.Int32: writer.Write_int(o); break; case TypeCode.Boolean: writer.Write_boolean(o); break; case TypeCode.Int16: writer.Write_short(o); break; case TypeCode.Int64: writer.Write_long(o); break; case TypeCode.Single: writer.Write_float(o); break; case TypeCode.Double: writer.Write_double(o); break; case TypeCode.Decimal: writer.Write_decimal(o); break; case TypeCode.DateTime: writer.Write_dateTime(o); break; case TypeCode.Char: writer.Write_char(o); break; case TypeCode.Byte: writer.Write_unsignedByte(o); break; case TypeCode.SByte: writer.Write_byte(o); break; case TypeCode.UInt16: writer.Write_unsignedShort(o); break; case TypeCode.UInt32: writer.Write_unsignedInt(o); break; case TypeCode.UInt64: writer.Write_unsignedLong(o); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { writer.Write_QName(o); } else if (_primitiveType == typeof(byte[])) { writer.Write_base64Binary(o); } else if (_primitiveType == typeof(Guid)) { writer.Write_guid(o); } else if (_primitiveType == typeof(TimeSpan)) { writer.Write_TimeSpan(o); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } } private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); object o; switch (_primitiveType.GetTypeCode()) { case TypeCode.String: o = reader.Read_string(); break; case TypeCode.Int32: o = reader.Read_int(); break; case TypeCode.Boolean: o = reader.Read_boolean(); break; case TypeCode.Int16: o = reader.Read_short(); break; case TypeCode.Int64: o = reader.Read_long(); break; case TypeCode.Single: o = reader.Read_float(); break; case TypeCode.Double: o = reader.Read_double(); break; case TypeCode.Decimal: o = reader.Read_decimal(); break; case TypeCode.DateTime: o = reader.Read_dateTime(); break; case TypeCode.Char: o = reader.Read_char(); break; case TypeCode.Byte: o = reader.Read_unsignedByte(); break; case TypeCode.SByte: o = reader.Read_byte(); break; case TypeCode.UInt16: o = reader.Read_unsignedShort(); break; case TypeCode.UInt32: o = reader.Read_unsignedInt(); break; case TypeCode.UInt64: o = reader.Read_unsignedLong(); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { o = reader.Read_QName(); } else if (_primitiveType == typeof(byte[])) { o = reader.Read_base64Binary(); } else if (_primitiveType == typeof(Guid)) { o = reader.Read_guid(); } else if (_primitiveType == typeof(TimeSpan)) { o = reader.Read_TimeSpan(); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } return o; } private class XmlSerializerMappingKey { public XmlMapping Mapping; public XmlSerializerMappingKey(XmlMapping mapping) { this.Mapping = mapping; } public override bool Equals(object obj) { XmlSerializerMappingKey other = obj as XmlSerializerMappingKey; if (other == null) return false; if (this.Mapping.Key != other.Mapping.Key) return false; if (this.Mapping.ElementName != other.Mapping.ElementName) return false; if (this.Mapping.Namespace != other.Mapping.Namespace) return false; if (this.Mapping.IsSoap != other.Mapping.IsSoap) return false; return true; } public override int GetHashCode() { int hashCode = this.Mapping.IsSoap ? 0 : 1; if (this.Mapping.Key != null) hashCode ^= this.Mapping.Key.GetHashCode(); if (this.Mapping.ElementName != null) hashCode ^= this.Mapping.ElementName.GetHashCode(); if (this.Mapping.Namespace != null) hashCode ^= this.Mapping.Namespace.GetHashCode(); return hashCode; } } } }
#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.Globalization; using System.Runtime.InteropServices; namespace log4net.Util { /// <summary> /// Represents a native error code and message. /// </summary> /// <remarks> /// <para> /// Represents a Win32 platform native error. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class NativeError { #region Protected Instance Constructors /// <summary> /// Create an instance of the <see cref="NativeError" /> class with the specified /// error number and message. /// </summary> /// <param name="number">The number of the native error.</param> /// <param name="message">The message of the native error.</param> /// <remarks> /// <para> /// Create an instance of the <see cref="NativeError" /> class with the specified /// error number and message. /// </para> /// </remarks> private NativeError(int number, string message) { m_number = number; m_message = message; } #endregion // Protected Instance Constructors #region Public Instance Properties /// <summary> /// Gets the number of the native error. /// </summary> /// <value> /// The number of the native error. /// </value> /// <remarks> /// <para> /// Gets the number of the native error. /// </para> /// </remarks> public int Number { get { return m_number; } } /// <summary> /// Gets the message of the native error. /// </summary> /// <value> /// The message of the native error. /// </value> /// <remarks> /// <para> /// </para> /// Gets the message of the native error. /// </remarks> public string Message { get { return m_message; } } #endregion // Public Instance Properties #region Public Static Methods /// <summary> /// Create a new instance of the <see cref="NativeError" /> class for the last Windows error. /// </summary> /// <returns> /// An instance of the <see cref="NativeError" /> class for the last windows error. /// </returns> /// <remarks> /// <para> /// The message for the <see cref="Marshal.GetLastWin32Error"/> error number is lookup up using the /// native Win32 <c>FormatMessage</c> function. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #elif !NETCF [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)] #endif public static NativeError GetLastError() { int number = Marshal.GetLastWin32Error(); return new NativeError(number, NativeError.GetErrorMessage(number)); } /// <summary> /// Create a new instance of the <see cref="NativeError" /> class. /// </summary> /// <param name="number">the error number for the native error</param> /// <returns> /// An instance of the <see cref="NativeError" /> class for the specified /// error number. /// </returns> /// <remarks> /// <para> /// The message for the specified error number is lookup up using the /// native Win32 <c>FormatMessage</c> function. /// </para> /// </remarks> public static NativeError GetError(int number) { return new NativeError(number, NativeError.GetErrorMessage(number)); } /// <summary> /// Retrieves the message corresponding with a Win32 message identifier. /// </summary> /// <param name="messageId">Message identifier for the requested message.</param> /// <returns> /// The message corresponding with the specified message identifier. /// </returns> /// <remarks> /// <para> /// The message will be searched for in system message-table resource(s) /// using the native <c>FormatMessage</c> function. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #elif !NETCF [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] #endif public static string GetErrorMessage(int messageId) { // Win32 constants int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; // The function should allocates a buffer large enough to hold the formatted message int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; // Insert sequences in the message definition are to be ignored int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; // The function should search the system message-table resource(s) for the requested message string msgBuf = ""; // buffer that will receive the message IntPtr sourcePtr = new IntPtr(); // Location of the message definition, will be ignored IntPtr argumentsPtr = new IntPtr(); // Pointer to array of values to insert, not supported as it requires unsafe code if (messageId != 0) { // If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character int messageSize = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, ref sourcePtr, messageId, 0, ref msgBuf, 255, argumentsPtr); if (messageSize > 0) { // Remove trailing null-terminating characters (\r\n) from the message msgBuf = msgBuf.TrimEnd(new char[] {'\r', '\n'}); } else { // A message could not be located. msgBuf = null; } } else { msgBuf = null; } return msgBuf; } #endregion // Public Static Methods #region Override Object Implementation /// <summary> /// Return error information string /// </summary> /// <returns>error information string</returns> /// <remarks> /// <para> /// Return error information string /// </para> /// </remarks> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", this.Number) + (this.Message != null ? ": " + this.Message : ""); } #endregion // Override Object Implementation #region Stubs For Native Function Calls /// <summary> /// Formats a message string. /// </summary> /// <param name="dwFlags">Formatting options, and how to interpret the <paramref name="lpSource" /> parameter.</param> /// <param name="lpSource">Location of the message definition.</param> /// <param name="dwMessageId">Message identifier for the requested message.</param> /// <param name="dwLanguageId">Language identifier for the requested message.</param> /// <param name="lpBuffer">If <paramref name="dwFlags" /> includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the <c>LocalAlloc</c> function, and places the pointer to the buffer at the address specified in <paramref name="lpBuffer" />.</param> /// <param name="nSize">If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer.</param> /// <param name="Arguments">Pointer to an array of values that are used as insert values in the formatted message.</param> /// <remarks> /// <para> /// The function requires a message definition as input. The message definition can come from a /// buffer passed into the function. It can come from a message table resource in an /// already-loaded module. Or the caller can ask the function to search the system's message /// table resource(s) for the message definition. The function finds the message definition /// in a message table resource based on a message identifier and a language identifier. /// The function copies the formatted message text to an output buffer, processing any embedded /// insert sequences if requested. /// </para> /// <para> /// To prevent the usage of unsafe code, this stub does not support inserting values in the formatted message. /// </para> /// </remarks> /// <returns> /// <para> /// If the function succeeds, the return value is the number of TCHARs stored in the output /// buffer, excluding the terminating null character. /// </para> /// <para> /// If the function fails, the return value is zero. To get extended error information, /// call <see cref="M:Marshal.GetLastWin32Error()" />. /// </para> /// </returns> #if NETCF [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] #else [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] #endif private static extern int FormatMessage( int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr Arguments); #endregion // Stubs For Native Function Calls #region Private Instance Fields private int m_number; private string m_message; #endregion } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElastiCache.Model { /// <summary> /// Container for the parameters to the CreateReplicationGroup operation. /// The <i>CreateReplicationGroup</i> action creates a replication group. A replication /// group is a collection of cache clusters, where one of the cache clusters is a read/write /// primary and the others are read-only replicas. Writes to the primary are automatically /// propagated to the replicas. /// /// /// <para> /// When you create a replication group, you must specify an existing cache cluster that /// is in the primary role. When the replication group has been successfully created, /// you can add one or more read replica replicas to it, up to a total of five read replicas. /// </para> /// /// <para> /// <b>Note:</b> This action is valid only for Redis. /// </para> /// </summary> public partial class CreateReplicationGroupRequest : AmazonElastiCacheRequest { private bool? _automaticFailoverEnabled; private bool? _autoMinorVersionUpgrade; private string _cacheNodeType; private string _cacheParameterGroupName; private List<string> _cacheSecurityGroupNames = new List<string>(); private string _cacheSubnetGroupName; private string _engine; private string _engineVersion; private string _notificationTopicArn; private int? _numCacheClusters; private int? _port; private List<string> _preferredCacheClusterAZs = new List<string>(); private string _preferredMaintenanceWindow; private string _primaryClusterId; private string _replicationGroupDescription; private string _replicationGroupId; private List<string> _securityGroupIds = new List<string>(); private List<string> _snapshotArns = new List<string>(); private string _snapshotName; private int? _snapshotRetentionLimit; private string _snapshotWindow; private List<Tag> _tags = new List<Tag>(); /// <summary> /// Gets and sets the property AutomaticFailoverEnabled. /// <para> /// Specifies whether a read-only replica will be automatically promoted to read/write /// primary if the existing primary fails. /// </para> /// /// <para> /// If <code>true</code>, Multi-AZ is enabled for this replication group. If <code>false</code>, /// Multi-AZ is disabled for this replication group. /// </para> /// /// <para> /// Default: false /// </para> /// <note> /// <para> /// ElastiCache Multi-AZ replication groups is not supported on: /// </para> /// <ul> <li>Redis versions earlier than 2.8.6.</li> <li>T1 and T2 cache node types.</li> /// </ul> </note> /// </summary> public bool AutomaticFailoverEnabled { get { return this._automaticFailoverEnabled.GetValueOrDefault(); } set { this._automaticFailoverEnabled = value; } } // Check to see if AutomaticFailoverEnabled property is set internal bool IsSetAutomaticFailoverEnabled() { return this._automaticFailoverEnabled.HasValue; } /// <summary> /// Gets and sets the property AutoMinorVersionUpgrade. /// <para> /// This parameter is currently disabled. /// </para> /// </summary> public bool AutoMinorVersionUpgrade { get { return this._autoMinorVersionUpgrade.GetValueOrDefault(); } set { this._autoMinorVersionUpgrade = value; } } // Check to see if AutoMinorVersionUpgrade property is set internal bool IsSetAutoMinorVersionUpgrade() { return this._autoMinorVersionUpgrade.HasValue; } /// <summary> /// Gets and sets the property CacheNodeType. /// <para> /// The compute and memory capacity of the nodes in the node group. /// </para> /// /// <para> /// Valid node types are as follows: /// </para> /// <ul> <li>General purpose: <ul> <li>Current generation: <code>cache.t2.micro</code>, /// <code>cache.t2.small</code>, <code>cache.t2.medium</code>, <code>cache.m3.medium</code>, /// <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>, <code>cache.m3.2xlarge</code></li> /// <li>Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>, /// <code>cache.m1.medium</code>, <code>cache.m1.large</code>, <code>cache.m1.xlarge</code></li> /// </ul></li> <li>Compute optimized: <code>cache.c1.xlarge</code></li> <li>Memory optimized /// <ul> <li>Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>, /// <code>cache.r3.2xlarge</code>, <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code></li> /// <li>Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>, /// <code>cache.m2.4xlarge</code></li> </ul></li> </ul> /// <para> /// <b>Notes:</b> /// </para> /// <ul> <li>All t2 instances are created in an Amazon Virtual Private Cloud (VPC).</li> /// <li>Redis backup/restore is not supported for t2 instances.</li> <li>Redis Append-only /// files (AOF) functionality is not supported for t1 or t2 instances.</li> </ul> /// <para> /// For a complete listing of cache node types and specifications, see <a href="http://aws.amazon.com/elasticache/details">Amazon /// ElastiCache Product Features and Details</a> and <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#CacheParameterGroups.Memcached.NodeSpecific">Cache /// Node Type-Specific Parameters for Memcached</a> or <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#CacheParameterGroups.Redis.NodeSpecific">Cache /// Node Type-Specific Parameters for Redis</a>. /// </para> /// </summary> public string CacheNodeType { get { return this._cacheNodeType; } set { this._cacheNodeType = value; } } // Check to see if CacheNodeType property is set internal bool IsSetCacheNodeType() { return this._cacheNodeType != null; } /// <summary> /// Gets and sets the property CacheParameterGroupName. /// <para> /// The name of the parameter group to associate with this replication group. If this /// argument is omitted, the default cache parameter group for the specified engine is /// used. /// </para> /// </summary> public string CacheParameterGroupName { get { return this._cacheParameterGroupName; } set { this._cacheParameterGroupName = value; } } // Check to see if CacheParameterGroupName property is set internal bool IsSetCacheParameterGroupName() { return this._cacheParameterGroupName != null; } /// <summary> /// Gets and sets the property CacheSecurityGroupNames. /// <para> /// A list of cache security group names to associate with this replication group. /// </para> /// </summary> public List<string> CacheSecurityGroupNames { get { return this._cacheSecurityGroupNames; } set { this._cacheSecurityGroupNames = value; } } // Check to see if CacheSecurityGroupNames property is set internal bool IsSetCacheSecurityGroupNames() { return this._cacheSecurityGroupNames != null && this._cacheSecurityGroupNames.Count > 0; } /// <summary> /// Gets and sets the property CacheSubnetGroupName. /// <para> /// The name of the cache subnet group to be used for the replication group. /// </para> /// </summary> public string CacheSubnetGroupName { get { return this._cacheSubnetGroupName; } set { this._cacheSubnetGroupName = value; } } // Check to see if CacheSubnetGroupName property is set internal bool IsSetCacheSubnetGroupName() { return this._cacheSubnetGroupName != null; } /// <summary> /// Gets and sets the property Engine. /// <para> /// The name of the cache engine to be used for the cache clusters in this replication /// group. /// </para> /// /// <para> /// Default: redis /// </para> /// </summary> public string Engine { get { return this._engine; } set { this._engine = value; } } // Check to see if Engine property is set internal bool IsSetEngine() { return this._engine != null; } /// <summary> /// Gets and sets the property EngineVersion. /// <para> /// The version number of the cache engine to be used for the cache clusters in this replication /// group. To view the supported cache engine versions, use the <i>DescribeCacheEngineVersions</i> /// action. /// </para> /// </summary> public string EngineVersion { get { return this._engineVersion; } set { this._engineVersion = value; } } // Check to see if EngineVersion property is set internal bool IsSetEngineVersion() { return this._engineVersion != null; } /// <summary> /// Gets and sets the property NotificationTopicArn. /// <para> /// The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS) topic /// to which notifications will be sent. /// </para> /// <note>The Amazon SNS topic owner must be the same as the cache cluster owner.</note> /// </summary> public string NotificationTopicArn { get { return this._notificationTopicArn; } set { this._notificationTopicArn = value; } } // Check to see if NotificationTopicArn property is set internal bool IsSetNotificationTopicArn() { return this._notificationTopicArn != null; } /// <summary> /// Gets and sets the property NumCacheClusters. /// <para> /// The number of cache clusters this replication group will initially have. /// </para> /// /// <para> /// If <i>Multi-AZ</i> is <code>enabled</code>, the value of this parameter must be at /// least 2. /// </para> /// /// <para> /// The maximum permitted value for <i>NumCacheClusters</i> is 6 (primary plus 5 replicas). /// If you need to exceed this limit, please fill out the ElastiCache Limit Increase Request /// form at <a href="http://aws.amazon.com/contact-us/elasticache-node-limit-request">http://aws.amazon.com/contact-us/elasticache-node-limit-request</a>. /// </para> /// </summary> public int NumCacheClusters { get { return this._numCacheClusters.GetValueOrDefault(); } set { this._numCacheClusters = value; } } // Check to see if NumCacheClusters property is set internal bool IsSetNumCacheClusters() { return this._numCacheClusters.HasValue; } /// <summary> /// Gets and sets the property Port. /// <para> /// The port number on which each member of the replication group will accept connections. /// </para> /// </summary> public int Port { get { return this._port.GetValueOrDefault(); } set { this._port = value; } } // Check to see if Port property is set internal bool IsSetPort() { return this._port.HasValue; } /// <summary> /// Gets and sets the property PreferredCacheClusterAZs. /// <para> /// A list of EC2 availability zones in which the replication group's cache clusters will /// be created. The order of the availability zones in the list is not important. /// </para> /// <note>If you are creating your replication group in an Amazon VPC (recommended), /// you can only locate cache clusters in availability zones associated with the subnets /// in the selected subnet group. /// <para> /// The number of availability zones listed must equal the value of <i>NumCacheClusters</i>. /// </para> /// </note> /// <para> /// Default: system chosen availability zones. /// </para> /// /// <para> /// Example: One Redis cache cluster in each of three availability zones. PreferredAvailabilityZones.member.1=us-west-2a /// PreferredAvailabilityZones.member.2=us-west-2c PreferredAvailabilityZones.member.3=us-west-2c /// </para> /// </summary> public List<string> PreferredCacheClusterAZs { get { return this._preferredCacheClusterAZs; } set { this._preferredCacheClusterAZs = value; } } // Check to see if PreferredCacheClusterAZs property is set internal bool IsSetPreferredCacheClusterAZs() { return this._preferredCacheClusterAZs != null && this._preferredCacheClusterAZs.Count > 0; } /// <summary> /// Gets and sets the property PreferredMaintenanceWindow. /// <para> /// Specifies the weekly time range during which maintenance on the cache cluster is performed. /// It is specified as a range in the format ddd:hh24:mi-ddd:hh24:mi (24H Clock UTC). /// The minimum maintenance window is a 60 minute period. Valid values for <code>ddd</code> /// are: /// </para> /// <ul> <li><code>sun</code></li> <li><code>mon</code></li> <li><code>tue</code></li> /// <li><code>wed</code></li> <li><code>thu</code></li> <li><code>fri</code></li> <li><code>sat</code></li> /// </ul> /// <para> /// Example: <code>sun:05:00-sun:09:00</code> /// </para> /// </summary> public string PreferredMaintenanceWindow { get { return this._preferredMaintenanceWindow; } set { this._preferredMaintenanceWindow = value; } } // Check to see if PreferredMaintenanceWindow property is set internal bool IsSetPreferredMaintenanceWindow() { return this._preferredMaintenanceWindow != null; } /// <summary> /// Gets and sets the property PrimaryClusterId. /// <para> /// The identifier of the cache cluster that will serve as the primary for this replication /// group. This cache cluster must already exist and have a status of <i>available</i>. /// </para> /// /// <para> /// This parameter is not required if <i>NumCacheClusters</i> is specified. /// </para> /// </summary> public string PrimaryClusterId { get { return this._primaryClusterId; } set { this._primaryClusterId = value; } } // Check to see if PrimaryClusterId property is set internal bool IsSetPrimaryClusterId() { return this._primaryClusterId != null; } /// <summary> /// Gets and sets the property ReplicationGroupDescription. /// <para> /// A user-created description for the replication group. /// </para> /// </summary> public string ReplicationGroupDescription { get { return this._replicationGroupDescription; } set { this._replicationGroupDescription = value; } } // Check to see if ReplicationGroupDescription property is set internal bool IsSetReplicationGroupDescription() { return this._replicationGroupDescription != null; } /// <summary> /// Gets and sets the property ReplicationGroupId. /// <para> /// The replication group identifier. This parameter is stored as a lowercase string. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li>A name must contain from 1 to 20 alphanumeric characters or hyphens.</li> /// <li>The first character must be a letter.</li> <li>A name cannot end with a hyphen /// or contain two consecutive hyphens.</li> </ul> /// </summary> public string ReplicationGroupId { get { return this._replicationGroupId; } set { this._replicationGroupId = value; } } // Check to see if ReplicationGroupId property is set internal bool IsSetReplicationGroupId() { return this._replicationGroupId != null; } /// <summary> /// Gets and sets the property SecurityGroupIds. /// <para> /// One or more Amazon VPC security groups associated with this replication group. /// </para> /// /// <para> /// Use this parameter only when you are creating a replication group in an Amazon Virtual /// Private Cloud (VPC). /// </para> /// </summary> public List<string> SecurityGroupIds { get { return this._securityGroupIds; } set { this._securityGroupIds = value; } } // Check to see if SecurityGroupIds property is set internal bool IsSetSecurityGroupIds() { return this._securityGroupIds != null && this._securityGroupIds.Count > 0; } /// <summary> /// Gets and sets the property SnapshotArns. /// <para> /// A single-element string list containing an Amazon Resource Name (ARN) that uniquely /// identifies a Redis RDB snapshot file stored in Amazon S3. The snapshot file will be /// used to populate the node group. The Amazon S3 object name in the ARN cannot contain /// any commas. /// </para> /// /// <para> /// <b>Note:</b> This parameter is only valid if the <code>Engine</code> parameter is /// <code>redis</code>. /// </para> /// /// <para> /// Example of an Amazon S3 ARN: <code>arn:aws:s3:::my_bucket/snapshot1.rdb</code> /// </para> /// </summary> public List<string> SnapshotArns { get { return this._snapshotArns; } set { this._snapshotArns = value; } } // Check to see if SnapshotArns property is set internal bool IsSetSnapshotArns() { return this._snapshotArns != null && this._snapshotArns.Count > 0; } /// <summary> /// Gets and sets the property SnapshotName. /// <para> /// The name of a snapshot from which to restore data into the new node group. The snapshot /// status changes to <code>restoring</code> while the new node group is being created. /// </para> /// /// <para> /// <b>Note:</b> This parameter is only valid if the <code>Engine</code> parameter is /// <code>redis</code>. /// </para> /// </summary> public string SnapshotName { get { return this._snapshotName; } set { this._snapshotName = value; } } // Check to see if SnapshotName property is set internal bool IsSetSnapshotName() { return this._snapshotName != null; } /// <summary> /// Gets and sets the property SnapshotRetentionLimit. /// <para> /// The number of days for which ElastiCache will retain automatic snapshots before deleting /// them. For example, if you set <code>SnapshotRetentionLimit</code> to 5, then a snapshot /// that was taken today will be retained for 5 days before being deleted. /// </para> /// /// <para> /// <b>Note:</b> This parameter is only valid if the <code>Engine</code> parameter is /// <code>redis</code>. /// </para> /// /// <para> /// Default: 0 (i.e., automatic backups are disabled for this cache cluster). /// </para> /// </summary> public int SnapshotRetentionLimit { get { return this._snapshotRetentionLimit.GetValueOrDefault(); } set { this._snapshotRetentionLimit = value; } } // Check to see if SnapshotRetentionLimit property is set internal bool IsSetSnapshotRetentionLimit() { return this._snapshotRetentionLimit.HasValue; } /// <summary> /// Gets and sets the property SnapshotWindow. /// <para> /// The daily time range (in UTC) during which ElastiCache will begin taking a daily snapshot /// of your node group. /// </para> /// /// <para> /// Example: <code>05:00-09:00</code> /// </para> /// /// <para> /// If you do not specify this parameter, then ElastiCache will automatically choose an /// appropriate time range. /// </para> /// /// <para> /// <b>Note:</b> This parameter is only valid if the <code>Engine</code> parameter is /// <code>redis</code>. /// </para> /// </summary> public string SnapshotWindow { get { return this._snapshotWindow; } set { this._snapshotWindow = value; } } // Check to see if SnapshotWindow property is set internal bool IsSetSnapshotWindow() { return this._snapshotWindow != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// A list of cost allocation tags to be added to this resource. A tag is a key-value /// pair. A tag key must be accompanied by a tag value. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
using System; using System.Collections; /// <summary> /// Sign(System.Double) /// </summary> public class MathSign2 { public static int Main(string[] args) { MathSign2 test = new MathSign2(); TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Sign(System.Double)."); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; TestLibrary.TestFramework.LogInformation("[Negtive]"); retVal = NegTest1() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Double.MaxValue is a positive number."); try { Double d = Double.MaxValue; if (Math.Sign(d) != 1) { TestLibrary.TestFramework.LogError("P01.1", "Double.MaxValue is not a positive number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify Double.MinValue is a negative number."); try { Double d = Double.MinValue; if (Math.Sign(d) != -1) { TestLibrary.TestFramework.LogError("P02.1", "Double.MinValue is not a negative number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify Double.PositiveInfinity is a positive number."); try { Double d = Double.PositiveInfinity; if (Math.Sign(d) != 1) { TestLibrary.TestFramework.LogError("P03.1", "Double.PositiveInfinity is not a positive number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Verify Double.NegativeInfinity is a negative number."); try { Double d = Double.NegativeInfinity; if (Math.Sign(d) != -1) { TestLibrary.TestFramework.LogError("P04.1", "Double.NegativeInfinity is not a negative number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Verify Double.Epsilon is a positive number."); try { Double d = Double.Epsilon; if (Math.Sign(d) != 1) { TestLibrary.TestFramework.LogError("P05.1", "Double.Epsilon is not a positive number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P05.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the return value should be 1 when the Double is positive."); try { Double d = TestLibrary.Generator.GetDouble(-55); while (d <= 0) { d = TestLibrary.Generator.GetDouble(-55); } if (Math.Sign(d) != 1) { TestLibrary.TestFramework.LogError("P06.1", "The return value is not 1 when the Double is positive!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P06.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the return value should be -1 when the Double is negative."); try { Double d = TestLibrary.Generator.GetDouble(-55); while (d <= 0) { d = TestLibrary.Generator.GetDouble(-55); } if (Math.Sign(-d) != -1) { TestLibrary.TestFramework.LogError("P07.1", "The return value is not -1 when the Double is negative!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P07.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest8: Verify the return value should be 0 when the Double is zero."); try { Double d = 0.0d; if (Math.Sign(d) != 0) { TestLibrary.TestFramework.LogError("P08.1", "The return value is not -1 when the Double is negative!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P08.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArithmeticException should be thrown when value is equal to NaN."); try { Double d = Double.NaN; Math.Sign(d); TestLibrary.TestFramework.LogError("N01.1", "ArithmeticException is not thrown when value is equal to NaN!"); retVal = false; } catch (ArithmeticException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N01.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
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 BugLogger.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) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion.Sessions; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions; namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion.Sessions { internal class CurlyBraceCompletionSession : AbstractTokenBraceCompletionSession { private readonly ISmartIndentationService _smartIndentationService; private readonly ITextBufferUndoManagerProvider _undoManager; public CurlyBraceCompletionSession(ISyntaxFactsService syntaxFactsService, ISmartIndentationService smartIndentationService, ITextBufferUndoManagerProvider undoManager) : base(syntaxFactsService, (int)SyntaxKind.OpenBraceToken, (int)SyntaxKind.CloseBraceToken) { _smartIndentationService = smartIndentationService; _undoManager = undoManager; } public override void AfterStart(IBraceCompletionSession session, CancellationToken cancellationToken) { FormatTrackingSpan(session, shouldHonorAutoFormattingOnCloseBraceOption: true); session.TextView.TryMoveCaretToAndEnsureVisible(session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Subtract(1)); } private ITextUndoHistory GetUndoHistory(ITextView textView) { return _undoManager.GetTextBufferUndoManager(textView.TextBuffer).TextBufferUndoHistory; } public override void AfterReturn(IBraceCompletionSession session, CancellationToken cancellationToken) { // check whether shape of the braces are what we support // shape must be either "{|}" or "{ }". | is where caret is. otherwise, we don't do any special behavior if (!ContainsOnlyWhitespace(session)) { return; } // alright, it is in right shape. var undoHistory = GetUndoHistory(session.TextView); using (var transaction = undoHistory.CreateTransaction(EditorFeaturesResources.Brace_Completion)) { var document = session.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { document.InsertText(session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot) - 1, Environment.NewLine, cancellationToken); FormatTrackingSpan(session, shouldHonorAutoFormattingOnCloseBraceOption: false, rules: GetFormattingRules(document)); // put caret at right indentation PutCaretOnLine(session, session.OpeningPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).GetContainingLineNumber() + 1); transaction.Complete(); } } } private static bool ContainsOnlyWhitespace(IBraceCompletionSession session) { var span = session.GetSessionSpan(); var snapshot = span.Snapshot; var start = span.Start.Position; start = snapshot[start] == session.OpeningBrace ? start + 1 : start; var end = span.End.Position - 1; end = snapshot[end] == session.ClosingBrace ? end - 1 : end; if (!start.PositionInSnapshot(snapshot) || !end.PositionInSnapshot(snapshot)) { return false; } for (int i = start; i <= end; i++) { if (!char.IsWhiteSpace(snapshot[i])) { return false; } } return true; } private IEnumerable<IFormattingRule> GetFormattingRules(Document document) { return SpecializedCollections.SingletonEnumerable(BraceCompletionFormattingRule.Instance).Concat(Formatter.GetDefaultFormattingRules(document)); } private void FormatTrackingSpan(IBraceCompletionSession session, bool shouldHonorAutoFormattingOnCloseBraceOption, IEnumerable<IFormattingRule> rules = null) { if (!session.SubjectBuffer.GetOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace) && shouldHonorAutoFormattingOnCloseBraceOption) { return; } var snapshot = session.SubjectBuffer.CurrentSnapshot; var startPoint = session.OpeningPoint.GetPoint(snapshot); var endPoint = session.ClosingPoint.GetPoint(snapshot); var startPosition = startPoint.Position; var endPosition = endPoint.Position; // Do not format within the braces if they're on the same line for array/collection/object initializer expressions. // This is a heuristic to prevent brace completion from breaking user expectation/muscle memory in common scenarios. // see bug Devdiv:823958 if (startPoint.GetContainingLineNumber() == endPoint.GetContainingLineNumber()) { // Brace completion is not cancellable var startToken = snapshot.FindToken(startPosition, CancellationToken.None); if (startToken.IsKind(SyntaxKind.OpenBraceToken) && (startToken.Parent.IsInitializerForArrayOrCollectionCreationExpression() || startToken.Parent is AnonymousObjectCreationExpressionSyntax)) { // format everything but the brace pair. var endToken = snapshot.FindToken(endPosition, CancellationToken.None); if (endToken.IsKind(SyntaxKind.CloseBraceToken)) { endPosition = endPosition - (endToken.Span.Length + startToken.Span.Length); } } } if (session.SubjectBuffer.GetOption(SmartIndent) == IndentStyle.Smart) { // skip whitespace while (startPosition >= 0 && char.IsWhiteSpace(snapshot[startPosition])) { startPosition--; } // skip token startPosition--; while (startPosition >= 0 && !char.IsWhiteSpace(snapshot[startPosition])) { startPosition--; } } session.SubjectBuffer.Format(TextSpan.FromBounds(Math.Max(startPosition, 0), endPosition), rules); } private void PutCaretOnLine(IBraceCompletionSession session, int lineNumber) { var lineOnSubjectBuffer = session.SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber); var indentation = GetDesiredIndentation(session, lineOnSubjectBuffer); session.TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(lineOnSubjectBuffer, indentation)); } private int GetDesiredIndentation(IBraceCompletionSession session, ITextSnapshotLine lineOnSubjectBuffer) { // first try VS's smart indentation service var indentation = session.TextView.GetDesiredIndentation(_smartIndentationService, lineOnSubjectBuffer); if (indentation.HasValue) { return indentation.Value; } // do poor man's indentation var openingPoint = session.OpeningPoint.GetPoint(lineOnSubjectBuffer.Snapshot); var openingSpanLine = openingPoint.GetContainingLine(); return openingPoint - openingSpanLine.Start; } private class BraceCompletionFormattingRule : BaseFormattingRule { private static readonly Predicate<SuppressOperation> s_predicate = o => o == null || o.Option.IsOn(SuppressOption.NoWrapping); public static readonly IFormattingRule Instance = new BraceCompletionFormattingRule(); public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation<AdjustNewLinesOperation> nextOperation) { // Eg Cases - // new MyObject { // new List<int> { // int[] arr = { // = new[] { // = new int[] { if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent != null && (currentToken.Parent.Kind() == SyntaxKind.ObjectInitializerExpression || currentToken.Parent.Kind() == SyntaxKind.CollectionInitializerExpression || currentToken.Parent.Kind() == SyntaxKind.ArrayInitializerExpression || currentToken.Parent.Kind() == SyntaxKind.ImplicitArrayCreationExpression)) { if (optionSet.GetOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } else { return null; } } return base.GetAdjustNewLinesOperation(previousToken, currentToken, optionSet, nextOperation); } public override void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<AlignTokensOperation> nextOperation) { base.AddAlignTokensOperations(list, node, optionSet, nextOperation); if (optionSet.GetOption(SmartIndent, node.Language) == IndentStyle.Block) { var bracePair = node.GetBracePair(); if (bracePair.IsValidBracePair()) { AddAlignIndentationOfTokensToBaseTokenOperation(list, node, bracePair.Item1, SpecializedCollections.SingletonEnumerable(bracePair.Item2), AlignTokensOption.AlignIndentationOfTokensToFirstTokenOfBaseTokenLine); } } } public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, SyntaxToken lastToken, OptionSet optionSet, NextAction<SuppressOperation> nextOperation) { base.AddSuppressOperations(list, node, lastToken, optionSet, nextOperation); // remove suppression rules for array and collection initializer if (node.IsInitializerForArrayOrCollectionCreationExpression()) { // remove any suppression operation list.RemoveAll(s_predicate); } } } } }
namespace LuaInterface { using System; using System.IO; using System.Collections; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using Lua511; /* * Cached method */ struct MethodCache { private MethodBase _cachedMethod; public MethodBase cachedMethod { get { return _cachedMethod; } set { _cachedMethod = value; MethodInfo mi = value as MethodInfo; if (mi != null) { IsReturnVoid = string.Compare(mi.ReturnType.Name, "System.Void", true) == 0; } } } public bool IsReturnVoid; // List or arguments public object[] args; // Positions of out parameters public int[] outList; // Types of parameters public MethodArgs[] argTypes; } /* * Parameter information */ struct MethodArgs { // Position of parameter public int index; // Type-conversion function public ExtractValue extractValue; public bool isParamsArray; public Type paramsArrayType; } /* * Argument extraction with type-conversion function */ delegate object ExtractValue(IntPtr luaState, int stackPos); /* * Wrapper class for methods/constructors accessed from Lua. * * Author: Fabio Mascarenhas * Version: 1.0 */ class LuaMethodWrapper { private ObjectTranslator _Translator; private MethodBase _Method; private MethodCache _LastCalledMethod = new MethodCache(); private string _MethodName; private MemberInfo[] _Members; private IReflect _TargetType; private ExtractValue _ExtractTarget; private object _Target; private BindingFlags _BindingType; /* * Constructs the wrapper for a known MethodBase instance */ public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method) { _Translator = translator; _Target = target; _TargetType = targetType; if (targetType != null) _ExtractTarget = translator.typeChecker.getExtractor(targetType); _Method = method; _MethodName = method.Name; if (method.IsStatic) { _BindingType = BindingFlags.Static; } else { _BindingType = BindingFlags.Instance; } } /* * Constructs the wrapper for a known method name */ public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType) { _Translator = translator; _MethodName = methodName; _TargetType = targetType; if (targetType != null) _ExtractTarget = translator.typeChecker.getExtractor(targetType); _BindingType = bindingType; //CP: Removed NonPublic binding search and added IgnoreCase _Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/); } /// <summary> /// Convert C# exceptions into Lua errors /// </summary> /// <returns>num of things on stack</returns> /// <param name="e">null for no pending exception</param> int SetPendingException(Exception e) { return _Translator.interpreter.SetPendingException(e); } /* * Calls the method. Receives the arguments from the Lua stack * and returns values in it. */ public int call(IntPtr luaState) { MethodBase methodToCall = _Method; object targetObject = _Target; bool failedCall = true; int nReturnValues = 0; if (!LuaDLL.lua_checkstack(luaState, 5)) throw new LuaException("Lua stack overflow"); bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static; SetPendingException(null); if (methodToCall == null) // Method from name { if (isStatic) targetObject = null; else targetObject = _ExtractTarget(luaState, 1); //LuaDLL.lua_remove(luaState,1); // Pops the receiver if (_LastCalledMethod.cachedMethod != null) // Cached? { int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject int numArgsPassed = LuaDLL.lua_gettop(luaState) - numStackToSkip; if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match? { if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6)) throw new LuaException("Lua stack overflow"); try { for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++) { if (_LastCalledMethod.argTypes[i].isParamsArray) { object luaParamValue = _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip); Type paramArrayType = _LastCalledMethod.argTypes[i].paramsArrayType; Array paramArray; if (luaParamValue is LuaTable) { LuaTable table = (LuaTable)luaParamValue; paramArray = Array.CreateInstance(paramArrayType, table.Values.Count); for (int x = 1; x <= table.Values.Count; x++) { paramArray.SetValue(Convert.ChangeType(table[x], paramArrayType), x - 1); } } else { paramArray = Array.CreateInstance(paramArrayType, 1); paramArray.SetValue(luaParamValue, 0); } _LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] = paramArray; } else { _LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] = _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip); } if (_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] == null && !LuaDLL.lua_isnil(luaState, i + 1 + numStackToSkip)) { throw new LuaException("argument number " + (i + 1) + " is invalid"); } } if ((_BindingType & BindingFlags.Static) == BindingFlags.Static) { _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args)); } else { if (_LastCalledMethod.cachedMethod.IsConstructor) _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args)); else _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args)); } failedCall = false; } catch (TargetInvocationException e) { // Failure of method invocation return SetPendingException(e.GetBaseException()); } catch (Exception e) { if (_Members.Length == 1) // Is the method overloaded? // No, throw error return SetPendingException(e); } } } // Cache miss if (failedCall) { // System.Diagnostics.Debug.WriteLine("cache miss on " + methodName); // If we are running an instance variable, we can now pop the targetObject from the stack if (!isStatic) { if (targetObject == null) { _Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName)); LuaDLL.lua_pushnil(luaState); return 1; } LuaDLL.lua_remove(luaState, 1); // Pops the receiver } bool hasMatch = false; string candidateName = null; foreach (MemberInfo member in _Members) { candidateName = member.ReflectedType.Name + "." + member.Name; MethodBase m = (MethodInfo)member; bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod); if (isMethod) { hasMatch = true; break; } } if (!hasMatch) { string msg = (candidateName == null) ? "invalid arguments to method call" : ("invalid arguments to method: " + candidateName); _Translator.throwError(luaState, msg); LuaDLL.lua_pushnil(luaState); return 1; } } } else // Method from MethodBase instance { if (methodToCall.ContainsGenericParameters) { bool isMethod = _Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod); if (methodToCall.IsGenericMethodDefinition) { //need to make a concrete type of the generic method definition List<Type> typeArgs = new List<Type>(); foreach (object arg in _LastCalledMethod.args) typeArgs.Add(arg.GetType()); MethodInfo concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray()); _Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args)); failedCall = false; } else if (methodToCall.ContainsGenericParameters) { _Translator.throwError(luaState, "unable to invoke method on generic class as the current method is an open generic method"); LuaDLL.lua_pushnil(luaState); return 1; } } else { if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) { targetObject = _ExtractTarget(luaState, 1); LuaDLL.lua_remove(luaState, 1); // Pops the receiver } if (!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod)) { _Translator.throwError(luaState, "invalid arguments to method call"); LuaDLL.lua_pushnil(luaState); return 1; } } } if (failedCall) { if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6)) throw new LuaException("Lua stack overflow"); try { if (isStatic) { _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args)); } else { if (_LastCalledMethod.cachedMethod.IsConstructor) _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args)); else _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args)); } } catch (TargetInvocationException e) { return SetPendingException(e.GetBaseException()); } catch (Exception e) { return SetPendingException(e); } } // Pushes out and ref return values for (int index = 0; index < _LastCalledMethod.outList.Length; index++) { nReturnValues++; //for(int i=0;i<lastCalledMethod.outList.Length;i++) _Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]); } //by isSingle 2010-09-10 11:26:31 //Desc: // if not return void,we need add 1, // or we will lost the function's return value // when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0) { nReturnValues++; } return nReturnValues < 1 ? 1 : nReturnValues; } } /// <summary> /// We keep track of what delegates we have auto attached to an event - to allow us to cleanly exit a LuaInterface session /// </summary> class EventHandlerContainer : IDisposable { Dictionary<Delegate, RegisterEventHandler> dict = new Dictionary<Delegate, RegisterEventHandler>(); public void Add(Delegate handler, RegisterEventHandler eventInfo) { dict.Add(handler, eventInfo); } public void Remove(Delegate handler) { bool found = dict.Remove(handler); Debug.Assert(found); } /// <summary> /// Remove any still registered handlers /// </summary> public void Dispose() { foreach (KeyValuePair<Delegate, RegisterEventHandler> pair in dict) { pair.Value.RemovePending(pair.Key); } dict.Clear(); } } /* * Wrapper class for events that does registration/deregistration * of event handlers. * * Author: Fabio Mascarenhas * Version: 1.0 */ class RegisterEventHandler { object target; EventInfo eventInfo; EventHandlerContainer pendingEvents; public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo) { this.target = target; this.eventInfo = eventInfo; this.pendingEvents = pendingEvents; } /* * Adds a new event handler */ public Delegate Add(LuaFunction function) { //CP: Fix by Ben Bryant for event handling with one parameter //link: http://luaforge.net/forum/message.php?msg_id=9266 Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(eventInfo.EventHandlerType, function); eventInfo.AddEventHandler(target, handlerDelegate); pendingEvents.Add(handlerDelegate, this); return handlerDelegate; //MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke"); //ParameterInfo[] pi = mi.GetParameters(); //LuaEventHandler handler=CodeGeneration.Instance.GetEvent(pi[1].ParameterType,function); //Delegate handlerDelegate=Delegate.CreateDelegate(eventInfo.EventHandlerType,handler,"HandleEvent"); //eventInfo.AddEventHandler(target,handlerDelegate); //pendingEvents.Add(handlerDelegate, this); //return handlerDelegate; } /* * Removes an existing event handler */ public void Remove(Delegate handlerDelegate) { RemovePending(handlerDelegate); pendingEvents.Remove(handlerDelegate); } /* * Removes an existing event handler (without updating the pending handlers list) */ internal void RemovePending(Delegate handlerDelegate) { eventInfo.RemoveEventHandler(target, handlerDelegate); } } /* * Base wrapper class for Lua function event handlers. * Subclasses that do actual event handling are created * at runtime. * * Author: Fabio Mascarenhas * Version: 1.0 */ public class LuaEventHandler { public LuaFunction handler = null; // CP: Fix provided by Ben Bryant for delegates with one param // link: http://luaforge.net/forum/message.php?msg_id=9318 public void handleEvent(object[] args) { handler.Call(args); } //public void handleEvent(object sender,object data) //{ // handler.call(new object[] { sender,data },new Type[0]); //} } /* * Wrapper class for Lua functions as delegates * Subclasses with correct signatures are created * at runtime. * * Author: Fabio Mascarenhas * Version: 1.0 */ public class LuaDelegate { public Type[] returnTypes; public LuaFunction function; public LuaDelegate() { function = null; returnTypes = null; } public object callFunction(object[] args, object[] inArgs, int[] outArgs) { // args is the return array of arguments, inArgs is the actual array // of arguments passed to the function (with in parameters only), outArgs // has the positions of out parameters object returnValue; int iRefArgs; object[] returnValues = function.call(inArgs, returnTypes); if (returnTypes[0] == typeof(void)) { returnValue = null; iRefArgs = 0; } else { returnValue = returnValues[0]; iRefArgs = 1; } // Sets the value of out and ref parameters (from // the values returned by the Lua function). for (int i = 0; i < outArgs.Length; i++) { args[outArgs[i]] = returnValues[iRefArgs]; iRefArgs++; } return returnValue; } } /* * Static helper methods for Lua tables acting as CLR objects. * * Author: Fabio Mascarenhas * Version: 1.0 */ public class LuaClassHelper { /* * Gets the function called name from the provided table, * returning null if it does not exist */ public static LuaFunction getTableFunction(LuaTable luaTable, string name) { object funcObj = luaTable.rawget(name); if (funcObj is LuaFunction) return (LuaFunction)funcObj; else return null; } /* * Calls the provided function with the provided parameters */ public static object callFunction(LuaFunction function, object[] args, Type[] returnTypes, object[] inArgs, int[] outArgs) { // args is the return array of arguments, inArgs is the actual array // of arguments passed to the function (with in parameters only), outArgs // has the positions of out parameters object returnValue; int iRefArgs; object[] returnValues = function.call(inArgs, returnTypes); if (returnTypes[0] == typeof(void)) { returnValue = null; iRefArgs = 0; } else { returnValue = returnValues[0]; iRefArgs = 1; } for (int i = 0; i < outArgs.Length; i++) { args[outArgs[i]] = returnValues[iRefArgs]; iRefArgs++; } return returnValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Globalization; using Microsoft.AspNetCore.HttpSys.Internal; namespace Microsoft.AspNetCore.Server.HttpSys { /// <summary> /// A set of URL parameters used to listen for incoming requests. /// </summary> public class UrlPrefix { private UrlPrefix(bool isHttps, string scheme, string host, string port, int portValue, string path) { IsHttps = isHttps; Scheme = scheme; Host = host; Port = port; HostAndPort = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", Host, Port); PortValue = portValue; Path = path; PathWithoutTrailingSlash = Path.Length > 1 ? Path[0..^1] : string.Empty; FullPrefix = string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}{3}", Scheme, Host, Port, Path); } /// <summary> /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364698(v=vs.85).aspx /// </summary> /// <param name="scheme">http or https. Will be normalized to lower case.</param> /// <param name="host">+, *, IPv4, [IPv6], or a dns name. Http.Sys does not permit punycode (xn--), use Unicode instead.</param> /// <param name="port">If empty, the default port for the given scheme will be used (80 or 443).</param> /// <param name="path">Should start and end with a '/', though a missing trailing slash will be added. This value must be un-escaped.</param> public static UrlPrefix Create(string scheme, string host, string port, string path) { int? portValue = null; if (!string.IsNullOrWhiteSpace(port)) { portValue = int.Parse(port, NumberStyles.None, CultureInfo.InvariantCulture); } return UrlPrefix.Create(scheme, host, portValue, path); } /// <summary> /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364698(v=vs.85).aspx /// </summary> /// <param name="scheme">http or https. Will be normalized to lower case.</param> /// <param name="host">+, *, IPv4, [IPv6], or a dns name. Http.Sys does not permit punycode (xn--), use Unicode instead.</param> /// <param name="portValue">If empty, the default port for the given scheme will be used (80 or 443).</param> /// <param name="path">Should start and end with a '/', though a missing trailing slash will be added. This value must be un-escaped.</param> public static UrlPrefix Create(string scheme, string host, int? portValue, string path) { bool isHttps; if (string.Equals(Constants.HttpScheme, scheme, StringComparison.OrdinalIgnoreCase)) { scheme = Constants.HttpScheme; // Always use a lower case scheme isHttps = false; } else if (string.Equals(Constants.HttpsScheme, scheme, StringComparison.OrdinalIgnoreCase)) { scheme = Constants.HttpsScheme; // Always use a lower case scheme isHttps = true; } else { throw new ArgumentOutOfRangeException(nameof(scheme), scheme, Resources.Exception_UnsupportedScheme); } if (string.IsNullOrWhiteSpace(host)) { throw new ArgumentNullException(nameof(host)); } string port; if (!portValue.HasValue) { port = isHttps ? "443" : "80"; portValue = isHttps ? 443 : 80; } else { port = portValue.Value.ToString(CultureInfo.InvariantCulture); } // Http.Sys requires the path end with a slash. if (string.IsNullOrWhiteSpace(path)) { path = "/"; } else if (!path.EndsWith("/", StringComparison.Ordinal)) { path += "/"; } return new UrlPrefix(isHttps, scheme, host, port, portValue.Value, path); } /// <summary> /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364698(v=vs.85).aspx /// </summary> /// <param name="prefix">The string that the <see cref="UrlPrefix"/> will be created from.</param> public static UrlPrefix Create(string prefix) { string scheme; string host; int? port = null; string path; var whole = prefix ?? string.Empty; var schemeDelimiterEnd = whole.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal); if (schemeDelimiterEnd < 0) { throw new FormatException("Invalid prefix, missing scheme separator: " + prefix); } var hostDelimiterStart = schemeDelimiterEnd + Uri.SchemeDelimiter.Length; var pathDelimiterStart = whole.IndexOf("/", hostDelimiterStart, StringComparison.Ordinal); if (pathDelimiterStart < 0) { pathDelimiterStart = whole.Length; } var hostDelimiterEnd = whole.LastIndexOf(":", pathDelimiterStart - 1, pathDelimiterStart - hostDelimiterStart, StringComparison.Ordinal); if (hostDelimiterEnd < 0) { hostDelimiterEnd = pathDelimiterStart; } scheme = whole.Substring(0, schemeDelimiterEnd); var portString = whole.Substring(hostDelimiterEnd, pathDelimiterStart - hostDelimiterEnd); // The leading ":" is included int portValue; if (!string.IsNullOrEmpty(portString)) { var portValueString = portString.Substring(1); // Trim the leading ":" if (int.TryParse(portValueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out portValue)) { host = whole.Substring(hostDelimiterStart, hostDelimiterEnd - hostDelimiterStart); port = portValue; } else { // This means a port was specified but was invalid or empty. throw new FormatException("Invalid prefix, invalid port specified: " + prefix); } } else { host = whole.Substring(hostDelimiterStart, pathDelimiterStart - hostDelimiterStart); } path = whole.Substring(pathDelimiterStart); return Create(scheme, host, port, path); } /// <summary> /// Gets a value that determines if the prefix's scheme is HTTPS. /// </summary> public bool IsHttps { get; } /// <summary> /// Gets the scheme used by the prefix. /// </summary> public string Scheme { get; } /// <summary> /// Gets the host domain name used by the prefix. /// </summary> public string Host { get; } /// <summary> /// Gets a string representation of the port used by the prefix. /// </summary> public string Port { get; } internal string HostAndPort { get; } /// <summary> /// Gets an integer representation of the port used by the prefix. /// </summary> public int PortValue { get; } /// <summary> /// Gets the path component of the prefix. /// </summary> public string Path { get; } internal string PathWithoutTrailingSlash { get; } /// <summary> /// Gets a string representation of the prefix /// </summary> public string FullPrefix { get; } /// <inheritdoc /> public override bool Equals(object? obj) { return string.Equals(FullPrefix, Convert.ToString(obj, CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase); } /// <inheritdoc /> public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(FullPrefix); } /// <inheritdoc /> public override string ToString() { return FullPrefix; } } }
#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; using log4net.Appender; using log4net.Util; using log4net.Core; namespace log4net.Repository.Hierarchy { /// <summary> /// Implementation of <see cref="ILogger"/> used by <see cref="Hierarchy"/> /// </summary> /// <remarks> /// <para> /// Internal class used to provide implementation of <see cref="ILogger"/> /// interface. Applications should use <see cref="LogManager"/> to get /// logger instances. /// </para> /// <para> /// This is one of the central classes in the log4net implementation. One of the /// distinctive features of log4net are hierarchical loggers and their /// evaluation. The <see cref="Hierarchy"/> organizes the <see cref="Logger"/> /// instances into a rooted tree hierarchy. /// </para> /// <para> /// The <see cref="Logger"/> class is abstract. Only concrete subclasses of /// <see cref="Logger"/> can be created. The <see cref="ILoggerFactory"/> /// is used to create instances of this type for the <see cref="Hierarchy"/>. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Aspi Havewala</author> /// <author>Douglas de la Torre</author> public abstract class Logger : IAppenderAttachable, ILogger { #region Protected Instance Constructors /// <summary> /// This constructor created a new <see cref="Logger" /> instance and /// sets its name. /// </summary> /// <param name="name">The name of the <see cref="Logger" />.</param> /// <remarks> /// <para> /// This constructor is protected and designed to be used by /// a subclass that is not abstract. /// </para> /// <para> /// Loggers are constructed by <see cref="ILoggerFactory"/> /// objects. See <see cref="DefaultLoggerFactory"/> for the default /// logger creator. /// </para> /// </remarks> protected Logger(string name) { #if NETCF || NETSTANDARD1_3 // NETCF: String.Intern causes Native Exception m_name = name; #else m_name = string.Intern(name); #endif } #endregion Protected Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the parent logger in the hierarchy. /// </summary> /// <value> /// The parent logger in the hierarchy. /// </value> /// <remarks> /// <para> /// Part of the Composite pattern that makes the hierarchy. /// The hierarchy is parent linked rather than child linked. /// </para> /// </remarks> virtual public Logger Parent { get { return m_parent; } set { m_parent = value; } } /// <summary> /// Gets or sets a value indicating if child loggers inherit their parent's appenders. /// </summary> /// <value> /// <c>true</c> if child loggers inherit their parent's appenders. /// </value> /// <remarks> /// <para> /// Additivity is set to <c>true</c> by default, that is children inherit /// the appenders of their ancestors by default. If this variable is /// set to <c>false</c> then the appenders found in the /// ancestors of this logger are not used. However, the children /// of this logger will inherit its appenders, unless the children /// have their additivity flag set to <c>false</c> too. See /// the user manual for more details. /// </para> /// </remarks> virtual public bool Additivity { get { return m_additive; } set { m_additive = value; } } /// <summary> /// Gets the effective level for this logger. /// </summary> /// <returns>The nearest level in the logger hierarchy.</returns> /// <remarks> /// <para> /// Starting from this logger, searches the logger hierarchy for a /// non-null level and returns it. Otherwise, returns the level of the /// root logger. /// </para> /// <para>The Logger class is designed so that this method executes as /// quickly as possible.</para> /// </remarks> virtual public Level EffectiveLevel { get { for(Logger c = this; c != null; c = c.m_parent) { Level level = c.m_level; // Casting level to Object for performance, otherwise the overloaded operator is called if ((object)level != null) { return level; } } return null; // If reached will cause an NullPointerException. } } /// <summary> /// Gets or sets the <see cref="Hierarchy"/> where this /// <c>Logger</c> instance is attached to. /// </summary> /// <value>The hierarchy that this logger belongs to.</value> /// <remarks> /// <para> /// This logger must be attached to a single <see cref="Hierarchy"/>. /// </para> /// </remarks> virtual public Hierarchy Hierarchy { get { return m_hierarchy; } set { m_hierarchy = value; } } /// <summary> /// Gets or sets the assigned <see cref="Level"/>, if any, for this Logger. /// </summary> /// <value> /// The <see cref="Level"/> of this logger. /// </value> /// <remarks> /// <para> /// The assigned <see cref="Level"/> can be <c>null</c>. /// </para> /// </remarks> virtual public Level Level { get { return m_level; } set { m_level = value; } } #endregion Public Instance Properties #region Implementation of IAppenderAttachable /// <summary> /// Add <paramref name="newAppender"/> to the list of appenders of this /// Logger instance. /// </summary> /// <param name="newAppender">An appender to add to this logger</param> /// <remarks> /// <para> /// Add <paramref name="newAppender"/> to the list of appenders of this /// Logger instance. /// </para> /// <para> /// If <paramref name="newAppender"/> is already in the list of /// appenders, then it won't be added again. /// </para> /// </remarks> virtual public void AddAppender(IAppender newAppender) { if (newAppender == null) { throw new ArgumentNullException("newAppender"); } m_appenderLock.AcquireWriterLock(); try { if (m_appenderAttachedImpl == null) { m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); } m_appenderAttachedImpl.AddAppender(newAppender); } finally { m_appenderLock.ReleaseWriterLock(); } } /// <summary> /// Get the appenders contained in this logger as an /// <see cref="System.Collections.ICollection"/>. /// </summary> /// <returns>A collection of the appenders in this logger</returns> /// <remarks> /// <para> /// Get the appenders contained in this logger as an /// <see cref="System.Collections.ICollection"/>. If no appenders /// can be found, then a <see cref="EmptyCollection"/> is returned. /// </para> /// </remarks> virtual public AppenderCollection Appenders { get { m_appenderLock.AcquireReaderLock(); try { if (m_appenderAttachedImpl == null) { return AppenderCollection.EmptyCollection; } else { return m_appenderAttachedImpl.Appenders; } } finally { m_appenderLock.ReleaseReaderLock(); } } } /// <summary> /// Look for the appender named as <c>name</c> /// </summary> /// <param name="name">The name of the appender to lookup</param> /// <returns>The appender with the name specified, or <c>null</c>.</returns> /// <remarks> /// <para> /// Returns the named appender, or null if the appender is not found. /// </para> /// </remarks> virtual public IAppender GetAppender(string name) { m_appenderLock.AcquireReaderLock(); try { if (m_appenderAttachedImpl == null || name == null) { return null; } return m_appenderAttachedImpl.GetAppender(name); } finally { m_appenderLock.ReleaseReaderLock(); } } /// <summary> /// Remove all previously added appenders from this Logger instance. /// </summary> /// <remarks> /// <para> /// Remove all previously added appenders from this Logger instance. /// </para> /// <para> /// This is useful when re-reading configuration information. /// </para> /// </remarks> virtual public void RemoveAllAppenders() { m_appenderLock.AcquireWriterLock(); try { if (m_appenderAttachedImpl != null) { m_appenderAttachedImpl.RemoveAllAppenders(); m_appenderAttachedImpl = null; } } finally { m_appenderLock.ReleaseWriterLock(); } } /// <summary> /// Remove the appender passed as parameter form the list of appenders. /// </summary> /// <param name="appender">The appender to remove</param> /// <returns>The appender removed from the list</returns> /// <remarks> /// <para> /// Remove the appender passed as parameter form the list of appenders. /// The appender removed is not closed. /// If you are discarding the appender you must call /// <see cref="IAppender.Close"/> on the appender removed. /// </para> /// </remarks> virtual public IAppender RemoveAppender(IAppender appender) { m_appenderLock.AcquireWriterLock(); try { if (appender != null && m_appenderAttachedImpl != null) { return m_appenderAttachedImpl.RemoveAppender(appender); } } finally { m_appenderLock.ReleaseWriterLock(); } return null; } /// <summary> /// Remove the appender passed as parameter form the list of appenders. /// </summary> /// <param name="name">The name of the appender to remove</param> /// <returns>The appender removed from the list</returns> /// <remarks> /// <para> /// Remove the named appender passed as parameter form the list of appenders. /// The appender removed is not closed. /// If you are discarding the appender you must call /// <see cref="IAppender.Close"/> on the appender removed. /// </para> /// </remarks> virtual public IAppender RemoveAppender(string name) { m_appenderLock.AcquireWriterLock(); try { if (name != null && m_appenderAttachedImpl != null) { return m_appenderAttachedImpl.RemoveAppender(name); } } finally { m_appenderLock.ReleaseWriterLock(); } return null; } #endregion #region Implementation of ILogger /// <summary> /// Gets the logger name. /// </summary> /// <value> /// The name of the logger. /// </value> /// <remarks> /// <para> /// The name of this logger /// </para> /// </remarks> virtual public string Name { get { return m_name; } } /// <summary> /// This generic form is intended to be used by wrappers. /// </summary> /// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is /// the stack boundary into the logging system for this call.</param> /// <param name="level">The level of the message to be logged.</param> /// <param name="message">The message object to log.</param> /// <param name="exception">The exception to log, including its stack trace.</param> /// <remarks> /// <para> /// Generate a logging event for the specified <paramref name="level"/> using /// the <paramref name="message"/> and <paramref name="exception"/>. /// </para> /// <para> /// This method must not throw any exception to the caller. /// </para> /// </remarks> virtual public void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) { try { if (IsEnabledFor(level)) { ForcedLog((callerStackBoundaryDeclaringType != null) ? callerStackBoundaryDeclaringType : declaringType, level, message, exception); } } catch (Exception ex) { log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { log4net.Util.LogLog.Error(declaringType, "Exception while logging"); } #endif } /// <summary> /// This is the most generic printing method that is intended to be used /// by wrappers. /// </summary> /// <param name="logEvent">The event being logged.</param> /// <remarks> /// <para> /// Logs the specified logging event through this logger. /// </para> /// <para> /// This method must not throw any exception to the caller. /// </para> /// </remarks> virtual public void Log(LoggingEvent logEvent) { try { if (logEvent != null) { if (IsEnabledFor(logEvent.Level)) { ForcedLog(logEvent); } } } catch (Exception ex) { log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { log4net.Util.LogLog.Error(declaringType, "Exception while logging"); } #endif } /// <summary> /// Checks if this logger is enabled for a given <see cref="Level"/> passed as parameter. /// </summary> /// <param name="level">The level to check.</param> /// <returns> /// <c>true</c> if this logger is enabled for <c>level</c>, otherwise <c>false</c>. /// </returns> /// <remarks> /// <para> /// Test if this logger is going to log events of the specified <paramref name="level"/>. /// </para> /// <para> /// This method must not throw any exception to the caller. /// </para> /// </remarks> virtual public bool IsEnabledFor(Level level) { try { if (level != null) { if (m_hierarchy.IsDisabled(level)) { return false; } return level >= this.EffectiveLevel; } } catch (Exception ex) { log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); } #if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 catch { log4net.Util.LogLog.Error(declaringType, "Exception while logging"); } #endif return false; } /// <summary> /// Gets the <see cref="ILoggerRepository"/> where this /// <c>Logger</c> instance is attached to. /// </summary> /// <value> /// The <see cref="ILoggerRepository" /> that this logger belongs to. /// </value> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> where this /// <c>Logger</c> instance is attached to. /// </para> /// </remarks> public ILoggerRepository Repository { get { return m_hierarchy; } } #endregion Implementation of ILogger /// <summary> /// Deliver the <see cref="LoggingEvent"/> to the attached appenders. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Call the appenders in the hierarchy starting at /// <c>this</c>. If no appenders could be found, emit a /// warning. /// </para> /// <para> /// This method calls all the appenders inherited from the /// hierarchy circumventing any evaluation of whether to log or not /// to log the particular log request. /// </para> /// </remarks> virtual protected void CallAppenders(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } int writes = 0; for(Logger c=this; c != null; c=c.m_parent) { if (c.m_appenderAttachedImpl != null) { // Protected against simultaneous call to addAppender, removeAppender,... c.m_appenderLock.AcquireReaderLock(); try { if (c.m_appenderAttachedImpl != null) { writes += c.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); } } finally { c.m_appenderLock.ReleaseReaderLock(); } } if (!c.m_additive) { break; } } // No appenders in hierarchy, warn user only once. // // Note that by including the AppDomain values for the currently running // thread, it becomes much easier to see which application the warning // is from, which is especially helpful in a multi-AppDomain environment // (like IIS with multiple VDIRS). Without this, it can be difficult // or impossible to determine which .config file is missing appender // definitions. // if (!m_hierarchy.EmittedNoAppenderWarning && writes == 0) { m_hierarchy.EmittedNoAppenderWarning = true; LogLog.Debug(declaringType, "No appenders could be found for logger [" + Name + "] repository [" + Repository.Name + "]"); LogLog.Debug(declaringType, "Please initialize the log4net system properly."); try { LogLog.Debug(declaringType, " Current AppDomain context information: "); LogLog.Debug(declaringType, " BaseDirectory : " + SystemInfo.ApplicationBaseDirectory); #if !(NETCF || NETSTANDARD1_3) LogLog.Debug(declaringType, " FriendlyName : " + AppDomain.CurrentDomain.FriendlyName); LogLog.Debug(declaringType, " DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory); #endif } catch(System.Security.SecurityException) { // Insufficient permissions to display info from the AppDomain } } } /// <summary> /// Closes all attached appenders implementing the <see cref="IAppenderAttachable"/> interface. /// </summary> /// <remarks> /// <para> /// Used to ensure that the appenders are correctly shutdown. /// </para> /// </remarks> virtual public void CloseNestedAppenders() { m_appenderLock.AcquireWriterLock(); try { if (m_appenderAttachedImpl != null) { AppenderCollection appenders = m_appenderAttachedImpl.Appenders; foreach(IAppender appender in appenders) { if (appender is IAppenderAttachable) { appender.Close(); } } } } finally { m_appenderLock.ReleaseWriterLock(); } } /// <summary> /// This is the most generic printing method. This generic form is intended to be used by wrappers /// </summary> /// <param name="level">The level of the message to be logged.</param> /// <param name="message">The message object to log.</param> /// <param name="exception">The exception to log, including its stack trace.</param> /// <remarks> /// <para> /// Generate a logging event for the specified <paramref name="level"/> using /// the <paramref name="message"/>. /// </para> /// </remarks> virtual public void Log(Level level, object message, Exception exception) { if (IsEnabledFor(level)) { ForcedLog(declaringType, level, message, exception); } } /// <summary> /// Creates a new logging event and logs the event without further checks. /// </summary> /// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is /// the stack boundary into the logging system for this call.</param> /// <param name="level">The level of the message to be logged.</param> /// <param name="message">The message object to log.</param> /// <param name="exception">The exception to log, including its stack trace.</param> /// <remarks> /// <para> /// Generates a logging event and delivers it to the attached /// appenders. /// </para> /// </remarks> virtual protected void ForcedLog(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) { CallAppenders(new LoggingEvent(callerStackBoundaryDeclaringType, this.Hierarchy, this.Name, level, message, exception)); } /// <summary> /// Creates a new logging event and logs the event without further checks. /// </summary> /// <param name="logEvent">The event being logged.</param> /// <remarks> /// <para> /// Delivers the logging event to the attached appenders. /// </para> /// </remarks> virtual protected void ForcedLog(LoggingEvent logEvent) { // The logging event may not have been created by this logger // the Repository may not be correctly set on the event. This // is required for the appenders to correctly lookup renderers etc... logEvent.EnsureRepository(this.Hierarchy); CallAppenders(logEvent); } #region Private Static Fields /// <summary> /// The fully qualified type of the Logger class. /// </summary> private readonly static Type declaringType = typeof(Logger); #endregion Private Static Fields #region Private Instance Fields /// <summary> /// The name of this logger. /// </summary> private readonly string m_name; /// <summary> /// The assigned level of this logger. /// </summary> /// <remarks> /// <para> /// The <c>level</c> variable need not be /// assigned a value in which case it is inherited /// form the hierarchy. /// </para> /// </remarks> private Level m_level; /// <summary> /// The parent of this logger. /// </summary> /// <remarks> /// <para> /// The parent of this logger. /// All loggers have at least one ancestor which is the root logger. /// </para> /// </remarks> private Logger m_parent; /// <summary> /// Loggers need to know what Hierarchy they are in. /// </summary> /// <remarks> /// <para> /// Loggers need to know what Hierarchy they are in. /// The hierarchy that this logger is a member of is stored /// here. /// </para> /// </remarks> private Hierarchy m_hierarchy; /// <summary> /// Helper implementation of the <see cref="IAppenderAttachable"/> interface /// </summary> private log4net.Util.AppenderAttachedImpl m_appenderAttachedImpl; /// <summary> /// Flag indicating if child loggers inherit their parents appenders /// </summary> /// <remarks> /// <para> /// Additivity is set to true by default, that is children inherit /// the appenders of their ancestors by default. If this variable is /// set to <c>false</c> then the appenders found in the /// ancestors of this logger are not used. However, the children /// of this logger will inherit its appenders, unless the children /// have their additivity flag set to <c>false</c> too. See /// the user manual for more details. /// </para> /// </remarks> private bool m_additive = true; /// <summary> /// Lock to protect AppenderAttachedImpl variable m_appenderAttachedImpl /// </summary> private readonly ReaderWriterLock m_appenderLock = new ReaderWriterLock(); #endregion } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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.Runtime.InteropServices; using UnityEngine; using Ovr; /// <summary> /// Configuration data for Oculus virtual reality. /// </summary> public class OVRManager : MonoBehaviour { /// <summary> /// Contains information about the user's preferences and body dimensions. /// </summary> public struct Profile { public float ipd; public float eyeHeight; public float neckHeight; } /// <summary> /// Gets the singleton instance. /// </summary> public static OVRManager instance { get; private set; } /// <summary> /// Gets a reference to the low-level C API Hmd Wrapper /// </summary> private static Hmd _capiHmd; public static Hmd capiHmd { get { #if !UNITY_ANDROID || UNITY_EDITOR if (_capiHmd == null) { IntPtr hmdPtr = IntPtr.Zero; OVR_GetHMD(ref hmdPtr); _capiHmd = (hmdPtr != IntPtr.Zero) ? new Hmd(hmdPtr) : null; } #else _capiHmd = null; #endif return _capiHmd; } } /// <summary> /// Gets a reference to the active OVRDisplay /// </summary> public static OVRDisplay display { get; private set; } /// <summary> /// Gets a reference to the active OVRTracker /// </summary> public static OVRTracker tracker { get; private set; } /// <summary> /// Gets the current profile, which contains information about the user's settings and body dimensions. /// </summary> private static bool _profileIsCached = false; private static Profile _profile; public static Profile profile { get { if (!_profileIsCached) { #if !UNITY_ANDROID || UNITY_EDITOR float ipd = capiHmd.GetFloat(Hmd.OVR_KEY_IPD, Hmd.OVR_DEFAULT_IPD); float eyeHeight = capiHmd.GetFloat(Hmd.OVR_KEY_EYE_HEIGHT, Hmd.OVR_DEFAULT_EYE_HEIGHT); float neckToEyeOffsetY = capiHmd.GetFloat(Hmd.OVR_KEY_NECK_TO_EYE_DISTANCE, Hmd.OVR_DEFAULT_NECK_TO_EYE_VERTICAL); float neckHeight = eyeHeight - neckToEyeOffsetY; _profile = new Profile { ipd = ipd, eyeHeight = eyeHeight, neckHeight = neckHeight, }; #else float ipd = 0.0f; OVR_GetInterpupillaryDistance(ref ipd); float eyeHeight = 0.0f; OVR_GetPlayerEyeHeight(ref eyeHeight); _profile = new Profile { ipd = ipd, eyeHeight = eyeHeight, neckHeight = 0.0f, // TODO }; #endif _profileIsCached = true; } return _profile; } } /// <summary> /// Occurs when an HMD attached. /// </summary> public static event Action HMDAcquired; /// <summary> /// Occurs when an HMD detached. /// </summary> public static event Action HMDLost; /// <summary> /// Occurs when the tracker gained tracking. /// </summary> public static event Action TrackingAcquired; /// <summary> /// Occurs when the tracker lost tracking. /// </summary> public static event Action TrackingLost; /// <summary> /// Occurs when HSW dismissed. /// </summary> public static event Action HSWDismissed; /// <summary> /// If true, then the Oculus health and safety warning (HSW) is currently visible. /// </summary> public static bool isHSWDisplayed { get { #if !UNITY_ANDROID || UNITY_EDITOR return capiHmd.GetHSWDisplayState().Displayed; #else return false; #endif } } /// <summary> /// If the HSW has been visible for the necessary amount of time, this will make it disappear. /// </summary> public static void DismissHSWDisplay() { #if !UNITY_ANDROID || UNITY_EDITOR capiHmd.DismissHSWDisplay(); #endif } /// <summary> /// Gets the current battery level. /// </summary> /// <returns><c>battery level in the range [0.0,1.0]</c> /// <param name="batteryLevel">Battery level.</param> public static float batteryLevel { get { #if !UNITY_ANDROID || UNITY_EDITOR return 1.0f; #else return OVR_GetBatteryLevel(); #endif } } /// <summary> /// Gets the current battery temperature. /// </summary> /// <returns><c>battery temperature in Celsius</c> /// <param name="batteryTemperature">Battery temperature.</param> public static float batteryTemperature { get { #if !UNITY_ANDROID || UNITY_EDITOR return 0.0f; #else return OVR_GetBatteryTemperature(); #endif } } /// <summary> /// Gets the current battery status. /// </summary> /// <returns><c>battery status</c> /// <param name="batteryStatus">Battery status.</param> public static int batteryStatus { get { #if !UNITY_ANDROID || UNITY_EDITOR return 0; #else return OVR_GetBatteryStatus(); #endif } } /// <summary> /// Controls the size of the eye textures. /// Values must be above 0. /// Values below 1 permit sub-sampling for improved performance. /// Values above 1 permit super-sampling for improved sharpness. /// </summary> public float nativeTextureScale = 1.0f; /// <summary> /// Controls the size of the rendering viewport. /// Values must be between 0 and 1. /// Values below 1 permit dynamic sub-sampling for improved performance. /// </summary> public float virtualTextureScale = 1.0f; /// <summary> /// If true, head tracking will affect the orientation of each OVRCameraRig's cameras. /// </summary> public bool usePositionTracking = true; /// <summary> /// The format of each eye texture. /// </summary> public RenderTextureFormat eyeTextureFormat = RenderTextureFormat.Default; /// <summary> /// The depth of each eye texture in bits. /// </summary> public int eyeTextureDepth = 24; /// <summary> /// If true, TimeWarp will be used to correct the output of each OVRCameraRig for rotational latency. /// </summary> public bool timeWarp = true; /// <summary> /// If this is true and TimeWarp is true, each OVRCameraRig will stop tracking and only TimeWarp will respond to head motion. /// </summary> public bool freezeTimeWarp = false; /// <summary> /// If true, each scene load will cause the head pose to reset. /// </summary> public bool resetTrackerOnLoad = true; /// <summary> /// If true, the eyes see the same image, which is rendered only by the left camera. /// </summary> public bool monoscopic = false; /// <summary> /// True if the current platform supports virtual reality. /// </summary> public bool isSupportedPlatform { get; private set; } private static bool usingPositionTracking = false; private static bool wasHmdPresent = false; private static bool wasPositionTracked = false; private static WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); #if UNITY_ANDROID && !UNITY_EDITOR // Get this from Unity on startup so we can call Activity java functions private static bool androidJavaInit = false; private static AndroidJavaObject activity; private static AndroidJavaClass javaVrActivityClass; internal static int timeWarpViewNumber = 0; public static event Action OnCustomPostRender; #endif public static bool isPaused { get { return _isPaused; } set { #if UNITY_ANDROID && !UNITY_EDITOR RenderEventType eventType = (value) ? RenderEventType.Pause : RenderEventType.Resume; OVRPluginEvent.Issue(eventType); #endif _isPaused = value; } } private static bool _isPaused; #region Unity Messages private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; #if !UNITY_ANDROID || UNITY_EDITOR var netVersion = new System.Version(Ovr.Hmd.OVR_VERSION_STRING); var ovrVersion = new System.Version(Ovr.Hmd.GetVersionString()); if (netVersion > ovrVersion) Debug.LogWarning("Using an older version of LibOVR."); #endif // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; isSupportedPlatform |= currPlatform == RuntimePlatform.Android; isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer; if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if UNITY_ANDROID && !UNITY_EDITOR Application.targetFrameRate = 60; // don't allow the app to run in the background Application.runInBackground = false; // Disable screen dimming Screen.sleepTimeout = SleepTimeout.NeverSleep; if (!androidJavaInit) { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); javaVrActivityClass = new AndroidJavaClass("com.oculusvr.vrlib.VrActivity"); // Prepare for the RenderThreadInit() SetInitVariables(activity.GetRawObject(), javaVrActivityClass.GetRawClass()); androidJavaInit = true; } // We want to set up our touchpad messaging system OVRTouchpad.Create(); // This will trigger the init on the render thread InitRenderThread(); #else SetEditorPlay(Application.isEditor); #endif display = new OVRDisplay(); tracker = new OVRTracker(); // Except for D3D9, SDK rendering forces vsync unless you pass ovrHmdCap_NoVSync to Hmd.SetEnabledCaps(). if (timeWarp) { bool useUnityVSync = SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9"); QualitySettings.vSyncCount = useUnityVSync ? 1 : 0; } } private void Start() { Camera cam = GetComponent<Camera>(); if (cam == null) { // Ensure there is a non-RT camera in the scene to force rendering of the left and right eyes. cam = gameObject.AddComponent<Camera>(); cam.cullingMask = 0; cam.clearFlags = CameraClearFlags.Nothing; cam.renderingPath = RenderingPath.Forward; cam.orthographic = true; cam.useOcclusionCulling = false; } bool isD3d = SystemInfo.graphicsDeviceVersion.Contains("Direct3D") || Application.platform == RuntimePlatform.WindowsEditor && SystemInfo.graphicsDeviceVersion.Contains("emulated"); display.flipInput = isD3d; StartCoroutine(CallbackCoroutine()); } private void Update() { if (usePositionTracking != usingPositionTracking) { tracker.isEnabled = usePositionTracking; usingPositionTracking = usePositionTracking; } // Dispatch any events. if (HMDLost != null && wasHmdPresent && !display.isPresent) HMDLost(); if (HMDAcquired != null && !wasHmdPresent && display.isPresent) HMDAcquired(); wasHmdPresent = display.isPresent; if (TrackingLost != null && wasPositionTracked && !tracker.isPositionTracked) TrackingLost(); if (TrackingAcquired != null && !wasPositionTracked && tracker.isPositionTracked) TrackingAcquired(); wasPositionTracked = tracker.isPositionTracked; if (isHSWDisplayed && Input.anyKeyDown) { DismissHSWDisplay(); if (HSWDismissed != null) HSWDismissed(); } display.timeWarp = timeWarp; #if (!UNITY_ANDROID || UNITY_EDITOR) display.Update(); #endif } #if (UNITY_EDITOR_OSX) private void OnPreCull() // TODO: Fix Mac Unity Editor memory corruption issue requiring OnPreCull workaround. #else private void LateUpdate() #endif { #if (!UNITY_ANDROID || UNITY_EDITOR) display.BeginFrame(); #endif } private IEnumerator CallbackCoroutine() { while (true) { yield return waitForEndOfFrame; #if UNITY_ANDROID && !UNITY_EDITOR OVRManager.DoTimeWarp(timeWarpViewNumber); #else display.EndFrame(); #endif } } #if UNITY_ANDROID && !UNITY_EDITOR private void OnPause() { isPaused = true; } private void OnApplicationPause(bool pause) { Debug.Log("OnApplicationPause() " + pause); if (pause) { OnPause(); } else { StartCoroutine(OnResume()); } } void OnDisable() { StopAllCoroutines(); } private IEnumerator OnResume() { yield return null; // delay 1 frame to allow Unity enough time to create the windowSurface isPaused = false; } /// <summary> /// Leaves the application/game and returns to the launcher/dashboard /// </summary> public void ReturnToLauncher() { // show the platform UI quit prompt OVRManager.PlatformUIConfirmQuit(); } private void OnPostRender() { // Allow custom code to render before we kick off the plugin if (OnCustomPostRender != null) { OnCustomPostRender(); } EndEye(OVREye.Left, display.GetEyeTextureId(OVREye.Left)); EndEye(OVREye.Right, display.GetEyeTextureId(OVREye.Right)); } #endif #endregion public static void SetEditorPlay(bool isEditor) { #if !UNITY_ANDROID || UNITY_EDITOR OVR_SetEditorPlay(isEditor); #endif } public static void SetDistortionCaps(uint distortionCaps) { #if !UNITY_ANDROID || UNITY_EDITOR OVR_SetDistortionCaps(distortionCaps); #endif } public static void SetInitVariables(IntPtr activity, IntPtr vrActivityClass) { #if UNITY_ANDROID && !UNITY_EDITOR OVR_SetInitVariables(activity, vrActivityClass); #endif } public static void PlatformUIConfirmQuit() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.PlatformUIConfirmQuit); #endif } public static void PlatformUIGlobalMenu() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.PlatformUI); #endif } public static void DoTimeWarp(int timeWarpViewNumber) { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.IssueWithData(RenderEventType.TimeWarp, timeWarpViewNumber); #endif } public static void EndEye(OVREye eye, int eyeTextureId) { #if UNITY_ANDROID && !UNITY_EDITOR RenderEventType eventType = (eye == OVREye.Left) ? RenderEventType.LeftEyeEndFrame : RenderEventType.RightEyeEndFrame; OVRPluginEvent.IssueWithData(eventType, eyeTextureId); #endif } public static void InitRenderThread() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.InitRenderThread); #endif } private const string LibOVR = "OculusPlugin"; #if !UNITY_ANDROID || UNITY_EDITOR [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_GetHMD(ref IntPtr hmdPtr); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_SetEditorPlay(bool isEditorPlay); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_SetDistortionCaps(uint distortionCaps); #else [DllImport(LibOVR)] private static extern void OVR_SetInitVariables(IntPtr activity, IntPtr vrActivityClass); [DllImport(LibOVR)] private static extern float OVR_GetBatteryLevel(); [DllImport(LibOVR)] private static extern int OVR_GetBatteryStatus(); [DllImport(LibOVR)] private static extern float OVR_GetBatteryTemperature(); [DllImport(LibOVR)] private static extern bool OVR_GetPlayerEyeHeight(ref float eyeHeight); [DllImport(LibOVR)] private static extern bool OVR_GetInterpupillaryDistance(ref float interpupillaryDistance); #endif }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedDivideNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableSByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Helpers public static byte DivideNullableByte(byte a, byte b) { return (byte)(a / b); } public static char DivideNullableChar(char a, char b) { return (char)(a / b); } public static decimal DivideNullableDecimal(decimal a, decimal b) { return (decimal)(a / b); } public static double DivideNullableDouble(double a, double b) { return (double)(a / b); } public static float DivideNullableFloat(float a, float b) { return (float)(a / b); } public static int DivideNullableInt(int a, int b) { return (int)(a / b); } public static long DivideNullableLong(long a, long b) { return (long)(a / b); } public static sbyte DivideNullableSByte(sbyte a, sbyte b) { return (sbyte)(a / b); } public static short DivideNullableShort(short a, short b) { return (short)(a / b); } public static uint DivideNullableUInt(uint a, uint b) { return (uint)(a / b); } public static ulong DivideNullableULong(ulong a, ulong b) { return (ulong)(a / b); } public static ushort DivideNullableUShort(ushort a, ushort b) { return (ushort)(a / b); } #endregion #region Test verifiers private static void VerifyDivideNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Divide( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableByte"))); Func<byte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((byte?)(a / b), f()); } private static void VerifyDivideNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Divide( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableChar"))); Func<char?> f = e.Compile(useInterpreter); if (a.HasValue && b == '\0') Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((char?)(a / b), f()); } private static void VerifyDivideNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Divide( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableDecimal"))); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Divide( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableDouble"))); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDivideNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Divide( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableFloat"))); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDivideNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Divide( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableInt"))); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == int.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Divide( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableLong"))); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == long.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Divide( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableSByte"))); Func<sbyte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((sbyte?)(a / b), f()); } private static void VerifyDivideNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Divide( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableShort"))); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((short?)(a / b), f()); } private static void VerifyDivideNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Divide( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableUInt"))); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Divide( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableULong"))); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Divide( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableUShort"))); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((ushort?)(a / b), f()); } #endregion } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; #if !(NET_1_1) using System.Collections.Generic; using System.Collections.ObjectModel; #endif using System.Reflection; using System.Text; using System.Collections; namespace FluorineFx.Util { /// <summary> /// Collection utility class. /// </summary> public abstract class CollectionUtils { private CollectionUtils() { } /// <summary> /// Determines whether the collection is null or empty. /// </summary> /// <param name="collection">The collection.</param> /// <returns> /// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmpty(ICollection collection) { if (collection != null) { return (collection.Count == 0); } return true; } /// <summary> /// Creates an IList. /// </summary> /// <param name="listType">The list type.</param> /// <returns>The newly created IList.</returns> public static IList CreateList(Type listType) { ValidationUtils.ArgumentNotNull(listType, "listType"); IList list; #if !(NET_1_1) Type readOnlyCollectionType; #endif bool isReadOnlyOrFixedSize = false; if (listType.IsArray) { // have to use an arraylist when creating array // there is no way to know the size until it is finised #if !(NET_1_1) list = new List<object>(); #else list = new ArrayList(); #endif isReadOnlyOrFixedSize = true; } #if !(NET_1_1) else if (ReflectionUtils.IsSubClass(listType, typeof(ReadOnlyCollection<>), out readOnlyCollectionType)) { Type readOnlyCollectionContentsType = readOnlyCollectionType.GetGenericArguments()[0]; Type genericEnumerable = ReflectionUtils.MakeGenericType(typeof(IEnumerable<>), readOnlyCollectionContentsType); bool suitableConstructor = false; foreach (ConstructorInfo constructor in listType.GetConstructors()) { IList<ParameterInfo> parameters = constructor.GetParameters(); if (parameters.Count == 1) { if (genericEnumerable.IsAssignableFrom(parameters[0].ParameterType)) { suitableConstructor = true; break; } } } if (!suitableConstructor) throw new Exception(string.Format("Readonly type {0} does not have a public constructor that takes a type that implements {1}.", listType, genericEnumerable)); // can't add or modify a readonly list // use List<T> and convert once populated list = (IList)CreateGenericList(readOnlyCollectionContentsType); isReadOnlyOrFixedSize = true; } #endif else if (typeof(IList).IsAssignableFrom(listType) && ReflectionUtils.IsInstantiatableType(listType)) { list = (IList)Activator.CreateInstance(listType); } else if (ReflectionUtils.IsSubClass(listType, typeof(IList<>))) { list = CreateGenericList(ReflectionUtils.GetGenericArguments(listType)[0]) as IList; } else { throw new Exception(string.Format("Cannot create and populate list type {0}.", listType)); } // create readonly and fixed sized collections using the temporary list if (isReadOnlyOrFixedSize) { if (listType.IsArray) #if !(NET_1_1) list = ((List<object>)list).ToArray(); #else list = ((ArrayList)list).ToArray(ReflectionUtils.GetListItemType(listType)); #endif #if !(NET_1_1) else if (ReflectionUtils.IsSubClass(listType, typeof(ReadOnlyCollection<>))) list = (IList)Activator.CreateInstance(listType, list); #endif } return list; } /// <summary> /// Creates a new Array by copying the elements from the specified collection. /// </summary> /// <param name="type">Array element type.</param> /// <param name="collection">The ICollection object to copy to a new Array.</param> /// <returns>The newly created Array.</returns> public static Array CreateArray(Type type, ICollection collection) { ValidationUtils.ArgumentNotNull(collection, "collection"); if (collection is Array) return collection as Array; #if !(NET_1_1) List<object> tempList = new List<object>(); foreach (object obj in collection) tempList.Add(obj); return tempList.ToArray(); #else ArrayList tempList = new ArrayList(collection); return tempList.ToArray(type); #endif } #region GetSingleItem /// <summary> /// Gets an element from the list. /// </summary> /// <param name="list">A list object.</param> /// <returns>The first element of the specified list.</returns> /// <exception cref="System.Exception">Throw when the list has no elements.</exception> public static object GetSingleItem(IList list) { return GetSingleItem(list, false); } /// <summary> /// Gets an element from the list. /// </summary> /// <param name="list">A list object.</param> /// <param name="returnDefaultIfEmpty">Specifies that null is returned if the list has no elements.</param> /// <returns>The first element of the specified list.</returns> /// /// <exception cref="System.Exception">Throw when the list has no elements and returnDefaultIfEmpty is <b>false</b>.</exception> public static object GetSingleItem(IList list, bool returnDefaultIfEmpty) { if (list.Count == 1) return list[0]; else if (returnDefaultIfEmpty && list.Count == 0) return null; else throw new Exception(string.Format("Expected single item in list but got {1}.", list.Count)); } #endregion #if !(NET_1_1) /// <summary> /// Creates a generic List. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="values">The collection whose elements values are copied to the new list.</param> /// <returns>The newly created List.</returns> public static List<T> CreateList<T>(params T[] values) { return new List<T>(values); } /// <summary> /// Determines whether the collection is null or empty. /// </summary> /// <param name="collection">The collection.</param> /// <returns> /// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmpty<T>(ICollection<T> collection) { if (collection != null) { return (collection.Count == 0); } return true; } /// <summary> /// Determines whether the collection is null, empty or its contents are uninitialized values. /// </summary> /// <param name="list">The list.</param> /// <returns> /// <c>true</c> if the collection is null or empty or its contents are uninitialized values; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmptyOrDefault<T>(IList<T> list) { if (IsNullOrEmpty<T>(list)) return true; return ReflectionUtils.ItemsUnitializedValue<T>(list); } /// <summary> /// Makes a slice of the specified list in between the start and end indexes. /// </summary> /// <param name="list">The list.</param> /// <param name="start">The start index.</param> /// <param name="end">The end index.</param> /// <returns>A slice of the list.</returns> public static IList<T> Slice<T>(IList<T> list, int? start, int? end) { return Slice<T>(list, start, end, null); } /// <summary> /// Makes a slice of the specified list in between the start and end indexes, /// getting every so many items based upon the step. /// </summary> /// <param name="list">The list.</param> /// <param name="start">The start index.</param> /// <param name="end">The end index.</param> /// <param name="step">The step.</param> /// <returns>A slice of the list.</returns> public static IList<T> Slice<T>(IList<T> list, int? start, int? end, int? step) { if (list == null) throw new ArgumentNullException("list"); if (step == 0) throw new ArgumentException("Step cannot be zero.", "step"); List<T> slicedList = new List<T>(); // nothing to slice if (list.Count == 0) return slicedList; // set defaults for null arguments int s = step ?? 1; int startIndex = start ?? 0; int endIndex = end ?? list.Count; // start from the end of the list if start is negitive startIndex = (startIndex < 0) ? list.Count + startIndex : startIndex; // end from the start of the list if end is negitive endIndex = (endIndex < 0) ? list.Count + endIndex : endIndex; // ensure indexes keep within collection bounds startIndex = Math.Max(startIndex, 0); endIndex = Math.Min(endIndex, list.Count - 1); // loop between start and end indexes, incrementing by the step for (int i = startIndex; i < endIndex; i += s) { slicedList.Add(list[i]); } return slicedList; } /// <summary> /// Adds the elements of the specified collection to the specified generic IList. /// </summary> /// <param name="initial">The list to add to.</param> /// <param name="collection">The collection of elements to add.</param> public static void AddRange<T>(IList<T> initial, IEnumerable<T> collection) { if (initial == null) throw new ArgumentNullException("initial"); if (collection == null) return; foreach (T value in collection) { initial.Add(value); } } /// <summary> /// Return a list containing only the different (distinct) values of the specified collection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection">A generic List.</param> /// <returns>A list containing only the different (distinct) values of the specified collection.</returns> public static List<T> Distinct<T>(List<T> collection) { List<T> distinctList = new List<T>(); foreach (T value in collection) { if (!distinctList.Contains(value)) distinctList.Add(value); } return distinctList; } /// <summary> /// Creates a new generic List by copying the elements from the specified collection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection">The ICollection object to copy to the generic List.</param> /// <returns>The newly created generic Lis.</returns> public static List<T> CreateList<T>(ICollection collection) { if (collection == null) throw new ArgumentNullException("collection"); T[] array = new T[collection.Count]; collection.CopyTo(array, 0); return new List<T>(array); } /// <summary> /// Determines whether two generic Lists are equal. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="a">A List object.</param> /// <param name="b">A List object.</param> /// <returns><b>true</b> if the lists are equal, otherwise <b>false</b>.</returns> /// <remarks>Two lists are considered equal if they have the same count and the default equality comparer for the generic argument determines that all elements are equal.</remarks> public static bool ListEquals<T>(IList<T> a, IList<T> b) { if (a == null || b == null) return (a == null && b == null); if (a.Count != b.Count) return false; EqualityComparer<T> comparer = EqualityComparer<T>.Default; for (int i = 0; i < a.Count; i++) { if (!comparer.Equals(a[i], b[i])) return false; } return true; } /// <summary> /// Creates a generic List. /// </summary> /// <param name="listType">The list type.</param> /// <returns>The newly created generic List.</returns> public static object CreateGenericList(Type listType) { ValidationUtils.ArgumentNotNull(listType, "listType"); return ReflectionUtils.CreateGeneric(typeof(List<>), listType); } /// <summary> /// Checks whether the specified type is a list type. /// </summary> /// <param name="type">A Type object.</param> /// <returns><b>true</b> if the type is a list type (array, IList, or generic List), otherwise <b>false</b>.</returns> public static bool IsListType(Type type) { ValidationUtils.ArgumentNotNull(type, "listType"); if (type.IsArray) return true; else if (typeof(IList).IsAssignableFrom(type)) return true; else if (ReflectionUtils.IsSubClass(type, typeof(IList<>))) return true; else return false; } /// <summary> /// Determines whether the specified type is a generic list type. /// </summary> /// <param name="type">A Type object.</param> /// <returns> /// <c>true</c> if it is a generic list type; otherwise, <c>false</c>. /// </returns> public static bool IsGenericListType(Type type) { ValidationUtils.ArgumentNotNull(type, "listType"); if (ReflectionUtils.IsSubClass(type, typeof(IList<>))) return true; else return false; } #endif } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Registrasi_HemoAddBaru : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["RegistrasiHemo"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>"; btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>"; GetListStatus(); GetListStatusPerkawinan(); GetListAgama(); GetListPendidikan(); GetListJenisPenjamin(); GetListHubungan(); txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); GetNomorRegistrasi(); GetNomorTunggu(); GetListKelompokPemeriksaan(); GetListSatuanKerja(); GetListSatuanKerjaPenjamin(); } } public void GetListStatus() { string StatusId = ""; SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status(); DataTable dt = myObj.GetList(); cmbStatusPasien.Items.Clear(); int i = 0; cmbStatusPasien.Items.Add(""); cmbStatusPasien.Items[i].Text = ""; cmbStatusPasien.Items[i].Value = ""; cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = ""; cmbStatusPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPasien.Items.Add(""); cmbStatusPasien.Items[i].Text = dr["Nama"].ToString(); cmbStatusPasien.Items[i].Value = dr["Id"].ToString(); cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusId) { cmbStatusPasien.SelectedIndex = i; cmbStatusPenjamin.SelectedIndex = i; } i++; } } public void GetListPangkatPasien() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPasien.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPasien.Items.Clear(); int i = 0; cmbPangkatPasien.Items.Add(""); cmbPangkatPasien.Items[i].Text = ""; cmbPangkatPasien.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPasien.Items.Add(""); cmbPangkatPasien.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPasien.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPasien.SelectedIndex = i; } i++; } } public void GetListPangkatPenjamin() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPenjamin.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPenjamin.Items.Clear(); int i = 0; cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = ""; cmbPangkatPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPenjamin.SelectedIndex = i; } i++; } } public void GetNomorTunggu() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 39; // Hemo myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString(); } public void GetListStatusPerkawinan() { string StatusPerkawinanId = ""; BkNet.DataAccess.StatusPerkawinan myObj = new BkNet.DataAccess.StatusPerkawinan(); DataTable dt = myObj.GetList(); cmbStatusPerkawinan.Items.Clear(); int i = 0; cmbStatusPerkawinan.Items.Add(""); cmbStatusPerkawinan.Items[i].Text = ""; cmbStatusPerkawinan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPerkawinan.Items.Add(""); cmbStatusPerkawinan.Items[i].Text = dr["Nama"].ToString(); cmbStatusPerkawinan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusPerkawinanId) cmbStatusPerkawinan.SelectedIndex = i; i++; } } public void GetListAgama() { string AgamaId = ""; BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama(); DataTable dt = myObj.GetList(); cmbAgama.Items.Clear(); int i = 0; cmbAgama.Items.Add(""); cmbAgama.Items[i].Text = ""; cmbAgama.Items[i].Value = ""; cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = ""; cmbAgamaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbAgama.Items.Add(""); cmbAgama.Items[i].Text = dr["Nama"].ToString(); cmbAgama.Items[i].Value = dr["Id"].ToString(); cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == AgamaId) cmbAgama.SelectedIndex = i; i++; } } public void GetListPendidikan() { string PendidikanId = ""; BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan(); DataTable dt = myObj.GetList(); cmbPendidikan.Items.Clear(); int i = 0; cmbPendidikan.Items.Add(""); cmbPendidikan.Items[i].Text = ""; cmbPendidikan.Items[i].Value = ""; cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = ""; cmbPendidikanPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPendidikan.Items.Add(""); cmbPendidikan.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikan.Items[i].Value = dr["Id"].ToString(); cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PendidikanId) cmbPendidikan.SelectedIndex = i; i++; } } public void GetListJenisPenjamin() { string JenisPenjaminId = ""; SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin(); DataTable dt = myObj.GetList(); cmbJenisPenjamin.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbJenisPenjamin.Items.Add(""); cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == JenisPenjaminId) cmbJenisPenjamin.SelectedIndex = i; i++; } } public void GetListHubungan() { string HubunganId = ""; SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan(); DataTable dt = myObj.GetList(); cmbHubungan.Items.Clear(); int i = 0; cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = ""; cmbHubungan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = dr["Nama"].ToString(); cmbHubungan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == HubunganId) cmbHubungan.SelectedIndex = i; i++; } } public void GetNomorRegistrasi() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 39;//Hemo myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNoRegistrasi.Text = myObj.GetNomorRegistrasi(); } public void GetListKelompokPemeriksaan() { SIMRS.DataAccess.RS_KelompokPemeriksaan myObj = new SIMRS.DataAccess.RS_KelompokPemeriksaan(); myObj.JenisPemeriksaanId = 3;//Hemo DataTable dt = myObj.GetListByJenisPemeriksaanId(); cmbKelompokPemeriksaan.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbKelompokPemeriksaan.Items.Add(""); cmbKelompokPemeriksaan.Items[i].Text = dr["Nama"].ToString(); cmbKelompokPemeriksaan.Items[i].Value = dr["Id"].ToString(); i++; } cmbKelompokPemeriksaan.SelectedIndex = 0; GetListPemeriksaan(); } public DataSet GetDataPemeriksaan() { DataSet ds = new DataSet(); if (Session["dsLayananHemo"] != null) ds = (DataSet)Session["dsLayananHemo"]; else { SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); myObj.PoliklinikId = 39;// Hemo DataTable myData = myObj.SelectAllWPoliklinikIdLogic(); ds.Tables.Add(myData); Session.Add("dsLayananHemo", ds); } return ds; } public void GetListPemeriksaan() { DataSet ds = new DataSet(); ds = GetDataPemeriksaan(); lstRefPemeriksaan.DataTextField = "Nama"; lstRefPemeriksaan.DataValueField = "Id"; DataView dv = ds.Tables[0].DefaultView; if (cmbKelompokPemeriksaan.Text!="") dv.RowFilter = " KelompokPemeriksaanId = " + cmbKelompokPemeriksaan.SelectedItem.Value; lstRefPemeriksaan.DataSource = dv; lstRefPemeriksaan.DataBind(); } public void OnSave(Object sender, EventArgs e) { lblError.Text = ""; if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return; } string noRM1 = txtNoRM.Text.Replace("_",""); string noRM2 = noRM1.Replace(".",""); if (noRM2 == "") { lblError.Text = "Nomor Rekam Medis Harus diisi"; return; } else if (noRM2.Length < 5) { lblError.Text = "Nomor Rekam Medis Harus diisi dengan benar"; return; } //if(noRM1.Substring(noRM1.LastIndexOf(".")) == "") SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien(); //txtNoRM.Text = txtNoRM1.Text + "." + txtNoRM2.Text + "." + txtNoRM3.Text; myPasien.PasienId = 0; myPasien.NoRM = txtNoRM.Text.Replace("_", ""); myPasien.Nama = txtNama.Text; if (cmbStatusPasien.SelectedIndex > 0) myPasien.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value); if (cmbPangkatPasien.SelectedIndex > 0) myPasien.PangkatId = int.Parse(cmbPangkatPasien.SelectedItem.Value); myPasien.NoAskes = txtNoASKES.Text; myPasien.NoKTP = txtNoKTP.Text; myPasien.GolDarah = txtGolDarah.Text; myPasien.NRP = txtNrpPasien.Text; myPasien.Jabatan = txtJabatanPasien.Text; //myPasien.Kesatuan = txtKesatuanPasien.Text; myPasien.Kesatuan = cmbSatuanKerja.SelectedItem.ToString(); myPasien.AlamatKesatuan = txtAlamatKesatuanPasien.Text; myPasien.TempatLahir = txtTempatLahir.Text; if (txtTanggalLahir.Text != "") myPasien.TanggalLahir = DateTime.Parse(txtTanggalLahir.Text); myPasien.Alamat = txtAlamatPasien.Text; myPasien.Telepon = txtTeleponPasien.Text; if (cmbJenisKelamin.SelectedIndex > 0) myPasien.JenisKelamin = cmbJenisKelamin.SelectedItem.Value; if (cmbStatusPerkawinan.SelectedIndex > 0) myPasien.StatusPerkawinanId = int.Parse(cmbStatusPerkawinan.SelectedItem.Value); if (cmbAgama.SelectedIndex > 0) myPasien.AgamaId = int.Parse(cmbAgama.SelectedItem.Value); if (cmbPendidikan.SelectedIndex > 0) myPasien.PendidikanId = int.Parse(cmbPendidikan.SelectedItem.Value); myPasien.Pekerjaan = txtPekerjaan.Text; myPasien.AlamatKantor = txtAlamatKantorPasien.Text; myPasien.TeleponKantor = txtTeleponKantorPasien.Text; myPasien.Keterangan = txtKeteranganPasien.Text; myPasien.CreatedBy = UserId; myPasien.CreatedDate = DateTime.Now; if (myPasien.IsExist()) { lblError.Text = myPasien.ErrorMessage.ToString(); return; } else { myPasien.Insert(); int PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex > 0) { //Input Data Penjamin SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin(); myPenj.PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex == 1) { myPenj.Nama = txtNamaPenjamin.Text; if (cmbHubungan.SelectedIndex > 0) myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value); myPenj.Umur = txtUmurPenjamin.Text; myPenj.Alamat = txtAlamatPenjamin.Text; myPenj.Telepon = txtTeleponPenjamin.Text; if (cmbAgamaPenjamin.SelectedIndex > 0) myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value); if (cmbPendidikanPenjamin.SelectedIndex > 0) myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value); if (cmbPangkatPenjamin.SelectedIndex > 0) myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value); myPenj.NoKTP = txtNoKTPPenjamin.Text; myPenj.GolDarah = txtGolDarahPenjamin.Text; myPenj.NRP = txtNRPPenjamin.Text; //myPenj.Kesatuan = txtKesatuanPenjamin.Text; myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString(); myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text; myPenj.Keterangan = txtKeteranganPenjamin.Text; } else { myPenj.Nama = txtNamaPerusahaan.Text; myPenj.NamaKontak = txtNamaKontak.Text; myPenj.Alamat = txtAlamatPerusahaan.Text; myPenj.Telepon = txtTeleponPerusahaan.Text; myPenj.Fax = txtFAXPerusahaan.Text; } myPenj.CreatedBy = UserId; myPenj.CreatedDate = DateTime.Now; myPenj.Insert(); PenjaminId = (int)myPenj.PenjaminId; } //Input Data Registrasi SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.RegistrasiId = 0; myReg.PasienId = myPasien.PasienId; GetNomorRegistrasi(); myReg.NoRegistrasi = txtNoRegistrasi.Text; myReg.JenisRegistrasiId = 1; myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text); myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value); if (PenjaminId != 0) myReg.PenjaminId = PenjaminId; myReg.CreatedBy = UserId; myReg.CreatedDate = DateTime.Now; //myReg.NoUrut = txtNoUrut.Text; myReg.Insert(); //Input Data Rawat Jalan SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan(); myRJ.RawatJalanId = 0; myRJ.RegistrasiId = myReg.RegistrasiId; myRJ.PoliklinikId = 39;// Hemo myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); GetNomorTunggu(); if (txtNomorTunggu.Text != "" ) myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text); myRJ.Status = 0;//Baru daftar myRJ.CreatedBy = UserId; myRJ.CreatedDate = DateTime.Now; myRJ.Insert(); ////Input Data Layanan SIMRS.DataAccess.RS_RJLayanan myLayanan = new SIMRS.DataAccess.RS_RJLayanan(); SIMRS.DataAccess.RS_Layanan myTarif = new SIMRS.DataAccess.RS_Layanan(); if (lstPemeriksaan.Items.Count > 0) { string[] kellay; string[] Namakellay; DataTable dt; for (int i = 0; i < lstPemeriksaan.Items.Count; i++) { myLayanan.RJLayananId = 0; myLayanan.RawatJalanId = myRJ.RawatJalanId; myLayanan.JenisLayananId = 3; kellay = lstPemeriksaan.Items[i].Value.Split('|'); Namakellay = lstPemeriksaan.Items[i].Text.Split(':'); myLayanan.KelompokLayananId = 2; myLayanan.LayananId = int.Parse(kellay[1]); myLayanan.NamaLayanan = Namakellay[1]; myTarif.Id = int.Parse(kellay[1]); dt = myTarif.GetTarifRIByLayananId(0); if (dt.Rows.Count > 0) myLayanan.Tarif = dt.Rows[0]["Tarif"].ToString() != "" ? (Decimal)dt.Rows[0]["Tarif"] : 0; else myLayanan.Tarif = 0; myLayanan.JumlahSatuan = double.Parse("1"); myLayanan.Discount = 0; myLayanan.BiayaTambahan = 0; myLayanan.JumlahTagihan = myLayanan.Tarif; myLayanan.Keterangan = ""; myLayanan.CreatedBy = UserId; myLayanan.CreatedDate = DateTime.Now; myLayanan.Insert(); } } //================= string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("HemoView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId); } } public void OnCancel(Object sender, EventArgs e) { string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("HemoList.aspx?CurrentPage=" + CurrentPage); } protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e) { if (cmbJenisPenjamin.SelectedIndex == 1) { tblPenjaminKeluarga.Visible = true; tblPenjaminPerusahaan.Visible = false; } else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3) { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = true; } else { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = false; } } protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { GetNomorTunggu(); GetNomorRegistrasi(); } protected void cmbStatusPasien_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPasien(); } protected void cmbStatusPenjamin_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPenjamin(); } protected void cmbKelompokPemeriksaan_SelectedIndexChanged(object sender, EventArgs e) { GetListPemeriksaan(); } protected void btnAddPemeriksaan_Click(object sender, EventArgs e) { if (lstRefPemeriksaan.SelectedIndex != -1) { int i = lstPemeriksaan.Items.Count; bool exist = false; string selectValue = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; for (int j = 0; j < i; j++) { if (lstPemeriksaan.Items[j].Value == selectValue) { exist = true; break; } } if (!exist) { ListItem newItem = new ListItem(); newItem.Text = cmbKelompokPemeriksaan.SelectedItem.Text + ": " + lstRefPemeriksaan.SelectedItem.Text; newItem.Value = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; lstPemeriksaan.Items.Add(newItem); } } } protected void btnRemovePemeriksaan_Click(object sender, EventArgs e) { if (lstPemeriksaan.SelectedIndex != -1) { lstPemeriksaan.Items.RemoveAt(lstPemeriksaan.SelectedIndex); } } protected void btnCek_Click(object sender, EventArgs e) { SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien(); myPasien.NoRM = txtNoRM.Text.Replace("_", ""); if (myPasien.IsExistRM()) { lblCek.Text = "No.RM sudah terpakai"; return; } else { lblCek.Text = "No.RM belum terpakai"; return; } } public void GetListSatuanKerja() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerja.Items.Clear(); int i = 0; cmbSatuanKerja.Items.Add(""); cmbSatuanKerja.Items[i].Text = ""; cmbSatuanKerja.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerja.Items.Add(""); cmbSatuanKerja.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerja.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) cmbSatuanKerja.SelectedIndex = i; i++; } } public void GetListSatuanKerjaPenjamin() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerjaPenjamin.Items.Clear(); int i = 0; cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = ""; cmbSatuanKerjaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) cmbSatuanKerjaPenjamin.SelectedIndex = i; i++; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; #pragma warning disable 0414 namespace System.Reflection.Tests { public class ConstructorInfoTests { [Fact] public void ConstructorName() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Equal(3, constructors.Length); foreach (ConstructorInfo constructorInfo in constructors) { Assert.Equal(ConstructorInfo.ConstructorName, constructorInfo.Name); } } public static IEnumerable<object[]> Equals_TestData() { ConstructorInfo[] methodSampleConstructors1 = GetConstructors(typeof(ClassWith3Constructors)); ConstructorInfo[] methodSampleConstructors2 = GetConstructors(typeof(ClassWith3Constructors)); yield return new object[] { methodSampleConstructors1[0], methodSampleConstructors2[0], true }; yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[1], true }; yield return new object[] { methodSampleConstructors1[2], methodSampleConstructors2[2], true }; yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[2], false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) { Assert.Equal(expected, constructorInfo1.Equals(constructorInfo2)); } [Fact] public void GetHashCodeTest() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); foreach (ConstructorInfo constructorInfo in constructors) { Assert.NotEqual(0, constructorInfo.GetHashCode()); } } [Fact] public void Invoke() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Equal(constructors.Length, 3); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[0].Invoke(null); Assert.NotNull(obj); } [Fact] public void Invoke_StaticConstructor_NullObject_NullParameters() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWithStaticConstructor)); object obj = constructors[0].Invoke(null, new object[] { }); Assert.Null(obj); } [Fact] public void Invoke_StaticConstructor_ThrowsMemberAccessException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWithStaticConstructor)); Assert.Throws<MemberAccessException>(() => constructors[0].Invoke(new object[0])); } [Fact] public void Invoke_OneDimensionalArray() { ConstructorInfo[] constructors = GetConstructors(typeof(object[])); int[] arraylength = { 1, 2, 99, 65535 }; // Try to invoke Array ctors with different lengths foreach (int length in arraylength) { // Create big Array with elements object[] arr = (object[])constructors[0].Invoke(new object[] { length }); Assert.Equal(arr.Length, length); } } [Fact] public void Invoke_OneDimensionalArray_NegativeLengths_ThrowsOverflowException() { ConstructorInfo[] constructors = GetConstructors(typeof(object[])); int[] arraylength = new int[] { -1, -2, -99 }; // Try to invoke Array ctors with different lengths foreach (int length in arraylength) { // Create big Array with elements Assert.Throws<OverflowException>(() => (object[])constructors[0].Invoke(new object[] { length })); } } [Fact] public void Invoke_OneParameter() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[1].Invoke(new object[] { 100 }); Assert.Equal(obj.intValue, 100); } [Fact] public void Invoke_TwoParameters() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[2].Invoke(new object[] { 101, "hello" }); Assert.Equal(obj.intValue, 101); Assert.Equal(obj.stringValue, "hello"); } [Fact] public void Invoke_NoParameters_ThowsTargetParameterCountException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Throws<TargetParameterCountException>(() => constructors[2].Invoke(new object[0])); } [Fact] public void Invoke_ParameterMismatch_ThrowsTargetParameterCountException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Throws<TargetParameterCountException>(() => (ClassWith3Constructors)constructors[2].Invoke(new object[] { 121 })); } [Fact] public void Invoke_ParameterWrongType_ThrowsArgumentException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Throws<ArgumentException>(null, () => (ClassWith3Constructors)constructors[1].Invoke(new object[] { "hello" })); } [Fact] public void Invoke_ExistingInstance() { // Should not prouce a second object. ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj1 = new ClassWith3Constructors(100, "hello"); ClassWith3Constructors obj2 = (ClassWith3Constructors)constructors[2].Invoke(obj1, new object[] { 999, "initialized" }); Assert.Null(obj2); Assert.Equal(obj1.intValue, 999); Assert.Equal(obj1.stringValue, "initialized"); } [Fact] public void Invoke_AbstractClass_ThrowsMemberAccessException() { ConstructorInfo[] constructors = GetConstructors(typeof(ConstructorInfoAbstractBase)); Assert.Throws<MemberAccessException>(() => (ConstructorInfoAbstractBase)constructors[0].Invoke(new object[0])); } [Fact] public void Invoke_SubClass() { ConstructorInfo[] constructors = GetConstructors(typeof(ConstructorInfoDerived)); ConstructorInfoDerived obj = null; obj = (ConstructorInfoDerived)constructors[0].Invoke(new object[] { }); Assert.NotNull(obj); } [Fact] public void Invoke_Struct() { ConstructorInfo[] constructors = GetConstructors(typeof(StructWith1Constructor)); StructWith1Constructor obj; obj = (StructWith1Constructor)constructors[0].Invoke(new object[] { 1, 2 }); Assert.Equal(obj.x, 1); Assert.Equal(obj.y, 2); } [Fact] public void IsConstructor_ReturnsTrue() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); foreach (ConstructorInfo constructorInfo in constructors) { Assert.True(constructorInfo.IsConstructor); } } [Fact] public void IsPublic() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.True(constructors[0].IsPublic); } public static ConstructorInfo[] GetConstructors(Type type) { return type.GetTypeInfo().DeclaredConstructors.ToArray(); } } // Metadata for Reflection public abstract class ConstructorInfoAbstractBase { public ConstructorInfoAbstractBase() { } } public class ConstructorInfoDerived : ConstructorInfoAbstractBase { public ConstructorInfoDerived() { } } public class ClassWith3Constructors { public int intValue = 0; public string stringValue = ""; public ClassWith3Constructors() { } public ClassWith3Constructors(int intValue) { this.intValue = intValue; } public ClassWith3Constructors(int intValue, string stringValue) { this.intValue = intValue; this.stringValue = stringValue; } public string Method1(DateTime dt) => ""; } public class ClassWithStaticConstructor { static ClassWithStaticConstructor() { } } public struct StructWith1Constructor { public int x; public int y; public StructWith1Constructor(int x, int y) { this.x = x; this.y = y; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.Models; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { /// <summary> /// Represents an IPublishedContent which is created based on an Xml structure. /// </summary> [Serializable] [XmlType(Namespace = "http://umbraco.org/webservices/")] internal class XmlPublishedContent : PublishedContentBase { /// <summary> /// Initializes a new instance of the <c>XmlPublishedContent</c> class with an Xml node. /// </summary> /// <param name="xmlNode">The Xml node.</param> /// <param name="isPreviewing">A value indicating whether the published content is being previewed.</param> public XmlPublishedContent(XmlNode xmlNode, bool isPreviewing) { _xmlNode = xmlNode; _isPreviewing = isPreviewing; InitializeStructure(); Initialize(); InitializeChildren(); } /// <summary> /// Initializes a new instance of the <c>XmlPublishedContent</c> class with an Xml node, /// and a value indicating whether to lazy-initialize the instance. /// </summary> /// <param name="xmlNode">The Xml node.</param> /// <param name="isPreviewing">A value indicating whether the published content is being previewed.</param> /// <param name="lazyInitialize">A value indicating whether to lazy-initialize the instance.</param> /// <remarks>Lazy-initializationg is NOT thread-safe.</remarks> internal XmlPublishedContent(XmlNode xmlNode, bool isPreviewing, bool lazyInitialize) { _xmlNode = xmlNode; _isPreviewing = isPreviewing; InitializeStructure(); if (lazyInitialize == false) { Initialize(); InitializeChildren(); } } private readonly XmlNode _xmlNode; private bool _initialized; private bool _childrenInitialized; private readonly ICollection<IPublishedContent> _children = new Collection<IPublishedContent>(); private IPublishedContent _parent; private int _id; private int _template; private string _name; private string _docTypeAlias; private int _docTypeId; private string _writerName; private string _creatorName; private int _writerId; private int _creatorId; private string _urlName; private string _path; private DateTime _createDate; private DateTime _updateDate; private Guid _version; private IPublishedProperty[] _properties; private int _sortOrder; private int _level; private bool _isDraft; private readonly bool _isPreviewing; private PublishedContentType _contentType; public override IEnumerable<IPublishedContent> Children { get { if (_initialized == false) Initialize(); if (_childrenInitialized == false) InitializeChildren(); return _children.OrderBy(x => x.SortOrder); } } public override IPublishedProperty GetProperty(string alias) { return Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias)); } // override to implement cache // cache at context level, ie once for the whole request // but cache is not shared by requests because we wouldn't know how to clear it public override IPublishedProperty GetProperty(string alias, bool recurse) { if (recurse == false) return GetProperty(alias); var cache = UmbracoContextCache.Current; if (cache == null) return base.GetProperty(alias, true); var key = string.Format("RECURSIVE_PROPERTY::{0}::{1}", Id, alias.ToLowerInvariant()); var value = cache.GetOrAdd(key, k => base.GetProperty(alias, true)); if (value == null) return null; var property = value as IPublishedProperty; if (property == null) throw new InvalidOperationException("Corrupted cache."); return property; } public override PublishedItemType ItemType { get { return PublishedItemType.Content; } } public override IPublishedContent Parent { get { if (_initialized == false) Initialize(); return _parent; } } public override int Id { get { if (_initialized == false) Initialize(); return _id; } } public override int TemplateId { get { if (_initialized == false) Initialize(); return _template; } } public override int SortOrder { get { if (_initialized == false) Initialize(); return _sortOrder; } } public override string Name { get { if (_initialized == false) Initialize(); return _name; } } public override string DocumentTypeAlias { get { if (_initialized == false) Initialize(); return _docTypeAlias; } } public override int DocumentTypeId { get { if (_initialized == false) Initialize(); return _docTypeId; } } public override string WriterName { get { if (_initialized == false) Initialize(); return _writerName; } } public override string CreatorName { get { if (_initialized == false) Initialize(); return _creatorName; } } public override int WriterId { get { if (_initialized == false) Initialize(); return _writerId; } } public override int CreatorId { get { if (_initialized == false) Initialize(); return _creatorId; } } public override string Path { get { if (_initialized == false) Initialize(); return _path; } } public override DateTime CreateDate { get { if (_initialized == false) Initialize(); return _createDate; } } public override DateTime UpdateDate { get { if (_initialized == false) Initialize(); return _updateDate; } } public override Guid Version { get { if (_initialized == false) Initialize(); return _version; } } public override string UrlName { get { if (_initialized == false) Initialize(); return _urlName; } } public override int Level { get { if (_initialized == false) Initialize(); return _level; } } public override bool IsDraft { get { if (_initialized == false) Initialize(); return _isDraft; } } public override ICollection<IPublishedProperty> Properties { get { if (_initialized == false) Initialize(); return _properties; } } public override PublishedContentType ContentType { get { if (_initialized == false) Initialize(); return _contentType; } } private void InitializeStructure() { // load parent if it exists and is a node var parent = _xmlNode == null ? null : _xmlNode.ParentNode; if (parent == null) return; if (parent.Name == "node" || (parent.Attributes != null && parent.Attributes.GetNamedItem("isDoc") != null)) _parent = PublishedContentModelFactory.CreateModel(new XmlPublishedContent(parent, _isPreviewing, true)); } private void Initialize() { if (_xmlNode == null) return; if (_xmlNode.Attributes != null) { _id = int.Parse(_xmlNode.Attributes.GetNamedItem("id").Value); if (_xmlNode.Attributes.GetNamedItem("template") != null) _template = int.Parse(_xmlNode.Attributes.GetNamedItem("template").Value); if (_xmlNode.Attributes.GetNamedItem("sortOrder") != null) _sortOrder = int.Parse(_xmlNode.Attributes.GetNamedItem("sortOrder").Value); if (_xmlNode.Attributes.GetNamedItem("nodeName") != null) _name = _xmlNode.Attributes.GetNamedItem("nodeName").Value; if (_xmlNode.Attributes.GetNamedItem("writerName") != null) _writerName = _xmlNode.Attributes.GetNamedItem("writerName").Value; if (_xmlNode.Attributes.GetNamedItem("urlName") != null) _urlName = _xmlNode.Attributes.GetNamedItem("urlName").Value; // Creatorname is new in 2.1, so published xml might not have it! try { _creatorName = _xmlNode.Attributes.GetNamedItem("creatorName").Value; } catch { _creatorName = _writerName; } //Added the actual userID, as a user cannot be looked up via full name only... if (_xmlNode.Attributes.GetNamedItem("creatorID") != null) _creatorId = int.Parse(_xmlNode.Attributes.GetNamedItem("creatorID").Value); if (_xmlNode.Attributes.GetNamedItem("writerID") != null) _writerId = int.Parse(_xmlNode.Attributes.GetNamedItem("writerID").Value); if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema) { if (_xmlNode.Attributes.GetNamedItem("nodeTypeAlias") != null) _docTypeAlias = _xmlNode.Attributes.GetNamedItem("nodeTypeAlias").Value; } else { _docTypeAlias = _xmlNode.Name; } if (_xmlNode.Attributes.GetNamedItem("nodeType") != null) _docTypeId = int.Parse(_xmlNode.Attributes.GetNamedItem("nodeType").Value); if (_xmlNode.Attributes.GetNamedItem("path") != null) _path = _xmlNode.Attributes.GetNamedItem("path").Value; if (_xmlNode.Attributes.GetNamedItem("version") != null) _version = new Guid(_xmlNode.Attributes.GetNamedItem("version").Value); if (_xmlNode.Attributes.GetNamedItem("createDate") != null) _createDate = DateTime.Parse(_xmlNode.Attributes.GetNamedItem("createDate").Value); if (_xmlNode.Attributes.GetNamedItem("updateDate") != null) _updateDate = DateTime.Parse(_xmlNode.Attributes.GetNamedItem("updateDate").Value); if (_xmlNode.Attributes.GetNamedItem("level") != null) _level = int.Parse(_xmlNode.Attributes.GetNamedItem("level").Value); _isDraft = (_xmlNode.Attributes.GetNamedItem("isDraft") != null); } // load data var dataXPath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "data" : "* [not(@isDoc)]"; var nodes = _xmlNode.SelectNodes(dataXPath); _contentType = PublishedContentType.Get(PublishedItemType.Content, _docTypeAlias); var propertyNodes = new Dictionary<string, XmlNode>(); if (nodes != null) foreach (XmlNode n in nodes) { var alias = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? n.Attributes.GetNamedItem("alias").Value : n.Name; propertyNodes[alias.ToLowerInvariant()] = n; } _properties = _contentType.PropertyTypes.Select(p => { XmlNode n; return propertyNodes.TryGetValue(p.PropertyTypeAlias.ToLowerInvariant(), out n) ? new XmlPublishedProperty(p, _isPreviewing, n) : new XmlPublishedProperty(p, _isPreviewing); }).Cast<IPublishedProperty>().ToArray(); // warn: this is not thread-safe... _initialized = true; } private void InitializeChildren() { if (_xmlNode == null) return; // load children var childXPath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : "* [@isDoc]"; var nav = _xmlNode.CreateNavigator(); var expr = nav.Compile(childXPath); expr.AddSort("@sortOrder", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number); var iterator = nav.Select(expr); while (iterator.MoveNext()) _children.Add(PublishedContentModelFactory.CreateModel( new XmlPublishedContent(((IHasXmlNode)iterator.Current).GetNode(), _isPreviewing, true))); // warn: this is not thread-safe _childrenInitialized = true; } } }
// 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="ConversionActionServiceClient"/> instances.</summary> public sealed partial class ConversionActionServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ConversionActionServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ConversionActionServiceSettings"/>.</returns> public static ConversionActionServiceSettings GetDefault() => new ConversionActionServiceSettings(); /// <summary> /// Constructs a new <see cref="ConversionActionServiceSettings"/> object with default settings. /// </summary> public ConversionActionServiceSettings() { } private ConversionActionServiceSettings(ConversionActionServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetConversionActionSettings = existing.GetConversionActionSettings; MutateConversionActionsSettings = existing.MutateConversionActionsSettings; OnCopy(existing); } partial void OnCopy(ConversionActionServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ConversionActionServiceClient.GetConversionAction</c> and /// <c>ConversionActionServiceClient.GetConversionActionAsync</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 GetConversionActionSettings { 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> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ConversionActionServiceClient.MutateConversionActions</c> and /// <c>ConversionActionServiceClient.MutateConversionActionsAsync</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 MutateConversionActionsSettings { 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="ConversionActionServiceSettings"/> object.</returns> public ConversionActionServiceSettings Clone() => new ConversionActionServiceSettings(this); } /// <summary> /// Builder class for <see cref="ConversionActionServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class ConversionActionServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionActionServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ConversionActionServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ConversionActionServiceClientBuilder() { UseJwtAccessWithScopes = ConversionActionServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ConversionActionServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionActionServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ConversionActionServiceClient Build() { ConversionActionServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ConversionActionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ConversionActionServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ConversionActionServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ConversionActionServiceClient.Create(callInvoker, Settings); } private async stt::Task<ConversionActionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ConversionActionServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ConversionActionServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConversionActionServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionActionServiceClient.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>ConversionActionService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage conversion actions. /// </remarks> public abstract partial class ConversionActionServiceClient { /// <summary> /// The default endpoint for the ConversionActionService 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 ConversionActionService scopes.</summary> /// <remarks> /// The default ConversionActionService 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="ConversionActionServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="ConversionActionServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ConversionActionServiceClient"/>.</returns> public static stt::Task<ConversionActionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ConversionActionServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ConversionActionServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="ConversionActionServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ConversionActionServiceClient"/>.</returns> public static ConversionActionServiceClient Create() => new ConversionActionServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ConversionActionServiceClient"/> 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="ConversionActionServiceSettings"/>.</param> /// <returns>The created <see cref="ConversionActionServiceClient"/>.</returns> internal static ConversionActionServiceClient Create(grpccore::CallInvoker callInvoker, ConversionActionServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ConversionActionService.ConversionActionServiceClient grpcClient = new ConversionActionService.ConversionActionServiceClient(callInvoker); return new ConversionActionServiceClientImpl(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 ConversionActionService client</summary> public virtual ConversionActionService.ConversionActionServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion action. /// /// 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::ConversionAction GetConversionAction(GetConversionActionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion action. /// /// 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::ConversionAction> GetConversionActionAsync(GetConversionActionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion action. /// /// 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::ConversionAction> GetConversionActionAsync(GetConversionActionRequest request, st::CancellationToken cancellationToken) => GetConversionActionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested conversion action. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion action to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ConversionAction GetConversionAction(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionAction(new GetConversionActionRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion action. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion action 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::ConversionAction> GetConversionActionAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionActionAsync(new GetConversionActionRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion action. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion action 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::ConversionAction> GetConversionActionAsync(string resourceName, st::CancellationToken cancellationToken) => GetConversionActionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested conversion action. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion action to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ConversionAction GetConversionAction(gagvr::ConversionActionName resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionAction(new GetConversionActionRequest { ResourceNameAsConversionActionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion action. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion action 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::ConversionAction> GetConversionActionAsync(gagvr::ConversionActionName resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionActionAsync(new GetConversionActionRequest { ResourceNameAsConversionActionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion action. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion action 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::ConversionAction> GetConversionActionAsync(gagvr::ConversionActionName resourceName, st::CancellationToken cancellationToken) => GetConversionActionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates or removes conversion actions. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionActionError]() /// [CurrencyCodeError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [StringLengthError]() /// </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 MutateConversionActionsResponse MutateConversionActions(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes conversion actions. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionActionError]() /// [CurrencyCodeError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [StringLengthError]() /// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes conversion actions. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionActionError]() /// [CurrencyCodeError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [StringLengthError]() /// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, st::CancellationToken cancellationToken) => MutateConversionActionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates or removes conversion actions. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionActionError]() /// [CurrencyCodeError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion actions are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion actions. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateConversionActionsResponse MutateConversionActions(string customerId, scg::IEnumerable<ConversionActionOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionActions(new MutateConversionActionsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes conversion actions. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionActionError]() /// [CurrencyCodeError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion actions are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion actions. /// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(string customerId, scg::IEnumerable<ConversionActionOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionActionsAsync(new MutateConversionActionsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes conversion actions. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionActionError]() /// [CurrencyCodeError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion actions are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion actions. /// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(string customerId, scg::IEnumerable<ConversionActionOperation> operations, st::CancellationToken cancellationToken) => MutateConversionActionsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ConversionActionService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage conversion actions. /// </remarks> public sealed partial class ConversionActionServiceClientImpl : ConversionActionServiceClient { private readonly gaxgrpc::ApiCall<GetConversionActionRequest, gagvr::ConversionAction> _callGetConversionAction; private readonly gaxgrpc::ApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse> _callMutateConversionActions; /// <summary> /// Constructs a client wrapper for the ConversionActionService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ConversionActionServiceSettings"/> used within this client. /// </param> public ConversionActionServiceClientImpl(ConversionActionService.ConversionActionServiceClient grpcClient, ConversionActionServiceSettings settings) { GrpcClient = grpcClient; ConversionActionServiceSettings effectiveSettings = settings ?? ConversionActionServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetConversionAction = clientHelper.BuildApiCall<GetConversionActionRequest, gagvr::ConversionAction>(grpcClient.GetConversionActionAsync, grpcClient.GetConversionAction, effectiveSettings.GetConversionActionSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetConversionAction); Modify_GetConversionActionApiCall(ref _callGetConversionAction); _callMutateConversionActions = clientHelper.BuildApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse>(grpcClient.MutateConversionActionsAsync, grpcClient.MutateConversionActions, effectiveSettings.MutateConversionActionsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateConversionActions); Modify_MutateConversionActionsApiCall(ref _callMutateConversionActions); 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_GetConversionActionApiCall(ref gaxgrpc::ApiCall<GetConversionActionRequest, gagvr::ConversionAction> call); partial void Modify_MutateConversionActionsApiCall(ref gaxgrpc::ApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse> call); partial void OnConstruction(ConversionActionService.ConversionActionServiceClient grpcClient, ConversionActionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ConversionActionService client</summary> public override ConversionActionService.ConversionActionServiceClient GrpcClient { get; } partial void Modify_GetConversionActionRequest(ref GetConversionActionRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateConversionActionsRequest(ref MutateConversionActionsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested conversion action. /// /// 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::ConversionAction GetConversionAction(GetConversionActionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetConversionActionRequest(ref request, ref callSettings); return _callGetConversionAction.Sync(request, callSettings); } /// <summary> /// Returns the requested conversion action. /// /// 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::ConversionAction> GetConversionActionAsync(GetConversionActionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetConversionActionRequest(ref request, ref callSettings); return _callGetConversionAction.Async(request, callSettings); } /// <summary> /// Creates, updates or removes conversion actions. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionActionError]() /// [CurrencyCodeError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [StringLengthError]() /// </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 MutateConversionActionsResponse MutateConversionActions(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionActionsRequest(ref request, ref callSettings); return _callMutateConversionActions.Sync(request, callSettings); } /// <summary> /// Creates, updates or removes conversion actions. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionActionError]() /// [CurrencyCodeError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [StringLengthError]() /// </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<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionActionsRequest(ref request, ref callSettings); return _callMutateConversionActions.Async(request, callSettings); } } }
using System; using System.Text; using System.IO; using System.Collections; namespace Zeus { /// <summary> /// The ZeusOutput object is only available in the template code segment and is very much like a /// StringBuilder. It contains methods that allow the developer to manipulate the current output buffer. /// </summary> /// <remarks> /// The ZeusOutput is simply an output buffer. It's primary methods are <see cref="write">write()</see> and /// <see cref="writeln">writeln()</see>, which naturally /// append string data to the buffer. Using the save and append methods, the buffer can be saved to disk. /// Code preservation is also supported using the ZeusOutput object. The two methods that enable code preservation /// are <see cref="setPreserveSource">setPreserveSource()</see>, <see cref="preserve">preserve()</see>, <see cref="getPreservedData">getPreservedData()</see>, /// and <see cref="getPreserveBlock">getPreserveBlock()</see>. The <see cref="preserve">preserve()</see> method /// writes directly to the output stream where the <see cref="getPreserveBlock">getPreserveBlock()</see> returns the entire preserve block as a string. /// You can then write that string to the output buffer manually. The <see cref="getPreservedData">getPreservedData()</see> method returns the data inside the /// preserve block without the preserve tags. /// </remarks> /// <example> /// Saving the buffer to disk, replacing an existing file: (JScript) /// <code> /// var filename = "c:\testfile.txt"; /// output.write("Hello World!"); /// output.save(filename, "o"); /// </code> /// </example> /// <example> /// Backing up an existing file before overwriting: (JScript) /// <code> /// var filename = "c:\testfile.txt"; /// output.write("Hello World!"); /// output.save(filename, "b"); /// </code> /// </example> /// <example> /// Append the buffer to an existing file before overwriting: (JScript) /// <code> /// var filename = "c:\testfile.txt"; /// output.write("Hello World!"); /// output.save(filename, "a"); /// </code> /// </example> /// <example> /// Save the buffer to an new file with no overwrite (if the file exists, nothing will happen): (JScript) /// <code> /// var filename = "c:\testfile.txt"; /// output.write("Hello World!"); /// output.save(filename, "d"); /// </code> /// </example> /// <example> /// Preserving a region the buffer to an existing file before overwriting: (JScript) /// <code> /// // The Template Code /// var filename = "c:\testfile.txt"; /// output.setPreserveSource(filePath, "/*::", "::*/"); /// output.write("Hello World!"); /// output.preserve("myCustomProperties"); /// output.write("Hello World Again!"); /// output.save(filename, "o"); /// </code> /// The existing file before template execution: "c:\testfile.txt" /// <code> /// Hello World! /// /*::PRESERVE_BEGIN myCustomProperties::*/ /// preserved data here /// /*::PRESERVE_END myCustomProperties::*/ /// Hello World Again! /// </code> /// Note that the preserved data is between the PRESERVE_BEGIN and PRESERVE_END tags. /// When you set the preserve source, the start and end tags for the PRESERVE tags /// are defined; is this case, it's "/*::" and "::*/". /// </example> public class ZeusOutput : IZeusOutput { private const string PRESERVE_BEGIN = "PRESERVE_BEGIN"; private const string PRESERVE_END = "PRESERVE_END"; private string _preservePrefix = "//::"; private string _preserveSuffix = ":://"; private int _tablevel = 0; private Hashtable _preserveData = null; private StringBuilder _output = new StringBuilder(); /// <summary> /// Creates a new ZeusOutput object. /// </summary> public ZeusOutput() {} /// <summary> /// Writes the inputed string, text, to the output buffer. /// </summary> /// <param name="text">A string to write to the output buffer</param> public void write(string text) { _output.Append(text); } /// <summary> /// Writes the inputed string, text, to the output buffer followed by a newline. /// </summary> /// <param name="text">A string to write to the output buffer</param> public void writeln(string text) { _output.Append(text); _output.Append("\r\n"); } /// <summary> /// Writes the inputed string, text, to the output buffer, prepended with the number of /// tabs specified by the tabLevel property. /// </summary> /// <param name="text">A string to write to the output buffer</param> public void autoTab(string text) { for (int i = 0; i < this._tablevel; i++) _output.Append("\t"); _output.Append(text); } /// <summary> /// Writes the inputed string, text, to the output buffer followed by a newline, /// prepended with the number of /// tabs specified by the tabLevel property. /// </summary> /// <param name="text"></param> public void autoTabLn(string text) { autoTab(text); _output.Append("\r\n"); } /// <summary> /// Increments the tabLevel property. /// </summary> public void incTab() { this._tablevel++; } /// <summary> /// Decrements the tabLevel property. /// </summary> public void decTab() { this._tablevel--; } /// <summary> /// The tabLevel property is the number of tabs that are prepended to outputted text /// when using the autoTab and autoTabLn methods. /// </summary> public int tabLevel { get { return _tablevel; } set { this._tablevel = value; } } /// <summary> /// Sets or gets the current output buffer. /// </summary> public string text { get { return _output.ToString(); } set { this.clear(); this._output.Append(value); } } /// <summary> /// Clears the output buffer. /// </summary> public void clear() { _output.Remove(0, _output.Length); } /// <summary> /// Save the current buffer to a file at path. If the file exists, append to the file. /// </summary> /// <param name="path">The path of the file to append to.</param> public void append(string path) { StreamWriter writer; if (File.Exists(path)) { writer = File.AppendText(path); } else { writer = File.CreateText(path); } writer.Write(_output.ToString()); writer.Close(); } public void save(string path, object action) { saveEnc(path, action, Encoding.Default); } /// <summary> /// Save the current buffer to a file at path. If the file exists, /// backup the existing file (by renaming it) and replace it. ///<code> ///output.save(filename, "d", "ascii"); // Save only if file doesn't exists ///output.save(filename, "o", "utf7"); // Overwrite ///output.save(filename, "b", "unicode"); // Backup and overwrite ///output.save(filename, "a", "utf8"); // Append ///</code> /// </summary> /// <param name="path">The path of the file to write to.</param> /// <param name="action"> /// "d" or "default" saves the file if it doesn't exist, /// "o" or "overwrite" saves the file even if it has to overwrite, /// "b" or "backup" backs up the existing file before overwriting it, /// "a" or "append" appends to the end of the current file if it exists, /// true or false for backup or overwrite (for legacy support)</param> /// <param name="encoding"> /// The encoding object or a string value ("utf8", "utf7", "ascii", "unicode", "bigendianunicode"). ///</param> public void saveEnc(string path, object action, object encoding) { Encoding enc = encoding as Encoding; if ((encoding != null) && (enc == null) && (enc != Encoding.Default)) { string tmp = encoding.ToString().ToLower(); if (tmp == "ascii") enc = Encoding.ASCII; else if (tmp == "unicode") enc = Encoding.Unicode; else if (tmp == "bigendianunicode") enc = Encoding.BigEndianUnicode; else if (tmp == "utf7") enc = Encoding.UTF7; else if (tmp == "utf8") enc = Encoding.UTF8; else enc = Encoding.Default; } StreamWriter writer = null; FileInfo finfo = new FileInfo(path); string a = "o"; if (action is Boolean) { a = ((bool)action) ? "b" : "o"; } else if (action is String) { if (action.ToString().Length > 0) { a = action.ToString().ToLower().Substring(0,1); } } if (finfo.Exists) { if (a == "b") { int i = 0; string tmpfilename = string.Empty; do { i++; tmpfilename = path + "." + i.ToString().PadLeft(3, '0') + ".bak"; } while (File.Exists(tmpfilename)); File.Move(path, tmpfilename); if (enc != Encoding.Default) writer = new StreamWriter(path, false, enc); else writer = new StreamWriter(path, false); } else if (a == "o") { File.Delete(path); if (enc != Encoding.Default) writer = new StreamWriter(path, false, enc); else writer = new StreamWriter(path, false); } else if (a == "a") { if (enc != Encoding.Default) writer = new StreamWriter(path, true, enc); else writer = new StreamWriter(path, true); //writer = File.AppendText(path); } } else { // Create the directory if it doesn't exist! DirectoryInfo dinfo = new DirectoryInfo(finfo.DirectoryName); if (!dinfo.Exists) { dinfo.Create(); } if (enc != Encoding.Default) writer = new StreamWriter(path, false, enc); else writer = new StreamWriter(path, false); //writer = File.CreateText(path); } if (writer != null) { writer.Write(_output.ToString()); writer.Close(); } } /// <summary> /// The file at the path parameter will be opened up and all PRESERVE blocks will be loaded /// and kept for use in this ZeusOutput object. The preserve(key) method can be used to get /// preserved code segments by it's key parameter. /// </summary> /// <param name="path">A path to the file that contains code segments that are to be preserved.</param> /// <param name="prefix">Prefix to the PRESERVE_BEGIN tag.</param> /// <param name="suffix">Suffix to the PRESERVE_END tag.</param> public void setPreserveSource(string path, string prefix, string suffix) { this._preservePrefix = prefix; this._preserveSuffix = suffix; this._preserveData = new Hashtable(); if (File.Exists(path)) { StreamReader reader = File.OpenText(path); bool inBlock = false; string beginPreserve = prefix + PRESERVE_BEGIN; string endPreserve = prefix + PRESERVE_END; string key = string.Empty; StringBuilder data = new StringBuilder(); string line = reader.ReadLine(); while (line != null) { if (inBlock) { int i = line.IndexOf(endPreserve); if (i >= 0) { data.Append(line.Substring(0, i)); this._preserveData[key] = data.ToString(); data = new StringBuilder(); line = line.Substring(i); inBlock = false; continue; } else { data.Append(line); data.Append(Environment.NewLine); } } else { int i = line.IndexOf(beginPreserve); if (i >= 0) { i = i + beginPreserve.Length; int j = line.IndexOf(suffix, i); if (j >= 0) { key = line.Substring(i, (j - i)).Trim(); j = j + suffix.Length; line = line.Substring(j); inBlock = true; continue; } } } line = reader.ReadLine(); } reader.Close(); } } /// <summary> /// If the setPreserveSource(targetFile, prefex, suffix) function was called, all of the custom code from /// the targetFile is stored in the ZeusOutput object. When the preserve method is called, the code /// segment that correlates to the key parameter is written to the output buffer surrounted by the appropriate preserve tags. /// </summary> /// <param name="key">The key that identifies the desired code segment</param> public void preserve(string key) { _output.Append( getPreserveBlock(key) ); } /// <summary> /// This function returns the preserved data (without the preserve tags) that corresponds to the key parameter. /// </summary> /// <param name="key">The key that identifies the desired code segment</param> /// <returns>The preserved data that corresponds to the key parameter</returns> public string getPreservedData(string key) { return this._preserveData[key].ToString(); } /// <summary> /// This function returns the preserved data with the preserve tags that corresponds to the key parameter. /// </summary> /// <param name="key">The key that identifies the desired code segment</param> /// <returns>The preserved data with the preserve tags.</returns> public string getPreserveBlock(string key) { if (this._preserveData != null) { StringBuilder sb = new StringBuilder(); sb.Append(this._preservePrefix); sb.Append(PRESERVE_BEGIN); sb.Append(" "); sb.Append(key); sb.Append(this._preserveSuffix); if (this._preserveData.Contains(key)) { sb.Append( this.getPreservedData(key) ); } sb.Append(this._preservePrefix); sb.Append(PRESERVE_END); sb.Append(" "); sb.Append(key); sb.Append(this._preserveSuffix); return sb.ToString(); } return string.Empty; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="KeywordPlanAdGroupServiceClient"/> instances.</summary> public sealed partial class KeywordPlanAdGroupServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="KeywordPlanAdGroupServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="KeywordPlanAdGroupServiceSettings"/>.</returns> public static KeywordPlanAdGroupServiceSettings GetDefault() => new KeywordPlanAdGroupServiceSettings(); /// <summary> /// Constructs a new <see cref="KeywordPlanAdGroupServiceSettings"/> object with default settings. /// </summary> public KeywordPlanAdGroupServiceSettings() { } private KeywordPlanAdGroupServiceSettings(KeywordPlanAdGroupServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetKeywordPlanAdGroupSettings = existing.GetKeywordPlanAdGroupSettings; MutateKeywordPlanAdGroupsSettings = existing.MutateKeywordPlanAdGroupsSettings; OnCopy(existing); } partial void OnCopy(KeywordPlanAdGroupServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordPlanAdGroupServiceClient.GetKeywordPlanAdGroup</c> and /// <c>KeywordPlanAdGroupServiceClient.GetKeywordPlanAdGroupAsync</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 GetKeywordPlanAdGroupSettings { 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> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordPlanAdGroupServiceClient.MutateKeywordPlanAdGroups</c> and /// <c>KeywordPlanAdGroupServiceClient.MutateKeywordPlanAdGroupsAsync</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 MutateKeywordPlanAdGroupsSettings { 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="KeywordPlanAdGroupServiceSettings"/> object.</returns> public KeywordPlanAdGroupServiceSettings Clone() => new KeywordPlanAdGroupServiceSettings(this); } /// <summary> /// Builder class for <see cref="KeywordPlanAdGroupServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class KeywordPlanAdGroupServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanAdGroupServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public KeywordPlanAdGroupServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public KeywordPlanAdGroupServiceClientBuilder() { UseJwtAccessWithScopes = KeywordPlanAdGroupServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref KeywordPlanAdGroupServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanAdGroupServiceClient> task); /// <summary>Builds the resulting client.</summary> public override KeywordPlanAdGroupServiceClient Build() { KeywordPlanAdGroupServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<KeywordPlanAdGroupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<KeywordPlanAdGroupServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private KeywordPlanAdGroupServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return KeywordPlanAdGroupServiceClient.Create(callInvoker, Settings); } private async stt::Task<KeywordPlanAdGroupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return KeywordPlanAdGroupServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => KeywordPlanAdGroupServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordPlanAdGroupServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanAdGroupServiceClient.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>KeywordPlanAdGroupService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage Keyword Plan ad groups. /// </remarks> public abstract partial class KeywordPlanAdGroupServiceClient { /// <summary> /// The default endpoint for the KeywordPlanAdGroupService 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 KeywordPlanAdGroupService scopes.</summary> /// <remarks> /// The default KeywordPlanAdGroupService 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="KeywordPlanAdGroupServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanAdGroupServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns> public static stt::Task<KeywordPlanAdGroupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new KeywordPlanAdGroupServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="KeywordPlanAdGroupServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanAdGroupServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns> public static KeywordPlanAdGroupServiceClient Create() => new KeywordPlanAdGroupServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="KeywordPlanAdGroupServiceClient"/> 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="KeywordPlanAdGroupServiceSettings"/>.</param> /// <returns>The created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns> internal static KeywordPlanAdGroupServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanAdGroupServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient = new KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient(callInvoker); return new KeywordPlanAdGroupServiceClientImpl(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 KeywordPlanAdGroupService client</summary> public virtual KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group 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::KeywordPlanAdGroup GetKeywordPlanAdGroup(GetKeywordPlanAdGroupRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group 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::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(GetKeywordPlanAdGroupRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group 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::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(GetKeywordPlanAdGroupRequest request, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested Keyword Plan ad group in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Keyword Plan ad group to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordPlanAdGroup GetKeywordPlanAdGroup(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroup(new GetKeywordPlanAdGroupRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Keyword Plan ad group 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::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupAsync(new GetKeywordPlanAdGroupRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Keyword Plan ad group 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::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(string resourceName, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested Keyword Plan ad group in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Keyword Plan ad group to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordPlanAdGroup GetKeywordPlanAdGroup(gagvr::KeywordPlanAdGroupName resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroup(new GetKeywordPlanAdGroupRequest { ResourceNameAsKeywordPlanAdGroupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Keyword Plan ad group 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::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(gagvr::KeywordPlanAdGroupName resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupAsync(new GetKeywordPlanAdGroupRequest { ResourceNameAsKeywordPlanAdGroupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Keyword Plan ad group 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::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(gagvr::KeywordPlanAdGroupName resourceName, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </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 MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </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<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </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<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, st::CancellationToken cancellationToken) => MutateKeywordPlanAdGroupsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad groups are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad groups. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateKeywordPlanAdGroups(new MutateKeywordPlanAdGroupsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad groups are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad groups. /// </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<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateKeywordPlanAdGroupsAsync(new MutateKeywordPlanAdGroupsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad groups are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad groups. /// </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<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, st::CancellationToken cancellationToken) => MutateKeywordPlanAdGroupsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>KeywordPlanAdGroupService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage Keyword Plan ad groups. /// </remarks> public sealed partial class KeywordPlanAdGroupServiceClientImpl : KeywordPlanAdGroupServiceClient { private readonly gaxgrpc::ApiCall<GetKeywordPlanAdGroupRequest, gagvr::KeywordPlanAdGroup> _callGetKeywordPlanAdGroup; private readonly gaxgrpc::ApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse> _callMutateKeywordPlanAdGroups; /// <summary> /// Constructs a client wrapper for the KeywordPlanAdGroupService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="KeywordPlanAdGroupServiceSettings"/> used within this client. /// </param> public KeywordPlanAdGroupServiceClientImpl(KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient, KeywordPlanAdGroupServiceSettings settings) { GrpcClient = grpcClient; KeywordPlanAdGroupServiceSettings effectiveSettings = settings ?? KeywordPlanAdGroupServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetKeywordPlanAdGroup = clientHelper.BuildApiCall<GetKeywordPlanAdGroupRequest, gagvr::KeywordPlanAdGroup>(grpcClient.GetKeywordPlanAdGroupAsync, grpcClient.GetKeywordPlanAdGroup, effectiveSettings.GetKeywordPlanAdGroupSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetKeywordPlanAdGroup); Modify_GetKeywordPlanAdGroupApiCall(ref _callGetKeywordPlanAdGroup); _callMutateKeywordPlanAdGroups = clientHelper.BuildApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse>(grpcClient.MutateKeywordPlanAdGroupsAsync, grpcClient.MutateKeywordPlanAdGroups, effectiveSettings.MutateKeywordPlanAdGroupsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateKeywordPlanAdGroups); Modify_MutateKeywordPlanAdGroupsApiCall(ref _callMutateKeywordPlanAdGroups); 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_GetKeywordPlanAdGroupApiCall(ref gaxgrpc::ApiCall<GetKeywordPlanAdGroupRequest, gagvr::KeywordPlanAdGroup> call); partial void Modify_MutateKeywordPlanAdGroupsApiCall(ref gaxgrpc::ApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse> call); partial void OnConstruction(KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient, KeywordPlanAdGroupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC KeywordPlanAdGroupService client</summary> public override KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient GrpcClient { get; } partial void Modify_GetKeywordPlanAdGroupRequest(ref GetKeywordPlanAdGroupRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateKeywordPlanAdGroupsRequest(ref MutateKeywordPlanAdGroupsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested Keyword Plan ad group 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::KeywordPlanAdGroup GetKeywordPlanAdGroup(GetKeywordPlanAdGroupRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetKeywordPlanAdGroupRequest(ref request, ref callSettings); return _callGetKeywordPlanAdGroup.Sync(request, callSettings); } /// <summary> /// Returns the requested Keyword Plan ad group 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::KeywordPlanAdGroup> GetKeywordPlanAdGroupAsync(GetKeywordPlanAdGroupRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetKeywordPlanAdGroupRequest(ref request, ref callSettings); return _callGetKeywordPlanAdGroup.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </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 MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateKeywordPlanAdGroupsRequest(ref request, ref callSettings); return _callMutateKeywordPlanAdGroups.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </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<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateKeywordPlanAdGroupsRequest(ref request, ref callSettings); return _callMutateKeywordPlanAdGroups.Async(request, callSettings); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Diagnostics { // Overview // -------- // We have a few constraints we're working under here: // - waitpid is used on Unix to get the exit status (including exit code) of a child process, but the first call // to it after the child has completed will reap the child removing the chance of subsequent calls getting status. // - The Process design allows for multiple indendent Process objects to be handed out, and each of those // objects may be used concurrently with each other, even if they refer to the same underlying process. // Same with ProcessWaitHandle objects. This is based on the Windows design where anyone with a handle to the // process can retrieve completion information about that process. // - There is no good Unix equivalent to a process handle nor to being able to asynchronously be notified // of a process' exit (without more intrusive mechanisms like ptrace), which means such support // needs to be layered on top of waitpid. // // As a result, we have the following scheme: // - We maintain a static/shared table that maps process ID to ProcessWaitState objects. // Access to this table requires taking a global lock, so we try to minimize the number of // times we need to access the table, primarily just the first time a Process object needs // access to process exit/wait information and subsequently when that Process object gets GC'd. // - Each process holds a ProcessWaitState.Holder object; when that object is constructed, // it ensures there's an appropriate entry in the mapping table and increments that entry's ref count. // - When a Process object is dropped and its ProcessWaitState.Holder is finalized, it'll // decrement the ref count, and when no more process objects exist for a particular process ID, // that entry in the table will be cleaned up. // - This approach effectively allows for multiple independent Process objects for the same process ID to all // share the same ProcessWaitState. And since they are sharing the same wait state object, // the wait state object uses its own lock to protect the per-process state. This includes // caching exit / exit code / exit time information so that a Process object for a process that's already // had waitpid called for it can get at its exit information. // // A negative ramification of this is that if a process exits, but there are outstanding wait handles // handed out (and rooted, so they can't be GC'd), and then a new process is created and the pid is recycled, // new calls to get that process's wait state will get the old processe's wait state. However, pid recycling // will be a more general issue, since pids are the only identifier we have to a process, so if a Process // object is created for a particular pid, then that process goes away and a new one comes in with the same pid, // our Process object will silently switch to referring to the new pid. Unix systems typically have a simple // policy for pid recycling, which is that they start at a low value, increment up to a system maximum (e.g. // 32768), and then wrap around and start reusing value that aren't currently in use. On Linux, // proc/sys/kernel/pid_max defines the max pid value. Given the conditions that would be required for this // to happen, it's possible but unlikely. /// <summary>Exit information and waiting capabilities for a process.</summary> internal sealed class ProcessWaitState : IDisposable { /// <summary> /// Finalizable holder for a process wait state. Instantiating one /// will ensure that a wait state object exists for a process, will /// grab it, and will increment its ref count. Dropping or disposing /// one will decrement the ref count and clean up after it if the ref /// count hits zero. /// </summary> internal sealed class Holder : IDisposable { internal ProcessWaitState _state; internal Holder(int processId) { _state = ProcessWaitState.AddRef(processId); } ~Holder() { if (_state != null) { _state.ReleaseRef(); } } public void Dispose() { if (_state != null) { _state.ReleaseRef(); _state = null; GC.SuppressFinalize(this); } } } /// <summary> /// Global table that maps process IDs to the associated shared wait state information. /// </summary> private static readonly Dictionary<int, ProcessWaitState> s_processWaitStates = new Dictionary<int, ProcessWaitState>(); /// <summary> /// Ensures that the mapping table contains an entry for the process ID, /// increments its ref count, and returns it. /// </summary> /// <param name="processId">The process ID for which we need wait state.</param> /// <returns>The wait state object.</returns> internal static ProcessWaitState AddRef(int processId) { lock (s_processWaitStates) { ProcessWaitState pws; if (!s_processWaitStates.TryGetValue(processId, out pws)) { pws = new ProcessWaitState(processId); s_processWaitStates.Add(processId, pws); } pws._outstandingRefCount++; return pws; } } /// <summary> /// Decrements the ref count on the wait state object, and if it's the last one, /// removes it from the table. /// </summary> internal void ReleaseRef() { lock (ProcessWaitState.s_processWaitStates) { ProcessWaitState pws; bool foundState = ProcessWaitState.s_processWaitStates.TryGetValue(_processId, out pws); Debug.Assert(foundState); if (foundState) { --pws._outstandingRefCount; if (pws._outstandingRefCount == 0) { ProcessWaitState.s_processWaitStates.Remove(_processId); pws.Dispose(); } } } } /// <summary> /// Synchroniation object used to protect all instance state. Any number of /// Process and ProcessWaitHandle objects may be using a ProcessWaitState /// instance concurrently. /// </summary> private readonly object _gate = new object(); /// <summary>ID of the associated process.</summary> private readonly int _processId; /// <summary>If a wait operation is in progress, the Task that represents it; otherwise, null.</summary> private Task _waitInProgress; /// <summary>The number of alive users of this object.</summary> private int _outstandingRefCount; /// <summary>Whether the associated process exited.</summary> private bool _exited; /// <summary>If the process exited, it's exit code, or null if we were unable to determine one.</summary> private int? _exitCode; /// <summary> /// The approximate time the process exited. We do not have the ability to know exact time a process /// exited, so we approximate it by storing the time that we discovered it exited. /// </summary> private DateTime _exitTime; /// <summary>A lazily-initialized event set when the process exits.</summary> private ManualResetEvent _exitedEvent; /// <summary>Initialize the wait state object.</summary> /// <param name="processId">The associated process' ID.</param> private ProcessWaitState(int processId) { Debug.Assert(processId >= 0); _processId = processId; } /// <summary>Releases managed resources used by the ProcessWaitState.</summary> public void Dispose() { Debug.Assert(!Monitor.IsEntered(_gate)); lock (_gate) { if (_exitedEvent != null) { _exitedEvent.Dispose(); _exitedEvent = null; } } } /// <summary>Notes that the process has exited.</summary> private void SetExited() { Debug.Assert(Monitor.IsEntered(_gate)); _exited = true; _exitTime = DateTime.Now; if (_exitedEvent != null) { _exitedEvent.Set(); } } /// <summary>Ensures an exited event has been initialized and returns it.</summary> /// <returns></returns> internal ManualResetEvent EnsureExitedEvent() { Debug.Assert(!Monitor.IsEntered(_gate)); lock (_gate) { // If we already have an initialized event, just return it. if (_exitedEvent == null) { // If we don't, create one, and if the process hasn't yet exited, // make sure we have a task that's actively monitoring the completion state. _exitedEvent = new ManualResetEvent(initialState: _exited); if (!_exited) { // If we haven't exited, we need to spin up an asynchronous operation that // will completed the exitedEvent when the other process exits. If there's already // another operation underway, then we'll just tack ours onto the end of it. _waitInProgress = _waitInProgress == null ? WaitForExitAsync() : _waitInProgress.ContinueWith((_, state) => ((ProcessWaitState)state).WaitForExitAsync(), this, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).Unwrap(); } } return _exitedEvent; } } internal DateTime ExitTime { get { lock (_gate) { Debug.Assert(_exited); return _exitTime; } } } internal bool HasExited { get { int? ignored; return GetExited(out ignored); } } internal bool GetExited(out int? exitCode) { lock (_gate) { // Have we already exited? If so, return the cached results. if (_exited) { exitCode = _exitCode; return true; } // Is another wait operation in progress? If so, then we haven't exited, // and that task owns the right to call CheckForExit. if (_waitInProgress != null) { exitCode = null; return false; } // We don't know if we've exited, but no one else is currently // checking, so check. CheckForExit(); // We now have an up-to-date snapshot for whether we've exited, // and if we have, what the exit code is (if we were able to find out). exitCode = _exitCode; return _exited; } } private void CheckForExit(bool blockingAllowed = false) { Debug.Assert(Monitor.IsEntered(_gate)); Debug.Assert(!blockingAllowed); // see "PERF NOTE" comment in WaitForExit while (true) // in case of EINTR during system call { // Try to get the state of the (child) process int status; int waitResult = Interop.libc.waitpid(_processId, out status, blockingAllowed ? Interop.libc.WaitPidOptions.None : Interop.libc.WaitPidOptions.WNOHANG); if (waitResult == _processId) { // Process has exited if (Interop.libc.WIFEXITED(status)) { _exitCode = Interop.libc.WEXITSTATUS(status); } else if (Interop.libc.WIFSIGNALED(status)) { const int ExitCodeSignalOffset = 128; _exitCode = ExitCodeSignalOffset + Interop.libc.WTERMSIG(status); } SetExited(); return; } else if (waitResult == 0) { // Process is still running return; } else if (waitResult == -1) { // Something went wrong, e.g. it's not a child process, // or waitpid was already called for this child, or // that the call was interrupted by a signal. Interop.Error errno = Interop.Sys.GetLastError(); if (errno == Interop.Error.EINTR) { // waitpid was interrupted. Try again. continue; } else if (errno == Interop.Error.ECHILD) { // waitpid was used with a non-child process. We won't be // able to get an exit code, but we'll at least be able // to determine if the process is still running (assuming // there's not a race on its id). int killResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.None); // 0 means don't send a signal if (killResult == 0) { // Process is still running. This could also be a defunct process that has completed // its work but still has an entry in the processes table due to its parent not yet // having waited on it to clean it up. return; } else // error from kill { errno = Interop.Sys.GetLastError(); if (errno == Interop.Error.ESRCH) { // Couldn't find the process; assume it's exited SetExited(); return; } else if (errno == Interop.Error.EPERM) { // Don't have permissions to the process; assume it's alive return; } else Debug.Fail("Unexpected errno value from kill"); } } else Debug.Fail("Unexpected errno value from waitpid"); } else Debug.Fail("Unexpected process ID from waitpid."); SetExited(); return; } } /// <summary>Waits for the associated process to exit.</summary> /// <param name="millisecondsTimeout">The amount of time to wait, or -1 to wait indefinitely.</param> /// <returns>true if the process exited; false if the timeout occurred.</returns> internal bool WaitForExit(int millisecondsTimeout) { Debug.Assert(!Monitor.IsEntered(_gate)); // Track the time the we start waiting. long startTime = Stopwatch.GetTimestamp(); // Polling loop while (true) { bool createdTask = false; CancellationTokenSource cts = null; Task waitTask; // We're in a polling loop... determine how much time remains int remainingTimeout = millisecondsTimeout == Timeout.Infinite ? Timeout.Infinite : (int)Math.Max(millisecondsTimeout - ((Stopwatch.GetTimestamp() - startTime) / (double)Stopwatch.Frequency * 1000), 0); lock (_gate) { // If we already know that the process exited, we're done. if (_exited) { return true; } // If a timeout of 0 was supplied, then we simply need to poll // to see if the process has already exited. if (remainingTimeout == 0) { // If there's currently a wait-in-progress, then we know the other process // hasn't exited (barring races and the polling interval). if (_waitInProgress != null) { return false; } // No one else is checking for the process' exit... so check. // We're currently holding the _gate lock, so we don't want to // allow CheckForExit to block indefinitely. CheckForExit(); return _exited; } // The process has not yet exited (or at least we don't know it yet) // so we need to wait for it to exit, outside of the lock. // If there's already a wait in progress, we'll do so later // by waiting on that existing task. Otherwise, we'll spin up // such a task. if (_waitInProgress != null) { waitTask = _waitInProgress; } else { createdTask = true; CancellationToken token = remainingTimeout == Timeout.Infinite ? CancellationToken.None : (cts = new CancellationTokenSource(remainingTimeout)).Token; waitTask = WaitForExitAsync(token); // PERF NOTE: // At the moment, we never call CheckForExit(true) (which in turn allows // waitpid to block until the child has completed) because we currently call it while // holdling the _gate lock. This is probably unnecessary in some situations, and in particular // here if remainingTimeout == Timeout.Infinite. In that case, we should be able to set // _waitInProgress to be a TaskCompletionSource task, and then below outside of the lock // we could do a CheckForExit(blockingAllowed:true) and complete the TaskCompletionSource // after that. We would just need to make sure that there's no risk of the other state // on this instance experiencing torn reads. } } // lock(_gate) if (createdTask) { // We created this task, and it'll get canceled automatically after our timeout. // This Wait should only wake up when either the process has exited or the timeout // has expired. Either way, we'll loop around again; if the process exited, that'll // be caught first thing in the loop where we check _exited, and if it didn't exit, // our remaining time will be zero, so we'll do a quick remaining check and bail. waitTask.Wait(); if (cts != null) { cts.Dispose(); } } else { // It's someone else's task. We'll wait for it to complete. This could complete // either because our remainingTimeout expired or because the task completed, // which could happen because the process exited or because whoever created // that task gave it a timeout. In any case, we'll loop around again, and the loop // will catch these cases, potentially issuing another wait to make up any // remaining time. waitTask.Wait(remainingTimeout); } } } /// <summary>Spawns an asynchronous polling loop for process completion.</summary> /// <param name="cancellationToken">A token to monitor to exit the polling loop.</param> /// <returns>The task representing the loop.</returns> private Task WaitForExitAsync(CancellationToken cancellationToken = default(CancellationToken)) { Debug.Assert(Monitor.IsEntered(_gate)); Debug.Assert(_waitInProgress == null); return _waitInProgress = Task.Run(async delegate // Task.Run used because of potential blocking in CheckForExit { try { // While we're not canceled while (!cancellationToken.IsCancellationRequested) { // Poll lock (_gate) { if (!_exited) { CheckForExit(); } if (_exited) // may have been updated by CheckForExit { return; } } // Wait try { const int PollingIntervalMs = 100; // arbitrary value chosen to balance delays with polling overhead await Task.Delay(PollingIntervalMs, cancellationToken); } catch (OperationCanceledException) { } } } finally { // Task is no longer active lock (_gate) { _waitInProgress = null; } } }); } } }
//------------------------------------------------------------------------------ // <copyright file="VirtualPath.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web { using System.Globalization; using System.Collections; using System.IO; using System.Web.Util; using System.Web.Hosting; using System.Web.Caching; using System.Security.Permissions; using Microsoft.Win32; [Serializable] internal sealed class VirtualPath : IComparable { private string _appRelativeVirtualPath; private string _virtualPath; // const masks into the BitVector32 private const int isWithinAppRootComputed = 0x00000001; private const int isWithinAppRoot = 0x00000002; private const int appRelativeAttempted = 0x00000004; #pragma warning disable 0649 private SimpleBitVector32 flags; #pragma warning restore 0649 #if DBG private static char[] s_illegalVirtualPathChars = new char[] { '\0' }; // Debug only method to check that the object is in a consistent state private void ValidateState() { Debug.Assert(_virtualPath != null || _appRelativeVirtualPath != null); if (_virtualPath != null) { CheckValidVirtualPath(_virtualPath); } if (_appRelativeVirtualPath != null) { Debug.Assert(UrlPath.IsAppRelativePath(_appRelativeVirtualPath)); CheckValidVirtualPath(_appRelativeVirtualPath); } } private static void CheckValidVirtualPath(string virtualPath) { Debug.Assert(virtualPath.IndexOfAny(s_illegalVirtualPathChars) < 0); Debug.Assert(virtualPath.IndexOf('\\') < 0); } #endif internal static VirtualPath RootVirtualPath = VirtualPath.Create("/"); private VirtualPath() { } // This is called to set the appropriate virtual path field when we already know // that the path is generally well formed. private VirtualPath(string virtualPath) { if (UrlPath.IsAppRelativePath(virtualPath)) { _appRelativeVirtualPath = virtualPath; } else { _virtualPath = virtualPath; } } int IComparable.CompareTo(object obj) { VirtualPath virtualPath = obj as VirtualPath; // Make sure we're compared to another VirtualPath if (virtualPath == null) throw new ArgumentException(); // Check if it's the same object if (virtualPath == this) return 0; return StringComparer.InvariantCultureIgnoreCase.Compare( this.VirtualPathString, virtualPath.VirtualPathString); } public string VirtualPathString { get { if (_virtualPath == null) { Debug.Assert(_appRelativeVirtualPath != null); // This is not valid if we don't know the app path if (HttpRuntime.AppDomainAppVirtualPathObject == null) { throw new HttpException(SR.GetString(SR.VirtualPath_CantMakeAppAbsolute, _appRelativeVirtualPath)); } if (_appRelativeVirtualPath.Length == 1) { _virtualPath = HttpRuntime.AppDomainAppVirtualPath; } else { _virtualPath = HttpRuntime.AppDomainAppVirtualPathString + _appRelativeVirtualPath.Substring(2); } } return _virtualPath; } } internal string VirtualPathStringNoTrailingSlash { get { return UrlPath.RemoveSlashFromPathIfNeeded(VirtualPathString); } } // Return the virtual path string if we have it, otherwise null internal string VirtualPathStringIfAvailable { get { return _virtualPath; } } internal string AppRelativeVirtualPathStringOrNull { get { if (_appRelativeVirtualPath == null) { Debug.Assert(_virtualPath != null); // If we already tried to get it and couldn't, return null if (flags[appRelativeAttempted]) return null; // This is not valid if we don't know the app path if (HttpRuntime.AppDomainAppVirtualPathObject == null) { throw new HttpException(SR.GetString(SR.VirtualPath_CantMakeAppRelative, _virtualPath)); } _appRelativeVirtualPath = UrlPath.MakeVirtualPathAppRelativeOrNull(_virtualPath); // Remember that we've attempted it flags[appRelativeAttempted] = true; // It could be null if it's not under the app root if (_appRelativeVirtualPath == null) return null; #if DBG ValidateState(); #endif } return _appRelativeVirtualPath; } } // Return the app relative path if possible. Otherwise, settle for the absolute. public string AppRelativeVirtualPathString { get { string appRelativeVirtualPath = AppRelativeVirtualPathStringOrNull; return (appRelativeVirtualPath != null) ? appRelativeVirtualPath : _virtualPath; } } // Return the app relative virtual path string if we have it, otherwise null internal string AppRelativeVirtualPathStringIfAvailable { get { return _appRelativeVirtualPath; } } // Return the virtual string that's either app relative or not, depending on which // one we already have internally. If we have both, we return absolute internal string VirtualPathStringWhicheverAvailable { get { return _virtualPath != null ? _virtualPath : _appRelativeVirtualPath; } } public string Extension { get { return UrlPath.GetExtension(VirtualPathString); } } public string FileName { get { return UrlPath.GetFileName(VirtualPathStringNoTrailingSlash); } } // If it's relative, combine it with the app root public VirtualPath CombineWithAppRoot() { return HttpRuntime.AppDomainAppVirtualPathObject.Combine(this); } public VirtualPath Combine(VirtualPath relativePath) { if (relativePath == null) throw new ArgumentNullException("relativePath"); // If it's not relative, return it unchanged if (!relativePath.IsRelative) return relativePath; // The base of the combine should never be relative FailIfRelativePath(); // Get either _appRelativeVirtualPath or _virtualPath string virtualPath = VirtualPathStringWhicheverAvailable; // Combine it with the relative virtualPath = UrlPath.Combine(virtualPath, relativePath.VirtualPathString); // Set the appropriate virtual path in the new object return new VirtualPath(virtualPath); } // This simple version of combine should only be used when the relative // path is known to be relative. It's more efficient, but doesn't do any // sanity checks. internal VirtualPath SimpleCombine(string relativePath) { return SimpleCombine(relativePath, false /*addTrailingSlash*/); } internal VirtualPath SimpleCombineWithDir(string directoryName) { return SimpleCombine(directoryName, true /*addTrailingSlash*/); } private VirtualPath SimpleCombine(string filename, bool addTrailingSlash) { // The left part should always be a directory Debug.Assert(HasTrailingSlash); // The right part should not start or end with a slash Debug.Assert(filename[0] != '/' && !UrlPath.HasTrailingSlash(filename)); // Use either _appRelativeVirtualPath or _virtualPath string virtualPath = VirtualPathStringWhicheverAvailable + filename; if (addTrailingSlash) virtualPath += "/"; // Set the appropriate virtual path in the new object VirtualPath combinedVirtualPath = new VirtualPath(virtualPath); // Copy some flags over to avoid having to recalculate them combinedVirtualPath.CopyFlagsFrom(this, isWithinAppRootComputed | isWithinAppRoot | appRelativeAttempted); #if DBG combinedVirtualPath.ValidateState(); #endif return combinedVirtualPath; } public VirtualPath MakeRelative(VirtualPath toVirtualPath) { VirtualPath resultVirtualPath = new VirtualPath(); // Neither path can be relative FailIfRelativePath(); toVirtualPath.FailIfRelativePath(); // Set it directly since we know the slashes are already ok resultVirtualPath._virtualPath = UrlPath.MakeRelative(this.VirtualPathString, toVirtualPath.VirtualPathString); #if DBG resultVirtualPath.ValidateState(); #endif return resultVirtualPath; } public string MapPath() { return HostingEnvironment.MapPath(this); } internal string MapPathInternal() { return HostingEnvironment.MapPathInternal(this); } internal string MapPathInternal(bool permitNull) { return HostingEnvironment.MapPathInternal(this, permitNull); } internal string MapPathInternal(VirtualPath baseVirtualDir, bool allowCrossAppMapping) { return HostingEnvironment.MapPathInternal(this, baseVirtualDir, allowCrossAppMapping); } ///////////// VirtualPathProvider wrapper methods ///////////// public string GetFileHash(IEnumerable virtualPathDependencies) { return HostingEnvironment.VirtualPathProvider.GetFileHash(this, virtualPathDependencies); } public CacheDependency GetCacheDependency(IEnumerable virtualPathDependencies, DateTime utcStart) { return HostingEnvironment.VirtualPathProvider.GetCacheDependency( this, virtualPathDependencies, utcStart); } public bool FileExists() { return HostingEnvironment.VirtualPathProvider.FileExists(this); } public bool DirectoryExists() { return HostingEnvironment.VirtualPathProvider.DirectoryExists(this); } public VirtualFile GetFile() { return HostingEnvironment.VirtualPathProvider.GetFile(this); } public VirtualDirectory GetDirectory() { Debug.Assert(this.HasTrailingSlash); return HostingEnvironment.VirtualPathProvider.GetDirectory(this); } public string GetCacheKey() { return HostingEnvironment.VirtualPathProvider.GetCacheKey(this); } public Stream OpenFile() { return VirtualPathProvider.OpenFile(this); } ///////////// end of VirtualPathProvider methods ///////////// internal bool HasTrailingSlash { get { if (_virtualPath != null) { return UrlPath.HasTrailingSlash(_virtualPath); } else { return UrlPath.HasTrailingSlash(_appRelativeVirtualPath); } } } public bool IsWithinAppRoot { get { // If we don't already know it, compute it and cache it if (!flags[isWithinAppRootComputed]) { if (HttpRuntime.AppDomainIdInternal == null) { Debug.Assert(false); return true; // app domain not initialized } if (flags[appRelativeAttempted]) { // If we already tried to get the app relative path, we can tell whether // it's in the app root by checking whether it's not null flags[isWithinAppRoot] = (_appRelativeVirtualPath != null); } else { flags[isWithinAppRoot] = UrlPath.IsEqualOrSubpath(HttpRuntime.AppDomainAppVirtualPathString, VirtualPathString); } flags[isWithinAppRootComputed] = true; } return flags[isWithinAppRoot]; } } internal void FailIfNotWithinAppRoot() { if (!this.IsWithinAppRoot) { throw new ArgumentException(SR.GetString(SR.Cross_app_not_allowed, this.VirtualPathString)); } } internal void FailIfRelativePath() { if (this.IsRelative) { throw new ArgumentException(SR.GetString(SR.VirtualPath_AllowRelativePath, _virtualPath)); } } public bool IsRelative { get { // Note that we don't need to check for "~/", since _virtualPath never contains // app relative paths (_appRelativeVirtualPath does) return _virtualPath != null && _virtualPath[0] != '/'; } } public bool IsRoot { get { return _virtualPath == "/"; } } public VirtualPath Parent { get { // Getting the parent doesn't make much sense on relative paths FailIfRelativePath(); // "/" doesn't have a parent, so return null if (IsRoot) return null; // Get either _appRelativeVirtualPath or _virtualPath string virtualPath = VirtualPathStringWhicheverAvailable; // Get rid of the ending slash, otherwise we end up with Parent("/app/sub/") == "/app/sub/" virtualPath = UrlPath.RemoveSlashFromPathIfNeeded(virtualPath); // But if it's just "~", use the absolute path instead to get the parent if (virtualPath == "~") virtualPath = VirtualPathStringNoTrailingSlash; int index = virtualPath.LastIndexOf('/'); Debug.Assert(index >= 0); // e.g. the parent of "/blah" is "/" if (index == 0) return RootVirtualPath; // // Get the parent virtualPath = virtualPath.Substring(0, index + 1); // Set the appropriate virtual path in the new object return new VirtualPath(virtualPath); } } internal static VirtualPath Combine(VirtualPath v1, VirtualPath v2) { // If the first is null, use the app root instead if (v1 == null) { v1 = HttpRuntime.AppDomainAppVirtualPathObject; } // If the first is still null, return the second, unless it's relative if (v1 == null) { v2.FailIfRelativePath(); return v2; } return v1.Combine(v2); } [System.Runtime.TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] public static bool operator == (VirtualPath v1, VirtualPath v2) { return VirtualPath.Equals(v1, v2); } [System.Runtime.TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] public static bool operator != (VirtualPath v1, VirtualPath v2) { return !VirtualPath.Equals(v1, v2); } [System.Runtime.TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] public static bool Equals(VirtualPath v1, VirtualPath v2) { // Check if it's the same object if ((Object)v1 == (Object)v2) { return true; } if ((Object)v1 == null || (Object)v2 == null) { return false; } return EqualsHelper(v1, v2); } [System.Runtime.TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] public override bool Equals(object value) { if (value == null) return false; VirtualPath virtualPath = value as VirtualPath; if ((object)virtualPath == null) { Debug.Assert(false); return false; } return EqualsHelper(virtualPath, this); } [System.Runtime.TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] private static bool EqualsHelper(VirtualPath v1, VirtualPath v2) { return StringComparer.InvariantCultureIgnoreCase.Compare( v1.VirtualPathString, v2.VirtualPathString) == 0; } public override int GetHashCode() { return StringComparer.InvariantCultureIgnoreCase.GetHashCode(VirtualPathString); } public override String ToString() { // If we only have the app relative path, and we don't know the app root, return // the app relative path instead of accessing VirtualPathString, which would throw if (_virtualPath == null && HttpRuntime.AppDomainAppVirtualPathObject == null) { Debug.Assert(_appRelativeVirtualPath != null); return _appRelativeVirtualPath; } return VirtualPathString; } // Copy a set of flags from another VirtualPath object private void CopyFlagsFrom(VirtualPath virtualPath, int mask) { flags.IntegerValue |= virtualPath.flags.IntegerValue & mask; } internal static string GetVirtualPathString(VirtualPath virtualPath) { return virtualPath == null ? null : virtualPath.VirtualPathString; } internal static string GetVirtualPathStringNoTrailingSlash(VirtualPath virtualPath) { return virtualPath == null ? null : virtualPath.VirtualPathStringNoTrailingSlash; } internal static string GetAppRelativeVirtualPathString(VirtualPath virtualPath) { return virtualPath == null ? null : virtualPath.AppRelativeVirtualPathString; } // Same as GetAppRelativeVirtualPathString, but returns "" instead of null internal static string GetAppRelativeVirtualPathStringOrEmpty(VirtualPath virtualPath) { return virtualPath == null ? String.Empty : virtualPath.AppRelativeVirtualPathString; } // Default Create method public static VirtualPath Create(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAllPath); } public static VirtualPath CreateTrailingSlash(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAllPath | VirtualPathOptions.EnsureTrailingSlash); } public static VirtualPath CreateAllowNull(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAllPath | VirtualPathOptions.AllowNull); } public static VirtualPath CreateAbsolute(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAbsolutePath); } public static VirtualPath CreateNonRelative(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAbsolutePath | VirtualPathOptions.AllowAppRelativePath); } public static VirtualPath CreateAbsoluteTrailingSlash(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAbsolutePath | VirtualPathOptions.EnsureTrailingSlash); } public static VirtualPath CreateNonRelativeTrailingSlash(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAbsolutePath | VirtualPathOptions.AllowAppRelativePath | VirtualPathOptions.EnsureTrailingSlash); } public static VirtualPath CreateAbsoluteAllowNull(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAbsolutePath | VirtualPathOptions.AllowNull); } public static VirtualPath CreateNonRelativeAllowNull(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAbsolutePath | VirtualPathOptions.AllowAppRelativePath | VirtualPathOptions.AllowNull); } public static VirtualPath CreateNonRelativeTrailingSlashAllowNull(string virtualPath) { return Create(virtualPath, VirtualPathOptions.AllowAbsolutePath | VirtualPathOptions.AllowAppRelativePath | VirtualPathOptions.AllowNull | VirtualPathOptions.EnsureTrailingSlash); } public static VirtualPath Create(string virtualPath, VirtualPathOptions options) { // Trim it first, so that blank strings (e.g. " ") get treated as empty if (virtualPath != null) virtualPath = virtualPath.Trim(); // If it's empty, check whether we allow it if (String.IsNullOrEmpty(virtualPath)) { if ((options & VirtualPathOptions.AllowNull) != 0) return null; throw new ArgumentNullException("virtualPath"); } // Dev10 767308: optimize for normal paths, and scan once for // i) invalid chars // ii) slashes // iii) '.' bool slashes = false; bool dot = false; int len = virtualPath.Length; unsafe { fixed (char * p = virtualPath) { for (int i = 0; i < len; i++) { switch (p[i]) { // need to fix slashes ? case '/': if (i > 0 && p[i-1] == '/') slashes = true; break; case '\\': slashes = true; break; // contains "." or ".." case '.': dot = true; break; // invalid chars case '\0': throw new HttpException(SR.GetString(SR.Invalid_vpath, virtualPath)); default: break; } } } } if (slashes) { // If we're supposed to fail on malformed path, then throw if ((options & VirtualPathOptions.FailIfMalformed) != 0) { throw new HttpException(SR.GetString(SR.Invalid_vpath, virtualPath)); } // Flip ----lashes, and remove duplicate slashes virtualPath = UrlPath.FixVirtualPathSlashes(virtualPath); } // Make sure it ends with a trailing slash if requested if ((options & VirtualPathOptions.EnsureTrailingSlash) != 0) virtualPath = UrlPath.AppendSlashToPathIfNeeded(virtualPath); VirtualPath virtualPathObject = new VirtualPath(); if (UrlPath.IsAppRelativePath(virtualPath)) { if (dot) virtualPath = UrlPath.ReduceVirtualPath(virtualPath); if (virtualPath[0] == UrlPath.appRelativeCharacter) { if ((options & VirtualPathOptions.AllowAppRelativePath) == 0) { throw new ArgumentException(SR.GetString(SR.VirtualPath_AllowAppRelativePath, virtualPath)); } virtualPathObject._appRelativeVirtualPath = virtualPath; } else { // It's possible for the path to become absolute after calling Reduce, // even though it started with "~/". e.g. if the app is "/app" and the path is // "~/../hello.aspx", it becomes "/hello.aspx", which is absolute if ((options & VirtualPathOptions.AllowAbsolutePath) == 0) { throw new ArgumentException(SR.GetString(SR.VirtualPath_AllowAbsolutePath, virtualPath)); } virtualPathObject._virtualPath = virtualPath; } } else { if (virtualPath[0] != '/') { if ((options & VirtualPathOptions.AllowRelativePath) == 0) { throw new ArgumentException(SR.GetString(SR.VirtualPath_AllowRelativePath, virtualPath)); } // Don't Reduce relative paths, since the Reduce method is broken (e.g. "../foo.aspx" --> "/foo.aspx!") // virtualPathObject._virtualPath = virtualPath; } else { if ((options & VirtualPathOptions.AllowAbsolutePath) == 0) { throw new ArgumentException(SR.GetString(SR.VirtualPath_AllowAbsolutePath, virtualPath)); } if (dot) virtualPath = UrlPath.ReduceVirtualPath(virtualPath); virtualPathObject._virtualPath = virtualPath; } } #if DBG virtualPathObject.ValidateState(); #endif return virtualPathObject; } } [Flags] internal enum VirtualPathOptions { AllowNull = 0x00000001, EnsureTrailingSlash = 0x00000002, AllowAbsolutePath = 0x00000004, AllowAppRelativePath = 0x00000008, AllowRelativePath = 0x00000010, FailIfMalformed = 0x00000020, AllowAllPath = AllowAbsolutePath | AllowAppRelativePath | AllowRelativePath, } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Patterns.Logging; namespace SocketHttpListener.Net { // FIXME: Does this buffer the response until Close? // Update: we send a single packet for the first non-chunked Write // What happens when we set content-length to X and write X-1 bytes then close? // what if we don't set content-length at all? class ResponseStream : Stream { HttpListenerResponse response; bool ignore_errors; bool disposed; bool trailer_sent; Stream stream; internal ResponseStream(Stream stream, HttpListenerResponse response, bool ignore_errors) { this.response = response; this.ignore_errors = ignore_errors; this.stream = stream; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } protected override void Dispose(bool disposing) { if (disposed == false) { disposed = true; byte[] bytes = null; MemoryStream ms = GetHeaders(true); bool chunked = response.SendChunked; if (stream.CanWrite) { try { if (ms != null) { long start = ms.Position; if (chunked && !trailer_sent) { bytes = GetChunkSizeBytes(0, true); ms.Position = ms.Length; ms.Write(bytes, 0, bytes.Length); } InternalWrite(ms.ToArray(), (int)start, (int)(ms.Length - start)); trailer_sent = true; } else if (chunked && !trailer_sent) { bytes = GetChunkSizeBytes(0, true); InternalWrite(bytes, 0, bytes.Length); trailer_sent = true; } } catch (IOException ex) { // Ignore error due to connection reset by peer } } response.Close(); } base.Dispose(disposing); } MemoryStream GetHeaders(bool closing) { // SendHeaders works on shared headers lock (response.headers_lock) { if (response.HeadersSent) return null; MemoryStream ms = new MemoryStream(); response.SendHeaders(closing, ms); return ms; } } public override void Flush() { } static byte[] crlf = new byte[] { 13, 10 }; static byte[] GetChunkSizeBytes(int size, bool final) { string str = String.Format("{0:x}\r\n{1}", size, final ? "\r\n" : ""); return Encoding.ASCII.GetBytes(str); } internal void InternalWrite(byte[] buffer, int offset, int count) { if (ignore_errors) { try { stream.Write(buffer, offset, count); } catch { } } else { stream.Write(buffer, offset, count); } } public override void Write(byte[] buffer, int offset, int count) { if (disposed) throw new ObjectDisposedException(GetType().ToString()); byte[] bytes = null; MemoryStream ms = GetHeaders(false); bool chunked = response.SendChunked; if (ms != null) { long start = ms.Position; // After the possible preamble for the encoding ms.Position = ms.Length; if (chunked) { bytes = GetChunkSizeBytes(count, false); ms.Write(bytes, 0, bytes.Length); } int new_count = Math.Min(count, 16384 - (int)ms.Position + (int)start); ms.Write(buffer, offset, new_count); count -= new_count; offset += new_count; InternalWrite(ms.ToArray(), (int)start, (int)(ms.Length - start)); ms.SetLength(0); ms.Capacity = 0; // 'dispose' the buffer in ms. } else if (chunked) { bytes = GetChunkSizeBytes(count, false); InternalWrite(bytes, 0, bytes.Length); } if (count > 0) InternalWrite(buffer, offset, count); if (chunked) InternalWrite(crlf, 0, 2); } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (disposed) throw new ObjectDisposedException(GetType().ToString()); byte[] bytes = null; MemoryStream ms = GetHeaders(false); bool chunked = response.SendChunked; if (ms != null) { long start = ms.Position; ms.Position = ms.Length; if (chunked) { bytes = GetChunkSizeBytes(count, false); ms.Write(bytes, 0, bytes.Length); } ms.Write(buffer, offset, count); buffer = ms.ToArray(); offset = (int)start; count = (int)(ms.Position - start); } else if (chunked) { bytes = GetChunkSizeBytes(count, false); InternalWrite(bytes, 0, bytes.Length); } try { if (count > 0) { await stream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); } if (response.SendChunked) stream.Write(crlf, 0, 2); } catch { if (!ignore_errors) { throw; } } } //public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, // AsyncCallback cback, object state) //{ // if (disposed) // throw new ObjectDisposedException(GetType().ToString()); // byte[] bytes = null; // MemoryStream ms = GetHeaders(false); // bool chunked = response.SendChunked; // if (ms != null) // { // long start = ms.Position; // ms.Position = ms.Length; // if (chunked) // { // bytes = GetChunkSizeBytes(count, false); // ms.Write(bytes, 0, bytes.Length); // } // ms.Write(buffer, offset, count); // buffer = ms.ToArray(); // offset = (int)start; // count = (int)(ms.Position - start); // } // else if (chunked) // { // bytes = GetChunkSizeBytes(count, false); // InternalWrite(bytes, 0, bytes.Length); // } // return stream.BeginWrite(buffer, offset, count, cback, state); //} //public override void EndWrite(IAsyncResult ares) //{ // if (disposed) // throw new ObjectDisposedException(GetType().ToString()); // if (ignore_errors) // { // try // { // stream.EndWrite(ares); // if (response.SendChunked) // stream.Write(crlf, 0, 2); // } // catch { } // } // else { // stream.EndWrite(ares); // if (response.SendChunked) // stream.Write(crlf, 0, 2); // } //} public override int Read([In, Out] byte[] buffer, int offset, int count) { throw new NotSupportedException(); } //public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, // AsyncCallback cback, object state) //{ // throw new NotSupportedException(); //} //public override int EndRead(IAsyncResult ares) //{ // throw new NotSupportedException(); //} public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Amazon.SimpleWorkflow; using Amazon.SimpleWorkflow.Model; using System.Threading; using NUnit.Framework; using CommonTests.Framework; namespace CommonTests.IntegrationTests { //[TestFixture] public class SimpleWorkflow : TestBase<AmazonSimpleWorkflowClient> { private static readonly TimeSpan SleepDuration = TimeSpan.FromSeconds(5); private const int MaxRetries = 3; public static readonly string ONE_HOUR_DURATION = (60 * 60).ToString(); public static readonly string TWO_HOUR_DURATION = (60 * 60 * 2).ToString(); public static readonly string THREE_HOUR_DURATION = (60 * 60 * 3).ToString(); public static readonly string FOUR_HOUR_DURATION = (60 * 60 * 4).ToString(); public static readonly string FIVE_HOUR_DURATION = (60 * 60 * 5).ToString(); static string DOMAIN = UtilityMethods.SDK_TEST_PREFIX + DateTime.Now.Ticks; static WorkflowType WORKFLOW_TYPE = new WorkflowType() { Name = UtilityMethods.SDK_TEST_PREFIX + DateTime.Now.Ticks, Version = "1.0" }; static TaskList TASKLIST = new TaskList() { Name = "TestTaskList" }; static ActivityType ACTIVITY_TYPE = new ActivityType() { Name = UtilityMethods.SDK_TEST_PREFIX + DateTime.Now.Ticks, Version = "1.0" }; [OneTimeSetUp] public void SetupWorkflowTypes() { var registerDomainRequest = new RegisterDomainRequest() { Name = DOMAIN, Description = "A Description", WorkflowExecutionRetentionPeriodInDays = "5" }; Client.RegisterDomainAsync(registerDomainRequest).Wait(); var registerWorkflowRequest = new RegisterWorkflowTypeRequest() { Name = WORKFLOW_TYPE.Name, Domain = DOMAIN, Description = "Another Description", Version = WORKFLOW_TYPE.Version, DefaultTaskList = TASKLIST, DefaultExecutionStartToCloseTimeout = FIVE_HOUR_DURATION, DefaultTaskStartToCloseTimeout = FOUR_HOUR_DURATION }; Client.RegisterWorkflowTypeAsync(registerWorkflowRequest).Wait(); var registerActivityRequest = new RegisterActivityTypeRequest() { Name = ACTIVITY_TYPE.Name, Domain = DOMAIN, Description = "My Description Activity", Version = ACTIVITY_TYPE.Version, DefaultTaskList = TASKLIST, DefaultTaskHeartbeatTimeout = ONE_HOUR_DURATION, DefaultTaskScheduleToCloseTimeout = TWO_HOUR_DURATION, DefaultTaskScheduleToStartTimeout = THREE_HOUR_DURATION, DefaultTaskStartToCloseTimeout = FOUR_HOUR_DURATION }; var registerActivityResponse = Client.RegisterActivityTypeAsync(registerActivityRequest).Result; } [OneTimeTearDown] public void Cleanup() { var deprecateWorkflowRequest = new DeprecateWorkflowTypeRequest() { Domain = DOMAIN, WorkflowType = WORKFLOW_TYPE }; var deprecateWorkflowTypeResponse = Client.DeprecateWorkflowTypeAsync(deprecateWorkflowRequest).Result; Assert.IsNotNull(deprecateWorkflowTypeResponse.ResponseMetadata.RequestId); var deprecateDomainRequest = new DeprecateDomainRequest() { Name = DOMAIN }; var deprecateDomainResponse = Client.DeprecateDomainAsync(deprecateDomainRequest).Result; Assert.IsNotNull(deprecateDomainResponse.ResponseMetadata.RequestId); BaseClean(); } [Test] [Category("SimpleWorkflow")] public void TestPollDecider() { string workflowId = DateTime.Now.Ticks.ToString(); var startRequest = new StartWorkflowExecutionRequest() { Domain = DOMAIN, WorkflowId = workflowId, ChildPolicy = "TERMINATE", TaskList = TASKLIST, Input = "ImportantKeyId", WorkflowType = WORKFLOW_TYPE }; var startResponse = Client.StartWorkflowExecutionAsync(startRequest).Result; var pollDeciderRequest = new PollForDecisionTaskRequest() { Domain = DOMAIN, TaskList = TASKLIST, Identity = "testdecider" }; var pollDeciderResponse = Client.PollForDecisionTaskAsync(pollDeciderRequest).Result; Assert.IsNotNull(pollDeciderResponse.DecisionTask); Assert.IsTrue(pollDeciderResponse.DecisionTask.Events.Count > 0); Assert.IsNotNull(pollDeciderResponse.DecisionTask.Events[0].EventId); Assert.IsNotNull(pollDeciderResponse.DecisionTask.Events[0].EventType); Assert.AreEqual(DateTime.Today, pollDeciderResponse.DecisionTask.Events[0].EventTimestamp.ToLocalTime().Date); var task = pollDeciderResponse.DecisionTask; var respondRequest = new RespondDecisionTaskCompletedRequest() { TaskToken = task.TaskToken, Decisions = new List<Decision>() { new Decision() { DecisionType = "ScheduleActivityTask", ScheduleActivityTaskDecisionAttributes = new ScheduleActivityTaskDecisionAttributes() { ActivityType = ACTIVITY_TYPE, ActivityId = DateTime.Now.Ticks.ToString(), TaskList = TASKLIST } } } }; Client.RespondDecisionTaskCompletedAsync(respondRequest).Wait(); var pollActivityRequest = new PollForActivityTaskRequest() { Domain = DOMAIN, TaskList = TASKLIST, Identity = "testactivity" }; var pollActivityResponse = Client.PollForActivityTaskAsync(pollActivityRequest).Result; Assert.IsNotNull(pollActivityResponse.ResponseMetadata.RequestId); Assert.AreEqual(ACTIVITY_TYPE.Name, pollActivityResponse.ActivityTask.ActivityType.Name); Assert.AreEqual(ACTIVITY_TYPE.Version, pollActivityResponse.ActivityTask.ActivityType.Version); var signalRequest = new SignalWorkflowExecutionRequest() { Domain = DOMAIN, RunId = startResponse.Run.RunId, WorkflowId = startRequest.WorkflowId, SignalName = "TestSignal" }; var signalResponse = Client.SignalWorkflowExecutionAsync(signalRequest).Result; Assert.IsNotNull(signalResponse.ResponseMetadata.RequestId); } [Test] [Category("SimpleWorkflow")] public void CompleteActivity() { var workflowId = DateTime.Now.Ticks.ToString(); var startRequest = new StartWorkflowExecutionRequest() { Domain = DOMAIN, WorkflowId = workflowId, ChildPolicy = "TERMINATE", TaskList = TASKLIST, Input = "ImportantKeyId", WorkflowType = WORKFLOW_TYPE }; var runId = Client.StartWorkflowExecutionAsync(startRequest).Result.Run.RunId; var task = startActivity(runId); var respondCompleteRequest = new RespondActivityTaskCompletedRequest() { TaskToken = task.TaskToken, Result = "completed" }; var respondCompleteRespond = Client.RespondActivityTaskCompletedAsync(respondCompleteRequest).Result; Assert.IsNotNull(respondCompleteRespond.ResponseMetadata.RequestId); } [Test] [Category("SimpleWorkflow")] public void CancelActivity() { var workflowId = DateTime.Now.Ticks.ToString(); var startRequest = new StartWorkflowExecutionRequest() { Domain = DOMAIN, WorkflowId = workflowId, ChildPolicy = "TERMINATE", TaskList = TASKLIST, Input = "ImportantKeyId", WorkflowType = WORKFLOW_TYPE }; var runId = Client.StartWorkflowExecutionAsync(startRequest).Result.Run.RunId; var task = startActivity(runId); var respondCanceledRequest = new RespondActivityTaskCanceledRequest() { TaskToken = task.TaskToken, Details = "cancel task" }; var respondCanceledRespond = Client.RespondActivityTaskCanceledAsync(respondCanceledRequest).Result; Assert.IsNotNull(respondCanceledRespond.ResponseMetadata.RequestId); } [Test] [Category("SimpleWorkflow")] public void FailedActivity() { var workflowId = DateTime.Now.Ticks.ToString(); var startRequest = new StartWorkflowExecutionRequest() { Domain = DOMAIN, WorkflowId = workflowId, ChildPolicy = "TERMINATE", TaskList = TASKLIST, Input = "ImportantKeyId", WorkflowType = WORKFLOW_TYPE }; var runId = Client.StartWorkflowExecutionAsync(startRequest).Result.Run.RunId; var task = startActivity(runId); var respondFailedRequest = new RespondActivityTaskFailedRequest() { TaskToken = task.TaskToken, Details = "fail task", Reason = "result not required" }; var respondFailedRespond = Client.RespondActivityTaskFailedAsync(respondFailedRequest).Result; Assert.IsNotNull(respondFailedRespond.ResponseMetadata.RequestId); } [Test] [Category("SimpleWorkflow")] public void CancelWorkflow() { var workflowId = DateTime.Now.Ticks.ToString(); var startRequest = new StartWorkflowExecutionRequest() { Domain = DOMAIN, WorkflowId = workflowId, ChildPolicy = "TERMINATE", TaskList = TASKLIST, Input = "ImportantKeyId", WorkflowType = WORKFLOW_TYPE }; var runId = Client.StartWorkflowExecutionAsync(startRequest).Result.Run.RunId; var cancelRequest = new RequestCancelWorkflowExecutionRequest() { Domain = DOMAIN, RunId = runId, WorkflowId = workflowId }; var cancelResponse = Client.RequestCancelWorkflowExecutionAsync(cancelRequest).Result; Assert.IsNotNull(cancelResponse.ResponseMetadata.RequestId); } [Test] [Category("SimpleWorkflow")] public void CRUDTest() { var domainName = "sdk-dotnet-crud-" + DateTime.Now.Ticks; var regRequest = new RegisterDomainRequest() { Name = domainName, Description = "A Description", WorkflowExecutionRetentionPeriodInDays = "3" }; var regResponse = Client.RegisterDomainAsync(regRequest).Result; try { Sleep(); // Sleep for the eventual consistency Assert.IsNotNull(regResponse.ResponseMetadata.RequestId); var descRequest = new DescribeDomainRequest() { Name = domainName }; var descResponse = Client.DescribeDomainAsync(descRequest).Result; Assert.AreEqual(domainName, descResponse.DomainDetail.DomainInfo.Name); Assert.AreEqual("A Description", descResponse.DomainDetail.DomainInfo.Description); Assert.AreEqual("3", descResponse.DomainDetail.Configuration.WorkflowExecutionRetentionPeriodInDays); Assert.IsNotNull(descResponse.DomainDetail.DomainInfo.Status); DomainInfo info = null; for (int i = 0; i < MaxRetries; i++) { Sleep(); // Sleep for the eventual consistency var listDomainResponse = Client.ListDomainsAsync( new ListDomainsRequest() { RegistrationStatus = descResponse.DomainDetail.DomainInfo.Status }).Result; Assert.IsTrue(listDomainResponse.DomainInfos.Infos.Count > 0); info = listDomainResponse.DomainInfos.Infos.FirstOrDefault(x => string.Equals(x.Name, domainName)); if (info != null) break; } Assert.IsNotNull(info); Assert.IsNotNull(info.Status); var activityDescription = "My Description Activity" + DateTime.Now.Ticks; var regActivityRequest = new RegisterActivityTypeRequest() { Name = "My Activity", Domain = domainName, Description = activityDescription, Version = "1.0", DefaultTaskList = new TaskList() { Name = "ImportantTasks" }, DefaultTaskHeartbeatTimeout = ONE_HOUR_DURATION, DefaultTaskScheduleToCloseTimeout = TWO_HOUR_DURATION, DefaultTaskScheduleToStartTimeout = THREE_HOUR_DURATION, DefaultTaskStartToCloseTimeout = FOUR_HOUR_DURATION }; var regActivityResponse = Client.RegisterActivityTypeAsync(regActivityRequest).Result; Assert.IsNotNull(regActivityResponse.ResponseMetadata.RequestId); try { Sleep(); // Sleep for the eventual consistency var descActivityTypeRequest = new DescribeActivityTypeRequest() { Domain = domainName, ActivityType = new ActivityType() { Name = "My Activity", Version = "1.0" } }; var descActivityTypeResponse = Client.DescribeActivityTypeAsync(descActivityTypeRequest).Result; Assert.AreEqual(ONE_HOUR_DURATION, descActivityTypeResponse.ActivityTypeDetail.Configuration.DefaultTaskHeartbeatTimeout); Assert.AreEqual(TWO_HOUR_DURATION, descActivityTypeResponse.ActivityTypeDetail.Configuration.DefaultTaskScheduleToCloseTimeout); Assert.AreEqual(THREE_HOUR_DURATION, descActivityTypeResponse.ActivityTypeDetail.Configuration.DefaultTaskScheduleToStartTimeout); Assert.AreEqual(FOUR_HOUR_DURATION, descActivityTypeResponse.ActivityTypeDetail.Configuration.DefaultTaskStartToCloseTimeout); ListActivityTypesResponse listActivityResponse = null; for (int i = 0; i < MaxRetries; i++) { Sleep(); // Sleep for the eventual consistency listActivityResponse = Client.ListActivityTypesAsync( new ListActivityTypesRequest() { Domain = domainName, RegistrationStatus = descActivityTypeResponse.ActivityTypeDetail.TypeInfo.Status }).Result; if (listActivityResponse.ActivityTypeInfos.TypeInfos.Count > 0) break; } Assert.IsNotNull(listActivityResponse); Assert.IsTrue(listActivityResponse.ActivityTypeInfos.TypeInfos.Count > 0); var acInfo = listActivityResponse.ActivityTypeInfos.TypeInfos.FirstOrDefault(x => x.Description == activityDescription); Assert.IsNotNull(acInfo); } finally { var depActivityRequest = new DeprecateActivityTypeRequest() { Domain = domainName, ActivityType = new ActivityType() { Name = "My Activity", Version = "1.0" } }; var depActivityTypeResponse = Client.DeprecateActivityTypeAsync(depActivityRequest).Result; } var workflowDescription = "My Workflow Description" + DateTime.Now.Ticks; var regWorkflowRequest = new RegisterWorkflowTypeRequest() { Name = "My Workflow", Domain = domainName, Description = workflowDescription, Version = "1.0", DefaultTaskList = new TaskList() { Name = "ImportantTasks" }, DefaultExecutionStartToCloseTimeout = THREE_HOUR_DURATION, DefaultTaskStartToCloseTimeout = FOUR_HOUR_DURATION }; var regWorkflowResponse = Client.RegisterWorkflowTypeAsync(regWorkflowRequest).Result; try { Sleep(); // Sleep for the eventual consistency var descWorkFlowRequest = new DescribeWorkflowTypeRequest() { Domain = domainName, WorkflowType = new WorkflowType() { Name = "My Workflow", Version = "1.0" } }; var descWorkflowResponse = Client.DescribeWorkflowTypeAsync(descWorkFlowRequest).Result; Assert.AreEqual("My Workflow", descWorkflowResponse.WorkflowTypeDetail.TypeInfo.WorkflowType.Name); Assert.AreEqual("1.0", descWorkflowResponse.WorkflowTypeDetail.TypeInfo.WorkflowType.Version); Assert.AreEqual(THREE_HOUR_DURATION, descWorkflowResponse.WorkflowTypeDetail.Configuration.DefaultExecutionStartToCloseTimeout); Assert.AreEqual(FOUR_HOUR_DURATION, descWorkflowResponse.WorkflowTypeDetail.Configuration.DefaultTaskStartToCloseTimeout); Assert.AreEqual("ImportantTasks", descWorkflowResponse.WorkflowTypeDetail.Configuration.DefaultTaskList.Name); ListWorkflowTypesResponse listWorkflowResponse = null; for (int retries = 0; retries < 5; retries++) { UtilityMethods.Sleep(TimeSpan.FromSeconds(retries)); listWorkflowResponse = Client.ListWorkflowTypesAsync( new ListWorkflowTypesRequest() { Domain = domainName, RegistrationStatus = descWorkflowResponse.WorkflowTypeDetail.TypeInfo.Status }).Result; if (listWorkflowResponse.WorkflowTypeInfos.TypeInfos.Count > 0) break; } Assert.IsTrue(listWorkflowResponse.WorkflowTypeInfos.TypeInfos.Count > 0); var wfInfo = listWorkflowResponse.WorkflowTypeInfos.TypeInfos.FirstOrDefault(x => x.Description == workflowDescription); Assert.IsNotNull(wfInfo); } finally { var depWorkflowRequest = new DeprecateWorkflowTypeRequest() { Domain = domainName, WorkflowType = new WorkflowType() { Name = "My Workflow", Version = "1.0" } }; var depWorkflowTypeResponse = Client.DeprecateWorkflowTypeAsync(depWorkflowRequest).Result; Assert.IsNotNull(depWorkflowTypeResponse.ResponseMetadata.RequestId); } } finally { var depRequest = new DeprecateDomainRequest() { Name = domainName }; var depResponse = Client.DeprecateDomainAsync(depRequest).Result; Assert.IsNotNull(depResponse.ResponseMetadata.RequestId); } } [Test] [Category("SimpleWorkflow")] public void StartAndTerminateWorkflowExecution() { string domainName = "sdk-dotnet-start-" + DateTime.Now.Ticks; var regRequest = new RegisterDomainRequest() { Name = domainName, Description = "A Description", WorkflowExecutionRetentionPeriodInDays = "4" }; Client.RegisterDomainAsync(regRequest).Wait(); try { var regWorkflowRequest = new RegisterWorkflowTypeRequest() { Name = "Start and Terminate Workflow", Domain = domainName, Description = "Another Description", Version = "1.0", DefaultExecutionStartToCloseTimeout = FIVE_HOUR_DURATION, DefaultTaskStartToCloseTimeout = FOUR_HOUR_DURATION }; var regWorkflowResponse = Client.RegisterWorkflowTypeAsync(regWorkflowRequest).Result; try { Sleep(); // Sleep for the eventual consistency var workflowId = DateTime.Now.Ticks.ToString(); var startRequest = new StartWorkflowExecutionRequest() { Domain = domainName, WorkflowId = workflowId, ChildPolicy = "TERMINATE", TaskList = new TaskList() { Name = "ImportantTasks" }, WorkflowType = new WorkflowType() { Name = regWorkflowRequest.Name, Version = regWorkflowRequest.Version } }; var startResponse = Client.StartWorkflowExecutionAsync(startRequest).Result; Assert.IsNotNull(startResponse.Run.RunId); UtilityMethods.Sleep(TimeSpan.FromSeconds(10)); var countWorkRequest = new CountOpenWorkflowExecutionsRequest() { Domain = domainName, StartTimeFilter = new ExecutionTimeFilter() { OldestDate = DateTime.Now.AddDays(-4), LatestDate = DateTime.Now.AddDays(1) }, ExecutionFilter = new WorkflowExecutionFilter() { WorkflowId = workflowId } }; var countWorkResponse = Client.CountOpenWorkflowExecutionsAsync(countWorkRequest).Result; Assert.AreEqual(1, countWorkResponse.WorkflowExecutionCount.Count); var listWorkRequest = new ListOpenWorkflowExecutionsRequest() { Domain = domainName, StartTimeFilter = new ExecutionTimeFilter() { OldestDate = DateTime.Now.AddDays(-4), LatestDate = DateTime.Now.AddDays(1) }, ExecutionFilter = new WorkflowExecutionFilter() { WorkflowId = workflowId } }; var listWorkResponse = Client.ListOpenWorkflowExecutionsAsync(listWorkRequest).Result; Assert.AreEqual(1, listWorkResponse.WorkflowExecutionInfos.ExecutionInfos.Count); var info = listWorkResponse.WorkflowExecutionInfos.ExecutionInfos[0]; Assert.AreEqual(regWorkflowRequest.Name, info.WorkflowType.Name); Assert.AreEqual(regWorkflowRequest.Version, info.WorkflowType.Version); Assert.AreEqual(startResponse.Run.RunId, info.Execution.RunId); Assert.AreEqual(startRequest.WorkflowId, info.Execution.WorkflowId); var descRequest = new DescribeWorkflowExecutionRequest() { Domain = domainName, Execution = new WorkflowExecution() { RunId = startResponse.Run.RunId, WorkflowId = startRequest.WorkflowId } }; var descResponse = Client.DescribeWorkflowExecutionAsync(descRequest).Result; Assert.IsNotNull(descResponse.WorkflowExecutionDetail); Assert.AreEqual(startRequest.TaskList.Name, descResponse.WorkflowExecutionDetail.ExecutionConfiguration.TaskList.Name); var termRequest = new TerminateWorkflowExecutionRequest() { Domain = domainName, ChildPolicy = "TERMINATE", WorkflowId = workflowId }; var termResponse = Client.TerminateWorkflowExecutionAsync(termRequest).Result; Assert.IsNotNull(termResponse.ResponseMetadata.RequestId); } finally { Client.DeprecateWorkflowTypeAsync(new DeprecateWorkflowTypeRequest() { Domain = domainName, WorkflowType = new WorkflowType() { Name = "Start and Terminate Workflow", Version = "1.0" } }).Wait(); } } finally { var depRequest = new DeprecateDomainRequest() { Name = domainName }; Client.DeprecateDomainAsync(depRequest).Wait(); } } ActivityTask pollActivity() { var pollActivityRequest = new PollForActivityTaskRequest() { Domain = DOMAIN, TaskList = TASKLIST, Identity = "testactivity" }; var pollActivityResponse = Client.PollForActivityTaskAsync(pollActivityRequest).Result; return pollActivityResponse.ActivityTask; } ActivityTask startActivity(string runId) { var pollDeciderRequest = new PollForDecisionTaskRequest() { Domain = DOMAIN, TaskList = TASKLIST, Identity = "testdecider" }; var pollDeciderResponse = Client.PollForDecisionTaskAsync(pollDeciderRequest).Result; var task = pollDeciderResponse.DecisionTask; var respondRequest = new RespondDecisionTaskCompletedRequest() { TaskToken = task.TaskToken, Decisions = new List<Decision>() { new Decision() { DecisionType = "ScheduleActivityTask", ScheduleActivityTaskDecisionAttributes = new ScheduleActivityTaskDecisionAttributes() { ActivityType = ACTIVITY_TYPE, ActivityId = DateTime.Now.Ticks.ToString(), TaskList = TASKLIST } } } }; Client.RespondDecisionTaskCompletedAsync(respondRequest).Wait(); return pollActivity(); } void Sleep() { UtilityMethods.Sleep(SleepDuration); } } }
/* * 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.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Assets; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Gather uuids for a given entity. /// </summary> /// <remarks> /// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts /// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets /// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be /// retrieved to work out which assets it references). /// </remarks> public class UuidGatherer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Is gathering complete? /// </summary> public bool Complete { get { return m_assetUuidsToInspect.Count <= 0; } } /// <summary> /// The dictionary of UUIDs gathered so far. If Complete == true then this is all the reachable UUIDs. /// </summary> /// <value>The gathered uuids.</value> public IDictionary<UUID, sbyte> GatheredUuids { get; private set; } /// <summary> /// Gets the next UUID to inspect. /// </summary> /// <value>If there is no next UUID then returns null</value> public UUID? NextUuidToInspect { get { if (Complete) return null; else return m_assetUuidsToInspect.Peek(); } } protected IAssetService m_assetService; protected Queue<UUID> m_assetUuidsToInspect; /// <summary> /// Initializes a new instance of the <see cref="OpenSim.Region.Framework.Scenes.UuidGatherer"/> class. /// </summary> /// <remarks>In this case the collection of gathered assets will start out blank.</remarks> /// <param name="assetService"> /// Asset service. /// </param> public UuidGatherer(IAssetService assetService) : this(assetService, new Dictionary<UUID, sbyte>()) {} /// <summary> /// Initializes a new instance of the <see cref="OpenSim.Region.Framework.Scenes.UuidGatherer"/> class. /// </summary> /// <param name="assetService"> /// Asset service. /// </param> /// <param name="collector"> /// Gathered UUIDs will be collected in this dictinaory. /// It can be pre-populated if you want to stop the gatherer from analyzing assets that have already been fetched and inspected. /// </param> public UuidGatherer(IAssetService assetService, IDictionary<UUID, sbyte> collector) { m_assetService = assetService; GatheredUuids = collector; // FIXME: Not efficient for searching, can improve. m_assetUuidsToInspect = new Queue<UUID>(); } /// <summary> /// Adds the asset uuid for inspection during the gathering process. /// </summary> /// <returns><c>true</c>, if for inspection was added, <c>false</c> otherwise.</returns> /// <param name="uuid">UUID.</param> public bool AddForInspection(UUID uuid) { if (m_assetUuidsToInspect.Contains(uuid)) return false; // m_log.DebugFormat("[UUID GATHERER]: Adding asset {0} for inspection", uuid); m_assetUuidsToInspect.Enqueue(uuid); return true; } /// <summary> /// Gather all the asset uuids associated with a given object. /// </summary> /// <remarks> /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// </remarks> /// <param name="sceneObject">The scene object for which to gather assets</param> public void AddForInspection(SceneObjectGroup sceneObject) { // m_log.DebugFormat( // "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID); SceneObjectPart[] parts = sceneObject.Parts; for (int i = 0; i < parts.Length; i++) { SceneObjectPart part = parts[i]; // m_log.DebugFormat( // "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID); try { Primitive.TextureEntry textureEntry = part.Shape.Textures; if (textureEntry != null) { // Get the prim's default texture. This will be used for faces which don't have their own texture if (textureEntry.DefaultTexture != null) RecordTextureEntryAssetUuids(textureEntry.DefaultTexture); if (textureEntry.FaceTextures != null) { // Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture) foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures) { if (texture != null) RecordTextureEntryAssetUuids(texture); } } } // If the prim is a sculpt then preserve this information too if (part.Shape.SculptTexture != UUID.Zero) GatheredUuids[part.Shape.SculptTexture] = (sbyte)AssetType.Texture; if (part.Shape.ProjectionTextureUUID != UUID.Zero) GatheredUuids[part.Shape.ProjectionTextureUUID] = (sbyte)AssetType.Texture; UUID collisionSound = part.CollisionSound; if ( collisionSound != UUID.Zero && collisionSound != part.invalidCollisionSoundUUID) GatheredUuids[collisionSound] = (sbyte)AssetType.Sound; if (part.ParticleSystem.Length > 0) { try { Primitive.ParticleSystem ps = new Primitive.ParticleSystem(part.ParticleSystem, 0); if (ps.Texture != UUID.Zero) GatheredUuids[ps.Texture] = (sbyte)AssetType.Texture; } catch (Exception) { m_log.WarnFormat( "[UUID GATHERER]: Could not check particle system for part {0} {1} in object {2} {3} since it is corrupt. Continuing.", part.Name, part.UUID, sceneObject.Name, sceneObject.UUID); } } TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone(); // Now analyze this prim's inventory items to preserve all the uuids that they reference foreach (TaskInventoryItem tii in taskDictionary.Values) { // m_log.DebugFormat( // "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}", // tii.Name, tii.Type, part.Name, part.UUID); if (!GatheredUuids.ContainsKey(tii.AssetID)) AddForInspection(tii.AssetID, (sbyte)tii.Type); } // FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed // to be called with scene objects that are in a scene (e.g. in the case of hg asset mapping and // inventory transfer. There needs to be a way for a module to register a method without assuming a // Scene.EventManager is present. // part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids); // still needed to retrieve textures used as materials for any parts containing legacy materials stored in DynAttrs RecordMaterialsUuids(part); } catch (Exception e) { m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e); m_log.DebugFormat( "[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)", part.Shape.TextureEntry.Length); } } } /// <summary> /// Gathers the next set of assets returned by the next uuid to get from the asset service. /// </summary> /// <returns>false if gathering is already complete, true otherwise</returns> public bool GatherNext() { if (Complete) return false; UUID nextToInspect = m_assetUuidsToInspect.Dequeue(); // m_log.DebugFormat("[UUID GATHERER]: Inspecting asset {0}", nextToInspect); GetAssetUuids(nextToInspect); return true; } /// <summary> /// Gathers all remaining asset UUIDS no matter how many calls are required to the asset service. /// </summary> /// <returns>false if gathering is already complete, true otherwise</returns> public bool GatherAll() { if (Complete) return false; while (GatherNext()); return true; } /// <summary> /// Gather all the asset uuids associated with the asset referenced by a given uuid /// </summary> /// <remarks> /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// This method assumes that the asset type associated with this asset in persistent storage is correct (which /// should always be the case). So with this method we always need to retrieve asset data even if the asset /// is of a type which is known not to reference any other assets /// </remarks> /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param> private void GetAssetUuids(UUID assetUuid) { // avoid infinite loops if (GatheredUuids.ContainsKey(assetUuid)) return; try { AssetBase assetBase = GetAsset(assetUuid); if (null != assetBase) { sbyte assetType = assetBase.Type; GatheredUuids[assetUuid] = assetType; if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType) { RecordWearableAssetUuids(assetBase); } else if ((sbyte)AssetType.Gesture == assetType) { RecordGestureAssetUuids(assetBase); } else if ((sbyte)AssetType.Notecard == assetType) { RecordTextEmbeddedAssetUuids(assetBase); } else if ((sbyte)AssetType.LSLText == assetType) { RecordTextEmbeddedAssetUuids(assetBase); } else if ((sbyte)OpenSimAssetType.Material == assetType) { RecordMaterialAssetUuids(assetBase); } else if ((sbyte)AssetType.Object == assetType) { RecordSceneObjectAssetUuids(assetBase); } } } catch (Exception) { m_log.ErrorFormat("[UUID GATHERER]: Failed to gather uuids for asset id {0}", assetUuid); throw; } } private void AddForInspection(UUID assetUuid, sbyte assetType) { // Here, we want to collect uuids which require further asset fetches but mark the others as gathered try { if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType || (sbyte)AssetType.Gesture == assetType || (sbyte)AssetType.Notecard == assetType || (sbyte)AssetType.LSLText == assetType || (sbyte)OpenSimAssetType.Material == assetType || (sbyte)AssetType.Object == assetType) { AddForInspection(assetUuid); } else { GatheredUuids[assetUuid] = assetType; } } catch (Exception) { m_log.ErrorFormat( "[UUID GATHERER]: Failed to gather uuids for asset id {0}, type {1}", assetUuid, assetType); throw; } } /// <summary> /// Collect all the asset uuids found in one face of a Texture Entry. /// </summary> private void RecordTextureEntryAssetUuids(Primitive.TextureEntryFace texture) { GatheredUuids[texture.TextureID] = (sbyte)AssetType.Texture; if (texture.MaterialID != UUID.Zero) AddForInspection(texture.MaterialID); } /// <summary> /// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps /// stored in legacy format in part.DynAttrs /// </summary> /// <param name="part"></param> private void RecordMaterialsUuids(SceneObjectPart part) { // scan thru the dynAttrs map of this part for any textures used as materials OSD osdMaterials = null; lock (part.DynAttrs) { if (part.DynAttrs.ContainsStore("OpenSim", "Materials")) { OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials"); if (materialsStore == null) return; materialsStore.TryGetValue("Materials", out osdMaterials); } if (osdMaterials != null) { //m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd)); if (osdMaterials is OSDArray) { OSDArray matsArr = osdMaterials as OSDArray; foreach (OSDMap matMap in matsArr) { try { if (matMap.ContainsKey("Material")) { OSDMap mat = matMap["Material"] as OSDMap; if (mat.ContainsKey("NormMap")) { UUID normalMapId = mat["NormMap"].AsUUID(); if (normalMapId != UUID.Zero) { GatheredUuids[normalMapId] = (sbyte)AssetType.Texture; //m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString()); } } if (mat.ContainsKey("SpecMap")) { UUID specularMapId = mat["SpecMap"].AsUUID(); if (specularMapId != UUID.Zero) { GatheredUuids[specularMapId] = (sbyte)AssetType.Texture; //m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString()); } } } } catch (Exception e) { m_log.Warn("[UUID Gatherer]: exception getting materials: " + e.Message); } } } } } } /// <summary> /// Get an asset synchronously, potentially using an asynchronous callback. If the /// asynchronous callback is used, we will wait for it to complete. /// </summary> /// <param name="uuid"></param> /// <returns></returns> protected virtual AssetBase GetAsset(UUID uuid) { return m_assetService.Get(uuid.ToString()); } /// <summary> /// Record the asset uuids embedded within the given text (e.g. a script). /// </summary> /// <param name="textAsset"></param> private void RecordTextEmbeddedAssetUuids(AssetBase textAsset) { // m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId); string text = Utils.BytesToString(textAsset.Data); // m_log.DebugFormat("[UUID GATHERER]: Text {0}", text); MatchCollection uuidMatches = Util.PermissiveUUIDPattern.Matches(text); // m_log.DebugFormat("[UUID GATHERER]: Found {0} matches in text", uuidMatches.Count); foreach (Match uuidMatch in uuidMatches) { UUID uuid = new UUID(uuidMatch.Value); // m_log.DebugFormat("[UUID GATHERER]: Recording {0} in text", uuid); AddForInspection(uuid); } } /// <summary> /// Record the uuids referenced by the given wearable asset /// </summary> /// <param name="assetBase"></param> private void RecordWearableAssetUuids(AssetBase assetBase) { //m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data)); AssetWearable wearableAsset = new AssetBodypart(assetBase.FullID, assetBase.Data); wearableAsset.Decode(); //m_log.DebugFormat( // "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count); foreach (UUID uuid in wearableAsset.Textures.Values) GatheredUuids[uuid] = (sbyte)AssetType.Texture; } /// <summary> /// Get all the asset uuids associated with a given object. This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// </summary> /// <param name="sceneObjectAsset"></param> private void RecordSceneObjectAssetUuids(AssetBase sceneObjectAsset) { string xml = Utils.BytesToString(sceneObjectAsset.Data); CoalescedSceneObjects coa; if (CoalescedSceneObjectsSerializer.TryFromXml(xml, out coa)) { foreach (SceneObjectGroup sog in coa.Objects) AddForInspection(sog); } else { SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml); if (null != sog) AddForInspection(sog); } } /// <summary> /// Get the asset uuid associated with a gesture /// </summary> /// <param name="gestureAsset"></param> private void RecordGestureAssetUuids(AssetBase gestureAsset) { using (MemoryStream ms = new MemoryStream(gestureAsset.Data)) using (StreamReader sr = new StreamReader(ms)) { sr.ReadLine(); // Unknown (Version?) sr.ReadLine(); // Unknown sr.ReadLine(); // Unknown sr.ReadLine(); // Name sr.ReadLine(); // Comment ? int count = Convert.ToInt32(sr.ReadLine()); // Item count for (int i = 0 ; i < count ; i++) { string type = sr.ReadLine(); if (type == null) break; string name = sr.ReadLine(); if (name == null) break; string id = sr.ReadLine(); if (id == null) break; string unknown = sr.ReadLine(); if (unknown == null) break; // If it can be parsed as a UUID, it is an asset ID UUID uuid; if (UUID.TryParse(id, out uuid)) GatheredUuids[uuid] = (sbyte)AssetType.Animation; // the asset is either an Animation or a Sound, but this distinction isn't important } } } /// <summary> /// Get the asset uuid's referenced in a material. /// </summary> private void RecordMaterialAssetUuids(AssetBase materialAsset) { OSDMap mat = (OSDMap)OSDParser.DeserializeLLSDXml(materialAsset.Data); UUID normMap = mat["NormMap"].AsUUID(); if (normMap != UUID.Zero) GatheredUuids[normMap] = (sbyte)AssetType.Texture; UUID specMap = mat["SpecMap"].AsUUID(); if (specMap != UUID.Zero) GatheredUuids[specMap] = (sbyte)AssetType.Texture; } } public class HGUuidGatherer : UuidGatherer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_assetServerURL; public HGUuidGatherer(IAssetService assetService, string assetServerURL) : this(assetService, assetServerURL, new Dictionary<UUID, sbyte>()) {} public HGUuidGatherer(IAssetService assetService, string assetServerURL, IDictionary<UUID, sbyte> collector) : base(assetService, collector) { m_assetServerURL = assetServerURL; if (!m_assetServerURL.EndsWith("/") && !m_assetServerURL.EndsWith("=")) m_assetServerURL = m_assetServerURL + "/"; } protected override AssetBase GetAsset(UUID uuid) { if (string.Empty == m_assetServerURL) return base.GetAsset(uuid); else return FetchAsset(uuid); } public AssetBase FetchAsset(UUID assetID) { // Test if it's already here AssetBase asset = m_assetService.Get(assetID.ToString()); if (asset == null) { // It's not, so fetch it from abroad asset = m_assetService.Get(m_assetServerURL + assetID.ToString()); if (asset != null) m_log.DebugFormat("[HGUUIDGatherer]: Copied asset {0} from {1} to local asset server", assetID, m_assetServerURL); else m_log.DebugFormat("[HGUUIDGatherer]: Failed to fetch asset {0} from {1}", assetID, m_assetServerURL); } //else // m_log.DebugFormat("[HGUUIDGatherer]: Asset {0} from {1} was already here", assetID, m_assetServerURL); return asset; } } }
// 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.Globalization; using System.Text; using Microsoft.CSharp.RuntimeBinder.Semantics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Errors { internal sealed class UserStringBuilder { private bool fHadUndisplayableStringInError; private bool m_buildingInProgress; private GlobalSymbolContext m_globalSymbols; private StringBuilder m_strBuilder; public UserStringBuilder( GlobalSymbolContext globalSymbols) { Debug.Assert(globalSymbols != null); fHadUndisplayableStringInError = false; m_buildingInProgress = false; m_globalSymbols = globalSymbols; } private void BeginString() { Debug.Assert(!m_buildingInProgress); m_buildingInProgress = true; m_strBuilder = new StringBuilder(); } private void EndString(out string s) { Debug.Assert(m_buildingInProgress); m_buildingInProgress = false; s = m_strBuilder.ToString(); m_strBuilder = null; } public bool HadUndisplayableString() { return fHadUndisplayableStringInError; } public void ResetUndisplayableStringFlag() { fHadUndisplayableStringInError = false; } private void ErrSK(out string psz, SYMKIND sk) { MessageID id; switch (sk) { case SYMKIND.SK_MethodSymbol: id = MessageID.SK_METHOD; break; case SYMKIND.SK_AggregateSymbol: id = MessageID.SK_CLASS; break; case SYMKIND.SK_NamespaceSymbol: id = MessageID.SK_NAMESPACE; break; case SYMKIND.SK_FieldSymbol: id = MessageID.SK_FIELD; break; case SYMKIND.SK_LocalVariableSymbol: id = MessageID.SK_VARIABLE; break; case SYMKIND.SK_PropertySymbol: id = MessageID.SK_PROPERTY; break; case SYMKIND.SK_EventSymbol: id = MessageID.SK_EVENT; break; case SYMKIND.SK_TypeParameterSymbol: id = MessageID.SK_TYVAR; break; case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol: Debug.Assert(false, "Illegal sk"); id = MessageID.SK_ALIAS; break; default: Debug.Assert(false, "impossible sk"); id = MessageID.SK_UNKNOWN; break; } ErrId(out psz, id); } /* * Create a fill-in string describing a parameter list. * Does NOT include () */ private void ErrAppendParamList(TypeArray @params, bool isVarargs, bool isParamArray) { if (null == @params) return; for (int i = 0; i < @params.size; i++) { if (i > 0) { ErrAppendString(", "); } if (isParamArray && i == @params.size - 1) { ErrAppendString("params "); } // parameter type name ErrAppendType(@params.Item(i), null); } if (isVarargs) { if (@params.size != 0) { ErrAppendString(", "); } ErrAppendString("..."); } } private void ErrAppendString(string str) { m_strBuilder.Append(str); } private void ErrAppendChar(char ch) { m_strBuilder.Append(ch); } private void ErrAppendPrintf(string format, params object[] args) { ErrAppendString(String.Format(CultureInfo.InvariantCulture, format, args)); } private void ErrAppendName(Name name) { CheckDisplayableName(name); if (name == GetNameManager().GetPredefName(PredefinedName.PN_INDEXERINTERNAL)) { ErrAppendString("this"); } else { ErrAppendString(name.Text); } } private void ErrAppendMethodParentSym(MethodSymbol sym, SubstContext pcxt, out TypeArray substMethTyParams) { substMethTyParams = null; ErrAppendParentSym(sym, pcxt); } private void ErrAppendParentSym(Symbol sym, SubstContext pctx) { ErrAppendParentCore(sym.parent, pctx); } private void ErrAppendParentType(CType pType, SubstContext pctx) { if (pType.IsErrorType()) { if (pType.AsErrorType().HasTypeParent()) { ErrAppendType(pType.AsErrorType().GetTypeParent(), null); ErrAppendChar('.'); } else { ErrAppendParentCore(pType.AsErrorType().GetNSParent(), pctx); } } else if (pType.IsAggregateType()) { ErrAppendParentCore(pType.AsAggregateType().GetOwningAggregate(), pctx); } else if (pType.GetBaseOrParameterOrElementType() != null) { ErrAppendType(pType.GetBaseOrParameterOrElementType(), null); ErrAppendChar('.'); } } private void ErrAppendParentCore(Symbol parent, SubstContext pctx) { if (null == parent) return; if (parent == getBSymmgr().GetRootNS()) return; if (pctx != null && !pctx.FNop() && parent.IsAggregateSymbol() && 0 != parent.AsAggregateSymbol().GetTypeVarsAll().size) { CType pType = GetTypeManager().SubstType(parent.AsAggregateSymbol().getThisType(), pctx); ErrAppendType(pType, null); } else { ErrAppendSym(parent, null); } ErrAppendChar('.'); } private void ErrAppendTypeParameters(TypeArray @params, SubstContext pctx, bool forClass) { if (@params != null && @params.size != 0) { ErrAppendChar('<'); ErrAppendType(@params.Item(0), pctx); for (int i = 1; i < @params.size; i++) { ErrAppendString(","); ErrAppendType(@params.Item(i), pctx); } ErrAppendChar('>'); } } private void ErrAppendMethod(MethodSymbol meth, SubstContext pctx, bool fArgs) { if (meth.IsExpImpl() && meth.swtSlot) { ErrAppendParentSym(meth, pctx); // Get the type args from the explicit impl type and substitute using pctx (if there is one). SubstContext ctx = new SubstContext(GetTypeManager().SubstType(meth.swtSlot.GetType(), pctx).AsAggregateType()); ErrAppendSym(meth.swtSlot.Sym, ctx, fArgs); // args already added return; } if (meth.isPropertyAccessor()) { PropertySymbol prop = meth.getProperty(); // this includes the parent class ErrAppendSym(prop, pctx); // add accessor name if (prop.methGet == meth) { ErrAppendString(".get"); } else { Debug.Assert(meth == prop.methSet); ErrAppendString(".set"); } // args already added return; } if (meth.isEventAccessor()) { EventSymbol @event = meth.getEvent(); // this includes the parent class ErrAppendSym(@event, pctx); // add accessor name if (@event.methAdd == meth) { ErrAppendString(".add"); } else { Debug.Assert(meth == @event.methRemove); ErrAppendString(".remove"); } // args already added return; } TypeArray replacementTypeArray = null; ErrAppendMethodParentSym(meth, pctx, out replacementTypeArray); if (meth.IsConstructor()) { // Use the name of the parent class instead of the name "<ctor>". ErrAppendName(meth.getClass().name); } else if (meth.IsDestructor()) { // Use the name of the parent class instead of the name "Finalize". ErrAppendChar('~'); ErrAppendName(meth.getClass().name); } else if (meth.isConversionOperator()) { // implicit/explicit ErrAppendString(meth.isImplicit() ? "implicit" : "explicit"); ErrAppendString(" operator "); // destination type name ErrAppendType(meth.RetType, pctx); } else if (meth.isOperator) { // handle user defined operators // map from CLS predefined names to "operator <X>" ErrAppendString("operator "); // // This is kinda slow, but the alternative is to add bits to methsym. // string operatorName; OperatorKind op = Operators.OperatorOfMethodName(GetNameManager(), meth.name); if (Operators.HasDisplayName(op)) { operatorName = Operators.GetDisplayName(op); } else { // // either equals or compare // if (meth.name == GetNameManager().GetPredefName(PredefinedName.PN_OPEQUALS)) { operatorName = "equals"; } else { Debug.Assert(meth.name == GetNameManager().GetPredefName(PredefinedName.PN_OPCOMPARE)); operatorName = "compare"; } } ErrAppendString(operatorName); } else if (meth.IsExpImpl()) { if (meth.errExpImpl != null) ErrAppendType(meth.errExpImpl, pctx, fArgs); } else { // regular method ErrAppendName(meth.name); } if (null == replacementTypeArray) { ErrAppendTypeParameters(meth.typeVars, pctx, false); } if (fArgs) { // append argument types ErrAppendChar('('); if (!meth.computeCurrentBogusState()) { ErrAppendParamList(GetTypeManager().SubstTypeArray(meth.Params, pctx), meth.isVarargs, meth.isParamArray); } ErrAppendChar(')'); } } private void ErrAppendIndexer(IndexerSymbol indexer, SubstContext pctx) { ErrAppendString("this["); ErrAppendParamList(GetTypeManager().SubstTypeArray(indexer.Params, pctx), false, indexer.isParamArray); ErrAppendChar(']'); } private void ErrAppendProperty(PropertySymbol prop, SubstContext pctx) { ErrAppendParentSym(prop, pctx); if (prop.IsExpImpl() && prop.swtSlot.Sym != null) { SubstContext ctx = new SubstContext(GetTypeManager().SubstType(prop.swtSlot.GetType(), pctx).AsAggregateType()); ErrAppendSym(prop.swtSlot.Sym, ctx); } else if (prop.IsExpImpl()) { if (prop.errExpImpl != null) ErrAppendType(prop.errExpImpl, pctx, false); if (prop.isIndexer()) { ErrAppendChar('.'); ErrAppendIndexer(prop.AsIndexerSymbol(), pctx); } } else if (prop.isIndexer()) { ErrAppendIndexer(prop.AsIndexerSymbol(), pctx); } else { ErrAppendName(prop.name); } } private void ErrAppendEvent(EventSymbol @event, SubstContext pctx) { } private void ErrAppendId(MessageID id) { string str; ErrId(out str, id); ErrAppendString(str); } /* * Create a fill-in string describing a symbol. */ private void ErrAppendSym(Symbol sym, SubstContext pctx) { ErrAppendSym(sym, pctx, true); } private void ErrAppendSym(Symbol sym, SubstContext pctx, bool fArgs) { switch (sym.getKind()) { case SYMKIND.SK_NamespaceDeclaration: // for namespace declarations just convert the namespace ErrAppendSym(sym.AsNamespaceDeclaration().NameSpace(), null); break; case SYMKIND.SK_GlobalAttributeDeclaration: ErrAppendName(sym.name); break; case SYMKIND.SK_AggregateDeclaration: ErrAppendSym(sym.AsAggregateDeclaration().Agg(), pctx); break; case SYMKIND.SK_AggregateSymbol: { // Check for a predefined class with a special "nice" name for // error reported. string text = PredefinedTypes.GetNiceName(sym.AsAggregateSymbol()); if (text != null) { // Found a nice name. ErrAppendString(text); } else if (sym.AsAggregateSymbol().IsAnonymousType()) { ErrAppendId(MessageID.AnonymousType); break; } else { ErrAppendParentSym(sym, pctx); ErrAppendName(sym.name); ErrAppendTypeParameters(sym.AsAggregateSymbol().GetTypeVars(), pctx, true); } break; } case SYMKIND.SK_MethodSymbol: ErrAppendMethod(sym.AsMethodSymbol(), pctx, fArgs); break; case SYMKIND.SK_PropertySymbol: ErrAppendProperty(sym.AsPropertySymbol(), pctx); break; case SYMKIND.SK_EventSymbol: ErrAppendEvent(sym.AsEventSymbol(), pctx); break; case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol: case SYMKIND.SK_NamespaceSymbol: if (sym == getBSymmgr().GetRootNS()) { ErrAppendId(MessageID.GlobalNamespace); } else { ErrAppendParentSym(sym, null); ErrAppendName(sym.name); } break; case SYMKIND.SK_FieldSymbol: ErrAppendParentSym(sym, pctx); ErrAppendName(sym.name); break; case SYMKIND.SK_TypeParameterSymbol: if (null == sym.name) { // It's a standard type variable. if (sym.AsTypeParameterSymbol().IsMethodTypeParameter()) ErrAppendChar('!'); ErrAppendChar('!'); ErrAppendPrintf("{0}", sym.AsTypeParameterSymbol().GetIndexInTotalParameters()); } else ErrAppendName(sym.name); break; case SYMKIND.SK_LocalVariableSymbol: case SYMKIND.SK_LabelSymbol: case SYMKIND.SK_TransparentIdentifierMemberSymbol: // Generate symbol name. ErrAppendName(sym.name); break; case SYMKIND.SK_Scope: case SYMKIND.SK_LambdaScope: default: // Shouldn't happen. Debug.Assert(false, "Bad symbol kind"); break; } } private void ErrAppendType(CType pType, SubstContext pCtx) { ErrAppendType(pType, pCtx, true); } private void ErrAppendType(CType pType, SubstContext pctx, bool fArgs) { if (pctx != null) { if (!pctx.FNop()) { pType = GetTypeManager().SubstType(pType, pctx); } // We shouldn't use the SubstContext again so set it to NULL. pctx = null; } switch (pType.GetTypeKind()) { case TypeKind.TK_AggregateType: { AggregateType pAggType = pType.AsAggregateType(); // Check for a predefined class with a special "nice" name for // error reported. string text = PredefinedTypes.GetNiceName(pAggType.getAggregate()); if (text != null) { // Found a nice name. ErrAppendString(text); } else if (pAggType.getAggregate().IsAnonymousType()) { ErrAppendPrintf("AnonymousType#{0}", GetTypeID(pAggType)); break; } else { if (pAggType.outerType != null) { ErrAppendType(pAggType.outerType, pctx); ErrAppendChar('.'); } else { // In a namespace. ErrAppendParentSym(pAggType.getAggregate(), pctx); } ErrAppendName(pAggType.getAggregate().name); } ErrAppendTypeParameters(pAggType.GetTypeArgsThis(), pctx, true); break; } case TypeKind.TK_TypeParameterType: if (null == pType.GetName()) { // It's a standard type variable. if (pType.AsTypeParameterType().IsMethodTypeParameter()) { ErrAppendChar('!'); } ErrAppendChar('!'); ErrAppendPrintf("{0}", pType.AsTypeParameterType().GetIndexInTotalParameters()); } else { ErrAppendName(pType.GetName()); } break; case TypeKind.TK_ErrorType: if (pType.AsErrorType().HasParent()) { Debug.Assert(pType.AsErrorType().nameText != null && pType.AsErrorType().typeArgs != null); ErrAppendParentType(pType, pctx); ErrAppendName(pType.AsErrorType().nameText); ErrAppendTypeParameters(pType.AsErrorType().typeArgs, pctx, true); } else { // Load the string "<error>". Debug.Assert(null == pType.AsErrorType().typeArgs); ErrAppendId(MessageID.ERRORSYM); } break; case TypeKind.TK_NullType: // Load the string "<null>". ErrAppendId(MessageID.NULL); break; case TypeKind.TK_OpenTypePlaceholderType: // Leave blank. break; case TypeKind.TK_BoundLambdaType: ErrAppendId(MessageID.AnonMethod); break; case TypeKind.TK_UnboundLambdaType: ErrAppendId(MessageID.Lambda); break; case TypeKind.TK_MethodGroupType: ErrAppendId(MessageID.MethodGroup); break; case TypeKind.TK_ArgumentListType: ErrAppendString(TokenFacts.GetText(TokenKind.ArgList)); break; case TypeKind.TK_ArrayType: { CType elementType = pType.AsArrayType().GetBaseElementType(); if (null == elementType) { Debug.Assert(false, "No element type"); break; } ErrAppendType(elementType, pctx); for (elementType = pType; elementType != null && elementType.IsArrayType(); elementType = elementType.AsArrayType().GetElementType()) { int rank = elementType.AsArrayType().rank; // Add [] with (rank-1) commas inside ErrAppendChar('['); #if ! CSEE // known rank. if (rank > 1) { ErrAppendChar('*'); } #endif for (int i = rank; i > 1; --i) { ErrAppendChar(','); #if ! CSEE ErrAppendChar('*'); #endif } ErrAppendChar(']'); } break; } case TypeKind.TK_VoidType: ErrAppendName(GetNameManager().Lookup(TokenFacts.GetText(TokenKind.Void))); break; case TypeKind.TK_ParameterModifierType: // add ref or out ErrAppendString(pType.AsParameterModifierType().isOut ? "out " : "ref "); // add base type name ErrAppendType(pType.AsParameterModifierType().GetParameterType(), pctx); break; case TypeKind.TK_PointerType: // Generate the base type. ErrAppendType(pType.AsPointerType().GetReferentType(), pctx); { // add the trailing * ErrAppendChar('*'); } break; case TypeKind.TK_NullableType: ErrAppendType(pType.AsNullableType().GetUnderlyingType(), pctx); ErrAppendChar('?'); break; case TypeKind.TK_NaturalIntegerType: default: // Shouldn't happen. Debug.Assert(false, "Bad type kind"); break; } } // Returns true if the argument could be converted to a string. public bool ErrArgToString(out string psz, ErrArg parg, out bool fUserStrings) { fUserStrings = false; psz = null; bool result = true; switch (parg.eak) { case ErrArgKind.Ids: ErrId(out psz, parg.ids); break; case ErrArgKind.SymKind: ErrSK(out psz, parg.sk); break; case ErrArgKind.Type: BeginString(); ErrAppendType(parg.pType, null); EndString(out psz); fUserStrings = true; break; case ErrArgKind.Sym: BeginString(); ErrAppendSym(parg.sym, null); EndString(out psz); fUserStrings = true; break; case ErrArgKind.Name: if (parg.name == GetNameManager().GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL)) { psz = "this"; } else { psz = parg.name.Text; } break; case ErrArgKind.Str: psz = parg.psz; break; case ErrArgKind.PredefName: BeginString(); ErrAppendName(GetNameManager().GetPredefName(parg.pdn)); EndString(out psz); break; case ErrArgKind.SymWithType: { SubstContext ctx = new SubstContext(parg.swtMemo.ats, null); BeginString(); ErrAppendSym(parg.swtMemo.sym, ctx, true); EndString(out psz); fUserStrings = true; break; } case ErrArgKind.MethWithInst: { SubstContext ctx = new SubstContext(parg.mpwiMemo.ats, parg.mpwiMemo.typeArgs); BeginString(); ErrAppendSym(parg.mpwiMemo.sym, ctx, true); EndString(out psz); fUserStrings = true; break; } default: result = false; break; } return result; } private bool IsDisplayableName(Name name) { return name != GetNameManager().GetPredefName(PredefinedName.PN_MISSING); } private void CheckDisplayableName(Name name) { if (!IsDisplayableName(name)) { fHadUndisplayableStringInError = true; } } private NameManager GetNameManager() { return m_globalSymbols.GetNameManager(); } private TypeManager GetTypeManager() { return m_globalSymbols.GetTypes(); } private BSYMMGR getBSymmgr() { return m_globalSymbols.GetGlobalSymbols(); } private int GetTypeID(CType type) { return 0; } private void ErrId(out string s, MessageID id) { s = ErrorFacts.GetMessage(id); } } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEngine.Audio; using System.Collections; /// GVR audio source component that enhances AudioSource to provide advanced spatial audio features. [AddComponentMenu("GoogleVR/Audio/GvrAudioSource")] public class GvrAudioSource : MonoBehaviour { /// Denotes whether the room effects should be bypassed. public bool bypassRoomEffects = false; /// Directivity pattern shaping factor. public float directivityAlpha = 0.0f; /// Directivity pattern order. public float directivitySharpness = 1.0f; /// Listener directivity pattern shaping factor. public float listenerDirectivityAlpha = 0.0f; /// Listener directivity pattern order. public float listenerDirectivitySharpness = 1.0f; /// Input gain in decibels. public float gainDb = 0.0f; /// Occlusion effect toggle. public bool occlusionEnabled = false; /// Play source on awake. public bool playOnAwake = true; /// Disable the gameobject when sound isn't playing. public bool disableOnStop = false; /// The default AudioClip to play. public AudioClip clip { get { return sourceClip; } set { sourceClip = value; if (audioSource != null) { audioSource.clip = sourceClip; } } } [SerializeField] private AudioClip sourceClip = null; /// Is the clip playing right now (Read Only)? public bool isPlaying { get { if (audioSource != null) { return audioSource.isPlaying; } return false; } } /// Is the audio clip looping? public bool loop { get { return sourceLoop; } set { sourceLoop = value; if (audioSource != null) { audioSource.loop = sourceLoop; } } } [SerializeField] private bool sourceLoop = false; /// Un- / Mutes the source. Mute sets the volume=0, Un-Mute restore the original volume. public bool mute { get { return sourceMute; } set { sourceMute = value; if (audioSource != null) { audioSource.mute = sourceMute; } } } [SerializeField] private bool sourceMute = false; /// The pitch of the audio source. public float pitch { get { return sourcePitch; } set { sourcePitch = value; if (audioSource != null) { audioSource.pitch = sourcePitch; } } } [SerializeField] [Range(-3.0f, 3.0f)] private float sourcePitch = 1.0f; /// Sets the priority of the audio source. public int priority { get { return sourcePriority; } set { sourcePriority = value; if(audioSource != null) { audioSource.priority = sourcePriority; } } } [SerializeField] [Range(0, 256)] private int sourcePriority = 128; /// Sets how much this source is affected by 3D spatialization calculations (attenuation, doppler). public float spatialBlend { get { return sourceSpatialBlend; } set { sourceSpatialBlend = value; if (audioSource != null) { audioSource.spatialBlend = sourceSpatialBlend; } } } [SerializeField] [Range(0.0f, 1.0f)] private float sourceSpatialBlend = 1.0f; /// Sets the Doppler scale for this audio source. public float dopplerLevel { get { return sourceDopplerLevel; } set { sourceDopplerLevel = value; if(audioSource != null) { audioSource.dopplerLevel = sourceDopplerLevel; } } } [SerializeField] [Range(0.0f, 5.0f)] private float sourceDopplerLevel = 1.0f; /// Sets the spread angle (in degrees) in 3D space. public float spread { get { return sourceSpread; } set { sourceSpread = value; if(audioSource != null) { audioSource.spread = sourceSpread; } } } [SerializeField] [Range(0.0f, 360.0f)] private float sourceSpread = 0.0f; /// Playback position in seconds. public float time { get { if(audioSource != null) { return audioSource.time; } return 0.0f; } set { if(audioSource != null) { audioSource.time = value; } } } /// Playback position in PCM samples. public int timeSamples { get { if(audioSource != null) { return audioSource.timeSamples; } return 0; } set { if(audioSource != null) { audioSource.timeSamples = value; } } } /// The volume of the audio source (0.0 to 1.0). public float volume { get { return sourceVolume; } set { sourceVolume = value; if (audioSource != null) { audioSource.volume = sourceVolume; } } } [SerializeField] [Range(0.0f, 1.0f)] private float sourceVolume = 1.0f; /// Volume rolloff model with respect to the distance. public AudioRolloffMode rolloffMode { get { return sourceRolloffMode; } set { sourceRolloffMode = value; if (audioSource != null) { audioSource.rolloffMode = sourceRolloffMode; if (rolloffMode == AudioRolloffMode.Custom) { // Custom rolloff is not supported, set the curve for no distance attenuation. audioSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, AnimationCurve.Linear(sourceMinDistance, 1.0f, sourceMaxDistance, 1.0f)); } } } } [SerializeField] private AudioRolloffMode sourceRolloffMode = AudioRolloffMode.Logarithmic; /// MaxDistance is the distance a sound stops attenuating at. public float maxDistance { get { return sourceMaxDistance; } set { sourceMaxDistance = Mathf.Clamp(value, sourceMinDistance + GvrAudio.distanceEpsilon, GvrAudio.maxDistanceLimit); if(audioSource != null) { audioSource.maxDistance = sourceMaxDistance; } } } [SerializeField] private float sourceMaxDistance = 500.0f; /// Within the Min distance the GvrAudioSource will cease to grow louder in volume. public float minDistance { get { return sourceMinDistance; } set { sourceMinDistance = Mathf.Clamp(value, 0.0f, GvrAudio.minDistanceLimit); if(audioSource != null) { audioSource.minDistance = sourceMinDistance; } } } [SerializeField] private float sourceMinDistance = 1.0f; /// Binaural (HRTF) rendering toggle. [SerializeField] private bool hrtfEnabled = true; // Unity audio source attached to the game object. [SerializeField] private AudioSource audioSource = null; // Unique source id. private int id = -1; // Current occlusion value; private float currentOcclusion = 0.0f; // Next occlusion update time in seconds. private float nextOcclusionUpdate = 0.0f; // Denotes whether the source is currently paused or not. private bool isPaused = false; void Awake () { if (audioSource == null) { // Ensure the audio source gets created once. audioSource = gameObject.AddComponent<AudioSource>(); } audioSource.enabled = false; audioSource.hideFlags = HideFlags.HideInInspector | HideFlags.HideAndDontSave; audioSource.playOnAwake = false; audioSource.bypassReverbZones = true; #if UNITY_5_5_OR_NEWER audioSource.spatializePostEffects = true; #endif // UNITY_5_5_OR_NEWER OnValidate(); if (Application.platform != RuntimePlatform.Android) { // TODO: GvrAudio bug on Android with Unity 2017 // Route the source output to |GvrAudioMixer|. AudioMixer mixer = (Resources.Load("GvrAudioMixer") as AudioMixer); if(mixer != null) { audioSource.outputAudioMixerGroup = mixer.FindMatchingGroups("Master")[0]; } else { Debug.LogError("GVRAudioMixer could not be found in Resources. Make sure that the GVR SDK " + "Unity package is imported properly."); } } } void OnEnable () { audioSource.enabled = true; if (playOnAwake && !isPlaying && InitializeSource()) { Play(); } } void Start () { if (playOnAwake && !isPlaying) { Play(); } } void OnDisable () { Stop(); audioSource.enabled = false; } void OnDestroy () { Destroy(audioSource); } void OnApplicationPause (bool pauseStatus) { if (pauseStatus) { Pause(); } else { UnPause(); } } void Update () { if (disableOnStop && isPlaying == false) { gameObject.SetActive(false); } // Update occlusion state. if (!occlusionEnabled) { currentOcclusion = 0.0f; } else if (Time.time >= nextOcclusionUpdate) { nextOcclusionUpdate = Time.time + GvrAudio.occlusionDetectionInterval; currentOcclusion = GvrAudio.ComputeOcclusion(transform); } // Update source. if (!isPlaying && !isPaused) { Stop(); } else { audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain, GvrAudio.ConvertAmplitudeFromDb(gainDb)); audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.MinDistance, sourceMinDistance); GvrAudio.UpdateAudioSource(id, this, currentOcclusion); } } /// Provides a block of the currently playing source's output data. /// /// @note The array given in samples will be filled with the requested data before spatialization. public void GetOutputData(float[] samples, int channel) { if (audioSource != null) { audioSource.GetOutputData(samples, channel); } } /// Provides a block of the currently playing audio source's spectrum data. /// /// @note The array given in samples will be filled with the requested data before spatialization. public void GetSpectrumData(float[] samples, int channel, FFTWindow window) { if (audioSource != null) { audioSource.GetSpectrumData(samples, channel, window); } } /// Pauses playing the clip. public void Pause () { if (audioSource != null) { isPaused = true; audioSource.Pause(); } } /// Plays the clip. public void Play () { if (audioSource != null && InitializeSource()) { audioSource.Play(); isPaused = false; } else { Debug.LogWarning ("GVR Audio source not initialized. Audio playback not supported " + "until after Awake() and OnEnable(). Try calling from Start() instead."); } } /// Plays the clip with a delay specified in seconds. public void PlayDelayed (float delay) { if (audioSource != null && InitializeSource()) { audioSource.PlayDelayed(delay); isPaused = false; } else { Debug.LogWarning ("GVR Audio source not initialized. Audio playback not supported " + "until after Awake() and OnEnable(). Try calling from Start() instead."); } } /// Plays an AudioClip. public void PlayOneShot (AudioClip clip) { PlayOneShot(clip, 1.0f); } /// Plays an AudioClip, and scales its volume. public void PlayOneShot (AudioClip clip, float volume) { if (audioSource != null && InitializeSource()) { audioSource.PlayOneShot(clip, volume); isPaused = false; } else { Debug.LogWarning ("GVR Audio source not initialized. Audio playback not supported " + "until after Awake() and OnEnable(). Try calling from Start() instead."); } } /// Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads /// from. public void PlayScheduled (double time) { if (audioSource != null && InitializeSource()) { audioSource.PlayScheduled(time); isPaused = false; } else { Debug.LogWarning ("GVR Audio source not initialized. Audio playback not supported " + "until after Awake() and OnEnable(). Try calling from Start() instead."); } } /// Changes the time at which a sound that has already been scheduled to play will end. public void SetScheduledEndTime(double time) { if (audioSource != null) { audioSource.SetScheduledEndTime(time); } } /// Changes the time at which a sound that has already been scheduled to play will start. public void SetScheduledStartTime(double time) { if (audioSource != null) { audioSource.SetScheduledStartTime(time); } } /// Stops playing the clip. public void Stop () { if (audioSource != null) { audioSource.Stop(); ShutdownSource(); isPaused = true; } } /// Unpauses the paused playback. public void UnPause () { if (audioSource != null) { audioSource.UnPause(); isPaused = false; } } // Initializes the source. private bool InitializeSource () { if (Application.platform == RuntimePlatform.Android) { // TODO: GvrAudio bug on Android with Unity 2017 return true; } if (id < 0) { id = GvrAudio.CreateAudioSource(hrtfEnabled); if (id >= 0) { GvrAudio.UpdateAudioSource(id, this, currentOcclusion); audioSource.spatialize = true; audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Type, (float) GvrAudio.SpatializerType.Source); audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain, GvrAudio.ConvertAmplitudeFromDb(gainDb)); audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.MinDistance, sourceMinDistance); audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 0.0f); // Source id must be set after all the spatializer parameters, to ensure that the source is // properly initialized before processing. audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, (float) id); } } return id >= 0; } // Shuts down the source. private void ShutdownSource () { if (id >= 0) { audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, -1.0f); // Ensure that the output is zeroed after shutdown. audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 1.0f); audioSource.spatialize = false; GvrAudio.DestroyAudioSource(id); id = -1; } } void OnDidApplyAnimationProperties () { OnValidate(); } void OnValidate () { clip = sourceClip; loop = sourceLoop; mute = sourceMute; pitch = sourcePitch; priority = sourcePriority; spatialBlend = sourceSpatialBlend; volume = sourceVolume; dopplerLevel = sourceDopplerLevel; spread = sourceSpread; minDistance = sourceMinDistance; maxDistance = sourceMaxDistance; rolloffMode = sourceRolloffMode; } void OnDrawGizmosSelected () { // Draw listener directivity gizmo. // Note that this is a very suboptimal way of finding the component, to be used in Unity Editor // only, should not be used to access the component in run time. GvrAudioListener listener = FindObjectOfType<GvrAudioListener>(); if(listener != null) { Gizmos.color = GvrAudio.listenerDirectivityColor; DrawDirectivityGizmo(listener.transform, listenerDirectivityAlpha, listenerDirectivitySharpness, 180); } // Draw source directivity gizmo. Gizmos.color = GvrAudio.sourceDirectivityColor; DrawDirectivityGizmo(transform, directivityAlpha, directivitySharpness, 180); } // Draws a 3D gizmo in the Scene View that shows the selected directivity pattern. private void DrawDirectivityGizmo (Transform target, float alpha, float sharpness, int resolution) { Vector2[] points = GvrAudio.Generate2dPolarPattern(alpha, sharpness, resolution); // Compute |vertices| from the polar pattern |points|. int numVertices = resolution + 1; Vector3[] vertices = new Vector3[numVertices]; vertices[0] = Vector3.zero; for (int i = 0; i < points.Length; ++i) { vertices[i + 1] = new Vector3(points[i].x, 0.0f, points[i].y); } // Generate |triangles| from |vertices|. Two triangles per each sweep to avoid backface culling. int[] triangles = new int[6 * numVertices]; for (int i = 0; i < numVertices - 1; ++i) { int index = 6 * i; if (i < numVertices - 2) { triangles[index] = 0; triangles[index + 1] = i + 1; triangles[index + 2] = i + 2; } else { // Last vertex is connected back to the first for the last triangle. triangles[index] = 0; triangles[index + 1] = numVertices - 1; triangles[index + 2] = 1; } // The second triangle facing the opposite direction. triangles[index + 3] = triangles[index]; triangles[index + 4] = triangles[index + 2]; triangles[index + 5] = triangles[index + 1]; } // Construct a new mesh for the gizmo. Mesh directivityGizmoMesh = new Mesh(); directivityGizmoMesh.hideFlags = HideFlags.DontSaveInEditor; directivityGizmoMesh.vertices = vertices; directivityGizmoMesh.triangles = triangles; directivityGizmoMesh.RecalculateNormals(); // Draw the mesh. Vector3 scale = 2.0f * Mathf.Max(target.lossyScale.x, target.lossyScale.z) * Vector3.one; Gizmos.DrawMesh(directivityGizmoMesh, target.position, target.rotation, scale); } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// TemplateSharedItem /// </summary> [DataContract] public partial class TemplateSharedItem : IEquatable<TemplateSharedItem>, IValidatableObject { public TemplateSharedItem() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="TemplateSharedItem" /> class. /// </summary> /// <param name="ErrorDetails">ErrorDetails.</param> /// <param name="Owner">Owner.</param> /// <param name="Shared">When set to **true**, this custom tab is shared..</param> /// <param name="SharedGroups">.</param> /// <param name="SharedUsers">.</param> /// <param name="TemplateId">The unique identifier of the template. If this is not provided, DocuSign will generate a value. .</param> /// <param name="TemplateName">.</param> public TemplateSharedItem(ErrorDetails ErrorDetails = default(ErrorDetails), UserInfo Owner = default(UserInfo), string Shared = default(string), List<MemberGroupSharedItem> SharedGroups = default(List<MemberGroupSharedItem>), List<UserSharedItem> SharedUsers = default(List<UserSharedItem>), string TemplateId = default(string), string TemplateName = default(string)) { this.ErrorDetails = ErrorDetails; this.Owner = Owner; this.Shared = Shared; this.SharedGroups = SharedGroups; this.SharedUsers = SharedUsers; this.TemplateId = TemplateId; this.TemplateName = TemplateName; } /// <summary> /// Gets or Sets ErrorDetails /// </summary> [DataMember(Name="errorDetails", EmitDefaultValue=false)] public ErrorDetails ErrorDetails { get; set; } /// <summary> /// Gets or Sets Owner /// </summary> [DataMember(Name="owner", EmitDefaultValue=false)] public UserInfo Owner { get; set; } /// <summary> /// When set to **true**, this custom tab is shared. /// </summary> /// <value>When set to **true**, this custom tab is shared.</value> [DataMember(Name="shared", EmitDefaultValue=false)] public string Shared { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="sharedGroups", EmitDefaultValue=false)] public List<MemberGroupSharedItem> SharedGroups { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="sharedUsers", EmitDefaultValue=false)] public List<UserSharedItem> SharedUsers { get; set; } /// <summary> /// The unique identifier of the template. If this is not provided, DocuSign will generate a value. /// </summary> /// <value>The unique identifier of the template. If this is not provided, DocuSign will generate a value. </value> [DataMember(Name="templateId", EmitDefaultValue=false)] public string TemplateId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="templateName", EmitDefaultValue=false)] public string TemplateName { 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 TemplateSharedItem {\n"); sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n"); sb.Append(" Owner: ").Append(Owner).Append("\n"); sb.Append(" Shared: ").Append(Shared).Append("\n"); sb.Append(" SharedGroups: ").Append(SharedGroups).Append("\n"); sb.Append(" SharedUsers: ").Append(SharedUsers).Append("\n"); sb.Append(" TemplateId: ").Append(TemplateId).Append("\n"); sb.Append(" TemplateName: ").Append(TemplateName).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as TemplateSharedItem); } /// <summary> /// Returns true if TemplateSharedItem instances are equal /// </summary> /// <param name="other">Instance of TemplateSharedItem to be compared</param> /// <returns>Boolean</returns> public bool Equals(TemplateSharedItem other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.ErrorDetails == other.ErrorDetails || this.ErrorDetails != null && this.ErrorDetails.Equals(other.ErrorDetails) ) && ( this.Owner == other.Owner || this.Owner != null && this.Owner.Equals(other.Owner) ) && ( this.Shared == other.Shared || this.Shared != null && this.Shared.Equals(other.Shared) ) && ( this.SharedGroups == other.SharedGroups || this.SharedGroups != null && this.SharedGroups.SequenceEqual(other.SharedGroups) ) && ( this.SharedUsers == other.SharedUsers || this.SharedUsers != null && this.SharedUsers.SequenceEqual(other.SharedUsers) ) && ( this.TemplateId == other.TemplateId || this.TemplateId != null && this.TemplateId.Equals(other.TemplateId) ) && ( this.TemplateName == other.TemplateName || this.TemplateName != null && this.TemplateName.Equals(other.TemplateName) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.ErrorDetails != null) hash = hash * 59 + this.ErrorDetails.GetHashCode(); if (this.Owner != null) hash = hash * 59 + this.Owner.GetHashCode(); if (this.Shared != null) hash = hash * 59 + this.Shared.GetHashCode(); if (this.SharedGroups != null) hash = hash * 59 + this.SharedGroups.GetHashCode(); if (this.SharedUsers != null) hash = hash * 59 + this.SharedUsers.GetHashCode(); if (this.TemplateId != null) hash = hash * 59 + this.TemplateId.GetHashCode(); if (this.TemplateName != null) hash = hash * 59 + this.TemplateName.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Web; using Codentia.Common.Data; using Codentia.Test.Helper; using NUnit.Framework; namespace Codentia.Common.Logging.DL.Test { /// <summary> /// Unit testing framework for DatabaseLogWriter /// </summary> [TestFixture] public class DatabaseLogWriterTest { private string _logTargetName = "logging_sql"; /// <summary> /// Prepare for testing /// </summary> [TestFixtureSetUp] public void TestFixtureSetUp() { } /// <summary> /// Scenario: Object constructed and disposed /// Expected: Process completes without error /// </summary> [Test] public void _001_ConstructAndDispose() { // without opening writer DatabaseLogWriter writer = new DatabaseLogWriter(); writer.Dispose(); // with opening writer writer = new DatabaseLogWriter(); writer.Open(); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Single message written - object not opened first /// Expected: Object opens and then writes message /// </summary> [Test] public void _002_SingleMessage_NotOpen() { LogMessage msg = new LogMessage(LogMessageType.Information, "Test002", "This is a test message"); DatabaseLogWriter writer = new DatabaseLogWriter(); writer.LogTarget = _logTargetName; writer.Write(msg); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Message written, object is open /// Expected: Writes message /// </summary> [Test] public void _003_SingleMessage_Open() { LogMessage msg = new LogMessage(LogMessageType.Information, "Test003", "This is a test message"); DatabaseLogWriter writer = new DatabaseLogWriter(); writer.LogTarget = _logTargetName; writer.Open(); writer.Write(msg); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: set of messages written - object not opened first /// Expected: Object opens and then writes messages /// </summary> [Test] public void _004_MultiMessage_NotOpen() { DatabaseLogWriter writer = new DatabaseLogWriter(); LogMessage[] msgs = new LogMessage[] { new LogMessage(LogMessageType.Information, "Test004", "This is a test message"), new LogMessage(LogMessageType.Information, "Test004", "This is another test message") }; writer.LogTarget = _logTargetName; writer.Write(msgs); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Messages written when object is open /// Expected: Completes without error /// </summary> [Test] public void _005_MultiMessage_Open() { DatabaseLogWriter writer = new DatabaseLogWriter(); LogMessage[] msgs = new LogMessage[] { new LogMessage(LogMessageType.Information, "Test004", "This is a test message"), new LogMessage(LogMessageType.Information, "Test004", "This is another test message") }; writer.Open(); writer.LogTarget = _logTargetName; writer.Write(msgs); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Objected closed when not open /// Expected: No effect /// </summary> [Test] public void _006_Close_NotOpen() { DatabaseLogWriter writer = new DatabaseLogWriter(); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Object closed when open /// Expected: Completes without error /// </summary> [Test] public void _007_Close_Open() { DatabaseLogWriter writer = new DatabaseLogWriter(); writer.Open(); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Object opened when not open /// Expected: Completes without error /// </summary> [Test] public void _008_Open_NotOpen() { DatabaseLogWriter writer = new DatabaseLogWriter(); writer.Open(); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Objected opened when already open /// Expected: No effect /// </summary> [Test] public void _009_Open_Open() { DatabaseLogWriter writer = new DatabaseLogWriter(); writer.Open(); writer.Open(); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Test all that methods that trap for empty LogTarget /// Expected: System.NotImplementedException(LogTarget cannot be null or empty string) /// </summary> [Test] public void _010_Write_InvalidLogTarget() { LogMessage msg = new LogMessage(LogMessageType.Information, "Test002", "This is a test message"); DatabaseLogWriter writer = new DatabaseLogWriter(); Assert.That(delegate { writer.LogTarget = null; }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Cannot set LogTarget as null or empty")); Assert.That(delegate { writer.LogTarget = string.Empty; }, Throws.InstanceOf<Exception>().With.Message.EqualTo("Cannot set LogTarget as null or empty")); Assert.That(delegate { writer.Write(msg); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("LogTarget has not been set")); DateTime writeDateTime = DateTime.Now; Dictionary<LogMessageType, DateTime> cleanUpParams = new Dictionary<LogMessageType, DateTime>(); cleanUpParams[LogMessageType.FatalError] = writeDateTime.AddMilliseconds(500); cleanUpParams[LogMessageType.Information] = writeDateTime.AddMilliseconds(500); cleanUpParams[LogMessageType.NonFatalError] = writeDateTime.AddMilliseconds(500); cleanUpParams[LogMessageType.UrlRequest] = writeDateTime.AddMilliseconds(500); Assert.That(delegate { writer.CleanUp(0, 0, cleanUpParams); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("LogTarget has not been set")); writer.Close(); writer.Dispose(); DatabaseLogWriter writerMulti = new DatabaseLogWriter(); LogMessage[] msgs = new LogMessage[] { new LogMessage(LogMessageType.Information, "Test004", "This is a test message"), new LogMessage(LogMessageType.Information, "Test004", "This is another test message") }; Assert.That(delegate { writerMulti.Write(msgs); }, Throws.InstanceOf<Exception>().With.Message.EqualTo("LogTarget has not been set")); writerMulti.Close(); writerMulti.Dispose(); } /// <summary> /// Scenario: Attempt to write a UrlAccessMessage /// Expected: Message written with no error /// </summary> [Test] public void _011_UrlAccessMessage() { HttpContext x = HttpHelper.CreateHttpContext(string.Empty); UrlAccessMessage msg = new UrlAccessMessage(x.Request); DatabaseLogWriter writer = new DatabaseLogWriter(); writer.LogTarget = _logTargetName; writer.Write((LogMessage)msg); writer.Close(); writer.Dispose(); } /// <summary> /// Scenario: Run the cleanup method, giving a purge date (the date at which data will be kept from) /// Expected: Only data added after that date/time is kept /// </summary> [Test] public void _012_CleanUp() { // populate log DatabaseLogWriter writer = new DatabaseLogWriter(); writer.LogTarget = _logTargetName; Assert.That(writer.LogTarget, Is.EqualTo(_logTargetName)); writer.Write(new LogMessage(LogMessageType.Information, "Test", "Test message")); writer.Write(new LogMessage(LogMessageType.FatalError, "Test", "Test message")); writer.Write(new LogMessage(LogMessageType.NonFatalError, "Test", "Test message")); HttpContext x = HttpHelper.CreateHttpContext(string.Empty); UrlAccessMessage msg = new UrlAccessMessage(x.Request); writer.Write((LogMessage)msg); // record the time, pause for a second and write again DateTime writeDateTime = DateTime.Now; System.Threading.Thread.Sleep(1000); writer.Write(new LogMessage(LogMessageType.Information, "Test", "Test message")); writer.Write(new LogMessage(LogMessageType.FatalError, "Test", "Test message")); writer.Write(new LogMessage(LogMessageType.NonFatalError, "Test", "Test message")); msg = new UrlAccessMessage(x.Request); writer.Write((LogMessage)msg); writer.Close(); writer.Dispose(); writer = new DatabaseLogWriter(); // now perform cleanup Dictionary<LogMessageType, DateTime> cleanUpParams = new Dictionary<LogMessageType, DateTime>(); cleanUpParams[LogMessageType.FatalError] = writeDateTime.AddMilliseconds(500); cleanUpParams[LogMessageType.Information] = writeDateTime.AddMilliseconds(500); cleanUpParams[LogMessageType.NonFatalError] = writeDateTime.AddMilliseconds(500); cleanUpParams[LogMessageType.UrlRequest] = writeDateTime.AddMilliseconds(500); writer.LogTarget = _logTargetName; writer.CleanUp(0, 0, cleanUpParams); // ensure one record of each type exists Assert.That(DbInterface.ExecuteQueryScalar<int>("SELECT COUNT(*) FROM SystemLog WHERE LogMessageType = 1"), Is.EqualTo(1)); Assert.That(DbInterface.ExecuteQueryScalar<int>("SELECT COUNT(*) FROM SystemLog WHERE LogMessageType = 2"), Is.EqualTo(1)); Assert.That(DbInterface.ExecuteQueryScalar<int>("SELECT COUNT(*) FROM SystemLog WHERE LogMessageType = 3"), Is.EqualTo(1)); Assert.That(DbInterface.ExecuteQueryScalar<int>("SELECT COUNT(*) FROM SystemAccessLog"), Is.EqualTo(1)); writer.Close(); writer.Dispose(); } } }
using System; namespace UnityEngine.Rendering.PostProcessing { public abstract class ParameterOverride { public bool overrideState; internal abstract void Interp(ParameterOverride from, ParameterOverride to, float t); public abstract int GetHash(); public T GetValue<T>() { return ((ParameterOverride<T>)this).value; } // This is used in case you need to access fields/properties that can't be accessed in the // constructor of a ScriptableObject (ParameterOverride are generally declared and inited in // a PostProcessEffectSettings which is a ScriptableObject). This will be called right // after the settings object has been constructed, thus allowing previously "forbidden" // fields/properties. protected internal virtual void OnEnable() { } // Here for consistency reasons (cf. OnEnable) protected internal virtual void OnDisable() { } internal abstract void SetValue(ParameterOverride parameter); } [Serializable] public class ParameterOverride<T> : ParameterOverride { public T value; public ParameterOverride() : this(default(T), false) { } public ParameterOverride(T value) : this(value, false) { } public ParameterOverride(T value, bool overrideState) { this.value = value; this.overrideState = overrideState; } internal override void Interp(ParameterOverride from, ParameterOverride to, float t) { // Note: this isn't completely safe but it'll do fine Interp(from.GetValue<T>(), to.GetValue<T>(), t); } public virtual void Interp(T from, T to, float t) { // Returns `b` if `dt > 0` by default so we don't have to write overrides for bools and // enumerations. value = t > 0f ? to : from; } public void Override(T x) { overrideState = true; value = x; } internal override void SetValue(ParameterOverride parameter) { value = parameter.GetValue<T>(); } public override int GetHash() { unchecked { int hash = 17; hash = hash * 23 + overrideState.GetHashCode(); hash = hash * 23 + value.GetHashCode(); return hash; } } // Implicit conversion; assuming the following: // // var myFloatProperty = new ParameterOverride<float> { value = 42f; }; // // It allows for implicit casts: // // float myFloat = myFloatProperty.value; // No implicit cast // float myFloat = myFloatProperty; // Implicit cast // // For safety reason this is one-way only. public static implicit operator T(ParameterOverride<T> prop) { return prop.value; } } // Bypassing the limited unity serialization system... [Serializable] public sealed class FloatParameter : ParameterOverride<float> { public override void Interp(float from, float to, float t) { value = from + (to - from) * t; } } [Serializable] public sealed class IntParameter : ParameterOverride<int> { public override void Interp(int from, int to, float t) { // Int snapping interpolation. Don't use this for enums as they don't necessarily have // contiguous values. Use the default interpolator instead (same as bool). value = (int)(from + (to - from) * t); } } [Serializable] public sealed class BoolParameter : ParameterOverride<bool> {} [Serializable] public sealed class ColorParameter : ParameterOverride<Color> { public override void Interp(Color from, Color to, float t) { // Lerping color values is a sensitive subject... We looked into lerping colors using // HSV and LCH but they have some downsides that make them not work correctly in all // situations, so we stick with RGB lerping for now, at least its behavior is // predictable despite looking desaturated when `t ~= 0.5` and it's faster anyway. value.r = from.r + (to.r - from.r) * t; value.g = from.g + (to.g - from.g) * t; value.b = from.b + (to.b - from.b) * t; value.a = from.a + (to.a - from.a) * t; } } [Serializable] public sealed class Vector2Parameter : ParameterOverride<Vector2> { public override void Interp(Vector2 from, Vector2 to, float t) { value.x = from.x + (to.x - from.x) * t; value.y = from.y + (to.y - from.y) * t; } } [Serializable] public sealed class Vector3Parameter : ParameterOverride<Vector3> { public override void Interp(Vector3 from, Vector3 to, float t) { value.x = from.x + (to.x - from.x) * t; value.y = from.y + (to.y - from.y) * t; value.z = from.z + (to.z - from.z) * t; } } [Serializable] public sealed class Vector4Parameter : ParameterOverride<Vector4> { public override void Interp(Vector4 from, Vector4 to, float t) { value.x = from.x + (to.x - from.x) * t; value.y = from.y + (to.y - from.y) * t; value.z = from.z + (to.z - from.z) * t; value.w = from.w + (to.w - from.w) * t; } } [Serializable] public sealed class SplineParameter : ParameterOverride<Spline> { protected internal override void OnEnable() { if (value != null) value.Cache(int.MinValue); } internal override void SetValue(ParameterOverride parameter) { base.SetValue(parameter); if (value != null) value.Cache(Time.renderedFrameCount); } public override void Interp(Spline from, Spline to, float t) { if (from == null || to == null) { base.Interp(from, to, t); return; } int frameCount = Time.renderedFrameCount; from.Cache(frameCount); to.Cache(frameCount); for (int i = 0; i < Spline.k_Precision; i++) { float a = from.cachedData[i]; float b = to.cachedData[i]; value.cachedData[i] = a + (b - a) * t; } } } [Serializable] public sealed class TextureParameter : ParameterOverride<Texture> { public override void Interp(Texture from, Texture to, float t) { if (from == null || to == null) { base.Interp(from, to, t); return; } value = TextureLerper.instance.Lerp(from, to, t); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Azure.Management.RecoveryServices.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices { /// <summary> /// Definition of vault operations for the Recovery Services extension. /// </summary> internal partial class VaultUsageOperations : IServiceOperations<RecoveryServicesManagementClient>, IVaultUsageOperations { /// <summary> /// Initializes a new instance of the VaultUsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VaultUsageOperations(RecoveryServicesManagementClient client) { this._client = client; } private RecoveryServicesManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.RecoveryServicesManagementClient. /// </summary> public RecoveryServicesManagementClient Client { get { return this._client; } } /// <summary> /// Get the Vault Usage. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the (resource group?) cloud service /// containing the vault collection. /// </param> /// <param name='vaultName'> /// Required. The name of the vault to get usage. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for Vault usage. /// </returns> public async Task<VaultUsageListResponse> ListAsync(string resourceGroupName, string vaultName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (vaultName == null) { throw new ArgumentNullException("vaultName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + "vaults"; url = url + "/"; url = url + Uri.EscapeDataString(vaultName); url = url + "/usages"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-05-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result VaultUsageListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VaultUsageListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Usage usageInstance = new Usage(); result.Value.Add(usageInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { Name nameInstance = new Name(); usageInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { string unitInstance = ((string)unitValue); usageInstance.Unit = unitInstance; } JToken currentValueValue = valueValue["currentValue"]; if (currentValueValue != null && currentValueValue.Type != JTokenType.Null) { long currentValueInstance = ((long)currentValueValue); usageInstance.CurrentValue = currentValueInstance; } JToken limitValue = valueValue["limit"]; if (limitValue != null && limitValue.Type != JTokenType.Null) { long limitInstance = ((long)limitValue); usageInstance.Limit = limitInstance; } JToken nextResetTimeValue = valueValue["nextResetTime"]; if (nextResetTimeValue != null && nextResetTimeValue.Type != JTokenType.Null) { string nextResetTimeInstance = ((string)nextResetTimeValue); usageInstance.NextResetTime = nextResetTimeInstance; } JToken quotaPeriodValue = valueValue["quotaPeriod"]; if (quotaPeriodValue != null && quotaPeriodValue.Type != JTokenType.Null) { string quotaPeriodInstance = ((string)quotaPeriodValue); usageInstance.QuotaPeriod = quotaPeriodInstance; } } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Security; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLMcode = Interop.Http.CURLMcode; using CURLoption = Interop.Http.CURLoption; namespace System.Net.Http { // Object model: // ------------- // CurlHandler provides an HttpMessageHandler implementation that wraps libcurl. The core processing for CurlHandler // is handled via a CurlHandler.MultiAgent instance, where currently a CurlHandler instance stores and uses a single // MultiAgent for the lifetime of the handler (with the MultiAgent lazily initialized on first use, so that it can // be initialized with all of the configured options on the handler). The MultiAgent is named as such because it wraps // a libcurl multi handle that's responsible for handling all requests on the instance. When a request arrives, it's // queued to the MultiAgent, which ensures that a thread is running to continually loop and process all work associated // with the multi handle until no more work is required; at that point, the thread is retired until more work arrives, // at which point another thread will be spun up. Any number of requests will have their handling multiplexed onto // this one event loop thread. Each request is represented by a CurlHandler.EasyRequest, so named because it wraps // a libcurl easy handle, libcurl's representation of a request. The EasyRequest stores all state associated with // the request, including the CurlHandler.CurlResponseMessage and CurlHandler.CurlResponseStream that are handed // back to the caller to provide access to the HTTP response information. // // Lifetime: // --------- // The MultiAgent is initialized on first use and is kept referenced by the CurlHandler for the remainder of the // handler's lifetime. Both are disposable, and disposing of the CurlHandler will dispose of the MultiAgent. // However, libcurl is not thread safe in that two threads can't be using the same multi or easy handles concurrently, // so any interaction with the multi handle must happen on the MultiAgent's thread. For this reason, the // SafeHandle storing the underlying multi handle has its ref count incremented when the MultiAgent worker is running // and decremented when it stops running, enabling any disposal requests to be delayed until the worker has quiesced. // To enable that to happen quickly when a dispose operation occurs, an "incoming request" (how all other threads // communicate with the MultiAgent worker) is queued to the worker to request a shutdown; upon receiving that request, // the worker will exit and allow the multi handle to be disposed of. // // An EasyRequest itself doesn't govern its own lifetime. Since an easy handle is added to a multi handle for // the multi handle to process, the easy handle must not be destroyed until after it's been removed from the multi handle. // As such, once the SafeHandle for an easy handle is created, although its stored in the EasyRequest instance, // it's also stored into a dictionary on the MultiAgent and has its ref count incremented to prevent it from being // disposed of while it's in use by the multi handle. // // When a request is made to the CurlHandler, callbacks are registered with libcurl, including state that will // be passed back into managed code and used to identify the associated EasyRequest. This means that the native // code needs to be able both to keep the EasyRequest alive and to refer to it using an IntPtr. For this, we // use a GCHandle to the EasyRequest. However, the native code needs to be able to refer to the EasyRequest for the // lifetime of the request, but we also need to avoid keeping the EasyRequest (and all state it references) alive artificially. // For the beginning phase of the request, the native code may be the only thing referencing the managed objects, since // when a caller invokes "Task<HttpResponseMessage> SendAsync(...)", there's nothing handed back to the caller that represents // the request until at least the HTTP response headers are received and the returned Task is completed with the response // message object. However, after that point, if the caller drops the HttpResponseMessage, we also want to cancel and // dispose of the associated state, which means something needs to be finalizable and not kept rooted while at the same // time still allowing the native code to continue using its GCHandle and lookup the associated state as long as it's alive. // Yet then when an async read is made on the response message, we want to postpone such finalization and ensure that the async // read can be appropriately completed with control and reference ownership given back to the reader. As such, we do two things: // we make the response stream finalizable, and we make the GCHandle be to a wrapper object for the EasyRequest rather than to // the EasyRequest itself. That wrapper object maintains a weak reference to the EasyRequest as well as sometimes maintaining // a strong reference. When the request starts out, the GCHandle is created to the wrapper, which has a strong reference to // the EasyRequest (which also back references to the wrapper so that the wrapper can be accessed via it). The GCHandle is // thus keeping the EasyRequest and all of the state it references alive, e.g. the CurlResponseStream, which itself has a reference // back to the EasyRequest. Once the request progresses to the point of receiving HTTP response headers and the HttpResponseMessage // is handed back to the caller, the wrapper object drops its strong reference and maintains only a weak reference. At this // point, if the caller were to drop its HttpResponseMessage object, that would also drop the only strong reference to the // CurlResponseStream; the CurlResponseStream would be available for collection and finalization, and its finalization would // request cancellation of the easy request to the multi agent. The multi agent would then in response remove the easy handle // from the multi handle and decrement the ref count on the SafeHandle for the easy handle, allowing it to be finalized and // the underlying easy handle released. If instead of dropping the HttpResponseMessage the caller makes a read request on the // response stream, the wrapper object is transitioned back to having a strong reference, so that even if the caller then drops // the HttpResponseMessage, the read Task returned from the read operation will still be completed eventually, at which point // the wrapper will transition back to being a weak reference. // // Even with that, of course, Dispose is still the recommended way of cleaning things up. Disposing the CurlResponseMessage // will Dispose the CurlResponseStream, which will Dispose of the SafeHandle for the easy handle and request that the MultiAgent // cancel the operation. Once canceled and removed, the SafeHandle will have its ref count decremented and the previous disposal // will proceed to release the underlying handle. internal partial class CurlHandler : HttpMessageHandler { #region Constants private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int MaxRequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const string NoExpect = HttpKnownHeaderNames.Expect + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private static readonly KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypes = new KeyValuePair<string, CURLAUTH>[] { new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate), new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM), new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest), new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic), }; // Max timeout value used by WinHttp handler, so mapping to that here. private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private static readonly bool s_supportsAutomaticDecompression; private static readonly bool s_supportsSSL; private static readonly bool s_supportsHttp2Multiplexing; private static string s_curlVersionDescription; private static string s_curlSslVersionDescription; private readonly MultiAgent _agent; private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy; private ICredentials _defaultProxyCredentials = null; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private bool _useDefaultCredentials = HttpHandlerDefaults.DefaultUseDefaultCredentials; private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private TimeSpan _connectTimeout = Timeout.InfiniteTimeSpan; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer; private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption; private X509Certificate2Collection _clientCertificates; private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback; private bool _checkCertificateRevocationList; private SslProtocols _sslProtocols = SslProtocols.None; // use default private IDictionary<String, Object> _properties; // Only create dictionary when required. private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.LibCurl's cctor Interop.Http.CurlFeatures features = Interop.Http.GetSupportedFeatures(); s_supportsSSL = (features & Interop.Http.CurlFeatures.CURL_VERSION_SSL) != 0; s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0; s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing(); if (NetEventSource.IsEnabled) { EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}"); } } public CurlHandler() { _agent = new MultiAgent(this); } #region Properties private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty); private static string CurlSslVersionDescription => s_curlSslVersionDescription ?? (s_curlSslVersionDescription = Interop.Http.GetSslVersionDescription() ?? string.Empty); internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy => true; internal bool SupportsRedirectConfiguration => true; internal bool UseProxy { get { return _useProxy; } set { CheckDisposedOrStarted(); _useProxy = value; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } internal X509Certificate2Collection ClientCertificates { get { if (_clientCertificateOption != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual")); } if (_clientCertificates == null) { _clientCertificates = new X509Certificate2Collection(); } return _clientCertificates; } } internal Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } internal bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } internal SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } internal bool SupportsAutomaticDecompression => s_supportsAutomaticDecompression; internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } internal int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } internal int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } internal bool UseDefaultCredentials { get { return _useDefaultCredentials; } set { CheckDisposedOrStarted(); _useDefaultCredentials = value; } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; if (disposing) { _agent.Dispose(); } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription)); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookie && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, _agent, request, cancellationToken); try { EventSourceTrace("{0}", request, easy: easy); _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.CleanupAndFailRequest(exc); } return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri) { // If preauthentication is enabled, we may have populated our internal credential cache, // so first check there to see if we have any credentials for this uri. if (_preAuthenticate) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); ncAndScheme = GetCredentials(requestUri, _credentialCache, s_orderedAuthTypes); } if (ncAndScheme.Key != null) { return ncAndScheme; } } // We either weren't preauthenticating or we didn't have any cached credentials // available, so check the credentials on the handler. return GetCredentials(requestUri, _serverCredentials, s_orderedAuthTypes); } private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail) { if (_serverCredentials == null) { // No credentials, nothing to put into the cache. return; } lock (LockObject) { // For each auth type we allow, check whether it's one supported by the server. KeyValuePair<string, CURLAUTH>[] validAuthTypes = s_orderedAuthTypes; for (int i = 0; i < validAuthTypes.Length; i++) { // Is it supported by the server? if ((serverAuthAvail & validAuthTypes[i].Value) != 0) { // And do we have a credential for it? NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key); if (nc != null) { // We have a credential for it, so add it, and we're done. Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); try { _credentialCache.Add(serverUri, validAuthTypes[i].Key, nc); } catch (ArgumentException) { // Ignore the case of key already present } break; } } } } } private void AddResponseCookies(EasyRequest state, string cookieHeader) { if (!_useCookie) { return; } try { _cookieContainer.SetCookies(state._requestMessage.RequestUri, cookieHeader); state.SetCookieOption(state._requestMessage.RequestUri); } catch (CookieException e) { EventSourceTrace( "Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}", e.Message, state._requestMessage.RequestUri, cookieHeader, easy: state); } } private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes) { NetworkCredential nc = null; CURLAUTH curlAuthScheme = CURLAUTH.None; if (credentials != null) { // For each auth type we consider valid, try to get a credential for it. // Union together the auth types for which we could get credentials, but validate // that the found credentials are all the same, as libcurl doesn't support differentiating // by auth type. for (int i = 0; i < validAuthTypes.Length; i++) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key); if (networkCredential != null) { curlAuthScheme |= validAuthTypes[i].Value; if (nc == null) { nc = networkCredential; } else if(!AreEqualNetworkCredentials(nc, networkCredential)) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription)); } } } } EventSourceTrace("Authentication scheme: {0}", curlAuthScheme); return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(CURLcode error) { if (error != CURLcode.CURLE_OK) // success { string msg = CurlException.GetCurlErrorString((int)error, isMulti: false); EventSourceTrace(msg); switch (error) { case CURLcode.CURLE_OPERATION_TIMEDOUT: throw new OperationCanceledException(msg); case CURLcode.CURLE_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLcode.CURLE_SEND_FAIL_REWIND: throw new InvalidOperationException(msg); default: throw new CurlException((int)error, msg); } } } private static void ThrowIfCURLMError(CURLMcode error) { if (error != CURLMcode.CURLM_OK && // success error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again { string msg = CurlException.GetCurlErrorString((int)error, isMulti: true); EventSourceTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException((int)error, msg); } } } private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2) { Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check"); return credential1.UserName == credential2.UserName && credential1.Domain == credential2.Domain && string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal); } // PERF NOTE: // These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler // nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking // NetEventSource.IsEnabled. Do not remove these without fixing the call sites accordingly. private static void EventSourceTrace<TArg0>( string formatMessage, TArg0 arg0, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName); } } private static void EventSourceTrace<TArg0, TArg1, TArg2> (string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName); } } private static void EventSourceTrace( string message, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(message, agent, easy, memberName); } } private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null) { agent = easy._associatedMultiAgent; } NetEventSource.Log.HandlerMessage( agent?.GetHashCode() ?? 0, (agent?.RunningWorkerId).GetValueOrDefault(), easy?.Task.Id ?? 0, memberName, message); } private static HttpRequestException CreateHttpRequestException(Exception inner) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static IOException MapToReadWriteIOException(Exception error, bool isRead) { return new IOException( isRead ? SR.net_http_io_read : SR.net_http_io_write, error is HttpRequestException && error.InnerException != null ? error.InnerException : error); } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Transfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion } }
//----------------------------------------------------------------------- // <copyright file="DataMapperTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using Csla.TestHelpers; #if !NUNIT using Microsoft.VisualStudio.TestTools.UnitTesting; #else using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #endif namespace Csla.Test.DataMapper { [TestClass] public class DataMapperTests { private static TestDIContext _testDIContext; [ClassInitialize] public static void ClassInitialize(TestContext context) { _testDIContext = TestDIContextFactory.CreateDefaultContext(); } [TestMethod] public void DictionaryMap() { IDataPortal<ManagedTarget> dataPortal = _testDIContext.CreateDataPortal<ManagedTarget>(); var target = dataPortal.Create(); var source = new Dictionary<string, object>(); source.Add("MyInt", 42); Csla.Data.DataMapper.Load(source, target, (n) => n); Assert.AreEqual(42, target.MyInt, "Int should match"); } [TestMethod] public void NumericTypes() { DataMapTarget target = new DataMapTarget(); Csla.Data.DataMapper.SetPropertyValue(target, "MyInt", 42); Assert.AreEqual(42, target.MyInt, "Int should match"); Csla.Data.DataMapper.SetPropertyValue(target, "MyInt", "24"); Assert.AreEqual(24, target.MyInt, "Int from string should be 24"); Csla.Data.DataMapper.SetPropertyValue(target, "MyInt", ""); Assert.AreEqual(0, target.MyInt, "Int from empty string should be 0"); Csla.Data.DataMapper.SetPropertyValue(target, "MyInt", null); Assert.AreEqual(0, target.MyInt, "Int from null should be 0"); Csla.Data.DataMapper.SetPropertyValue(target, "MyDouble", 4.2); Assert.AreEqual(4.2, target.MyDouble, "Double should match"); } [TestMethod] public void BooleanTypes() { DataMapTarget target = new DataMapTarget(); Csla.Data.DataMapper.SetPropertyValue(target, "MyBool", true); Assert.AreEqual(true, target.MyBool, "Bool should be true"); Csla.Data.DataMapper.SetPropertyValue(target, "MyBool", false); Assert.AreEqual(false, target.MyBool, "Bool should be false"); Csla.Data.DataMapper.SetPropertyValue(target, "MyBool", ""); Assert.AreEqual(false, target.MyBool, "Bool from empty string should be false"); Csla.Data.DataMapper.SetPropertyValue(target, "MyBool", null); Assert.AreEqual(false, target.MyBool, "Bool from null should be false"); } [TestMethod] public void GuidTypes() { DataMapTarget target = new DataMapTarget(); Guid testValue = Guid.NewGuid(); Csla.Data.DataMapper.SetPropertyValue(target, "MyGuid", testValue); Assert.AreEqual(testValue, target.MyGuid, "Guid values should match"); Csla.Data.DataMapper.SetPropertyValue(target, "MyGuid", Guid.Empty); Assert.AreEqual(Guid.Empty, target.MyGuid, "Empty guid values should match"); Csla.Data.DataMapper.SetPropertyValue(target, "MyGuid", testValue.ToString()); Assert.AreEqual(testValue, target.MyGuid, "Guid values from string should match"); } [TestMethod] public void NullableTypes() { DataMapTarget target = new DataMapTarget(); Csla.Data.DataMapper.SetPropertyValue(target, "MyNInt", 42); Assert.AreEqual(42, target.MyNInt, "Int should match"); Csla.Data.DataMapper.SetPropertyValue(target, "MyNInt", 0); Assert.AreEqual(0, target.MyNInt, "Int should be 0"); Csla.Data.DataMapper.SetPropertyValue(target, "MyNInt", string.Empty); Assert.AreEqual(null, target.MyNInt, "Int from string.Empty should be null"); Csla.Data.DataMapper.SetPropertyValue(target, "MyNInt", null); Assert.AreEqual(null, target.MyNInt, "Int should be null"); } [TestMethod] public void EnumTypes() { DataMapTarget target = new DataMapTarget(); Csla.Data.DataMapper.SetPropertyValue(target, "MyEnum", DataMapEnum.Second); Assert.AreEqual(DataMapEnum.Second, target.MyEnum, "Enum should be Second"); Csla.Data.DataMapper.SetPropertyValue(target, "MyEnum", "First"); Assert.AreEqual(DataMapEnum.First, target.MyEnum, "Enum should be First"); Csla.Data.DataMapper.SetPropertyValue(target, "MyEnum", 2); Assert.AreEqual(DataMapEnum.Third, target.MyEnum, "Enum should be Third"); } [TestMethod] public void DateTimeTypes() { DataMapTarget target = new DataMapTarget(); Csla.Data.DataMapper.SetPropertyValue(target, "MyDate", DateTime.Today); Assert.AreEqual(DateTime.Today, target.MyDate, "Date should be Today"); Csla.Data.DataMapper.SetPropertyValue(target, "MyDate", "1/1/2007"); Assert.AreEqual(new DateTime(2007, 1, 1), target.MyDate, "Date should be 1/1/2007"); Csla.Data.DataMapper.SetPropertyValue(target, "MyDate", new Csla.SmartDate("1/1/2007")); Assert.AreEqual(new DateTime(2007, 1, 1), target.MyDate, "Date should be 1/1/2007"); } [TestMethod] public void SmartDateTypes() { DataMapTarget target = new DataMapTarget(); Csla.Data.DataMapper.SetPropertyValue(target, "MySmartDate", DateTime.Today); Assert.AreEqual(new Csla.SmartDate(DateTime.Today), target.MySmartDate, "SmartDate should be Today"); Csla.Data.DataMapper.SetPropertyValue(target, "MySmartDate", "1/1/2007"); Assert.AreEqual(new Csla.SmartDate(new DateTime(2007, 1, 1)), target.MySmartDate, "SmartDate should be 1/1/2007"); Csla.Data.DataMapper.SetPropertyValue(target, "MySmartDate", new Csla.SmartDate("1/1/2007")); Assert.AreEqual(new Csla.SmartDate(new DateTime(2007, 1, 1)), target.MySmartDate, "SmartDate should be 1/1/2007"); Csla.Data.DataMapper.SetPropertyValue(target, "MySmartDate", new DateTimeOffset(new DateTime(2004, 3, 2))); Assert.AreEqual(new Csla.SmartDate(new DateTime(2004, 3, 2)), target.MySmartDate, "SmartDate should be 3/2/2004"); target.MySmartDate = new Csla.SmartDate(DateTime.Today, Csla.SmartDate.EmptyValue.MaxDate); Assert.IsFalse(target.MySmartDate.EmptyIsMin, "EmptyIsMin should be false before set"); Csla.Data.DataMapper.SetPropertyValue(target, "MySmartDate", DateTime.Parse("1/1/2007")); Assert.IsFalse(target.MySmartDate.EmptyIsMin, "EmptyIsMin should be false after set"); } [TestMethod] public void SetFields() { DataMapTarget target = new DataMapTarget(); Csla.Data.DataMapper.SetFieldValue(target, "_int", 42); Assert.AreEqual(42, target.MyInt, "Int should match"); Csla.Data.DataMapper.SetFieldValue(target, "_double", 4.2); Assert.AreEqual(4.2, target.MyDouble, "Double should match"); Csla.Data.DataMapper.SetFieldValue(target, "_bool", true); Assert.AreEqual(true, target.MyBool, "Bool should be true"); Csla.Data.DataMapper.SetFieldValue(target, "_bool", false); Assert.AreEqual(false, target.MyBool, "Bool should be false"); Csla.Data.DataMapper.SetFieldValue(target, "_smartDate", "2/1/2007"); Assert.AreEqual(new Csla.SmartDate("2/1/2007"), target.MySmartDate, "SmartDate should be 2/1/2007"); Csla.Data.DataMapper.SetFieldValue(target, "_smartDate", new Csla.SmartDate("1/1/2007")); Assert.AreEqual(new Csla.SmartDate("1/1/2007"), target.MySmartDate, "SmartDate should be 1/1/2007"); Csla.Data.DataMapper.SetFieldValue(target, "_smartDate", new DateTimeOffset(new DateTime(2004, 3, 2))); Assert.AreEqual(new Csla.SmartDate(new DateTime(2004, 3, 2)), target.MySmartDate, "SmartDate should be 3/2/2004"); } [TestMethod] public void BasicDataMap() { Csla.Data.DataMap map = new Csla.Data.DataMap(typeof(DataMapTarget), typeof(DataMapTarget)); DataMapTarget source = new DataMapTarget(); DataMapTarget target = new DataMapTarget(); source.MyInt = 123; source.MyDouble = 456; source.MyBool = true; source.MyEnum = DataMapEnum.Second; var g = Guid.NewGuid(); source.MyGuid = g; source.MyNInt = 321; source.MySmartDate = new Csla.SmartDate(new DateTime(2002, 12, 4)); source.MyDate = new DateTime(2002, 11, 2); source.MyString = "Third"; map.AddFieldMapping("_int", "_int"); map.AddFieldToPropertyMapping("_double", "MyDouble"); map.AddPropertyMapping("MyBool", "MyBool"); map.AddPropertyToFieldMapping("MyGuid", "_guid"); map.AddPropertyMapping("MyEnum", "MyString"); map.AddPropertyMapping("MyString", "MyEnum"); Csla.Data.DataMapper.Map(source, target, map); Assert.AreEqual(123, target.MyInt, "Int should match"); Assert.AreEqual(456, target.MyDouble, "Double should match"); Assert.AreEqual(true, target.MyBool, "bool should match"); Assert.AreEqual(g, target.MyGuid, "guid should match"); Assert.AreEqual("Second", target.MyString, "string should match (converted enum)"); Assert.AreEqual(DataMapEnum.Third, target.MyEnum, "enum should match (parsed enum)"); Assert.AreNotEqual(source.MyDate, target.MyDate, "Dates should not match"); } } public enum DataMapEnum { First, Second, Third } [Serializable] public class ManagedTarget : BusinessBase<ManagedTarget> { public static PropertyInfo<int> MyIntProperty = RegisterProperty<int>(c => c.MyInt); public int MyInt { get { return GetProperty(MyIntProperty); } set { SetProperty(MyIntProperty, value); } } [Create] private void Create() { } } public class DataMapTarget { private int _int; public int MyInt { get { return _int; } set { _int = value; } } private double _double; public double MyDouble { get { return _double; } set { _double = value; } } private bool _bool; public bool MyBool { get { return _bool; } set { _bool = value; } } private Nullable<int> _nint; public Nullable<int> MyNInt { get { return _nint; } set { _nint = value; } } private DataMapEnum _enum; public DataMapEnum MyEnum { get { return _enum; } set { _enum = value; } } private DateTime _date; public DateTime MyDate { get { return _date; } set { _date = value; } } private Csla.SmartDate _smartDate; public Csla.SmartDate MySmartDate { get { return _smartDate; } set { _smartDate = value; } } private Guid _guid; public Guid MyGuid { get { return _guid; } set { _guid = value; } } private string _string; public string MyString { get { return _string; } set { _string = value; } } } }
using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Data; using NServiceKit.DataAnnotations; using NServiceKit.OrmLite.Firebird.DbSchema; namespace NServiceKit.OrmLite.Firebird { /// <summary>A schema.</summary> public class Schema : ISchema<Table, Column, Procedure, Parameter> { /// <summary>The SQL tables.</summary> private string sqlTables; /// <summary>The SQL columns.</summary> private StringBuilder sqlColumns = new StringBuilder(); /// <summary>The SQL field generator.</summary> private StringBuilder sqlFieldGenerator = new StringBuilder(); /// <summary>The SQL generator.</summary> private StringBuilder sqlGenerator = new StringBuilder(); /// <summary>The SQL procedures.</summary> private StringBuilder sqlProcedures = new StringBuilder(); /// <summary>Options for controlling the SQL.</summary> private StringBuilder sqlParameters = new StringBuilder(); /// <summary>Sets the connection.</summary> /// <value>The connection.</value> public IDbConnection Connection { private get; set; } /// <summary> /// Initializes a new instance of the NServiceKit.OrmLite.Firebird.Schema class. /// </summary> public Schema() { Init(); } /// <summary>Gets the tables.</summary> /// <value>The tables.</value> public List<Table> Tables { get { return Connection.Select<Table>(sqlTables); } } /// <summary>Gets a table.</summary> /// <param name="name">The name.</param> /// <returns>The table.</returns> public Table GetTable(string name) { string sql = sqlTables + string.Format(" AND a.rdb$relation_name ='{0}' ", name); var query = Connection.Select<Table>(sql); return query.FirstOrDefault(); } /// <summary>Gets the columns.</summary> /// <param name="tableName">Name of the table.</param> /// <returns>The columns.</returns> public List<Column> GetColumns(string tableName) { string sql = string.Format(sqlColumns.ToString(), string.IsNullOrEmpty(tableName) ? "idx.rdb$relation_name" : string.Format("'{0}'", tableName), string.IsNullOrEmpty(tableName) ? "r.rdb$relation_name" : string.Format("'{0}'", tableName)); List<Column> columns =Connection.Select<Column>(sql); List<Generador> gens = Connection.Select<Generador>(sqlGenerator.ToString()); sql = string.Format(sqlFieldGenerator.ToString(), string.IsNullOrEmpty(tableName) ? "TRIGGERS.RDB$RELATION_NAME" : string.Format("'{0}'", tableName)); List<FieldGenerator> fg = Connection.Select<FieldGenerator>(sql); foreach (var record in columns) { IEnumerable<string> query= from q in fg where q.TableName == record.TableName && q.FieldName == record.Name select q.SequenceName; if (query.Count() == 1) record.Sequence = query.First(); else { string g = (from gen in gens where gen.Name == tableName + "_" + record.Name + "_GEN" select gen.Name).FirstOrDefault(); if (!string.IsNullOrEmpty(g)) record.Sequence = g.Trim(); } } return columns; } /// <summary>Gets the columns.</summary> /// <param name="table">The table.</param> /// <returns>The columns.</returns> public List<Column> GetColumns(Table table) { return GetColumns(table.Name); } /// <summary>Gets a procedure.</summary> /// <param name="name">The name.</param> /// <returns>The procedure.</returns> public Procedure GetProcedure(string name) { string sql= sqlProcedures.ToString() + string.Format("WHERE b.rdb$procedure_name ='{0}'", name); var query = Connection.Select<Procedure>(sql); return query.FirstOrDefault(); } /// <summary>Gets the procedures.</summary> /// <value>The procedures.</value> public List<Procedure> Procedures { get { return Connection.Select<Procedure>(sqlProcedures.ToString()); } } /// <summary>Gets the parameters.</summary> /// <param name="procedure">The procedure.</param> /// <returns>The parameters.</returns> public List<Parameter> GetParameters(Procedure procedure) { return GetParameters(procedure.Name); } /// <summary>Gets the parameters.</summary> /// <param name="procedureName">Name of the procedure.</param> /// <returns>The parameters.</returns> public List<Parameter> GetParameters(string procedureName) { string sql = string.Format(sqlParameters.ToString(), string.IsNullOrEmpty(procedureName) ? "a.rdb$procedure_name" : string.Format("'{0}'", procedureName)); return Connection.Select<Parameter>(sql); } /// <summary>Initialises this object.</summary> private void Init() { sqlTables = "SELECT \n" + " trim(a.rdb$relation_name) AS name, \n" + " trim(a.rdb$owner_name) AS owner \n" + "FROM \n" + " rdb$relations a \n" + "WHERE\n" + " rdb$system_flag = 0 \n" + " AND rdb$view_blr IS NULL \n"; sqlColumns.Append("SELECT TRIM(r.rdb$field_name) AS field_name, \n"); sqlColumns.Append(" r.rdb$field_position AS field_position, \n"); sqlColumns.Append(" CASE f.rdb$field_type \n"); sqlColumns.Append(" WHEN 261 THEN " + " trim(iif(f.rdb$field_sub_type = 0,'BLOB', 'TEXT')) \n"); sqlColumns.Append(" WHEN 14 THEN trim(iif( cset.rdb$character_set_name='OCTETS'and f.rdb$field_length=16,'GUID', 'CHAR' )) \n"); //CHAR sqlColumns.Append(" WHEN 40 THEN trim('VARCHAR') \n"); //CSTRING sqlColumns.Append(" WHEN 11 THEN trim('FLOAT') \n"); //D_FLOAT sqlColumns.Append(" WHEN 27 THEN trim('DOUBLE') \n"); sqlColumns.Append(" WHEN 10 THEN trim('FLOAT') \n"); sqlColumns.Append(" WHEN 16 THEN trim(Iif(f.rdb$field_sub_type = 0, 'BIGINT', \n"); sqlColumns.Append(" Iif(f.rdb$field_sub_type = 1, 'NUMERIC', 'DECIMAL'))) \n"); sqlColumns.Append(" WHEN 8 THEN trim(Iif(f.rdb$field_sub_type = 0, 'INTEGER', \n"); sqlColumns.Append(" Iif(f.rdb$field_sub_type = 1, 'NUMERIC', 'DECIMAL'))) \n"); sqlColumns.Append(" WHEN 9 THEN trim('BIGINT') \n"); //QUAD sqlColumns.Append(" WHEN 7 THEN trim('SMALLINT') \n"); sqlColumns.Append(" WHEN 12 THEN trim('DATE') \n"); sqlColumns.Append(" WHEN 13 THEN trim('TIME') \n"); sqlColumns.Append(" WHEN 35 THEN trim('TIMESTAMP') \n"); sqlColumns.Append(" WHEN 37 THEN trim('VARCHAR') \n"); sqlColumns.Append(" ELSE trim('UNKNOWN') \n"); sqlColumns.Append(" END AS field_type, \n"); //sqlColumns.Append(" f.rdb$field_sub_type as field_subtype, \n"); sqlColumns.Append(" cast(f.rdb$field_length as smallint) AS field_length, \n"); sqlColumns.Append(" cast(Coalesce(f.rdb$field_precision, -1) as smallint) AS field_precision, \n"); sqlColumns.Append(" cast( Abs(f.rdb$field_scale) as smallint ) AS field_scale, \n"); //sqlColumns.Append(" r.rdb$default_value AS default_value, \n"); sqlColumns.Append(" Iif(Coalesce(r.rdb$null_flag, 0) = 1, 0, 1) AS nullable, \n"); sqlColumns.Append(" Coalesce(r.rdb$description, '') AS DESCRIPTION, \n"); sqlColumns.Append(" TRIM(r.rdb$relation_name) AS tablename, \n"); sqlColumns.Append(" Iif(idxs.constraint_type = 'PRIMARY KEY', 1, 0) AS is_primary_key, \n"); sqlColumns.Append(" Iif(idxs.constraint_type = 'UNIQUE', 1, 0) AS is_unique, \n"); sqlColumns.Append(" cast ('' as varchar(31) ) as SEQUENCE_NAME, \n"); sqlColumns.Append(" iif(R.RDB$UPDATE_FLAG=1,0,1) as IS_COMPUTED \n"); sqlColumns.Append("FROM rdb$relation_fields r \n"); sqlColumns.Append(" LEFT JOIN rdb$fields f \n"); sqlColumns.Append(" ON r.rdb$field_source = f.rdb$field_name \n"); sqlColumns.Append(" LEFT JOIN rdb$character_sets cset \n"); sqlColumns.Append(" ON f.rdb$character_set_id = cset.rdb$character_set_id \n"); sqlColumns.Append(" LEFT JOIN (SELECT DISTINCT rc.rdb$constraint_type AS constraint_type, \n"); sqlColumns.Append(" idxflds.rdb$field_name AS field_name \n"); sqlColumns.Append(" FROM rdb$indices idx \n"); sqlColumns.Append(" LEFT JOIN rdb$relation_constraints rc \n"); sqlColumns.Append(" ON ( idx.rdb$index_name = rc.rdb$index_name ) \n"); sqlColumns.Append(" LEFT JOIN rdb$index_segments idxflds \n"); sqlColumns.Append(" ON ( idx.rdb$index_name = idxflds.rdb$index_name ) \n"); sqlColumns.Append(" WHERE idx.rdb$relation_name = {0} \n"); sqlColumns.Append(" AND rc.rdb$constraint_type IN ( 'PRIMARY KEY', 'UNIQUE' \n"); sqlColumns.Append(" )) \n"); sqlColumns.Append(" idxs \n"); sqlColumns.Append(" ON idxs.field_name = r.rdb$field_name \n"); sqlColumns.Append("WHERE r.rdb$system_flag = '0' \n"); sqlColumns.Append(" AND r.rdb$relation_name = {1} \n"); sqlColumns.Append(" ORDER BY r.rdb$relation_name,r.rdb$field_position \n"); sqlFieldGenerator.Append("SELECT trim(TRIGGERS.RDB$RELATION_NAME) as TableName,"); sqlFieldGenerator.Append("trim(deps.rdb$field_name) AS field_name, \n"); sqlFieldGenerator.Append(" trim(deps2.rdb$depended_on_name) AS sequence_name \n"); sqlFieldGenerator.Append("FROM rdb$triggers triggers \n"); sqlFieldGenerator.Append(" JOIN rdb$dependencies deps \n"); sqlFieldGenerator.Append(" ON deps.rdb$dependent_name = triggers.rdb$trigger_name \n"); sqlFieldGenerator.Append(" AND deps.rdb$depended_on_name = triggers.rdb$relation_name \n"); sqlFieldGenerator.Append(" AND deps.rdb$dependent_type = 2 \n"); sqlFieldGenerator.Append(" AND deps.rdb$depended_on_type = 0 \n"); sqlFieldGenerator.Append(" JOIN rdb$dependencies deps2 \n"); sqlFieldGenerator.Append(" ON deps2.rdb$dependent_name = triggers.rdb$trigger_name \n"); sqlFieldGenerator.Append(" AND deps2.rdb$field_name IS NULL \n"); sqlFieldGenerator.Append(" AND deps2.rdb$dependent_type = 2 \n"); sqlFieldGenerator.Append(" AND deps2.rdb$depended_on_type = 14 \n"); sqlFieldGenerator.Append("WHERE triggers.rdb$system_flag = 0 \n"); sqlFieldGenerator.Append(" AND triggers.rdb$trigger_type = 1 \n"); sqlFieldGenerator.Append(" AND triggers.rdb$trigger_inactive = 0 \n"); sqlFieldGenerator.Append(" AND triggers.rdb$relation_name = {0} "); sqlProcedures.Append("SELECT TRIM(b.rdb$procedure_name) AS name, \n"); sqlProcedures.Append(" TRIM(b.rdb$owner_name) AS owner, \n"); sqlProcedures.Append(" cast(Coalesce(b.rdb$procedure_inputs, 0) as smallint) AS inputs, \n"); sqlProcedures.Append(" cast(Coalesce(b.rdb$procedure_outputs, 0) as smallint) AS outputs \n"); sqlProcedures.Append("FROM rdb$procedures b \n"); sqlParameters.Append("SELECT TRIM(a.rdb$procedure_name) AS procedure_name, \n"); sqlParameters.Append(" TRIM(a.rdb$parameter_name) AS parameter_name, \n"); sqlParameters.Append(" CAST(a.rdb$parameter_number AS SMALLINT) AS parameter_number \n"); sqlParameters.Append(" , \n"); sqlParameters.Append(" CAST(a.rdb$parameter_type AS SMALLINT) AS \n"); sqlParameters.Append(" parameter_type, \n"); sqlParameters.Append(" TRIM(t.rdb$type_name) AS field_type, \n"); sqlParameters.Append(" CAST(b.rdb$field_length AS SMALLINT) AS field_length, \n"); sqlParameters.Append(" CAST(Coalesce(b.rdb$field_precision, -1) AS SMALLINT) AS field_precision, \n"); sqlParameters.Append(" CAST(b.rdb$field_scale AS SMALLINT) AS field_scale \n"); //sqlParameters.Append(" --b.rdb$field_type AS field_type, \n"); //sqlParameters.Append(" --b.rdb$field_sub_type AS field_sub_type, \n"); sqlParameters.Append("FROM rdb$procedure_parameters a \n"); sqlParameters.Append(" JOIN rdb$fields b \n"); sqlParameters.Append(" ON b.rdb$field_name = a.rdb$field_source \n"); sqlParameters.Append(" JOIN rdb$types t \n"); sqlParameters.Append(" ON t.rdb$type = b.rdb$field_type \n"); sqlParameters.Append("WHERE t.rdb$field_name = 'RDB$FIELD_TYPE' \n"); sqlParameters.Append(" AND a.rdb$procedure_name = {0} \n"); sqlParameters.Append("ORDER BY a.rdb$procedure_name, \n"); sqlParameters.Append(" a.rdb$parameter_type, \n"); sqlParameters.Append(" a.rdb$parameter_number "); sqlGenerator.Append("SELECT trim(RDB$GENERATOR_NAME) AS \"Name\" FROM RDB$GENERATORS"); } /// <summary>A field generator.</summary> private class FieldGenerator { /// <summary>Gets or sets the name of the table.</summary> /// <value>The name of the table.</value> [Alias("TABLENAME")] public string TableName { get; set; } /// <summary>Gets or sets the name of the field.</summary> /// <value>The name of the field.</value> [Alias("FIELD_NAME")] public string FieldName { get; set; } /// <summary>Gets or sets the name of the sequence.</summary> /// <value>The name of the sequence.</value> [Alias("SEQUENCE_NAME")] public string SequenceName { get; set; } } /// <summary>A generador.</summary> private class Generador{ /// <summary>Gets or sets the name.</summary> /// <value>The name.</value> public string Name { get; set;} } } } /*ID--0--False--2 -- SMALLINT-- System.Int16-- NAME--1--False--60 -- VARCHAR-- System.String-- PASSWORD--2--False--30 -- VARCHAR-- System.String-- FULL_NAME--3--True--60 -- VARCHAR-- System.String-- COL1--4--False--2 -- VARCHAR-- System.String-- COL2--5--False--2 -- VARCHAR-- System.String-- COL3--6--False--2 -- VARCHAR-- System.String-- COL4--7--True--4 -- NUMERIC-- System.Nullable`1[System.Decimal]-- COL5--8--True--4 -- FLOAT-- System.Nullable`1[System.Single]-- COL6--9--True--4 -- INTEGER-- System.Nullable`1[System.Int32]-- COL7--10--True--8 -- DOUBLE-- System.Nullable`1[System.Double]-- COL8--11--True--8 -- BIGINT-- System.Nullable`1[System.Int64]-- COL9--12--True--4 -- DATE-- System.Nullable`1[System.DateTime]-- COL10--13--True--8 -- TIMESTAMP-- System.Nullable`1[System.DateTime]-- COL11--14--True--8 -- BLOB-- System.Nullable`1[System.Byte][]-- COLNUM--15--True--8 -- NUMERIC-- System.Nullable`1[System.Decimal]-- COLDECIMAL--16--True--8 -- DECIMAL-- System.Nullable`1[System.Decimal]-- -------------------------------------------- Columns for EMPLOYEE: EMP_NO--0--False--2 -- SMALLINT-- System.Int16--EMP_NO_GEN FIRST_NAME--1--False--15 -- VARCHAR-- System.String-- LAST_NAME--2--False--20 -- VARCHAR-- System.String-- PHONE_EXT--3--True--4 -- VARCHAR-- System.String-- HIRE_DATE--4--False--8 -- TIMESTAMP-- System.DateTime-- DEPT_NO--5--False--3 -- CHAR-- System.String-- JOB_CODE--6--False--5 -- VARCHAR-- System.String-- JOB_GRADE--7--False--2 -- SMALLINT-- System.Int16-- JOB_COUNTRY--8--False--15 -- VARCHAR-- System.String-- SALARY--9--False--8 -- NUMERIC-- System.Decimal-- FULL_NAME--10--True--37 -- VARCHAR-- System.String-- Caculado !!!!! Computed True ID--0--False--4 -- INTEGER-- System.Int32--COMPANY_ID_GEN NAME--1--True--100 -- VARCHAR-- System.String-- TURNOVER--2--True--4 -- FLOAT-- System.Nullable`1[System.Single]-- STARTED--3--True--4 -- DATE-- System.Nullable`1[System.DateTime]-- EMPLOYEES--4--True--4 -- INTEGER-- System.Nullable`1[System.Int32]-- CREATED_DATE--5--True--8 -- TIMESTAMP-- System.Nullable`1[System.DateTime]-- GUID--6--True--16 -- GUID-- System.Nullable`1[System.Guid]-- * * * */
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// An Azure Batch job. /// </summary> public partial class CloudJob : ITransportObjectProvider<Models.JobAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<IList<EnvironmentSetting>> CommonEnvironmentSettingsProperty; public readonly PropertyAccessor<JobConstraints> ConstraintsProperty; public readonly PropertyAccessor<DateTime?> CreationTimeProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<string> ETagProperty; public readonly PropertyAccessor<JobExecutionInformation> ExecutionInformationProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<JobManagerTask> JobManagerTaskProperty; public readonly PropertyAccessor<JobPreparationTask> JobPreparationTaskProperty; public readonly PropertyAccessor<JobReleaseTask> JobReleaseTaskProperty; public readonly PropertyAccessor<DateTime?> LastModifiedProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<Common.OnAllTasksComplete?> OnAllTasksCompleteProperty; public readonly PropertyAccessor<Common.OnTaskFailure?> OnTaskFailureProperty; public readonly PropertyAccessor<PoolInformation> PoolInformationProperty; public readonly PropertyAccessor<Common.JobState?> PreviousStateProperty; public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty; public readonly PropertyAccessor<int?> PriorityProperty; public readonly PropertyAccessor<Common.JobState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<JobStatistics> StatisticsProperty; public readonly PropertyAccessor<string> UrlProperty; public readonly PropertyAccessor<bool?> UsesTaskDependenciesProperty; public PropertyContainer() : base(BindingState.Unbound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("CommonEnvironmentSettings", BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor<JobConstraints>("Constraints", BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>("CreationTime", BindingAccess.None); this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write); this.ETagProperty = this.CreatePropertyAccessor<string>("ETag", BindingAccess.None); this.ExecutionInformationProperty = this.CreatePropertyAccessor<JobExecutionInformation>("ExecutionInformation", BindingAccess.None); this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write); this.JobManagerTaskProperty = this.CreatePropertyAccessor<JobManagerTask>("JobManagerTask", BindingAccess.Read | BindingAccess.Write); this.JobPreparationTaskProperty = this.CreatePropertyAccessor<JobPreparationTask>("JobPreparationTask", BindingAccess.Read | BindingAccess.Write); this.JobReleaseTaskProperty = this.CreatePropertyAccessor<JobReleaseTask>("JobReleaseTask", BindingAccess.Read | BindingAccess.Write); this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>("LastModified", BindingAccess.None); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>("Metadata", BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor<Common.OnAllTasksComplete?>("OnAllTasksComplete", BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor<Common.OnTaskFailure?>("OnTaskFailure", BindingAccess.Read | BindingAccess.Write); this.PoolInformationProperty = this.CreatePropertyAccessor<PoolInformation>("PoolInformation", BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor<Common.JobState?>("PreviousState", BindingAccess.None); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("PreviousStateTransitionTime", BindingAccess.None); this.PriorityProperty = this.CreatePropertyAccessor<int?>("Priority", BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor<Common.JobState?>("State", BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("StateTransitionTime", BindingAccess.None); this.StatisticsProperty = this.CreatePropertyAccessor<JobStatistics>("Statistics", BindingAccess.None); this.UrlProperty = this.CreatePropertyAccessor<string>("Url", BindingAccess.None); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor<bool?>("UsesTaskDependencies", BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.CloudJob protocolObject) : base(BindingState.Bound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor( EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.CommonEnvironmentSettings), "CommonEnvironmentSettings", BindingAccess.Read); this.ConstraintsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new JobConstraints(o)), "Constraints", BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor( protocolObject.CreationTime, "CreationTime", BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, "DisplayName", BindingAccess.Read); this.ETagProperty = this.CreatePropertyAccessor( protocolObject.ETag, "ETag", BindingAccess.Read); this.ExecutionInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new JobExecutionInformation(o).Freeze()), "ExecutionInformation", BindingAccess.Read); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, "Id", BindingAccess.Read); this.JobManagerTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobManagerTask, o => new JobManagerTask(o).Freeze()), "JobManagerTask", BindingAccess.Read); this.JobPreparationTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobPreparationTask, o => new JobPreparationTask(o).Freeze()), "JobPreparationTask", BindingAccess.Read); this.JobReleaseTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobReleaseTask, o => new JobReleaseTask(o).Freeze()), "JobReleaseTask", BindingAccess.Read); this.LastModifiedProperty = this.CreatePropertyAccessor( protocolObject.LastModified, "LastModified", BindingAccess.Read); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), "Metadata", BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnAllTasksComplete, Common.OnAllTasksComplete>(protocolObject.OnAllTasksComplete), "OnAllTasksComplete", BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnTaskFailure, Common.OnTaskFailure>(protocolObject.OnTaskFailure), "OnTaskFailure", BindingAccess.Read); this.PoolInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PoolInfo, o => new PoolInformation(o)), "PoolInformation", BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.PreviousState), "PreviousState", BindingAccess.Read); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.PreviousStateTransitionTime, "PreviousStateTransitionTime", BindingAccess.Read); this.PriorityProperty = this.CreatePropertyAccessor( protocolObject.Priority, "Priority", BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.State), "State", BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, "StateTransitionTime", BindingAccess.Read); this.StatisticsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new JobStatistics(o).Freeze()), "Statistics", BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, "Url", BindingAccess.Read); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor( protocolObject.UsesTaskDependencies, "UsesTaskDependencies", BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CloudJob"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> internal CloudJob( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } internal CloudJob( BatchClient parentBatchClient, Models.CloudJob protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="CloudJob"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region CloudJob /// <summary> /// Gets or sets a list of common environment variable settings. These environment variables are set for all tasks /// in this <see cref="CloudJob"/> (including the Job Manager, Job Preparation and Job Release tasks). /// </summary> public IList<EnvironmentSetting> CommonEnvironmentSettings { get { return this.propertyContainer.CommonEnvironmentSettingsProperty.Value; } set { this.propertyContainer.CommonEnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the execution constraints for the job. /// </summary> public JobConstraints Constraints { get { return this.propertyContainer.ConstraintsProperty.Value; } set { this.propertyContainer.ConstraintsProperty.Value = value; } } /// <summary> /// Gets the creation time of the job. /// </summary> public DateTime? CreationTime { get { return this.propertyContainer.CreationTimeProperty.Value; } } /// <summary> /// Gets or sets the display name of the job. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets the ETag for the job. /// </summary> public string ETag { get { return this.propertyContainer.ETagProperty.Value; } } /// <summary> /// Gets the execution information for the job. /// </summary> public JobExecutionInformation ExecutionInformation { get { return this.propertyContainer.ExecutionInformationProperty.Value; } } /// <summary> /// Gets or sets the id of the job. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets the Job Manager task. The Job Manager task is launched when the <see cref="CloudJob"/> is started. /// </summary> public JobManagerTask JobManagerTask { get { return this.propertyContainer.JobManagerTaskProperty.Value; } set { this.propertyContainer.JobManagerTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Preparation task. The Batch service will run the Job Preparation task on a compute node /// before starting any tasks of that job on that compute node. /// </summary> public JobPreparationTask JobPreparationTask { get { return this.propertyContainer.JobPreparationTaskProperty.Value; } set { this.propertyContainer.JobPreparationTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Release task. The Batch service runs the Job Release task when the job ends, on each compute /// node where any task of the job has run. /// </summary> public JobReleaseTask JobReleaseTask { get { return this.propertyContainer.JobReleaseTaskProperty.Value; } set { this.propertyContainer.JobReleaseTaskProperty.Value = value; } } /// <summary> /// Gets the last modified time of the job. /// </summary> public DateTime? LastModified { get { return this.propertyContainer.LastModifiedProperty.Value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the job as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the action the Batch service should take when all tasks in the job are in the <see cref="Common.JobState.Completed"/> /// state. /// </summary> public Common.OnAllTasksComplete? OnAllTasksComplete { get { return this.propertyContainer.OnAllTasksCompleteProperty.Value; } set { this.propertyContainer.OnAllTasksCompleteProperty.Value = value; } } /// <summary> /// Gets or sets the action the Batch service should take when any task in the job fails. /// </summary> /// <remarks> /// A task is considered to have failed if it completes with a non-zero exit code and has exhausted its retry count, /// or if it had a scheduling error. /// </remarks> public Common.OnTaskFailure? OnTaskFailure { get { return this.propertyContainer.OnTaskFailureProperty.Value; } set { this.propertyContainer.OnTaskFailureProperty.Value = value; } } /// <summary> /// Gets or sets the pool on which the Batch service runs the job's tasks. /// </summary> public PoolInformation PoolInformation { get { return this.propertyContainer.PoolInformationProperty.Value; } set { this.propertyContainer.PoolInformationProperty.Value = value; } } /// <summary> /// Gets the previous state of the job. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousState property is not defined. /// </remarks> public Common.JobState? PreviousState { get { return this.propertyContainer.PreviousStateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its previous state. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousStateTransitionTime property /// is not defined. /// </remarks> public DateTime? PreviousStateTransitionTime { get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; } } /// <summary> /// Gets or sets the priority of the job. Priority values can range from -1000 to 1000, with -1000 being the lowest /// priority and 1000 being the highest priority. /// </summary> /// <remarks> /// The default value is 0. /// </remarks> public int? Priority { get { return this.propertyContainer.PriorityProperty.Value; } set { this.propertyContainer.PriorityProperty.Value = value; } } /// <summary> /// Gets the current state of the job. /// </summary> public Common.JobState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets resource usage statistics for the entire lifetime of the job. /// </summary> /// <remarks> /// This property is populated only if the <see cref="CloudJob"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/> /// including the 'stats' attribute; otherwise it is null. /// </remarks> public JobStatistics Statistics { get { return this.propertyContainer.StatisticsProperty.Value; } } /// <summary> /// Gets the URL of the job. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } /// <summary> /// Gets or sets whether tasks in the job can define dependencies on each other. /// </summary> /// <remarks> /// The default value is false. /// </remarks> public bool? UsesTaskDependencies { get { return this.propertyContainer.UsesTaskDependenciesProperty.Value; } set { this.propertyContainer.UsesTaskDependenciesProperty.Value = value; } } #endregion // CloudJob #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.JobAddParameter ITransportObjectProvider<Models.JobAddParameter>.GetTransportObject() { Models.JobAddParameter result = new Models.JobAddParameter() { CommonEnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.CommonEnvironmentSettings), Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, Id = this.Id, JobManagerTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobManagerTask, (o) => o.GetTransportObject()), JobPreparationTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobPreparationTask, (o) => o.GetTransportObject()), JobReleaseTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobReleaseTask, (o) => o.GetTransportObject()), Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), OnAllTasksComplete = UtilitiesInternal.MapNullableEnum<Common.OnAllTasksComplete, Models.OnAllTasksComplete>(this.OnAllTasksComplete), OnTaskFailure = UtilitiesInternal.MapNullableEnum<Common.OnTaskFailure, Models.OnTaskFailure>(this.OnTaskFailure), PoolInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.PoolInformation, (o) => o.GetTransportObject()), Priority = this.Priority, UsesTaskDependencies = this.UsesTaskDependencies, }; return result; } #endregion // Internal/private methods } }
using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using umbraco.DataLayer; using System.Collections.Generic; using System.Reflection; using umbraco.BusinessLogic.Utils; namespace umbraco.BusinessLogic { /// <summary> /// Summary description for Log. /// </summary> public class Log { #region Statics private Interfaces.ILog _externalLogger; private bool _externalLoggerInitiated; internal Interfaces.ILog ExternalLogger { get { if (_externalLoggerInitiated == false) { _externalLoggerInitiated = true; if (string.IsNullOrEmpty(UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerAssembly) == false && string.IsNullOrEmpty(UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerType) == false) { try { var assemblyPath = IOHelper.MapPath(UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerAssembly); _externalLogger = Assembly.LoadFrom(assemblyPath).CreateInstance(UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerType) as Interfaces.ILog; } catch (Exception ee) { LogHelper.Error<Log>("Error loading external logger", ee); } } } return _externalLogger; } } #region Singleton public static Log Instance { get { return Singleton<Log>.Instance; } } #endregion /// <summary> /// Adds the specified log item to the log. /// </summary> /// <param name="type">The log type.</param> /// <param name="user">The user adding the item.</param> /// <param name="nodeId">The affected node id.</param> /// <param name="comment">Comment.</param> public static void Add(LogTypes type, User user, int nodeId, string comment) { if (Instance.ExternalLogger != null) { Instance.ExternalLogger.Add(type, user, nodeId, comment); if (UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerEnableAuditTrail == false) { AddLocally(type, user, nodeId, comment); } } else { if (UmbracoConfig.For.UmbracoSettings().Logging.EnableLogging == false) return; if (UmbracoConfig.For.UmbracoSettings().Logging.DisabledLogTypes.Any(x => x.LogTypeAlias.InvariantEquals(type.ToString())) == false) { if (comment != null && comment.Length > 3999) comment = comment.Substring(0, 3955) + "..."; if (UmbracoConfig.For.UmbracoSettings().Logging.EnableAsyncLogging) { ThreadPool.QueueUserWorkItem( delegate { AddSynced(type, user == null ? 0 : user.Id, nodeId, comment); }); return; } AddSynced(type, user == null ? 0 : user.Id, nodeId, comment); } } } [Obsolete("Use LogHelper to log exceptions/errors")] public void AddException(Exception ee) { if (ExternalLogger != null) { ExternalLogger.Add(ee); } else { var ex2 = ee; while (ex2 != null) { ex2 = ex2.InnerException; } LogHelper.Error<Log>("An error occurred", ee); } } /// <summary> /// Adds the specified log item to the Umbraco log no matter if an external logger has been defined. /// </summary> /// <param name="type">The log type.</param> /// <param name="user">The user adding the item.</param> /// <param name="nodeId">The affected node id.</param> /// <param name="comment">Comment.</param> public static void AddLocally(LogTypes type, User user, int nodeId, string comment) { if (comment.Length > 3999) comment = comment.Substring(0, 3955) + "..."; if (UmbracoConfig.For.UmbracoSettings().Logging.EnableAsyncLogging) { ThreadPool.QueueUserWorkItem( delegate { AddSynced(type, user == null ? 0 : user.Id, nodeId, comment); }); return; } AddSynced(type, user == null ? 0 : user.Id, nodeId, comment); } /// <summary> /// Adds the specified log item to the log without any user information attached. /// </summary> /// <param name="type">The log type.</param> /// <param name="nodeId">The affected node id.</param> /// <param name="comment">Comment.</param> public static void Add(LogTypes type, int nodeId, string comment) { Add(type, null, nodeId, comment); } /// <summary> /// Adds a log item to the log immidiately instead of Queuing it as a work item. /// </summary> /// <param name="type">The type.</param> /// <param name="userId">The user id.</param> /// <param name="nodeId">The node id.</param> /// <param name="comment">The comment.</param> public static void AddSynced(LogTypes type, int userId, int nodeId, string comment) { var logTypeIsAuditType = type.GetType().GetField(type.ToString()).GetCustomAttributes(typeof(AuditTrailLogItem), true).Length != 0; if (logTypeIsAuditType) { try { using (var sqlHelper = Application.SqlHelper) sqlHelper.ExecuteNonQuery( "insert into umbracoLog (userId, nodeId, logHeader, logComment) values (@userId, @nodeId, @logHeader, @comment)", sqlHelper.CreateParameter("@userId", userId), sqlHelper.CreateParameter("@nodeId", nodeId), sqlHelper.CreateParameter("@logHeader", type.ToString()), sqlHelper.CreateParameter("@comment", comment)); } catch (Exception e) { LogHelper.Error<Log>("An error occurred adding an audit trail log to the umbracoLog table", e); } //Because 'Custom' log types are also Audit trail (for some wacky reason) but we also want these logged normally so we have to check for this: if (type != LogTypes.Custom) { return; } } //if we've made it this far it means that the log type is not an audit trail log or is a custom log. LogHelper.Info<Log>( "Redirected log call (please use Umbraco.Core.Logging.LogHelper instead of umbraco.BusinessLogic.Log) | Type: {0} | User: {1} | NodeId: {2} | Comment: {3}", () => type.ToString(), () => userId, () => nodeId.ToString(CultureInfo.InvariantCulture), () => comment); } public List<LogItem> GetAuditLogItems(int NodeId) { if (UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerEnableAuditTrail && ExternalLogger != null) return ExternalLogger.GetAuditLogReader(NodeId); using (var sqlHelper = Application.SqlHelper) return LogItem.ConvertIRecordsReader(sqlHelper.ExecuteReader( "select userId, nodeId, logHeader, DateStamp, logComment from umbracoLog where nodeId = @id and logHeader not in ('open','system') order by DateStamp desc", sqlHelper.CreateParameter("@id", NodeId))); } public List<LogItem> GetLogItems(LogTypes type, DateTime sinceDate) { if (ExternalLogger != null) return ExternalLogger.GetLogItems(type, sinceDate); using (var sqlHelper = Application.SqlHelper) return LogItem.ConvertIRecordsReader(sqlHelper.ExecuteReader( "select userId, NodeId, DateStamp, logHeader, logComment from umbracoLog where logHeader = @logHeader and DateStamp >= @dateStamp order by dateStamp desc", sqlHelper.CreateParameter("@logHeader", type.ToString()), sqlHelper.CreateParameter("@dateStamp", sinceDate))); } public List<LogItem> GetLogItems(int nodeId) { if (ExternalLogger != null) return ExternalLogger.GetLogItems(nodeId); using (var sqlHelper = Application.SqlHelper) return LogItem.ConvertIRecordsReader(sqlHelper.ExecuteReader( "select userId, NodeId, DateStamp, logHeader, logComment from umbracoLog where id = @id order by dateStamp desc", sqlHelper.CreateParameter("@id", nodeId))); } public List<LogItem> GetLogItems(User user, DateTime sinceDate) { if (ExternalLogger != null) return ExternalLogger.GetLogItems(user, sinceDate); using (var sqlHelper = Application.SqlHelper) return LogItem.ConvertIRecordsReader(sqlHelper.ExecuteReader( "select userId, NodeId, DateStamp, logHeader, logComment from umbracoLog where UserId = @user and DateStamp >= @dateStamp order by dateStamp desc", sqlHelper.CreateParameter("@user", user.Id), sqlHelper.CreateParameter("@dateStamp", sinceDate))); } public List<LogItem> GetLogItems(User user, LogTypes type, DateTime sinceDate) { if (ExternalLogger != null) return ExternalLogger.GetLogItems(user, type, sinceDate); using (var sqlHelper = Application.SqlHelper) return LogItem.ConvertIRecordsReader(sqlHelper.ExecuteReader( "select userId, NodeId, DateStamp, logHeader, logComment from umbracoLog where UserId = @user and logHeader = @logHeader and DateStamp >= @dateStamp order by dateStamp desc", sqlHelper.CreateParameter("@logHeader", type.ToString()), sqlHelper.CreateParameter("@user", user.Id), sqlHelper.CreateParameter("@dateStamp", sinceDate))); } public static void CleanLogs(int maximumAgeOfLogsInMinutes) { if (Instance.ExternalLogger != null) Instance.ExternalLogger.CleanLogs(maximumAgeOfLogsInMinutes); else { try { DateTime oldestPermittedLogEntry = DateTime.Now.Subtract(new TimeSpan(0, maximumAgeOfLogsInMinutes, 0)); var formattedDate = oldestPermittedLogEntry.ToString("yyyy-MM-dd HH:mm:ss"); using (var sqlHelper = Application.SqlHelper) sqlHelper.ExecuteNonQuery("delete from umbracoLog where datestamp < @oldestPermittedLogEntry and logHeader in ('open','system')", sqlHelper.CreateParameter("@oldestPermittedLogEntry", oldestPermittedLogEntry)); LogHelper.Info<Log>(string.Format("Log scrubbed. Removed all items older than {0}", formattedDate)); } catch (Exception e) { Debug.WriteLine(e.ToString(), "Error"); Trace.WriteLine(e.ToString()); } } } #region New GetLog methods - DataLayer layer compatible /// <summary> /// Gets a reader for the audit log. /// </summary> /// <param name="NodeId">The node id.</param> /// <returns>A reader for the audit log.</returns> [Obsolete("Use the Instance.GetAuditLogItems method which return a list of LogItems instead")] public static IRecordsReader GetAuditLogReader(int NodeId) { using (var sqlHelper = Application.SqlHelper) return sqlHelper.ExecuteReader( "select u.userName as [User], logHeader as Action, DateStamp as Date, logComment as Comment from umbracoLog inner join umbracoUser u on u.id = userId where nodeId = @id and logHeader not in ('open','system') order by DateStamp desc", sqlHelper.CreateParameter("@id", NodeId)); } /// <summary> /// Gets a reader for the log for the specified types. /// </summary> /// <param name="Type">The type of log message.</param> /// <param name="SinceDate">The start date.</param> /// <returns>A reader for the log.</returns> [Obsolete("Use the Instance.GetLogItems method which return a list of LogItems instead")] public static IRecordsReader GetLogReader(LogTypes Type, DateTime SinceDate) { using (var sqlHelper = Application.SqlHelper) return sqlHelper.ExecuteReader( "select userId, NodeId, DateStamp, logHeader, logComment from umbracoLog where logHeader = @logHeader and DateStamp >= @dateStamp order by dateStamp desc", sqlHelper.CreateParameter("@logHeader", Type.ToString()), sqlHelper.CreateParameter("@dateStamp", SinceDate)); } /// <summary> /// Gets a reader for the log of the specified node. /// </summary> /// <param name="NodeId">The node id.</param> /// <returns>A reader for the log.</returns> [Obsolete("Use the Instance.GetLogItems method which return a list of LogItems instead")] public static IRecordsReader GetLogReader(int NodeId) { using (var sqlHelper = Application.SqlHelper) return sqlHelper.ExecuteReader( "select u.userName, DateStamp, logHeader, logComment from umbracoLog inner join umbracoUser u on u.id = userId where nodeId = @id", sqlHelper.CreateParameter("@id", NodeId)); } /// <summary> /// Gets a reader for the log for the specified user. /// </summary> /// <param name="user">The user.</param> /// <param name="SinceDate">The start date.</param> /// <returns>A reader for the log.</returns> [Obsolete("Use the Instance.GetLogItems method which return a list of LogItems instead")] public static IRecordsReader GetLogReader(User user, DateTime SinceDate) { using (var sqlHelper = Application.SqlHelper) return sqlHelper.ExecuteReader( "select userId, NodeId, DateStamp, logHeader, logComment from umbracoLog where UserId = @user and DateStamp >= @dateStamp order by dateStamp desc", sqlHelper.CreateParameter("@user", user.Id), sqlHelper.CreateParameter("@dateStamp", SinceDate)); } /// <summary> /// Gets a reader of specific for the log for specific types and a specified user. /// </summary> /// <param name="user">The user.</param> /// <param name="Type">The type of log message.</param> /// <param name="SinceDate">The since date.</param> /// <returns>A reader for the log.</returns> [Obsolete("Use the Instance.GetLogItems method which return a list of LogItems instead")] public static IRecordsReader GetLogReader(User user, LogTypes Type, DateTime SinceDate) { using (var sqlHelper = Application.SqlHelper) return sqlHelper.ExecuteReader( "select userId, NodeId, DateStamp, logHeader, logComment from umbracoLog where UserId = @user and logHeader = @logHeader and DateStamp >= @dateStamp order by dateStamp desc", sqlHelper.CreateParameter("@logHeader", Type.ToString()), sqlHelper.CreateParameter("@user", user.Id), sqlHelper.CreateParameter("@dateStamp", SinceDate)); } /// <summary> /// Gets a reader of specific for the log for specific types and a specified user. /// </summary> /// <param name="user">The user.</param> /// <param name="type">The type of log message.</param> /// <param name="sinceDate">The since date.</param> /// <param name="numberOfResults">Number of rows returned</param> /// <returns>A reader for the log.</returns> [Obsolete("Use the Instance.GetLogItems method which return a list of LogItems instead")] internal static IRecordsReader GetLogReader(User user, LogTypes type, DateTime sinceDate, int numberOfResults) { var query = "select {0} userId, NodeId, DateStamp, logHeader, logComment from umbracoLog where UserId = @user and logHeader = @logHeader and DateStamp >= @dateStamp order by dateStamp desc {1}"; query = ApplicationContext.Current.DatabaseContext.DatabaseProvider == DatabaseProviders.MySql ? string.Format(query, string.Empty, "limit 0," + numberOfResults) : string.Format(query, "top " + numberOfResults, string.Empty); using (var sqlHelper = Application.SqlHelper) return sqlHelper.ExecuteReader(query, sqlHelper.CreateParameter("@logHeader", type.ToString()), sqlHelper.CreateParameter("@user", user.Id), sqlHelper.CreateParameter("@dateStamp", sinceDate)); } #endregion #endregion } public class LogItem { public int UserId { get; set; } public int NodeId { get; set; } public DateTime Timestamp { get; set; } public LogTypes LogType { get; set; } public string Comment { get; set; } public LogItem() { } public LogItem(int userId, int nodeId, DateTime timestamp, LogTypes logType, string comment) { UserId = userId; NodeId = nodeId; Timestamp = timestamp; LogType = logType; Comment = comment; } public static List<LogItem> ConvertIRecordsReader(IRecordsReader reader) { var items = new List<LogItem>(); while (reader.Read()) { items.Add(new LogItem( reader.GetInt("userId"), reader.GetInt("nodeId"), reader.GetDateTime("DateStamp"), ConvertLogHeader(reader.GetString("logHeader")), reader.GetString("logComment"))); } reader.Close(); reader.Dispose(); return items; } private static LogTypes ConvertLogHeader(string logHeader) { try { return (LogTypes)Enum.Parse(typeof(LogTypes), logHeader, true); } catch { return LogTypes.Custom; } } } public class AuditTrailLogItem : Attribute { } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data.SimpleDB; using System.Data; namespace Halcyon.Data.Inventory.MySQL { /// <summary> /// A MySQL interface for the inventory server /// </summary> public class MysqlStorageImpl { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); ConnectionFactory _connFactory; private string _connectString; public MysqlStorageImpl(string connStr) { _connectString = connStr; _connFactory = new ConnectionFactory("MySQL", _connectString); } public InventoryFolderBase findUserFolderForType(UUID owner, int typeId) { InventoryFolderBase rootFolder = getUserRootFolder(owner); if (typeId == 8) // by convention, this means root folder return rootFolder; string query = "SELECT * FROM inventoryfolders WHERE agentID = ?agentId AND type = ?type and parentFolderId = ?parent;"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?agentId", owner); parms.Add("?type", typeId); parms.Add("?parent", rootFolder.ID); try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { if (reader.Read()) { // A null item (because something went wrong) breaks everything in the folder InventoryFolderBase folder = readInventoryFolder(reader); folder.Level = InventoryFolderBase.FolderLevel.TopLevel; return folder; } else { // m_log.WarnFormat("[Inventory]: findUserFolderForType folder for type {0} not found.", typeId); return null; } } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Returns the folder info for the given folder, or null if one could not be found. /// </summary> /// <param name="userId"></param> /// <param name="type"></param> /// <returns></returns> public InventoryFolderBase findFolder(UUID owner, UUID folderID) { string query = "SELECT * FROM inventoryfolders WHERE agentID = ?agentId AND folderId = ?folderId;"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?agentId", owner); parms.Add("?folderId", folderID); try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { if (reader.Read()) { // A null item (because something went wrong) breaks everything in the folder return readInventoryFolder(reader); } else { m_log.WarnFormat("[Inventory]: findUserTopLevelFolderFor: No top-level folders."); return null; } } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Works its way up the parentage and returns the most top-level folder for the given folder, or null if one could not be found. /// </summary> /// <param name="userId"></param> /// <param name="type"></param> /// <returns></returns> public InventoryFolderBase findUserTopLevelFolderFor(UUID owner, UUID folderID) { InventoryFolderBase rootFolder = getUserRootFolder(owner); if (folderID == rootFolder.ID) return rootFolder; InventoryFolderBase folder = findFolder(owner, folderID); while (folder != null) { InventoryFolderBase parentFolder = findFolder(owner, folder.ParentID); if (parentFolder == null) return null; if (parentFolder.ID == rootFolder.ID) { folder.Level = InventoryFolderBase.FolderLevel.TopLevel; return folder; } // walk up the parentage chain folder = findFolder(owner, folder.ParentID); } return null; // top-level folder not found } /// <summary> /// Returns a list of items in the given folders /// </summary> /// <param name="folders"></param> /// <returns></returns> public List<InventoryItemBase> getItemsInFolders(IEnumerable<InventoryFolderBase> folders) { string inList = String.Empty; foreach (InventoryFolderBase folder in folders) { if (!String.IsNullOrEmpty(inList)) inList += ","; inList += "'" + folder.ID.ToString() + "'"; } if (String.IsNullOrEmpty(inList)) return new List<InventoryItemBase>(); string query = "SELECT * FROM inventoryitems WHERE parentFolderID IN (" + inList + ");"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (IDataReader reader = conn.QueryAndUseReader(query)) { List<InventoryItemBase> items = new List<InventoryItemBase>(); while (reader.Read()) { // A null item (because something went wrong) breaks everything in the folder InventoryItemBase item = readInventoryItem(reader); if (item != null) { items.Add(item); } } return items; } } } catch (Exception e) { m_log.Error(e.ToString()); return new List<InventoryItemBase>(); } } /// <summary> /// Returns a list of items in a specified folder /// </summary> /// <param name="folderID">The folder to search</param> /// <returns>A list containing inventory items</returns> public List<InventoryItemBase> getInventoryInFolder(UUID folderID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", folderID.ToString()); List<InventoryItemBase> items = new List<InventoryItemBase>(); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { while (reader.Read()) { // A null item (because something went wrong) breaks everything in the folder InventoryItemBase item = readInventoryItem(reader); if (item != null) { items.Add(item); } } } return items; } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Returns a list of the root folders within a users inventory (folders that only have the root as their parent) /// </summary> /// <param name="user">The user whos inventory is to be searched</param> /// <returns>A list of folder objects</returns> public List<InventoryFolderBase> getUserRootFolders(UUID user, UUID root) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?root AND agentID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", user.ToString()); parms.Add("?root", root.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { List<InventoryFolderBase> items = new List<InventoryFolderBase>(); while (reader.Read()) items.Add(readInventoryFolder(reader)); return items; } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// see <see cref="InventoryItemBase.getUserRootFolder"/> /// </summary> /// <param name="user">The user UUID</param> /// <returns></returns> public InventoryFolderBase getUserRootFolder(UUID user) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", user.ToString()); parms.Add("?zero", UUID.Zero.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { List<InventoryFolderBase> items = new List<InventoryFolderBase>(); while (reader.Read()) items.Add(readInventoryFolder(reader)); InventoryFolderBase rootFolder = null; // There should only ever be one root folder for a user. However, if there's more // than one we'll simply use the first one rather than failing. It would be even // nicer to print some message to this effect, but this feels like it's too low a // to put such a message out, and it's too minor right now to spare the time to // suitably refactor. if (items.Count > 0) { rootFolder = items[0]; } rootFolder.Level = InventoryFolderBase.FolderLevel.Root; return rootFolder; } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Return a list of folders in a users inventory contained within the specified folder. /// This method is only used in tests - in normal operation the user always have one, /// and only one, root folder. /// </summary> /// <param name="parentID">The folder to search</param> /// <returns>A list of inventory folders</returns> public List<InventoryFolderBase> getInventoryFolders(UUID parentID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", parentID.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { List<InventoryFolderBase> items = new List<InventoryFolderBase>(); while (reader.Read()) { InventoryFolderBase folder = readInventoryFolder(reader); items.Add(folder); } return items; } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Reads a one item from an SQL result /// </summary> /// <param name="reader">The SQL Result</param> /// <returns>the item read</returns> private static InventoryItemBase readInventoryItem(IDataReader reader) { try { InventoryItemBase item = new InventoryItemBase(); // TODO: this is to handle a case where NULLs creep in there, which we are not sure is indemic to the system, or legacy. It would be nice to live fix these. if (reader["creatorID"] == null) { item.CreatorId = UUID.Zero.ToString(); } else { item.CreatorId = (string)reader["creatorID"]; } // Be a bit safer in parsing these because the // database doesn't enforce them to be not null, and // the inventory still works if these are weird in the // db UUID Owner = UUID.Zero; UUID GroupID = UUID.Zero; UUID.TryParse(Convert.ToString(reader["avatarID"]), out Owner); UUID.TryParse(Convert.ToString(reader["groupID"]), out GroupID); item.Owner = Owner; item.GroupID = GroupID; // Rest of the parsing. If these UUID's fail, we're dead anyway item.ID = new UUID(Convert.ToString(reader["inventoryID"])); item.AssetID = new UUID(Convert.ToString(reader["assetID"])); item.AssetType = (int)reader["assetType"]; item.Folder = new UUID(Convert.ToString(reader["parentFolderID"])); item.Name = (string)reader["inventoryName"]; item.Description = (string)reader["inventoryDescription"]; item.NextPermissions = (uint)reader["inventoryNextPermissions"]; item.CurrentPermissions = (uint)reader["inventoryCurrentPermissions"]; item.InvType = (int)reader["invType"]; item.BasePermissions = (uint)reader["inventoryBasePermissions"]; item.EveryOnePermissions = (uint)reader["inventoryEveryOnePermissions"]; item.GroupPermissions = (uint)reader["inventoryGroupPermissions"]; item.SalePrice = (int)reader["salePrice"]; item.SaleType = Convert.ToByte(reader["saleType"]); item.CreationDate = (int)reader["creationDate"]; item.GroupOwned = Convert.ToBoolean(reader["groupOwned"]); item.Flags = (uint)reader["flags"]; return item; } catch (Exception e) { m_log.Error(e.ToString()); } return null; } /// <summary> /// Returns a specified inventory item /// </summary> /// <param name="item">The item to return</param> /// <returns>An inventory item</returns> public InventoryItemBase getInventoryItem(UUID itemID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryitems WHERE inventoryID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", itemID.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { InventoryItemBase item = null; if (reader.Read()) item = readInventoryItem(reader); return item; } } } catch (Exception e) { m_log.Error(e.ToString()); } return null; } /// <summary> /// Reads a list of inventory folders returned by a query. /// </summary> /// <param name="reader">A MySQL Data Reader</param> /// <returns>A List containing inventory folders</returns> protected static InventoryFolderBase readInventoryFolder(IDataReader reader) { try { InventoryFolderBase folder = new InventoryFolderBase(); folder.Owner = new UUID(Convert.ToString(reader["agentID"])); folder.ParentID = new UUID(Convert.ToString(reader["parentFolderID"])); folder.ID = new UUID(Convert.ToString(reader["folderID"])); folder.Name = (string)reader["folderName"]; folder.Type = (short)reader["type"]; folder.Version = (ushort)((int)reader["version"]); return folder; } catch (Exception e) { m_log.Error(e.ToString()); } return null; } /// <summary> /// Returns a specified inventory folder /// </summary> /// <param name="folder">The folder to return</param> /// <returns>A folder class</returns> public InventoryFolderBase getInventoryFolder(UUID folderID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryfolders WHERE folderID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", folderID.ToString()); using (IDataReader reader = conn.QueryAndUseReader(query, parms)) { if (reader.Read()) { InventoryFolderBase folder = readInventoryFolder(reader); return folder; } else { return null; } } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Adds a specified item to the database /// </summary> /// <param name="item">The inventory item</param> public void addInventoryItem(InventoryItemBase item) { string query = "REPLACE INTO inventoryitems (inventoryID, assetID, assetType, parentFolderID, avatarID, inventoryName" + ", inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType" + ", creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, inventoryGroupPermissions, salePrice, saleType" + ", creationDate, groupID, groupOwned, flags) VALUES "; query += "(?inventoryID, ?assetID, ?assetType, ?parentFolderID, ?avatarID, ?inventoryName, ?inventoryDescription" + ", ?inventoryNextPermissions, ?inventoryCurrentPermissions, ?invType, ?creatorID" + ", ?inventoryBasePermissions, ?inventoryEveryOnePermissions, ?inventoryGroupPermissions, ?salePrice, ?saleType, ?creationDate" + ", ?groupID, ?groupOwned, ?flags)"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?inventoryID", item.ID.ToString()); parms.Add("?assetID", item.AssetID.ToString()); parms.Add("?assetType", item.AssetType.ToString()); parms.Add("?parentFolderID", item.Folder.ToString()); parms.Add("?avatarID", item.Owner.ToString()); parms.Add("?inventoryName", item.Name); parms.Add("?inventoryDescription", item.Description); parms.Add("?inventoryNextPermissions", item.NextPermissions.ToString()); parms.Add("?inventoryCurrentPermissions", item.CurrentPermissions.ToString()); parms.Add("?invType", item.InvType); parms.Add("?creatorID", item.CreatorId); parms.Add("?inventoryBasePermissions", item.BasePermissions); parms.Add("?inventoryEveryOnePermissions", item.EveryOnePermissions); parms.Add("?inventoryGroupPermissions", item.GroupPermissions); parms.Add("?salePrice", item.SalePrice); parms.Add("?saleType", item.SaleType); parms.Add("?creationDate", item.CreationDate); parms.Add("?groupID", item.GroupID); parms.Add("?groupOwned", item.GroupOwned); parms.Add("?flags", item.Flags); conn.QueryNoResults(query, parms); // Also increment the parent version number if not null. this.IncrementSpecifiedFolderVersion(conn, item.Folder); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Updates the specified inventory item /// </summary> /// <param name="item">Inventory item to update</param> public void updateInventoryItem(InventoryItemBase item) { //addInventoryItem(item); /* 12/9/2009 - Ele's Edit - Rather than simply adding a whole new item, which seems kind of pointless to me, let's actually try UPDATING the item as it should be. This is not fully functioning yet from the updating of items * within Scene.Inventory.cs MoveInventoryItem yet. Not sure the effect it will have on the rest of the updates either, as they * originally pointed back to addInventoryItem above. */ string query = "UPDATE inventoryitems SET assetID=?assetID, assetType=?assetType, parentFolderID=?parentFolderID, " + "avatarID=?avatarID, inventoryName=?inventoryName, inventoryDescription=?inventoryDescription, inventoryNextPermissions=?inventoryNextPermissions, " + "inventoryCurrentPermissions=?inventoryCurrentPermissions, invType=?invType, creatorID=?creatorID, inventoryBasePermissions=?inventoryBasePermissions, " + "inventoryEveryOnePermissions=?inventoryEveryOnePermissions, inventoryGroupPermissions=?inventoryGroupPermissions, salePrice=?salePrice, " + "saleType=?saleType, creationDate=?creationDate, groupID=?groupID, groupOwned=?groupOwned, flags=?flags " + "WHERE inventoryID=?inventoryID"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?inventoryID", item.ID.ToString()); parms.Add("?assetID", item.AssetID.ToString()); parms.Add("?assetType", item.AssetType.ToString()); parms.Add("?parentFolderID", item.Folder.ToString()); parms.Add("?avatarID", item.Owner.ToString()); parms.Add("?inventoryName", item.Name); parms.Add("?inventoryDescription", item.Description); parms.Add("?inventoryNextPermissions", item.NextPermissions.ToString()); parms.Add("?inventoryCurrentPermissions", item.CurrentPermissions.ToString()); parms.Add("?invType", item.InvType); parms.Add("?creatorID", item.CreatorId); parms.Add("?inventoryBasePermissions", item.BasePermissions); parms.Add("?inventoryEveryOnePermissions", item.EveryOnePermissions); parms.Add("?inventoryGroupPermissions", item.GroupPermissions); parms.Add("?salePrice", item.SalePrice); parms.Add("?saleType", item.SaleType); parms.Add("?creationDate", item.CreationDate); parms.Add("?groupID", item.GroupID); parms.Add("?groupOwned", item.GroupOwned); parms.Add("?flags", item.Flags); conn.QueryNoResults(query, parms); // Also increment the parent version number if not null. this.IncrementSpecifiedFolderVersion(conn, item.Folder); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Detele the specified inventory item /// </summary> /// <param name="item">The inventory item UUID to delete</param> public void deleteInventoryItem(InventoryItemBase item) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "DELETE FROM inventoryitems WHERE inventoryID=?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", item.ID.ToString()); conn.QueryNoResults(query, parms); // Also increment the parent version number if not null. this.IncrementSpecifiedFolderVersion(conn, item.Folder); } } catch (Exception e) { m_log.Error(e.ToString()); } } public InventoryItemBase queryInventoryItem(UUID itemID) { return getInventoryItem(itemID); } public InventoryFolderBase queryInventoryFolder(UUID folderID) { return getInventoryFolder(folderID); } /// <summary> /// Creates a new inventory folder /// </summary> /// <param name="folder">Folder to create</param> public void addInventoryFolder(InventoryFolderBase folder) { if (folder.ID == UUID.Zero) { m_log.Error("[Inventory]: Not storing zero UUID folder for " + folder.Owner.ToString()); return; } string query = "REPLACE INTO inventoryfolders (folderID, agentID, parentFolderID, folderName, type, version) VALUES "; query += "(?folderID, ?agentID, ?parentFolderID, ?folderName, ?type, ?version)"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?folderID", folder.ID.ToString()); parms.Add("?agentID", folder.Owner.ToString()); parms.Add("?parentFolderID", folder.ParentID.ToString()); parms.Add("?folderName", folder.Name); parms.Add("?type", (short)folder.Type); parms.Add("?version", folder.Version); conn.QueryNoResults(query, parms); // Also increment the parent version number if not null. this.IncrementSpecifiedFolderVersion(conn, folder.ParentID); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Increments the version of the passed folder, making sure the folder isn't Zero. Must be called from within a using{} block! /// </summary> /// <param name="conn">Database connection.</param> /// <param name="folderId">Folder UUID to increment</param> private void IncrementSpecifiedFolderVersion(ISimpleDB conn, UUID folderId) { if (folderId != UUID.Zero) { string query = "update inventoryfolders set version=version+1 where folderID = ?folderID"; Dictionary<string, object> updParms = new Dictionary<string, object>(); updParms.Add("?folderID", folderId.ToString()); conn.QueryNoResults(query, updParms); } } /// <summary> /// Updates an inventory folder /// </summary> /// <param name="folder">Folder to update</param> public void updateInventoryFolder(InventoryFolderBase folder) { string query = "update inventoryfolders set folderName=?folderName where folderID=?folderID"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?folderName", folder.Name); parms.Add("?folderID", folder.ID.ToString()); conn.QueryNoResults(query, parms); // Also increment the version number if not null. this.IncrementSpecifiedFolderVersion(conn, folder.ID); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Move an inventory folder /// </summary> /// <param name="folder">Folder to move</param> /// <remarks>UPDATE inventoryfolders SET parentFolderID=?parentFolderID WHERE folderID=?folderID</remarks> public void moveInventoryFolder(InventoryFolderBase folder, UUID parentId) { string query = "UPDATE inventoryfolders SET parentFolderID=?parentFolderID WHERE folderID=?folderID"; try { using (ISimpleDB conn = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?folderID", folder.ID.ToString()); parms.Add("?parentFolderID", parentId.ToString()); conn.QueryNoResults(query, parms); folder.ParentID = parentId; // Only change if the above succeeded. // Increment both the old and the new parents - checking for null. this.IncrementSpecifiedFolderVersion(conn, parentId); this.IncrementSpecifiedFolderVersion(conn, folder.ParentID); } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Append a list of all the child folders of a parent folder /// </summary> /// <param name="folders">list where folders will be appended</param> /// <param name="parentID">ID of parent</param> protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID) { List<InventoryFolderBase> subfolderList = getInventoryFolders(parentID); foreach (InventoryFolderBase f in subfolderList) folders.Add(f); } /// <summary> /// See IInventoryDataPlugin /// </summary> /// <param name="parentID"></param> /// <returns></returns> public List<InventoryFolderBase> getFolderHierarchy(UUID parentID) { /* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one * - We will only need to hit the database twice instead of n times. * - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned * by the same person, each user only has 1 inventory heirarchy * - The returned list is not ordered, instead of breadth-first ordered There are basically 2 usage cases for getFolderHeirarchy: 1) Getting the user's entire inventory heirarchy when they log in 2) Finding a subfolder heirarchy to delete when emptying the trash. This implementation will pull all inventory folders from the database, and then prune away any folder that is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the database than to make n requests. This pays off only if requested heirarchy is large. By making this choice, we are making the worst case better at the cost of making the best case worse. This way is generally better because we don't have to rebuild the connection/sql query per subfolder, even if we end up getting more data from the SQL server than we need. - Francis */ try { List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); Dictionary<UUID, List<InventoryFolderBase>> hashtable = new Dictionary<UUID, List<InventoryFolderBase>>(); ; List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>(); using (ISimpleDB conn = _connFactory.GetConnection()) { bool buildResultsFromHashTable = false; /* Fetch the parent folder from the database to determine the agent ID, and if * we're querying the root of the inventory folder tree */ string query = "SELECT * FROM inventoryfolders WHERE folderID = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", parentID.ToString()); IDataReader reader; using (reader = conn.QueryAndUseReader(query, parms)) { while (reader.Read()) // Should be at most 1 result parentFolder.Add(readInventoryFolder(reader)); } if (parentFolder.Count >= 1) // No result means parent folder does not exist { if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder { /* Get all of the agent's folders from the database, put them in a list and return it */ parms.Clear(); query = "SELECT * FROM inventoryfolders WHERE agentID = ?uuid"; parms.Add("?uuid", parentFolder[0].Owner.ToString()); using (reader = conn.QueryAndUseReader(query, parms)) { while (reader.Read()) { InventoryFolderBase curFolder = readInventoryFolder(reader); if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list folders.Add(curFolder); } } } // if we are querying the root folder else // else we are querying a subtree of the inventory folder tree { /* Get all of the agent's folders from the database, put them all in a hash table * indexed by their parent ID */ parms.Clear(); query = "SELECT * FROM inventoryfolders WHERE agentID = ?uuid"; parms.Add("?uuid", parentFolder[0].Owner.ToString()); using (reader = conn.QueryAndUseReader(query, parms)) { while (reader.Read()) { InventoryFolderBase curFolder = readInventoryFolder(reader); if (hashtable.ContainsKey(curFolder.ParentID)) // Current folder already has a sibling hashtable[curFolder.ParentID].Add(curFolder); // append to sibling list else // else current folder has no known (yet) siblings { List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>(); siblingList.Add(curFolder); // Current folder has no known (yet) siblings hashtable.Add(curFolder.ParentID, siblingList); } } // while more items to read from the database } // Set flag so we know we need to build the results from the hash table after // we unlock the database buildResultsFromHashTable = true; } // else we are querying a subtree of the inventory folder tree } // if folder parentID exists if (buildResultsFromHashTable) { /* We have all of the user's folders stored in a hash table indexed by their parent ID * and we need to return the requested subtree. We will build the requested subtree * by performing a breadth-first-search on the hash table */ if (hashtable.ContainsKey(parentID)) folders.AddRange(hashtable[parentID]); for (int i = 0; i < folders.Count; i++) // **Note: folders.Count is *not* static if (hashtable.ContainsKey(folders[i].ID)) folders.AddRange(hashtable[folders[i].ID]); } } // lock (database) return folders; } catch (Exception e) { m_log.Error(e.ToString()); return null; } } /// <summary> /// Delete a folder from database. Must be called from within a using{} block for the database connection. /// </summary> /// Passing in the connection allows for consolidation of the DB connections, important as this method is often called from an inner loop. /// <param name="folderID">the folder UUID</param> /// <param name="conn">the database connection</param> private void deleteOneFolder(ISimpleDB conn, InventoryFolderBase folder) { string query = "DELETE FROM inventoryfolders WHERE folderID=?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", folder.ID.ToString()); conn.QueryNoResults(query, parms); // As the callers of this function will increment the version, there's no need to do so here. } /// <summary> /// Delete all subfolders and items in a folder. Must be called from within a using{} block for the database connection. /// </summary> /// Passing in the connection allows for consolidation of the DB connections, important as this method is often called from an inner loop. /// <param name="folderID">the folder UUID</param> /// <param name="conn">the database connection</param> private void deleteFolderContents(ISimpleDB conn, UUID folderID) { // Get a flattened list of all subfolders. List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID); // Delete all sub-folders foreach (InventoryFolderBase f in subFolders) { deleteFolderContents(conn, f.ID); // Recurse! deleteOneFolder(conn, f); } // Delete the actual items in this folder. string query = "DELETE FROM inventoryitems WHERE parentFolderID=?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", folderID.ToString()); conn.QueryNoResults(query, parms); // As the callers of this function will increment the version, there's no need to do so here where this is most often ceing called from an inner loop! } /// <summary> /// Delete all subfolders and items in a folder. /// </summary> /// <param name="folderID">the folder UUID</param> public void deleteFolderContents(UUID folderID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (ITransaction transaction = conn.BeginTransaction()) // Use a transaction to guarantee that the following it atomic - it'd be bad to have a partial delete of the tree! { deleteFolderContents(conn, folderID); // Increment the version of the purged folder. this.IncrementSpecifiedFolderVersion(conn, folderID); transaction.Commit(); } } } catch (Exception e) { m_log.Error(e.ToString()); } } /// <summary> /// Deletes an inventory folder /// </summary> /// <param name="folderId">Id of folder to delete</param> public void deleteInventoryFolder(InventoryFolderBase folder) { // Get a flattened list of all subfolders. List<InventoryFolderBase> subFolders = getFolderHierarchy(folder.ID); try { using (ISimpleDB conn = _connFactory.GetConnection()) { using (ITransaction transaction = conn.BeginTransaction()) // Use a transaction to guarantee that the following it atomic - it'd be bad to have a partial delete of the tree! { // Since the DB doesn't currently have foreign key constraints the order of delete ops doean't matter, // however it's better practice to remove the contents and then remove the folder itself. // Delete all sub-folders foreach (InventoryFolderBase f in subFolders) { deleteFolderContents(conn, f.ID); deleteOneFolder(conn, f); } // Delete the actual row deleteFolderContents(conn, folder.ID); deleteOneFolder(conn, folder); // Increment the version of the parent of the purged folder. this.IncrementSpecifiedFolderVersion(conn, folder.ParentID); transaction.Commit(); } } } catch (Exception e) { m_log.Error(e.ToString()); } } public List<InventoryItemBase> fetchActiveGestures(UUID avatarID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags & 1"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", avatarID.ToString()); parms.Add("?type", (int)AssetType.Gesture); using (IDataReader result = conn.QueryAndUseReader(query, parms)) { List<InventoryItemBase> list = new List<InventoryItemBase>(); while (result.Read()) { InventoryItemBase item = readInventoryItem(result); if (item != null) list.Add(item); } return list; } } } catch (Exception e) { m_log.Error(e.ToString()); return new List<InventoryItemBase>(); } } public List<InventoryItemBase> getAllItems(UUID avatarID) { try { using (ISimpleDB conn = _connFactory.GetConnection()) { string query = "SELECT * FROM inventoryitems WHERE avatarId = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", avatarID.ToString()); using (IDataReader result = conn.QueryAndUseReader(query, parms)) { List<InventoryItemBase> list = new List<InventoryItemBase>(); while (result.Read()) { InventoryItemBase item = readInventoryItem(result); if (item != null) list.Add(item); } return list; } } } catch (Exception e) { m_log.Error(e.ToString()); return null; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using 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.V10.Services { /// <summary>Settings for <see cref="AdGroupAdServiceClient"/> instances.</summary> public sealed partial class AdGroupAdServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupAdServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupAdServiceSettings"/>.</returns> public static AdGroupAdServiceSettings GetDefault() => new AdGroupAdServiceSettings(); /// <summary>Constructs a new <see cref="AdGroupAdServiceSettings"/> object with default settings.</summary> public AdGroupAdServiceSettings() { } private AdGroupAdServiceSettings(AdGroupAdServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateAdGroupAdsSettings = existing.MutateAdGroupAdsSettings; OnCopy(existing); } partial void OnCopy(AdGroupAdServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupAdServiceClient.MutateAdGroupAds</c> and <c>AdGroupAdServiceClient.MutateAdGroupAdsAsync</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 MutateAdGroupAdsSettings { 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="AdGroupAdServiceSettings"/> object.</returns> public AdGroupAdServiceSettings Clone() => new AdGroupAdServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupAdServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class AdGroupAdServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupAdServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupAdServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupAdServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupAdServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupAdServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupAdServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupAdServiceClient Build() { AdGroupAdServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupAdServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupAdServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupAdServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupAdServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupAdServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupAdServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupAdServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupAdServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupAdServiceClient.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>AdGroupAdService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ads in an ad group. /// </remarks> public abstract partial class AdGroupAdServiceClient { /// <summary> /// The default endpoint for the AdGroupAdService 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 AdGroupAdService scopes.</summary> /// <remarks> /// The default AdGroupAdService 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="AdGroupAdServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="AdGroupAdServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupAdServiceClient"/>.</returns> public static stt::Task<AdGroupAdServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupAdServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupAdServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="AdGroupAdServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupAdServiceClient"/>.</returns> public static AdGroupAdServiceClient Create() => new AdGroupAdServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupAdServiceClient"/> 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="AdGroupAdServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupAdServiceClient"/>.</returns> internal static AdGroupAdServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupAdServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupAdService.AdGroupAdServiceClient grpcClient = new AdGroupAdService.AdGroupAdServiceClient(callInvoker); return new AdGroupAdServiceClientImpl(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 AdGroupAdService client</summary> public virtual AdGroupAdService.AdGroupAdServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ads. Operation statuses are returned. /// /// List of thrown errors: /// [AdCustomizerError]() /// [AdError]() /// [AdGroupAdError]() /// [AdSharingError]() /// [AdxError]() /// [AssetError]() /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [ContextError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedAttributeReferenceError]() /// [FieldError]() /// [FieldMaskError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [ImageError]() /// [InternalError]() /// [ListOperationError]() /// [MediaBundleError]() /// [MediaFileError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyFindingError]() /// [PolicyValidationParameterError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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 MutateAdGroupAdsResponse MutateAdGroupAds(MutateAdGroupAdsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ads. Operation statuses are returned. /// /// List of thrown errors: /// [AdCustomizerError]() /// [AdError]() /// [AdGroupAdError]() /// [AdSharingError]() /// [AdxError]() /// [AssetError]() /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [ContextError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedAttributeReferenceError]() /// [FieldError]() /// [FieldMaskError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [ImageError]() /// [InternalError]() /// [ListOperationError]() /// [MediaBundleError]() /// [MediaFileError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyFindingError]() /// [PolicyValidationParameterError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupAdsResponse> MutateAdGroupAdsAsync(MutateAdGroupAdsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ads. Operation statuses are returned. /// /// List of thrown errors: /// [AdCustomizerError]() /// [AdError]() /// [AdGroupAdError]() /// [AdSharingError]() /// [AdxError]() /// [AssetError]() /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [ContextError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedAttributeReferenceError]() /// [FieldError]() /// [FieldMaskError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [ImageError]() /// [InternalError]() /// [ListOperationError]() /// [MediaBundleError]() /// [MediaFileError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyFindingError]() /// [PolicyValidationParameterError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupAdsResponse> MutateAdGroupAdsAsync(MutateAdGroupAdsRequest request, st::CancellationToken cancellationToken) => MutateAdGroupAdsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ads. Operation statuses are returned. /// /// List of thrown errors: /// [AdCustomizerError]() /// [AdError]() /// [AdGroupAdError]() /// [AdSharingError]() /// [AdxError]() /// [AssetError]() /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [ContextError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedAttributeReferenceError]() /// [FieldError]() /// [FieldMaskError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [ImageError]() /// [InternalError]() /// [ListOperationError]() /// [MediaBundleError]() /// [MediaFileError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyFindingError]() /// [PolicyValidationParameterError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ads are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ads. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupAdsResponse MutateAdGroupAds(string customerId, scg::IEnumerable<AdGroupAdOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupAds(new MutateAdGroupAdsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ads. Operation statuses are returned. /// /// List of thrown errors: /// [AdCustomizerError]() /// [AdError]() /// [AdGroupAdError]() /// [AdSharingError]() /// [AdxError]() /// [AssetError]() /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [ContextError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedAttributeReferenceError]() /// [FieldError]() /// [FieldMaskError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [ImageError]() /// [InternalError]() /// [ListOperationError]() /// [MediaBundleError]() /// [MediaFileError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyFindingError]() /// [PolicyValidationParameterError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ads are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ads. /// </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<MutateAdGroupAdsResponse> MutateAdGroupAdsAsync(string customerId, scg::IEnumerable<AdGroupAdOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupAdsAsync(new MutateAdGroupAdsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ads. Operation statuses are returned. /// /// List of thrown errors: /// [AdCustomizerError]() /// [AdError]() /// [AdGroupAdError]() /// [AdSharingError]() /// [AdxError]() /// [AssetError]() /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [ContextError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedAttributeReferenceError]() /// [FieldError]() /// [FieldMaskError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [ImageError]() /// [InternalError]() /// [ListOperationError]() /// [MediaBundleError]() /// [MediaFileError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyFindingError]() /// [PolicyValidationParameterError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ads are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ads. /// </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<MutateAdGroupAdsResponse> MutateAdGroupAdsAsync(string customerId, scg::IEnumerable<AdGroupAdOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupAdsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupAdService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ads in an ad group. /// </remarks> public sealed partial class AdGroupAdServiceClientImpl : AdGroupAdServiceClient { private readonly gaxgrpc::ApiCall<MutateAdGroupAdsRequest, MutateAdGroupAdsResponse> _callMutateAdGroupAds; /// <summary> /// Constructs a client wrapper for the AdGroupAdService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="AdGroupAdServiceSettings"/> used within this client.</param> public AdGroupAdServiceClientImpl(AdGroupAdService.AdGroupAdServiceClient grpcClient, AdGroupAdServiceSettings settings) { GrpcClient = grpcClient; AdGroupAdServiceSettings effectiveSettings = settings ?? AdGroupAdServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateAdGroupAds = clientHelper.BuildApiCall<MutateAdGroupAdsRequest, MutateAdGroupAdsResponse>(grpcClient.MutateAdGroupAdsAsync, grpcClient.MutateAdGroupAds, effectiveSettings.MutateAdGroupAdsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupAds); Modify_MutateAdGroupAdsApiCall(ref _callMutateAdGroupAds); 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_MutateAdGroupAdsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupAdsRequest, MutateAdGroupAdsResponse> call); partial void OnConstruction(AdGroupAdService.AdGroupAdServiceClient grpcClient, AdGroupAdServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupAdService client</summary> public override AdGroupAdService.AdGroupAdServiceClient GrpcClient { get; } partial void Modify_MutateAdGroupAdsRequest(ref MutateAdGroupAdsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes ads. Operation statuses are returned. /// /// List of thrown errors: /// [AdCustomizerError]() /// [AdError]() /// [AdGroupAdError]() /// [AdSharingError]() /// [AdxError]() /// [AssetError]() /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [ContextError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedAttributeReferenceError]() /// [FieldError]() /// [FieldMaskError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [ImageError]() /// [InternalError]() /// [ListOperationError]() /// [MediaBundleError]() /// [MediaFileError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyFindingError]() /// [PolicyValidationParameterError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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 MutateAdGroupAdsResponse MutateAdGroupAds(MutateAdGroupAdsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupAdsRequest(ref request, ref callSettings); return _callMutateAdGroupAds.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes ads. Operation statuses are returned. /// /// List of thrown errors: /// [AdCustomizerError]() /// [AdError]() /// [AdGroupAdError]() /// [AdSharingError]() /// [AdxError]() /// [AssetError]() /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [ContextError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FeedAttributeReferenceError]() /// [FieldError]() /// [FieldMaskError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [ImageError]() /// [InternalError]() /// [ListOperationError]() /// [MediaBundleError]() /// [MediaFileError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyFindingError]() /// [PolicyValidationParameterError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupAdsResponse> MutateAdGroupAdsAsync(MutateAdGroupAdsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupAdsRequest(ref request, ref callSettings); return _callMutateAdGroupAds.Async(request, callSettings); } } }
// 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.Text { using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System; using System.Diagnostics.Contracts; // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // [Serializable] internal class DecoderNLS : Decoder, ISerializable { // Remember our encoding protected Encoding m_encoding; [NonSerialized] protected bool m_mustFlush; [NonSerialized] internal bool m_throwOnOverflow; [NonSerialized] internal int m_bytesUsed; #region Serialization // Constructor called by serialization. called during deserialization. internal DecoderNLS(SerializationInfo info, StreamingContext context) { throw new NotSupportedException( String.Format( System.Globalization.CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType())); } // ISerializable implementation. called during serialization. [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { SerializeDecoder(info); info.AddValue("encoding", this.m_encoding); info.SetType(typeof(Encoding.DefaultDecoder)); } #endregion Serialization internal DecoderNLS( Encoding encoding ) { this.m_encoding = encoding; this.m_fallback = this.m_encoding.DecoderFallback; this.Reset(); } // This is used by our child deserializers internal DecoderNLS( ) { this.m_encoding = null; this.Reset(); } public override void Reset() { if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // Avoid null fixed problem if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, flush); } [System.Security.SecurityCritical] // auto-generated public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Remember the flush this.m_mustFlush = flush; this.m_throwOnOverflow = true; // By default just call the encoding version, no flush by default return m_encoding.GetCharCount(bytes, count, this); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); // Avoid empty input fixed problem if (bytes.Length == 0) bytes = new byte[1]; int charCount = chars.Length - charIndex; if (chars.Length == 0) chars = new char[1]; // Just call pointer version fixed (byte* pBytes = bytes) fixed (char* pChars = chars) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } [System.Security.SecurityCritical] // auto-generated public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Remember our flush m_mustFlush = flush; m_throwOnOverflow = true; // By default just call the encoding's version return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) [System.Security.SecuritySafeCritical] // auto-generated public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // Avoid empty input problem if (bytes.Length == 0) bytes = new byte[1]; if (chars.Length == 0) chars = new char[1]; // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = bytes) { fixed (char* pChars = chars) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars [System.Security.SecurityCritical] // auto-generated public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // We don't want to throw this.m_mustFlush = flush; this.m_throwOnOverflow = false; this.m_bytesUsed = 0; // Do conversion charsUsed = this.m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = this.m_bytesUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); // Our data thingys are now full, we can return } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our decoder? internal virtual bool HasState { get { return false; } } // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Exceptions; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Mapping; using Umbraco.Cms.Core.Models.ContentEditing; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Models.Mapping { /// <summary> /// Defines mappings for content/media/members type mappings /// </summary> public class ContentTypeMapDefinition : IMapDefinition { private readonly CommonMapper _commonMapper; private readonly IContentTypeService _contentTypeService; private readonly IDataTypeService _dataTypeService; private readonly IFileService _fileService; private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly ILogger<ContentTypeMapDefinition> _logger; private readonly ILoggerFactory _loggerFactory; private readonly IMediaTypeService _mediaTypeService; private readonly IMemberTypeService _memberTypeService; private readonly PropertyEditorCollection _propertyEditors; private readonly IShortStringHelper _shortStringHelper; private ContentSettings _contentSettings; [Obsolete("Use ctor with all params injected")] public ContentTypeMapDefinition(CommonMapper commonMapper, PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService, ILoggerFactory loggerFactory, IShortStringHelper shortStringHelper, IOptions<GlobalSettings> globalSettings, IHostingEnvironment hostingEnvironment) : this(commonMapper, propertyEditors, dataTypeService, fileService, contentTypeService, mediaTypeService, memberTypeService, loggerFactory, shortStringHelper, globalSettings, hostingEnvironment, StaticServiceProvider.Instance.GetRequiredService<IOptionsMonitor<ContentSettings>>()) { } public ContentTypeMapDefinition(CommonMapper commonMapper, PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService, ILoggerFactory loggerFactory, IShortStringHelper shortStringHelper, IOptions<GlobalSettings> globalSettings, IHostingEnvironment hostingEnvironment, IOptionsMonitor<ContentSettings> contentSettings) { _commonMapper = commonMapper; _propertyEditors = propertyEditors; _dataTypeService = dataTypeService; _fileService = fileService; _contentTypeService = contentTypeService; _mediaTypeService = mediaTypeService; _memberTypeService = memberTypeService; _loggerFactory = loggerFactory; _logger = _loggerFactory.CreateLogger<ContentTypeMapDefinition>(); _shortStringHelper = shortStringHelper; _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; _contentSettings = contentSettings.CurrentValue; contentSettings.OnChange(x => _contentSettings = x); } public void DefineMaps(IUmbracoMapper mapper) { mapper.Define<DocumentTypeSave, IContentType>( (source, context) => new ContentType(_shortStringHelper, source.ParentId), Map); mapper.Define<MediaTypeSave, IMediaType>( (source, context) => new MediaType(_shortStringHelper, source.ParentId), Map); mapper.Define<MemberTypeSave, IMemberType>( (source, context) => new MemberType(_shortStringHelper, source.ParentId), Map); mapper.Define<IContentType, DocumentTypeDisplay>((source, context) => new DocumentTypeDisplay(), Map); mapper.Define<IMediaType, MediaTypeDisplay>((source, context) => new MediaTypeDisplay(), Map); mapper.Define<IMemberType, MemberTypeDisplay>((source, context) => new MemberTypeDisplay(), Map); mapper.Define<PropertyTypeBasic, IPropertyType>( (source, context) => { IDataType dataType = _dataTypeService.GetDataType(source.DataTypeId); if (dataType == null) { throw new NullReferenceException("No data type found with id " + source.DataTypeId); } return new PropertyType(_shortStringHelper, dataType, source.Alias); }, Map); // TODO: isPublishing in ctor? mapper.Define<PropertyGroupBasic<PropertyTypeBasic>, PropertyGroup>( (source, context) => new PropertyGroup(false), Map); mapper.Define<PropertyGroupBasic<MemberPropertyTypeBasic>, PropertyGroup>( (source, context) => new PropertyGroup(false), Map); mapper.Define<IContentTypeComposition, ContentTypeBasic>((source, context) => new ContentTypeBasic(), Map); mapper.Define<IContentType, ContentTypeBasic>((source, context) => new ContentTypeBasic(), Map); mapper.Define<IMediaType, ContentTypeBasic>((source, context) => new ContentTypeBasic(), Map); mapper.Define<IMemberType, ContentTypeBasic>((source, context) => new ContentTypeBasic(), Map); mapper.Define<DocumentTypeSave, DocumentTypeDisplay>((source, context) => new DocumentTypeDisplay(), Map); mapper.Define<MediaTypeSave, MediaTypeDisplay>((source, context) => new MediaTypeDisplay(), Map); mapper.Define<MemberTypeSave, MemberTypeDisplay>((source, context) => new MemberTypeDisplay(), Map); mapper.Define<PropertyGroupBasic<PropertyTypeBasic>, PropertyGroupDisplay<PropertyTypeDisplay>>( (source, context) => new PropertyGroupDisplay<PropertyTypeDisplay>(), Map); mapper.Define<PropertyGroupBasic<MemberPropertyTypeBasic>, PropertyGroupDisplay<MemberPropertyTypeDisplay>>( (source, context) => new PropertyGroupDisplay<MemberPropertyTypeDisplay>(), Map); mapper.Define<PropertyTypeBasic, PropertyTypeDisplay>((source, context) => new PropertyTypeDisplay(), Map); mapper.Define<MemberPropertyTypeBasic, MemberPropertyTypeDisplay>( (source, context) => new MemberPropertyTypeDisplay(), Map); } // no MapAll - take care private void Map(DocumentTypeSave source, IContentType target, MapperContext context) { MapSaveToTypeBase<DocumentTypeSave, PropertyTypeBasic>(source, target, context); MapComposition(source, target, alias => _contentTypeService.Get(alias)); if (target is IContentTypeWithHistoryCleanup targetWithHistoryCleanup) { targetWithHistoryCleanup.HistoryCleanup = source.HistoryCleanup; } target.AllowedTemplates = source.AllowedTemplates .Where(x => x != null) .Select(_fileService.GetTemplate) .Where(x => x != null) .ToArray(); target.SetDefaultTemplate(source.DefaultTemplate == null ? null : _fileService.GetTemplate(source.DefaultTemplate)); } // no MapAll - take care private void Map(MediaTypeSave source, IMediaType target, MapperContext context) { MapSaveToTypeBase<MediaTypeSave, PropertyTypeBasic>(source, target, context); MapComposition(source, target, alias => _mediaTypeService.Get(alias)); } // no MapAll - take care private void Map(MemberTypeSave source, IMemberType target, MapperContext context) { MapSaveToTypeBase<MemberTypeSave, MemberPropertyTypeBasic>(source, target, context); MapComposition(source, target, alias => _memberTypeService.Get(alias)); foreach (MemberPropertyTypeBasic propertyType in source.Groups.SelectMany(x => x.Properties)) { MemberPropertyTypeBasic localCopy = propertyType; IPropertyType destProp = target.PropertyTypes.SingleOrDefault(x => x.Alias.InvariantEquals(localCopy.Alias)); if (destProp == null) { continue; } target.SetMemberCanEditProperty(localCopy.Alias, localCopy.MemberCanEditProperty); target.SetMemberCanViewProperty(localCopy.Alias, localCopy.MemberCanViewProperty); target.SetIsSensitiveProperty(localCopy.Alias, localCopy.IsSensitiveData); } } // no MapAll - take care private void Map(IContentType source, DocumentTypeDisplay target, MapperContext context) { MapTypeToDisplayBase<DocumentTypeDisplay, PropertyTypeDisplay>(source, target); if (source is IContentTypeWithHistoryCleanup sourceWithHistoryCleanup) { target.HistoryCleanup = new HistoryCleanupViewModel { PreventCleanup = sourceWithHistoryCleanup.HistoryCleanup?.PreventCleanup ?? false, KeepAllVersionsNewerThanDays = sourceWithHistoryCleanup.HistoryCleanup?.KeepAllVersionsNewerThanDays, KeepLatestVersionPerDayForDays = sourceWithHistoryCleanup.HistoryCleanup?.KeepLatestVersionPerDayForDays, GlobalKeepAllVersionsNewerThanDays = _contentSettings.ContentVersionCleanupPolicy.KeepAllVersionsNewerThanDays, GlobalKeepLatestVersionPerDayForDays = _contentSettings.ContentVersionCleanupPolicy.KeepLatestVersionPerDayForDays, GlobalEnableCleanup = _contentSettings.ContentVersionCleanupPolicy.EnableCleanup }; } target.AllowCultureVariant = source.VariesByCulture(); target.AllowSegmentVariant = source.VariesBySegment(); target.ContentApps = _commonMapper.GetContentApps(source); //sync templates target.AllowedTemplates = context.MapEnumerable<ITemplate, EntityBasic>(source.AllowedTemplates); if (source.DefaultTemplate != null) { target.DefaultTemplate = context.Map<EntityBasic>(source.DefaultTemplate); } //default listview target.ListViewEditorName = Constants.Conventions.DataTypes.ListViewPrefix + "Content"; if (string.IsNullOrEmpty(source.Alias)) { return; } var name = Constants.Conventions.DataTypes.ListViewPrefix + source.Alias; if (_dataTypeService.GetDataType(name) != null) { target.ListViewEditorName = name; } } // no MapAll - take care private void Map(IMediaType source, MediaTypeDisplay target, MapperContext context) { MapTypeToDisplayBase<MediaTypeDisplay, PropertyTypeDisplay>(source, target); //default listview target.ListViewEditorName = Constants.Conventions.DataTypes.ListViewPrefix + "Media"; target.IsSystemMediaType = source.IsSystemMediaType(); if (string.IsNullOrEmpty(source.Name)) { return; } var name = Constants.Conventions.DataTypes.ListViewPrefix + source.Name; if (_dataTypeService.GetDataType(name) != null) { target.ListViewEditorName = name; } } // no MapAll - take care private void Map(IMemberType source, MemberTypeDisplay target, MapperContext context) { MapTypeToDisplayBase<MemberTypeDisplay, MemberPropertyTypeDisplay>(source, target); //map the MemberCanEditProperty,MemberCanViewProperty,IsSensitiveData foreach (IPropertyType propertyType in source.PropertyTypes) { IPropertyType localCopy = propertyType; MemberPropertyTypeDisplay displayProp = target.Groups.SelectMany(dest => dest.Properties) .SingleOrDefault(dest => dest.Alias.InvariantEquals(localCopy.Alias)); if (displayProp == null) { continue; } displayProp.MemberCanEditProperty = source.MemberCanEditProperty(localCopy.Alias); displayProp.MemberCanViewProperty = source.MemberCanViewProperty(localCopy.Alias); displayProp.IsSensitiveData = source.IsSensitiveProperty(localCopy.Alias); } } // Umbraco.Code.MapAll -Blueprints private void Map(IContentTypeBase source, ContentTypeBasic target, string entityType) { target.Udi = Udi.Create(entityType, source.Key); target.Alias = source.Alias; target.CreateDate = source.CreateDate; target.Description = source.Description; target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty : $"{_globalSettings.GetBackOfficePath(_hostingEnvironment).EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Trashed = source.Trashed; target.Id = source.Id; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; target.Key = source.Key; target.Name = source.Name; target.ParentId = source.ParentId; target.Path = source.Path; target.Thumbnail = source.Thumbnail; target.ThumbnailFilePath = target.ThumbnailIsClass ? string.Empty : _hostingEnvironment.ToAbsolute("~/umbraco/images/thumbnails/" + source.Thumbnail); target.UpdateDate = source.UpdateDate; } // no MapAll - uses the IContentTypeBase map method, which has MapAll private void Map(IContentTypeComposition source, ContentTypeBasic target, MapperContext context) => Map(source, target, Constants.UdiEntityType.MemberType); // no MapAll - uses the IContentTypeBase map method, which has MapAll private void Map(IContentType source, ContentTypeBasic target, MapperContext context) => Map(source, target, Constants.UdiEntityType.DocumentType); // no MapAll - uses the IContentTypeBase map method, which has MapAll private void Map(IMediaType source, ContentTypeBasic target, MapperContext context) => Map(source, target, Constants.UdiEntityType.MediaType); // no MapAll - uses the IContentTypeBase map method, which has MapAll private void Map(IMemberType source, ContentTypeBasic target, MapperContext context) => Map(source, target, Constants.UdiEntityType.MemberType); // Umbraco.Code.MapAll -CreateDate -DeleteDate -UpdateDate // Umbraco.Code.MapAll -SupportsPublishing -Key -PropertyEditorAlias -ValueStorageType -Variations private static void Map(PropertyTypeBasic source, IPropertyType target, MapperContext context) { target.Name = source.Label; target.DataTypeId = source.DataTypeId; target.DataTypeKey = source.DataTypeKey; target.Mandatory = source.Validation.Mandatory; target.MandatoryMessage = source.Validation.MandatoryMessage; target.ValidationRegExp = source.Validation.Pattern; target.ValidationRegExpMessage = source.Validation.PatternMessage; target.SetVariesBy(ContentVariation.Culture, source.AllowCultureVariant); target.SetVariesBy(ContentVariation.Segment, source.AllowSegmentVariant); if (source.Id > 0) { target.Id = source.Id; } if (source.GroupId > 0) { target.PropertyGroupId = new Lazy<int>(() => source.GroupId, false); } target.Alias = source.Alias; target.Description = source.Description; target.SortOrder = source.SortOrder; target.LabelOnTop = source.LabelOnTop; } // no MapAll - take care private void Map(DocumentTypeSave source, DocumentTypeDisplay target, MapperContext context) { MapTypeToDisplayBase<DocumentTypeSave, PropertyTypeBasic, DocumentTypeDisplay, PropertyTypeDisplay>(source, target, context); //sync templates IEnumerable<string> destAllowedTemplateAliases = target.AllowedTemplates.Select(x => x.Alias); //if the dest is set and it's the same as the source, then don't change if (destAllowedTemplateAliases.SequenceEqual(source.AllowedTemplates) == false) { IEnumerable<ITemplate> templates = _fileService.GetTemplates(source.AllowedTemplates.ToArray()); target.AllowedTemplates = source.AllowedTemplates .Select(x => { ITemplate template = templates.SingleOrDefault(t => t.Alias == x); return template != null ? context.Map<EntityBasic>(template) : null; }) .WhereNotNull() .ToArray(); } if (source.DefaultTemplate.IsNullOrWhiteSpace() == false) { //if the dest is set and it's the same as the source, then don't change if (target.DefaultTemplate == null || source.DefaultTemplate != target.DefaultTemplate.Alias) { ITemplate template = _fileService.GetTemplate(source.DefaultTemplate); target.DefaultTemplate = template == null ? null : context.Map<EntityBasic>(template); } } else { target.DefaultTemplate = null; } } // no MapAll - take care private void Map(MediaTypeSave source, MediaTypeDisplay target, MapperContext context) => MapTypeToDisplayBase<MediaTypeSave, PropertyTypeBasic, MediaTypeDisplay, PropertyTypeDisplay>(source, target, context); // no MapAll - take care private void Map(MemberTypeSave source, MemberTypeDisplay target, MapperContext context) => MapTypeToDisplayBase<MemberTypeSave, MemberPropertyTypeBasic, MemberTypeDisplay, MemberPropertyTypeDisplay>( source, target, context); // Umbraco.Code.MapAll -CreateDate -UpdateDate -DeleteDate -Key -PropertyTypes private static void Map(PropertyGroupBasic<PropertyTypeBasic> source, PropertyGroup target, MapperContext context) { if (source.Id > 0) { target.Id = source.Id; } target.Key = source.Key; target.Type = source.Type; target.Name = source.Name; target.Alias = source.Alias; target.SortOrder = source.SortOrder; } // Umbraco.Code.MapAll -CreateDate -UpdateDate -DeleteDate -Key -PropertyTypes private static void Map(PropertyGroupBasic<MemberPropertyTypeBasic> source, PropertyGroup target, MapperContext context) { if (source.Id > 0) { target.Id = source.Id; } target.Key = source.Key; target.Type = source.Type; target.Name = source.Name; target.Alias = source.Alias; target.SortOrder = source.SortOrder; } // Umbraco.Code.MapAll -ContentTypeId -ParentTabContentTypes -ParentTabContentTypeNames private static void Map(PropertyGroupBasic<PropertyTypeBasic> source, PropertyGroupDisplay<PropertyTypeDisplay> target, MapperContext context) { target.Inherited = source.Inherited; if (source.Id > 0) { target.Id = source.Id; } target.Key = source.Key; target.Type = source.Type; target.Name = source.Name; target.Alias = source.Alias; target.SortOrder = source.SortOrder; target.Properties = context.MapEnumerable<PropertyTypeBasic, PropertyTypeDisplay>(source.Properties); } // Umbraco.Code.MapAll -ContentTypeId -ParentTabContentTypes -ParentTabContentTypeNames private static void Map(PropertyGroupBasic<MemberPropertyTypeBasic> source, PropertyGroupDisplay<MemberPropertyTypeDisplay> target, MapperContext context) { target.Inherited = source.Inherited; if (source.Id > 0) { target.Id = source.Id; } target.Key = source.Key; target.Type = source.Type; target.Name = source.Name; target.Alias = source.Alias; target.SortOrder = source.SortOrder; target.Properties = context.MapEnumerable<MemberPropertyTypeBasic, MemberPropertyTypeDisplay>(source.Properties); } // Umbraco.Code.MapAll -Editor -View -Config -ContentTypeId -ContentTypeName -Locked -DataTypeIcon -DataTypeName private static void Map(PropertyTypeBasic source, PropertyTypeDisplay target, MapperContext context) { target.Alias = source.Alias; target.AllowCultureVariant = source.AllowCultureVariant; target.AllowSegmentVariant = source.AllowSegmentVariant; target.DataTypeId = source.DataTypeId; target.DataTypeKey = source.DataTypeKey; target.Description = source.Description; target.GroupId = source.GroupId; target.Id = source.Id; target.Inherited = source.Inherited; target.Label = source.Label; target.SortOrder = source.SortOrder; target.Validation = source.Validation; target.LabelOnTop = source.LabelOnTop; } // Umbraco.Code.MapAll -Editor -View -Config -ContentTypeId -ContentTypeName -Locked -DataTypeIcon -DataTypeName private static void Map(MemberPropertyTypeBasic source, MemberPropertyTypeDisplay target, MapperContext context) { target.Alias = source.Alias; target.AllowCultureVariant = source.AllowCultureVariant; target.AllowSegmentVariant = source.AllowSegmentVariant; target.DataTypeId = source.DataTypeId; target.DataTypeKey = source.DataTypeKey; target.Description = source.Description; target.GroupId = source.GroupId; target.Id = source.Id; target.Inherited = source.Inherited; target.IsSensitiveData = source.IsSensitiveData; target.Label = source.Label; target.MemberCanEditProperty = source.MemberCanEditProperty; target.MemberCanViewProperty = source.MemberCanViewProperty; target.SortOrder = source.SortOrder; target.Validation = source.Validation; target.LabelOnTop = source.LabelOnTop; } // Umbraco.Code.MapAll -CreatorId -Level -SortOrder -Variations // Umbraco.Code.MapAll -CreateDate -UpdateDate -DeleteDate // Umbraco.Code.MapAll -ContentTypeComposition (done by AfterMapSaveToType) private static void MapSaveToTypeBase<TSource, TSourcePropertyType>(TSource source, IContentTypeComposition target, MapperContext context) where TSource : ContentTypeSave<TSourcePropertyType> where TSourcePropertyType : PropertyTypeBasic { // TODO: not so clean really var isPublishing = target is IContentType; var id = Convert.ToInt32(source.Id); if (id > 0) { target.Id = id; } target.Alias = source.Alias; target.Description = source.Description; target.Icon = source.Icon; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; target.Key = source.Key; target.Name = source.Name; target.ParentId = source.ParentId; target.Path = source.Path; target.Thumbnail = source.Thumbnail; target.AllowedAsRoot = source.AllowAsRoot; target.AllowedContentTypes = source.AllowedContentTypes.Select((t, i) => new ContentTypeSort(t, i)); if (!(target is IMemberType)) { target.SetVariesBy(ContentVariation.Culture, source.AllowCultureVariant); target.SetVariesBy(ContentVariation.Segment, source.AllowSegmentVariant); } // handle property groups and property types // note that ContentTypeSave has // - all groups, inherited and local; only *one* occurrence per group *name* // - potentially including the generic properties group // - all properties, inherited and local // // also, see PropertyTypeGroupResolver.ResolveCore: // - if a group is local *and* inherited, then Inherited is true // and the identifier is the identifier of the *local* group // // IContentTypeComposition AddPropertyGroup, AddPropertyType methods do some // unique-alias-checking, etc that is *not* compatible with re-mapping everything // the way we do it here, so we should exclusively do it by // - managing a property group's PropertyTypes collection // - managing the content type's PropertyTypes collection (for generic properties) // handle actual groups (non-generic-properties) PropertyGroup[] destOrigGroups = target.PropertyGroups.ToArray(); // local groups IPropertyType[] destOrigProperties = target.PropertyTypes.ToArray(); // all properties, in groups or not var destGroups = new List<PropertyGroup>(); PropertyGroupBasic<TSourcePropertyType>[] sourceGroups = source.Groups.Where(x => x.IsGenericProperties == false).ToArray(); var sourceGroupParentAliases = sourceGroups.Select(x => x.GetParentAlias()).Distinct().ToArray(); foreach (PropertyGroupBasic<TSourcePropertyType> sourceGroup in sourceGroups) { // get the dest group PropertyGroup destGroup = MapSaveGroup(sourceGroup, destOrigGroups, context); // handle local properties IPropertyType[] destProperties = sourceGroup.Properties .Where(x => x.Inherited == false) .Select(x => MapSaveProperty(x, destOrigProperties, context)) .ToArray(); // if the group has no local properties and is not used as parent, skip it, ie sort-of garbage-collect // local groups which would not have local properties anymore if (destProperties.Length == 0 && !sourceGroupParentAliases.Contains(sourceGroup.Alias)) { continue; } // ensure no duplicate alias, then assign the group properties collection EnsureUniqueAliases(destProperties); destGroup.PropertyTypes = new PropertyTypeCollection(isPublishing, destProperties); destGroups.Add(destGroup); } // ensure no duplicate name, then assign the groups collection EnsureUniqueAliases(destGroups); target.PropertyGroups = new PropertyGroupCollection(destGroups); // because the property groups collection was rebuilt, there is no need to remove // the old groups - they are just gone and will be cleared by the repository // handle non-grouped (ie generic) properties PropertyGroupBasic<TSourcePropertyType> genericPropertiesGroup = source.Groups.FirstOrDefault(x => x.IsGenericProperties); if (genericPropertiesGroup != null) { // handle local properties IPropertyType[] destProperties = genericPropertiesGroup.Properties .Where(x => x.Inherited == false) .Select(x => MapSaveProperty(x, destOrigProperties, context)) .ToArray(); // ensure no duplicate alias, then assign the generic properties collection EnsureUniqueAliases(destProperties); target.NoGroupPropertyTypes = new PropertyTypeCollection(isPublishing, destProperties); } // because all property collections were rebuilt, there is no need to remove // some old properties, they are just gone and will be cleared by the repository } // Umbraco.Code.MapAll -Blueprints -Errors -ListViewEditorName -Trashed private void MapTypeToDisplayBase(IContentTypeComposition source, ContentTypeCompositionDisplay target) { target.Alias = source.Alias; target.AllowAsRoot = source.AllowedAsRoot; target.CreateDate = source.CreateDate; target.Description = source.Description; target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty : $"{_globalSettings.GetBackOfficePath(_hostingEnvironment).EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Id = source.Id; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; target.Key = source.Key; target.Name = source.Name; target.ParentId = source.ParentId; target.Path = source.Path; target.Thumbnail = source.Thumbnail; target.ThumbnailFilePath = target.ThumbnailIsClass ? string.Empty : _hostingEnvironment.ToAbsolute("~/umbraco/images/thumbnails/" + source.Thumbnail); target.Udi = MapContentTypeUdi(source); target.UpdateDate = source.UpdateDate; target.AllowedContentTypes = source.AllowedContentTypes.OrderBy(c => c.SortOrder).Select(x => x.Id.Value); target.CompositeContentTypes = source.ContentTypeComposition.Select(x => x.Alias); target.LockedCompositeContentTypes = MapLockedCompositions(source); } // no MapAll - relies on the non-generic method private void MapTypeToDisplayBase<TTarget, TTargetPropertyType>(IContentTypeComposition source, TTarget target) where TTarget : ContentTypeCompositionDisplay<TTargetPropertyType> where TTargetPropertyType : PropertyTypeDisplay, new() { MapTypeToDisplayBase(source, target); var groupsMapper = new PropertyTypeGroupMapper<TTargetPropertyType>(_propertyEditors, _dataTypeService, _shortStringHelper, _loggerFactory.CreateLogger<PropertyTypeGroupMapper<TTargetPropertyType>>()); target.Groups = groupsMapper.Map(source); } // Umbraco.Code.MapAll -CreateDate -UpdateDate -ListViewEditorName -Errors -LockedCompositeContentTypes private void MapTypeToDisplayBase(ContentTypeSave source, ContentTypeCompositionDisplay target) { target.Alias = source.Alias; target.AllowAsRoot = source.AllowAsRoot; target.AllowedContentTypes = source.AllowedContentTypes; target.Blueprints = source.Blueprints; target.CompositeContentTypes = source.CompositeContentTypes; target.Description = source.Description; target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty : $"{_globalSettings.GetBackOfficePath(_hostingEnvironment).EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Id = source.Id; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; target.Key = source.Key; target.Name = source.Name; target.ParentId = source.ParentId; target.Path = source.Path; target.Thumbnail = source.Thumbnail; target.ThumbnailFilePath = target.ThumbnailIsClass ? string.Empty : _hostingEnvironment.ToAbsolute("~/umbraco/images/thumbnails/" + source.Thumbnail); target.Trashed = source.Trashed; target.Udi = source.Udi; } // no MapAll - relies on the non-generic method private void MapTypeToDisplayBase<TSource, TSourcePropertyType, TTarget, TTargetPropertyType>(TSource source, TTarget target, MapperContext context) where TSource : ContentTypeSave<TSourcePropertyType> where TSourcePropertyType : PropertyTypeBasic where TTarget : ContentTypeCompositionDisplay<TTargetPropertyType> where TTargetPropertyType : PropertyTypeDisplay { MapTypeToDisplayBase(source, target); target.Groups = context .MapEnumerable<PropertyGroupBasic<TSourcePropertyType>, PropertyGroupDisplay<TTargetPropertyType>>( source.Groups); } private IEnumerable<string> MapLockedCompositions(IContentTypeComposition source) { // get ancestor ids from path of parent if not root if (source.ParentId == Constants.System.Root) { return Enumerable.Empty<string>(); } IContentType parent = _contentTypeService.Get(source.ParentId); if (parent == null) { return Enumerable.Empty<string>(); } var aliases = new List<string>(); IEnumerable<int> ancestorIds = parent.Path.Split(Constants.CharArrays.Comma) .Select(s => int.Parse(s, CultureInfo.InvariantCulture)); // loop through all content types and return ordered aliases of ancestors IContentType[] allContentTypes = _contentTypeService.GetAll().ToArray(); foreach (var ancestorId in ancestorIds) { IContentType ancestor = allContentTypes.FirstOrDefault(x => x.Id == ancestorId); if (ancestor != null) { aliases.Add(ancestor.Alias); } } return aliases.OrderBy(x => x); } public static Udi MapContentTypeUdi(IContentTypeComposition source) { if (source == null) { return null; } string udiType; switch (source) { case IMemberType _: udiType = Constants.UdiEntityType.MemberType; break; case IMediaType _: udiType = Constants.UdiEntityType.MediaType; break; case IContentType _: udiType = Constants.UdiEntityType.DocumentType; break; default: throw new PanicException($"Source is of type {source.GetType()} which isn't supported here"); } return Udi.Create(udiType, source.Key); } private static PropertyGroup MapSaveGroup<TPropertyType>(PropertyGroupBasic<TPropertyType> sourceGroup, IEnumerable<PropertyGroup> destOrigGroups, MapperContext context) where TPropertyType : PropertyTypeBasic { PropertyGroup destGroup; if (sourceGroup.Id > 0) { // update an existing group // ensure it is still there, then map/update destGroup = destOrigGroups.FirstOrDefault(x => x.Id == sourceGroup.Id); if (destGroup != null) { context.Map(sourceGroup, destGroup); return destGroup; } // force-clear the ID as it does not match anything sourceGroup.Id = 0; } // insert a new group, or update an existing group that has // been deleted in the meantime and we need to re-create // map/create destGroup = context.Map<PropertyGroup>(sourceGroup); return destGroup; } private static IPropertyType MapSaveProperty(PropertyTypeBasic sourceProperty, IEnumerable<IPropertyType> destOrigProperties, MapperContext context) { IPropertyType destProperty; if (sourceProperty.Id > 0) { // updating an existing property // ensure it is still there, then map/update destProperty = destOrigProperties.FirstOrDefault(x => x.Id == sourceProperty.Id); if (destProperty != null) { context.Map(sourceProperty, destProperty); return destProperty; } // force-clear the ID as it does not match anything sourceProperty.Id = 0; } // insert a new property, or update an existing property that has // been deleted in the meantime and we need to re-create // map/create destProperty = context.Map<IPropertyType>(sourceProperty); return destProperty; } private static void EnsureUniqueAliases(IEnumerable<IPropertyType> properties) { IPropertyType[] propertiesA = properties.ToArray(); var distinctProperties = propertiesA .Select(x => x.Alias?.ToUpperInvariant()) .Distinct() .Count(); if (distinctProperties != propertiesA.Length) { throw new InvalidOperationException("Cannot map properties due to alias conflict."); } } private static void EnsureUniqueAliases(IEnumerable<PropertyGroup> groups) { PropertyGroup[] groupsA = groups.ToArray(); var distinctProperties = groupsA .Select(x => x.Alias) .Distinct() .Count(); if (distinctProperties != groupsA.Length) { throw new InvalidOperationException("Cannot map groups due to alias conflict."); } } private static void MapComposition(ContentTypeSave source, IContentTypeComposition target, Func<string, IContentTypeComposition> getContentType) { var current = target.CompositionAliases().ToArray(); IEnumerable<string> proposed = source.CompositeContentTypes; IEnumerable<string> remove = current.Where(x => !proposed.Contains(x)); IEnumerable<string> add = proposed.Where(x => !current.Contains(x)); foreach (var alias in remove) { target.RemoveContentType(alias); } foreach (var alias in add) { // TODO: Remove N+1 lookup IContentTypeComposition contentType = getContentType(alias); if (contentType != null) { target.AddContentType(contentType); } } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.ComponentModel; namespace Dalssoft.DiagramNet { [Serializable] public class RightAngleLinkElement: BaseLinkElement, IControllable, ILabelElement { internal protected LineElement[] lines = {new LineElement(0,0,0,0)}; internal protected Orientation orientation; internal protected CardinalDirection conn1Dir; internal protected CardinalDirection conn2Dir; protected bool needCalcLinkLocation = true; protected bool needCalcLinkSize = true; protected LabelElement label = new LabelElement(); [NonSerialized] private RightAngleLinkController controller; public RightAngleLinkElement(ConnectorElement conn1, ConnectorElement conn2): base(conn1, conn2) { needCalcLink = true; InitConnectors(conn1, conn2); foreach(LineElement l in lines) { l.StartCap = LineCap.Round; l.EndCap = LineCap.Round; } startCap = LineCap.Round; endCap = LineCap.Round; label.PositionBySite(lines[1]); } #region Properties [Browsable(false)] public override Point Point1 { get { return lines[0].Point1; } } [Browsable(false)] public override Point Point2 { get { return lines[lines.Length - 1].Point2; } } public override Color BorderColor { get { return base.borderColor; } set { base.borderColor = value; foreach (LineElement l in lines) l.BorderColor = value; OnAppearanceChanged(new EventArgs()); } } public override int BorderWidth { get { return base.borderWidth; } set { base.borderWidth = value; foreach (LineElement l in lines) l.BorderWidth = value; OnAppearanceChanged(new EventArgs()); } } public override Point Location { get { CalcLinkLocation(); return location; } set { IMoveController ctrl = (IMoveController) ((IControllable) this).GetController(); if (!ctrl.IsMoving) return; Point locBefore = this.Location; Point locAfter = value; Point locDiff = new Point(locAfter.X - locBefore.X, locAfter.Y - locBefore.Y); foreach(LineElement l in lines) { Point lPoint1 = l.Point1; Point lPoint2 = l.Point2; l.Point1 = new Point(lPoint1.X + locDiff.X, lPoint1.Y + locDiff.Y); l.Point2 = new Point(lPoint2.X + locDiff.X, lPoint2.Y + locDiff.Y); } needCalcLink = true; OnAppearanceChanged(new EventArgs()); } } public override Size Size { get { CalcLinkSize(); return size; } } public override int Opacity { get { return base.opacity; } set { base.opacity = value; foreach (LineElement l in lines) l.Opacity = value; OnAppearanceChanged(new EventArgs()); } } public override LineCap StartCap { get { return base.startCap; } set { base.startCap = value; lines[0].StartCap = value; OnAppearanceChanged(new EventArgs()); } } public override LineCap EndCap { get { return base.endCap; } set { base.endCap = value; lines[lines.Length - 1].EndCap = value; OnAppearanceChanged(new EventArgs()); } } public override LineElement[] Lines { get { return (LineElement[]) lines.Clone(); } } #endregion internal override void Draw(Graphics g) { IsInvalidated = false; CalcLink(); for(int i = 0; i < lines.Length; i++) lines[i].Draw(g); } private void InitConnectors(ConnectorElement conn1, ConnectorElement conn2) { conn1Dir = conn1.GetDirection(); conn2Dir = conn2.GetDirection(); if ((conn1Dir == CardinalDirection.North) || (conn1Dir == CardinalDirection.South)) orientation = Orientation.Vertical; else orientation = Orientation.Horizontal; if ( ( ((conn1Dir == CardinalDirection.North) || (conn1Dir == CardinalDirection.South)) && ((conn2Dir == CardinalDirection.East) || (conn2Dir == CardinalDirection.West))) || ( ((conn1Dir == CardinalDirection.East) || (conn1Dir == CardinalDirection.West)) && ((conn2Dir == CardinalDirection.North) || (conn2Dir == CardinalDirection.South))) ) { lines = new LineElement[2]; lines[0] = new LineElement(0, 0, 0, 0); lines[1] = new LineElement(0, 0, 0, 0); } else { lines = new LineElement[3]; lines[0] = new LineElement(0, 0, 0, 0); lines[1] = new LineElement(0, 0, 0, 0); lines[2] = new LineElement(0, 0, 0, 0); } CalcLinkFirtTime(); CalcLink(); RestartProps(); } private void RestartProps() { foreach(LineElement line in lines) { line.BorderColor = base.borderColor; line.BorderWidth = base.borderWidth; line.Opacity = base.opacity; line.StartCap = base.startCap; line.EndCap = base.endCap; } } protected override void OnConnectorChanged(EventArgs e) { InitConnectors(connector1, connector2); base.OnConnectorChanged (e); } internal void CalcLinkFirtTime() { if (lines == null) return; LineElement lastLine = lines[lines.Length - 1]; Point connector1Location = connector1.Location; Point connector2Location = connector2.Location; Size connector1Size = connector1.Size; Size connector2Size = connector2.Size; lines[0].Point1 = new Point(connector1Location.X + connector1Size.Width / 2, connector1Location.Y + connector1Size.Height / 2); lastLine.Point2 = new Point(connector2Location.X + connector2Size.Width / 2, connector2Location.Y + connector2Size.Height / 2); if (lines.Length == 3) { Point lines0Point1 = lines[0].Point1; Point lastLinePoint2 = lastLine.Point2; if (orientation == Orientation.Horizontal) { lines[0].Point2 = new Point(lines0Point1.X + ((lastLinePoint2.X - lines0Point1.X) / 2), lines0Point1.Y); lastLine.Point1 = new Point(lines0Point1.X + ((lastLinePoint2.X - lines0Point1.X) / 2), lastLinePoint2.Y); } else if (orientation == Orientation.Vertical) { lines[0].Point2 = new Point(lines0Point1.X, lines0Point1.Y + ((lastLinePoint2.Y - lines0Point1.Y) / 2)); lastLine.Point1 = new Point(lastLinePoint2.X, lines0Point1.Y + ((lastLinePoint2.Y - lines0Point1.Y) / 2)); } } } internal override void CalcLink() { if (needCalcLink == false) return; if (lines == null) return; LineElement lastLine = lines[lines.Length - 1]; //Otimization - Get prop. value only one time Point connector1Location = connector1.Location; Point connector2Location = connector2.Location; Size connector1Size = connector1.Size; Size connector2Size = connector2.Size; lines[0].Point1 = new Point(connector1Location.X + connector1Size.Width / 2, connector1Location.Y + connector1Size.Height / 2); lastLine.Point2 = new Point(connector2Location.X + connector2Size.Width / 2, connector2Location.Y + connector2Size.Height / 2); if (lines.Length == 3) { if (orientation == Orientation.Horizontal) { lines[0].Point2 = new Point(lines[0].Point2.X, lines[0].Point1.Y); lastLine.Point1 = new Point(lastLine.Point1.X, lastLine.Point2.Y); lines[1].Point1 = lines[0].Point2; lines[1].Point2 = lines[2].Point1; } else if (orientation == Orientation.Vertical) { lines[0].Point2 = new Point(lines[0].Point1.X, lines[0].Point2.Y); lastLine.Point1 = new Point(lastLine.Point2.X, lastLine.Point1.Y); lines[1].Point1 = lines[0].Point2; lines[1].Point2 = lines[2].Point1; } } else if (lines.Length == 2) { if ((conn1Dir == CardinalDirection.North) || (conn1Dir == CardinalDirection.South)) lines[0].Point2 = new Point(lines[0].Point1.X, lastLine.Point2.Y); else lines[0].Point2 = new Point(lastLine.Point2.X, lines[0].Point1.Y); lastLine.Point1 = lines[0].Point2; } needCalcLinkLocation = true; needCalcLinkSize = true; needCalcLink = false; } private void CalcLinkLocation() { //CalcLink(); if (!needCalcLinkLocation) return; Point[] points = new Point[lines.Length * 2]; int i = 0; foreach(LineElement ln in lines) { points[i] = ln.Point1; points[i + 1] = ln.Point2; i+=2; } location = DiagramUtil.GetUpperPoint(points); needCalcLinkLocation = false; } private void CalcLinkSize() { if (!needCalcLinkSize) return; Size sizeTmp = Size.Empty; if (lines.Length > 1) { Point[] points = new Point[lines.Length * 2]; int i = 0; foreach(LineElement ln in lines) { points[i] = ln.Point1; points[i + 1] = ln.Point2; i+=2; } Point upper = DiagramUtil.GetUpperPoint(points); Point lower = DiagramUtil.GetLowerPoint(points); sizeTmp = new Size(lower.X - upper.X, lower.Y - upper.Y); } size = sizeTmp; needCalcLinkSize = false; } #region IControllable Members IController IControllable.GetController() { if (controller == null) controller = new RightAngleLinkController(this); return controller; } #endregion #region ILabelElement Members public virtual LabelElement Label { get { return label; } set { label = value; OnAppearanceChanged(new EventArgs()); } } #endregion } }
using System.Collections.Generic; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Orders; using Nop.Services.Discounts; namespace Nop.Services.Orders { /// <summary> /// Order service interface /// </summary> public partial interface IOrderTotalCalculationService { /// <summary> /// Gets shopping cart subtotal /// </summary> /// <param name="cart">Cart</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="discountAmount">Applied discount amount</param> /// <param name="appliedDiscounts">Applied discounts</param> /// <param name="subTotalWithoutDiscount">Sub total (without discount)</param> /// <param name="subTotalWithDiscount">Sub total (with discount)</param> void GetShoppingCartSubTotal(IList<ShoppingCartItem> cart, bool includingTax, out decimal discountAmount, out List<DiscountForCaching> appliedDiscounts, out decimal subTotalWithoutDiscount, out decimal subTotalWithDiscount); /// <summary> /// Gets shopping cart subtotal /// </summary> /// <param name="cart">Cart</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="discountAmount">Applied discount amount</param> /// <param name="appliedDiscounts">Applied discounts</param> /// <param name="subTotalWithoutDiscount">Sub total (without discount)</param> /// <param name="subTotalWithDiscount">Sub total (with discount)</param> /// <param name="taxRates">Tax rates (of order sub total)</param> void GetShoppingCartSubTotal(IList<ShoppingCartItem> cart, bool includingTax, out decimal discountAmount, out List<DiscountForCaching> appliedDiscounts, out decimal subTotalWithoutDiscount, out decimal subTotalWithDiscount, out SortedDictionary<decimal, decimal> taxRates); /// <summary> /// Adjust shipping rate (free shipping, additional charges, discounts) /// </summary> /// <param name="shippingRate">Shipping rate to adjust</param> /// <param name="cart">Cart</param> /// <param name="appliedDiscounts">Applied discounts</param> /// <returns>Adjusted shipping rate</returns> decimal AdjustShippingRate(decimal shippingRate, IList<ShoppingCartItem> cart, out List<DiscountForCaching> appliedDiscounts); /// <summary> /// Gets shopping cart additional shipping charge /// </summary> /// <param name="cart">Cart</param> /// <returns>Additional shipping charge</returns> decimal GetShoppingCartAdditionalShippingCharge(IList<ShoppingCartItem> cart); /// <summary> /// Gets a value indicating whether shipping is free /// </summary> /// <param name="cart">Cart</param> /// <param name="subTotal">Subtotal amount; pass null to calculate subtotal</param> /// <returns>A value indicating whether shipping is free</returns> bool IsFreeShipping(IList<ShoppingCartItem> cart, decimal? subTotal = null); /// <summary> /// Gets shopping cart shipping total /// </summary> /// <param name="cart">Cart</param> /// <returns>Shipping total</returns> decimal? GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart); /// <summary> /// Gets shopping cart shipping total /// </summary> /// <param name="cart">Cart</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <returns>Shipping total</returns> decimal? GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax); /// <summary> /// Gets shopping cart shipping total /// </summary> /// <param name="cart">Cart</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="taxRate">Applied tax rate</param> /// <returns>Shipping total</returns> decimal? GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax, out decimal taxRate); /// <summary> /// Gets shopping cart shipping total /// </summary> /// <param name="cart">Cart</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="taxRate">Applied tax rate</param> /// <param name="appliedDiscounts">Applied discounts</param> /// <returns>Shipping total</returns> decimal? GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax, out decimal taxRate, out List<DiscountForCaching> appliedDiscounts); /// <summary> /// Gets tax /// </summary> /// <param name="cart">Shopping cart</param> /// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating tax</param> /// <returns>Tax total</returns> decimal GetTaxTotal(IList<ShoppingCartItem> cart, bool usePaymentMethodAdditionalFee = true); /// <summary> /// Gets tax /// </summary> /// <param name="cart">Shopping cart</param> /// <param name="taxRates">Tax rates</param> /// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating tax</param> /// <returns>Tax total</returns> decimal GetTaxTotal(IList<ShoppingCartItem> cart, out SortedDictionary<decimal, decimal> taxRates, bool usePaymentMethodAdditionalFee = true); /// <summary> /// Gets shopping cart total /// </summary> /// <param name="cart">Cart</param> /// <param name="useRewardPoints">A value indicating reward points should be used; null to detect current choice of the customer</param> /// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating order total</param> /// <returns>Shopping cart total;Null if shopping cart total couldn't be calculated now</returns> decimal? GetShoppingCartTotal(IList<ShoppingCartItem> cart, bool? useRewardPoints = null, bool usePaymentMethodAdditionalFee = true); /// <summary> /// Gets shopping cart total /// </summary> /// <param name="cart">Cart</param> /// <param name="appliedGiftCards">Applied gift cards</param> /// <param name="discountAmount">Applied discount amount</param> /// <param name="appliedDiscounts">Applied discounts</param> /// <param name="redeemedRewardPoints">Reward points to redeem</param> /// <param name="redeemedRewardPointsAmount">Reward points amount in primary store currency to redeem</param> /// <param name="useRewardPoints">A value indicating reward points should be used; null to detect current choice of the customer</param> /// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating order total</param> /// <returns>Shopping cart total;Null if shopping cart total couldn't be calculated now</returns> decimal? GetShoppingCartTotal(IList<ShoppingCartItem> cart, out decimal discountAmount, out List<DiscountForCaching> appliedDiscounts, out List<AppliedGiftCard> appliedGiftCards, out int redeemedRewardPoints, out decimal redeemedRewardPointsAmount, bool? useRewardPoints = null, bool usePaymentMethodAdditionalFee = true); /// <summary> /// Update order totals /// </summary> /// <param name="updateOrderParameters">Parameters for the updating order</param> /// <param name="restoredCart">Shopping cart</param> void UpdateOrderTotals(UpdateOrderParameters updateOrderParameters, IList<ShoppingCartItem> restoredCart); /// <summary> /// Converts existing reward points to amount /// </summary> /// <param name="rewardPoints">Reward points</param> /// <returns>Converted value</returns> decimal ConvertRewardPointsToAmount(int rewardPoints); /// <summary> /// Converts an amount to reward points /// </summary> /// <param name="amount">Amount</param> /// <returns>Converted value</returns> int ConvertAmountToRewardPoints(decimal amount); /// <summary> /// Gets a value indicating whether a customer has minimum amount of reward points to use (if enabled) /// </summary> /// <param name="rewardPoints">Reward points to check</param> /// <returns>true - reward points could use; false - cannot be used.</returns> bool CheckMinimumRewardPointsToUseRequirement(int rewardPoints); /// <summary> /// Calculate how order total (maximum amount) for which reward points could be earned/reduced /// </summary> /// <param name="orderShippingInclTax">Order shipping (including tax)</param> /// <param name="orderTotal">Order total</param> /// <returns>Applicable order total</returns> decimal CalculateApplicableOrderTotalForRewardPoints(decimal orderShippingInclTax, decimal orderTotal); /// <summary> /// Calculate how much reward points will be earned/reduced based on certain amount spent /// </summary> /// <param name="customer">Customer</param> /// <param name="amount">Amount (in primary store currency)</param> /// <returns>Number of reward points</returns> int CalculateRewardPoints(Customer customer, decimal amount); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Media { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for MediaServiceOperations. /// </summary> public static partial class MediaServiceOperationsExtensions { /// <summary> /// Check whether the Media Service resource name is available. The name must /// be globally unique. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='checkNameAvailabilityInput'> /// Properties needed to check the availability of a name. /// </param> public static CheckNameAvailabilityOutput CheckNameAvailabilty(this IMediaServiceOperations operations, CheckNameAvailabilityInput checkNameAvailabilityInput) { return Task.Factory.StartNew(s => ((IMediaServiceOperations)s).CheckNameAvailabiltyAsync(checkNameAvailabilityInput), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Check whether the Media Service resource name is available. The name must /// be globally unique. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='checkNameAvailabilityInput'> /// Properties needed to check the availability of a name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckNameAvailabilityOutput> CheckNameAvailabiltyAsync(this IMediaServiceOperations operations, CheckNameAvailabilityInput checkNameAvailabilityInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckNameAvailabiltyWithHttpMessagesAsync(checkNameAvailabilityInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// List all of the Media Services in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> public static IEnumerable<MediaService> ListByResourceGroup(this IMediaServiceOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((IMediaServiceOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List all of the Media Services in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<MediaService>> ListByResourceGroupAsync(this IMediaServiceOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> public static MediaService Get(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName) { return Task.Factory.StartNew(s => ((IMediaServiceOperations)s).GetAsync(resourceGroupName, mediaServiceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MediaService> GetAsync(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, mediaServiceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='mediaService'> /// Media Service properties needed for creation. /// </param> public static MediaService Create(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, MediaService mediaService) { return Task.Factory.StartNew(s => ((IMediaServiceOperations)s).CreateAsync(resourceGroupName, mediaServiceName, mediaService), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='mediaService'> /// Media Service properties needed for creation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MediaService> CreateAsync(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, MediaService mediaService, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, mediaServiceName, mediaService, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> public static void Delete(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName) { Task.Factory.StartNew(s => ((IMediaServiceOperations)s).DeleteAsync(resourceGroupName, mediaServiceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, mediaServiceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Update a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='mediaService'> /// Media Service properties needed for update. /// </param> public static MediaService Update(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, MediaService mediaService) { return Task.Factory.StartNew(s => ((IMediaServiceOperations)s).UpdateAsync(resourceGroupName, mediaServiceName, mediaService), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='mediaService'> /// Media Service properties needed for update. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MediaService> UpdateAsync(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, MediaService mediaService, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, mediaServiceName, mediaService, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerate the key for a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='regenerateKeyInput'> /// Properties needed to regenerate the Media Service key. /// </param> public static RegenerateKeyOutput RegenerateKey(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, RegenerateKeyInput regenerateKeyInput) { return Task.Factory.StartNew(s => ((IMediaServiceOperations)s).RegenerateKeyAsync(resourceGroupName, mediaServiceName, regenerateKeyInput), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerate the key for a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='regenerateKeyInput'> /// Properties needed to regenerate the Media Service key. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RegenerateKeyOutput> RegenerateKeyAsync(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, RegenerateKeyInput regenerateKeyInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, mediaServiceName, regenerateKeyInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// List the keys for a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> public static ServiceKeys ListKeys(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName) { return Task.Factory.StartNew(s => ((IMediaServiceOperations)s).ListKeysAsync(resourceGroupName, mediaServiceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List the keys for a Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ServiceKeys> ListKeysAsync(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, mediaServiceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Synchronize the keys for a storage account to the Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='syncStorageKeysInput'> /// Properties needed to sycnronize the keys for a storage account to the /// Media Service. /// </param> public static MediaService SyncStorageKeys(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, SyncStorageKeysInput syncStorageKeysInput) { return Task.Factory.StartNew(s => ((IMediaServiceOperations)s).SyncStorageKeysAsync(resourceGroupName, mediaServiceName, syncStorageKeysInput), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Synchronize the keys for a storage account to the Media Service. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the Azure subscription. /// </param> /// <param name='mediaServiceName'> /// Name of the Media Service. /// </param> /// <param name='syncStorageKeysInput'> /// Properties needed to sycnronize the keys for a storage account to the /// Media Service. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MediaService> SyncStorageKeysAsync(this IMediaServiceOperations operations, string resourceGroupName, string mediaServiceName, SyncStorageKeysInput syncStorageKeysInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.SyncStorageKeysWithHttpMessagesAsync(resourceGroupName, mediaServiceName, syncStorageKeysInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.Extensions.DependencyInjection; using OrchardCore.DisplayManagement.Razor; using OrchardCore.DisplayManagement.Shapes; using OrchardCore.DisplayManagement.Title; using OrchardCore.Settings; namespace OrchardCore.DisplayManagement.RazorPages { public abstract class Page : Microsoft.AspNetCore.Mvc.RazorPages.Page { private dynamic _displayHelper; private IShapeFactory _shapeFactory; private IOrchardDisplayHelper _orchardHelper; private ISite _site; public override ViewContext ViewContext { get => base.ViewContext; set { // We make the ViewContext available to other sub-systems that need it. var viewContextAccessor = value.HttpContext.RequestServices.GetService<ViewContextAccessor>(); base.ViewContext = viewContextAccessor.ViewContext = value; } } private void EnsureDisplayHelper() { if (_displayHelper == null) { _displayHelper = HttpContext.RequestServices.GetService<IDisplayHelper>(); } } private void EnsureShapeFactory() { if (_shapeFactory == null) { _shapeFactory = HttpContext.RequestServices.GetService<IShapeFactory>(); } } /// <summary> /// Gets a dynamic shape factory to create new shapes. /// </summary> /// <example> /// Usage: /// <code> /// await New.MyShape() /// await New.MyShape(A: 1, B: "Some text") /// (await New.MyShape()).A(1).B("Some text") /// </code> /// </example> public dynamic New => Factory; /// <summary> /// Gets an <see cref="IShapeFactory"/> to create new shapes. /// </summary> public IShapeFactory Factory { get { EnsureShapeFactory(); return _shapeFactory; } } /// <summary> /// Renders a shape. /// </summary> /// <param name="shape">The shape.</param> public Task<IHtmlContent> DisplayAsync(dynamic shape) { EnsureDisplayHelper(); return (Task<IHtmlContent>)_displayHelper(shape); } public IOrchardDisplayHelper Orchard { get { if (_orchardHelper == null) { EnsureDisplayHelper(); _orchardHelper = new OrchardDisplayHelper(HttpContext, _displayHelper); } return _orchardHelper; } } private dynamic _themeLayout; public dynamic ThemeLayout { get { if (_themeLayout == null) { _themeLayout = HttpContext.Features.Get<RazorViewFeature>()?.ThemeLayout; } return _themeLayout; } set { _themeLayout = value; } } public string ViewLayout { get { if (ThemeLayout is IShape layout) { if (layout.Metadata.Alternates.Count > 0) { return layout.Metadata.Alternates.Last; } return layout.Metadata.Type; } return String.Empty; } set { if (ThemeLayout is IShape layout) { if (layout.Metadata.Alternates.Contains(value)) { if (layout.Metadata.Alternates.Last == value) { return; } layout.Metadata.Alternates.Remove(value); } layout.Metadata.Alternates.Add(value); } } } private IPageTitleBuilder _pageTitleBuilder; public IPageTitleBuilder Title { get { if (_pageTitleBuilder == null) { _pageTitleBuilder = HttpContext.RequestServices.GetRequiredService<IPageTitleBuilder>(); } return _pageTitleBuilder; } } private IViewLocalizer _t; /// <summary> /// The <see cref="IViewLocalizer"/> instance for the current view. /// </summary> public IViewLocalizer T { get { if (_t == null) { _t = HttpContext.RequestServices.GetRequiredService<IViewLocalizer>(); ((IViewContextAware)_t).Contextualize(ViewContext); } return _t; } } /// <summary> /// Adds a segment to the title and returns all segments. /// </summary> /// <param name="segment">The segment to add to the title.</param> /// <param name="position">Optional. The position of the segment in the title.</param> /// <param name="separator">The html string that should separate all segments.</param> /// <returns>And <see cref="IHtmlContent"/> instance representing the full title.</returns> public IHtmlContent RenderTitleSegments(IHtmlContent segment, string position = "0", IHtmlContent separator = null) { Title.AddSegment(segment, position); return Title.GenerateTitle(separator); } /// <summary> /// Adds a segment to the title and returns all segments. /// </summary> /// <param name="segment">The segment to add to the title.</param> /// <param name="position">Optional. The position of the segment in the title.</param> /// <param name="separator">The html string that should separate all segments.</param> /// <returns>And <see cref="IHtmlContent"/> instance representing the full title.</returns> public IHtmlContent RenderTitleSegments(string segment, string position = "0", IHtmlContent separator = null) { Title.AddSegment(new StringHtmlContent(segment), position); return Title.GenerateTitle(separator); } /// <summary> /// Creates a <see cref="TagBuilder"/> to render a shape. /// </summary> /// <param name="shape">The shape.</param> /// <returns>A new <see cref="TagBuilder"/>.</returns> public TagBuilder Tag(dynamic shape) { return Shape.GetTagBuilder(shape); } public TagBuilder Tag(dynamic shape, string tag) { return Shape.GetTagBuilder(shape, tag); } public object OrDefault(object text, object other) { if (text == null || Convert.ToString(text) == "") { return other; } return text; } /// <summary> /// Returns the full escaped path of the current request. /// </summary> public string FullRequestPath => HttpContext.Request.PathBase + HttpContext.Request.Path + HttpContext.Request.QueryString; /// <summary> /// Gets the <see cref="ISite"/> instance. /// </summary> public ISite Site { get { if (_site == null) { _site = HttpContext.Features.Get<RazorViewFeature>()?.Site; } return _site; } } } }
#if !SILVERLIGHT using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace ReflectionAccessor { internal static class DynamicMethodFactory { public static Func<object, object[], object> CreateMethod(MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException(nameof(methodInfo)); var dynamicMethod = CreateDynamicMethod( "Dynamic" + methodInfo.Name, typeof(object), new[] { typeof(object), typeof(object[]) }, methodInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); var parameters = methodInfo.GetParameters(); var paramTypes = new Type[parameters.Length]; for (int i = 0; i < paramTypes.Length; i++) { var parameterInfo = parameters[i]; if (parameterInfo.ParameterType.IsByRef) paramTypes[i] = parameterInfo.ParameterType.GetElementType(); else paramTypes[i] = parameterInfo.ParameterType; } var locals = new LocalBuilder[paramTypes.Length]; for (int i = 0; i < paramTypes.Length; i++) locals[i] = generator.DeclareLocal(paramTypes[i], true); for (int i = 0; i < paramTypes.Length; i++) { generator.Emit(OpCodes.Ldarg_1); generator.FastInt(i); generator.Emit(OpCodes.Ldelem_Ref); generator.UnboxIfNeeded(paramTypes[i]); generator.Emit(OpCodes.Stloc, locals[i]); } if (!methodInfo.IsStatic) generator.Emit(OpCodes.Ldarg_0); for (int i = 0; i < paramTypes.Length; i++) { if (parameters[i].ParameterType.IsByRef) generator.Emit(OpCodes.Ldloca_S, locals[i]); else generator.Emit(OpCodes.Ldloc, locals[i]); } if (methodInfo.IsStatic) generator.EmitCall(OpCodes.Call, methodInfo, null); else generator.EmitCall(OpCodes.Callvirt, methodInfo, null); if (methodInfo.ReturnType == typeof(void)) generator.Emit(OpCodes.Ldnull); else generator.BoxIfNeeded(methodInfo.ReturnType); for (int i = 0; i < paramTypes.Length; i++) { if (!parameters[i].ParameterType.IsByRef) continue; generator.Emit(OpCodes.Ldarg_1); generator.FastInt(i); generator.Emit(OpCodes.Ldloc, locals[i]); var localType = locals[i].LocalType; if (localType.GetTypeInfo().IsValueType) generator.Emit(OpCodes.Box, localType); generator.Emit(OpCodes.Stelem_Ref); } generator.Emit(OpCodes.Ret); return dynamicMethod.CreateDelegate(typeof(Func<object, object[], object>)) as Func<object, object[], object>; } public static Func<object> CreateConstructor(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); var dynamicMethod = CreateDynamicMethod( "Create" + type.FullName, typeof(object), Type.EmptyTypes, type); dynamicMethod.InitLocals = true; var generator = dynamicMethod.GetILGenerator(); var typeInfo = type.GetTypeInfo(); if (typeInfo.IsValueType) { generator.DeclareLocal(type); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Box, type); } else { #if NETSTANDARD1_3 var constructorInfo = typeInfo.DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Length == 0); #else var constructorInfo = typeInfo.GetConstructor(Type.EmptyTypes); #endif if (constructorInfo == null) throw new InvalidOperationException($"Could not get constructor for {type}."); generator.Emit(OpCodes.Newobj, constructorInfo); } generator.Return(); return dynamicMethod.CreateDelegate(typeof(Func<object>)) as Func<object>; } public static Func<object, object> CreateGet(PropertyInfo propertyInfo) { if (propertyInfo == null) throw new ArgumentNullException(nameof(propertyInfo)); if (!propertyInfo.CanRead) return null; var methodInfo = propertyInfo.GetGetMethod(true); if (methodInfo == null) return null; var dynamicMethod = CreateDynamicMethod( "Get" + propertyInfo.Name, typeof(object), new[] { typeof(object) }, propertyInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); if (!methodInfo.IsStatic) generator.PushInstance(propertyInfo.DeclaringType); generator.CallMethod(methodInfo); generator.BoxIfNeeded(propertyInfo.PropertyType); generator.Return(); return dynamicMethod.CreateDelegate(typeof(Func<object, object>)) as Func<object, object>; } public static Func<object, object> CreateGet(FieldInfo fieldInfo) { if (fieldInfo == null) throw new ArgumentNullException(nameof(fieldInfo)); var dynamicMethod = CreateDynamicMethod( "Get" + fieldInfo.Name, typeof(object), new[] { typeof(object) }, fieldInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); if (fieldInfo.IsStatic) generator.Emit(OpCodes.Ldsfld, fieldInfo); else generator.PushInstance(fieldInfo.DeclaringType); generator.Emit(OpCodes.Ldfld, fieldInfo); generator.BoxIfNeeded(fieldInfo.FieldType); generator.Return(); return dynamicMethod.CreateDelegate(typeof(Func<object, object>)) as Func<object, object>; } public static Action<object, object> CreateSet(PropertyInfo propertyInfo) { if (propertyInfo == null) throw new ArgumentNullException(nameof(propertyInfo)); if (!propertyInfo.CanWrite) return null; var methodInfo = propertyInfo.GetSetMethod(true); if (methodInfo == null) return null; var dynamicMethod = CreateDynamicMethod( "Set" + propertyInfo.Name, null, new[] { typeof(object), typeof(object) }, propertyInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); if (!methodInfo.IsStatic) generator.PushInstance(propertyInfo.DeclaringType); generator.Emit(OpCodes.Ldarg_1); generator.UnboxIfNeeded(propertyInfo.PropertyType); generator.CallMethod(methodInfo); generator.Return(); return dynamicMethod.CreateDelegate(typeof(Action<object, object>)) as Action<object, object>; } public static Action<object, object> CreateSet(FieldInfo fieldInfo) { if (fieldInfo == null) throw new ArgumentNullException(nameof(fieldInfo)); var dynamicMethod = CreateDynamicMethod( "Set" + fieldInfo.Name, null, new[] { typeof(object), typeof(object) }, fieldInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); if (fieldInfo.IsStatic) generator.Emit(OpCodes.Ldsfld, fieldInfo); else generator.PushInstance(fieldInfo.DeclaringType); generator.Emit(OpCodes.Ldarg_1); generator.UnboxIfNeeded(fieldInfo.FieldType); generator.Emit(OpCodes.Stfld, fieldInfo); generator.Return(); return dynamicMethod.CreateDelegate(typeof(Action<object, object>)) as Action<object, object>; } private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) { var typeInfo = owner.GetTypeInfo(); return !typeInfo.IsInterface ? new DynamicMethod(name, returnType, parameterTypes, owner, true) : new DynamicMethod(name, returnType, parameterTypes, typeInfo.Assembly.ManifestModule, true); } } } #endif
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Data.Services.Common; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; using Orleans.AzureUtils; using Orleans.Providers.Azure; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Providers; using Orleans.Serialization; namespace Orleans.Storage { /// <summary> /// Simple storage provider for writing grain state data to Azure table storage. /// </summary> /// <remarks> /// <para> /// Required configuration params: <c>DataConnectionString</c> /// </para> /// <para> /// Optional configuration params: /// <c>TableName</c> -- defaults to <c>OrleansGrainState</c> /// <c>DeleteStateOnClear</c> -- defaults to <c>false</c> /// </para> /// </remarks> /// <example> /// Example configuration for this storage provider in OrleansConfiguration.xml file: /// <code> /// &lt;OrleansConfiguration xmlns="urn:orleans"> /// &lt;Globals> /// &lt;StorageProviders> /// &lt;Provider Type="Orleans.Storage.AzureTableStorage" Name="AzureStore" /// DataConnectionString="UseDevelopmentStorage=true" /// DeleteStateOnClear="true" /// /> /// &lt;/StorageProviders> /// </code> /// </example> public class AzureTableStorage : IStorageProvider, IRestExceptionDecoder { private const string DATA_CONNECTION_STRING = "DataConnectionString"; private const string TABLE_NAME_PROPERTY = "TableName"; private const string DELETE_ON_CLEAR_PROPERTY = "DeleteStateOnClear"; private const string GRAIN_STATE_TABLE_NAME_DEFAULT = "OrleansGrainState"; private string dataConnectionString; private string tableName; private string serviceId; private GrainStateTableDataManager tableDataManager; private bool isDeleteStateOnClear; private static int counter; private readonly int id; private const int MAX_DATA_SIZE = 64 * 1024; // 64KB private const string USE_JSON_FORMAT_PROPERTY = "UseJsonFormat"; private bool useJsonFormat; private Newtonsoft.Json.JsonSerializerSettings jsonSettings; /// <summary> Name of this storage provider instance. </summary> /// <see cref="IProvider.Name"/> public string Name { get; private set; } /// <summary> Logger used by this storage provider instance. </summary> /// <see cref="IStorageProvider.Log"/> public Logger Log { get; private set; } /// <summary> Default constructor </summary> public AzureTableStorage() { tableName = GRAIN_STATE_TABLE_NAME_DEFAULT; id = Interlocked.Increment(ref counter); } /// <summary> Initialization function for this storage provider. </summary> /// <see cref="IProvider.Init"/> public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config) { Name = name; serviceId = providerRuntime.ServiceId.ToString(); if (!config.Properties.ContainsKey(DATA_CONNECTION_STRING) || string.IsNullOrWhiteSpace(config.Properties[DATA_CONNECTION_STRING])) throw new ArgumentException("DataConnectionString property not set"); dataConnectionString = config.Properties["DataConnectionString"]; if (config.Properties.ContainsKey(TABLE_NAME_PROPERTY)) tableName = config.Properties[TABLE_NAME_PROPERTY]; isDeleteStateOnClear = config.Properties.ContainsKey(DELETE_ON_CLEAR_PROPERTY) && "true".Equals(config.Properties[DELETE_ON_CLEAR_PROPERTY], StringComparison.OrdinalIgnoreCase); Log = providerRuntime.GetLogger("Storage.AzureTableStorage." + id); var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}", Name, serviceId, tableName, isDeleteStateOnClear); if (config.Properties.ContainsKey(USE_JSON_FORMAT_PROPERTY)) useJsonFormat = "true".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase); if (useJsonFormat) { jsonSettings = new Newtonsoft.Json.JsonSerializerSettings(); jsonSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All; } initMsg = String.Format("{0} UseJsonFormat={1}", initMsg, useJsonFormat); Log.Info((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, initMsg); Log.Info((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(dataConnectionString)); tableDataManager = new GrainStateTableDataManager(tableName, dataConnectionString, Log); return tableDataManager.InitTableAsync(); } // Internal method to initialize for testing internal void InitLogger(Logger logger) { Log = logger; } /// <summary> Shutdown this storage provider. </summary> /// <see cref="IProvider.Close"/> public Task Close() { tableDataManager = null; return TaskDone.Done; } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IStorageProvider.ReadStateAsync"/> public async Task ReadStateAsync(string grainType, GrainReference grainReference, GrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_ReadingData, "Reading: GrainType={0} Pk={1} Grainid={2} from Table={3}", grainType, pk, grainReference, tableName); string partitionKey = pk; string rowKey = grainType; GrainStateRecord record = await tableDataManager.Read(partitionKey, rowKey); if (record != null) { var entity = record.Entity; if (entity != null) { ConvertFromStorageFormat(grainState, entity); grainState.Etag = record.ETag; } } // Else leave grainState in previous default condition } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IStorageProvider.WriteStateAsync"/> public async Task WriteStateAsync(string grainType, GrainReference grainReference, GrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Writing: GrainType={0} Pk={1} Grainid={2} ETag={3} to Table={4}", grainType, pk, grainReference, grainState.Etag, tableName); var entity = new GrainStateEntity { PartitionKey = pk, RowKey = grainType }; ConvertToStorageFormat(grainState, entity); var record = new GrainStateRecord { Entity = entity, ETag = grainState.Etag }; try { await tableDataManager.Write(record); grainState.Etag = record.ETag; } catch (Exception exc) { Log.Error((int)AzureProviderErrorCode.AzureTableProvider_WriteError, string.Format("Error Writing: GrainType={0} Grainid={1} ETag={2} to Table={3} Exception={4}", grainType, grainReference, grainState.Etag, tableName, exc.Message), exc); throw; } } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <remarks> /// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row /// for this grain will be deleted / removed, otherwise the table row will be /// cleared by overwriting with default / null values. /// </remarks> /// <see cref="IStorageProvider.ClearStateAsync"/> public async Task ClearStateAsync(string grainType, GrainReference grainReference, GrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Clearing: GrainType={0} Pk={1} Grainid={2} ETag={3} DeleteStateOnClear={4} from Table={5}", grainType, pk, grainReference, grainState.Etag, isDeleteStateOnClear, tableName); var entity = new GrainStateEntity { PartitionKey = pk, RowKey = grainType }; var record = new GrainStateRecord { Entity = entity, ETag = grainState.Etag }; string operation = "Clearing"; try { if (isDeleteStateOnClear) { operation = "Deleting"; await tableDataManager.Delete(record); } else { await tableDataManager.Write(record); } grainState.Etag = record.ETag; // Update in-memory data to the new ETag } catch (Exception exc) { Log.Error((int)AzureProviderErrorCode.AzureTableProvider_DeleteError, string.Format("Error {0}: GrainType={1} Grainid={2} ETag={3} from Table={4} Exception={5}", operation, grainType, grainReference, grainState.Etag, tableName, exc.Message), exc); throw; } } /// <summary> /// Serialize to Azure storage format in either binary or JSON format. /// </summary> /// <param name="grainState">The grain state data to be serialized</param> /// <param name="entity">The Azure table entity the data should be stored in</param> /// <remarks> /// See: /// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx /// for more on the JSON serializer. /// </remarks> internal void ConvertToStorageFormat(GrainState grainState, GrainStateEntity entity) { // Dehydrate var dataValues = grainState.AsDictionary(); int dataSize; if (useJsonFormat) { // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm string data = Newtonsoft.Json.JsonConvert.SerializeObject(dataValues, jsonSettings); if (Log.IsVerbose3) Log.Verbose3("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); dataSize = data.Length; entity.StringData = data; } else { // Convert to binary format byte[] data = SerializationManager.SerializeToByteArray(dataValues); if (Log.IsVerbose3) Log.Verbose3("Writing binary data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); dataSize = data.Length; entity.Data = data; } if (dataSize > MAX_DATA_SIZE) { var msg = string.Format("Data too large to write to Azure table. Size={0} MaxSize={1}", dataSize, MAX_DATA_SIZE); Log.Error(0, msg); throw new ArgumentOutOfRangeException("GrainState.Size", msg); } } /// <summary> /// Deserialize from Azure storage format /// </summary> /// <param name="grainState">The grain state data to be deserialized in to</param> /// <param name="entity">The Azure table entity the stored data</param> internal void ConvertFromStorageFormat(GrainState grainState, GrainStateEntity entity) { Dictionary<string, object> dataValues = null; try { if (entity.Data != null) { // Rehydrate dataValues = SerializationManager.DeserializeFromByteArray<Dictionary<string, object>>(entity.Data); } else if (entity.StringData != null) { dataValues = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(entity.StringData, jsonSettings); } if (dataValues != null) { grainState.SetAll(dataValues); } // Else, no data found } catch (Exception exc) { var sb = new StringBuilder(); if (entity.Data != null) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", entity.Data); } else if (entity.StringData != null) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", entity.StringData); } if (dataValues != null) { int i = 1; foreach (var dvKey in dataValues.Keys) { object dvValue = dataValues[dvKey]; sb.AppendLine(); sb.AppendFormat("Data #{0} Key={1} Value={2} Type={3}", i, dvKey, dvValue, dvValue.GetType()); i++; } } Log.Error(0, sb.ToString(), exc); throw new AggregateException(sb.ToString(), exc); } } private string GetKeyString(GrainReference grainReference) { var key = String.Format("{0}_{1}", serviceId, grainReference.ToKeyString()); return AzureStorageUtils.SanitizeTableProperty(key); } [Serializable] internal class GrainStateEntity : TableEntity { public byte[] Data { get; set; } public string StringData { get; set; } } internal class GrainStateRecord { public string ETag { get; set; } public GrainStateEntity Entity { get; set; } } private class GrainStateTableDataManager { public string TableName { get; private set; } private readonly AzureTableDataManager<GrainStateEntity> tableManager; private readonly Logger logger; public GrainStateTableDataManager(string tableName, string storageConnectionString, Logger logger) { this.logger = logger; TableName = tableName; tableManager = new AzureTableDataManager<GrainStateEntity>(tableName, storageConnectionString); } public Task InitTableAsync() { return tableManager.InitTableAsync(); } public async Task<GrainStateRecord> Read(string partitionKey, string rowKey) { if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Reading, "Reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); try { Tuple<GrainStateEntity, string> data = await tableManager.ReadSingleTableEntryAsync(partitionKey, rowKey); if (data == null || data.Item1 == null) { if (logger.IsVerbose2) logger.Verbose2((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); return null; } GrainStateEntity stateEntity = data.Item1; var record = new GrainStateRecord { Entity = stateEntity, ETag = data.Item2 }; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_DataRead, "Read: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", stateEntity.PartitionKey, stateEntity.RowKey, TableName, record.ETag); return record; } catch (Exception exc) { if (AzureStorageUtils.TableStorageDataNotFound(exc)) { if (logger.IsVerbose2) logger.Verbose2((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading (exception): PartitionKey={0} RowKey={1} from Table={2} Exception={3}", partitionKey, rowKey, TableName, TraceLogger.PrintException(exc)); return null; // No data } throw; } } public async Task Write(GrainStateRecord record) { GrainStateEntity entity = record.Entity; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Writing: PartitionKey={0} RowKey={1} to Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); string eTag = String.IsNullOrEmpty(record.ETag) ? await tableManager.CreateTableEntryAsync(record.Entity) : await tableManager.UpdateTableEntryAsync(entity, record.ETag); record.ETag = eTag; } public async Task Delete(GrainStateRecord record) { GrainStateEntity entity = record.Entity; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Deleting: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); await tableManager.DeleteTableEntryAsync(entity, record.ETag); record.ETag = null; } } /// <summary> Decodes Storage exceptions.</summary> public bool DecodeException(Exception e, out HttpStatusCode httpStatusCode, out string restStatus, bool getRESTErrors = false) { return AzureStorageUtils.EvaluateException(e, out httpStatusCode, out restStatus, getRESTErrors); } } }
using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Hosting; using OrchardCore.DisplayManagement.Events; using OrchardCore.DisplayManagement.Extensions; using OrchardCore.Environment.Extensions; using OrchardCore.Environment.Extensions.Features; using OrchardCore.Modules; using OrchardCore.Tests.Stubs; using Xunit; namespace OrchardCore.Tests.Extensions { public class ExtensionManagerTests { private static IHostEnvironment HostingEnvironment = new StubHostingEnvironment(); private static IApplicationContext ApplicationContext = new ModularApplicationContext(HostingEnvironment, new List<IModuleNamesProvider>() { new ModuleNamesProvider() }); private static IFeaturesProvider ModuleFeatureProvider = new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); private static IFeaturesProvider ThemeFeatureProvider = new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); private IExtensionManager ModuleScopedExtensionManager; private IExtensionManager ThemeScopedExtensionManager; private IExtensionManager ModuleThemeScopedExtensionManager; public ExtensionManagerTests() { ModuleScopedExtensionManager = new ExtensionManager( ApplicationContext, new[] { new ExtensionDependencyStrategy() }, new[] { new ExtensionPriorityStrategy() }, new TypeFeatureProvider(), ModuleFeatureProvider, new NullLogger<ExtensionManager>() ); ThemeScopedExtensionManager = new ExtensionManager( ApplicationContext, new[] { new ExtensionDependencyStrategy() }, new[] { new ExtensionPriorityStrategy() }, new TypeFeatureProvider(), ThemeFeatureProvider, new NullLogger<ExtensionManager>() ); ModuleThemeScopedExtensionManager = new ExtensionManager( ApplicationContext, new IExtensionDependencyStrategy[] { new ExtensionDependencyStrategy(), new ThemeExtensionDependencyStrategy() }, new[] { new ExtensionPriorityStrategy() }, new TypeFeatureProvider(), ThemeFeatureProvider, new NullLogger<ExtensionManager>() ); } private class ModuleNamesProvider : IModuleNamesProvider { private readonly string[] _moduleNames; public ModuleNamesProvider() { _moduleNames = new[] { "BaseThemeSample", "BaseThemeSample2", "DerivedThemeSample", "DerivedThemeSample2", "ModuleSample" }; } public IEnumerable<string> GetModuleNames() { return _moduleNames; } } [Fact] public void ShouldReturnExtension() { var extensions = ModuleThemeScopedExtensionManager.GetExtensions() .Where(e => e.Manifest.ModuleInfo.Category == "Test"); Assert.Equal(5, extensions.Count()); } [Fact] public void ShouldReturnAllDependenciesIncludingFeatureForAGivenFeatureOrdered() { var features = ModuleScopedExtensionManager.GetFeatureDependencies("Sample3"); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); } [Fact] public void ShouldNotReturnFeaturesNotDependentOn() { var features = ModuleScopedExtensionManager.GetFeatureDependencies("Sample2"); Assert.Equal(2, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); } [Fact] public void GetDependentFeaturesShouldReturnAllFeaturesThatHaveADependencyOnAFeature() { var features = ModuleScopedExtensionManager.GetDependentFeatures("Sample1"); Assert.Equal(4, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); } [Fact] public void GetFeaturesShouldReturnAllFeaturesOrderedByDependency() { var features = ModuleScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test" && !f.IsTheme()); Assert.Equal(4, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); } [Fact] public void GetFeaturesWithAIdShouldReturnThatFeatureWithDependenciesOrdered() { var features = ModuleScopedExtensionManager.GetFeatures(new[] { "Sample2" }); Assert.Equal(2, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); } [Fact] public void GetFeaturesWithAIdShouldReturnThatFeatureWithDependenciesOrderedWithNoDuplicates() { var features = ModuleScopedExtensionManager.GetFeatures(new[] { "Sample2", "Sample3" }); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); } [Fact] public void GetFeaturesWithAIdShouldNotReturnFeaturesTheHaveADependencyOutsideOfGraph() { var features = ModuleScopedExtensionManager.GetFeatures(new[] { "Sample4" }); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample4", features.ElementAt(2).Id); } /* Theme Base Theme Dependencies */ [Fact] public void GetFeaturesShouldReturnCorrectThemeHeirarchy() { var features = ThemeScopedExtensionManager.GetFeatures(new[] { "DerivedThemeSample" }); Assert.Equal(2, features.Count()); Assert.Equal("BaseThemeSample", features.ElementAt(0).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(1).Id); } /* Theme and Module Dependencies */ [Fact] public void GetFeaturesShouldReturnBothThemesAndModules() { var features = ModuleThemeScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test"); Assert.Equal(8, features.Count()); } [Fact] public void GetFeaturesShouldReturnThemesAfterModules() { var features = ModuleThemeScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test"); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); Assert.Equal("BaseThemeSample", features.ElementAt(4).Id); Assert.Equal("BaseThemeSample2", features.ElementAt(5).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(6).Id); Assert.Equal("DerivedThemeSample2", features.ElementAt(7).Id); } [Fact] public void GetFeaturesShouldReturnThemesAfterModulesWhenRequestingBoth() { var features = ModuleThemeScopedExtensionManager.GetFeatures(new[] { "DerivedThemeSample", "Sample3" }); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("BaseThemeSample", features.ElementAt(3).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(4).Id); } [Fact] public void ShouldReturnNotFoundExtensionInfoWhenNotFound() { var extension = ModuleThemeScopedExtensionManager.GetExtension("NotFound"); Assert.False(extension.Exists); } } }
//------------------------------------------------------------------------------ // <copyright file="Channels.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <disclaimer> // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. // </disclaimer> //------------------------------------------------------------------------------ using System.Diagnostics; namespace Microsoft.Research.Joins { /// <summary> /// The most basic internal view of a Channel, which serves as the /// target of any Channel delegate type. /// </summary> internal interface IChannelTarget { //: System.MarshalByRefObject { void CheckOwner(Join join); bool IsAsync { get; } /// <summary>Channel's ID, unique within a Join (and each channel belongs to a Join).</summary> int id { get; } } /// <summary> /// A typed internal view of a ChannelTarget. /// </summary> /// <typeparam name="A">The type of messages over the channel. Void /// argument channels are given type Unit</typeparam> internal interface IChannelTarget<A> : IChannelTarget { } /// <summary> /// Contains nested classes for synchronous channels returning one result of type <c>R</c>. /// </summary> /// <typeparam name="R"> the return type of nested channel types <c>Channel&lt;A&gt;</c> <c>Channel&lt;A&gt;</c> </typeparam> public static partial class Synchronous<R> { /// <summary> /// A synchronous channel that returns a value of type <c>R</c> and takes one argument of type <c>A</c>. /// <para> /// A value <c>channel</c>of type <c>Synchronous&lt;R&gt;.Channel&lt;A&gt;</c> allocated by some <see cref="Join"/> instance <c>j</c> /// may then be joined with other asynchronous channels initialised on <c>j</c>. /// Invoking <c>channel(a)</c> on an argument of type <c>A</c> will wait (block) until or unless some join pattern declared on <c>j</c> is enabled by zero or more pending asynchronous channel invocations. /// </para> /// </summary> /// <typeparam name="A">The type of the single argument to the delegate's implicit <c>Invoke</c> method.</typeparam> /// <param name="a">The single argument of the delegate's implicit <c>Invoke</c> method.</param> /// <returns>The result of type <c>R</c> of some join pattern declared on the synchronous channel.</returns> [DebuggerDisplay("{Target}")] public delegate R Channel<A>(A a); /// <summary> /// A synchronous channel that returns a value of type <c>R</c> and takes no arguments. /// <para> /// A value <c>channel</c>of type <c>Synchronous&lt;R&gt;.Channel</c> allocated by some <see cref="Join"/> instance <c>j</c> /// may then be joined with other asynchronous channels initialised on <c>j</c>. /// Invoking <c>channel()</c> will wait (block) until or unless some join pattern declared on <c>j</c> is enabled by zero or more pending asynchronous channel invocations. /// </para> /// </summary> /// <returns>The result of type <c>R</c> of some join pattern declared on the synchronous channel.</returns> [DebuggerDisplay("{Target}")] public delegate R Channel(); /// <summary> /// Allocate a new synchronous channel (returning a value of type <c>R</c> and taking one argument of type <c>A</c>) on <see cref="Join"/> instance <paramref name="owner"/> . /// This is an alternative to <c>Initialize(out channel)</c> /// that does not use an <c>out</c> parameter. /// </summary> /// <typeparam name="A"> the argument type of the channel.</typeparam> /// <param name="owner"> the join instance that owns the new channel.</param> /// <returns> a new channel owned by <paramref name="owner"/>.</returns> /// <exception cref = "JoinException"> when owner <paramref name="owner"/> is null. </exception> public static Synchronous<R>.Channel<A> CreateChannel<A>(Join owner) { if (owner == null) JoinException.OwnerNull(); Synchronous<R>.Channel<A> sync; owner.Initialize(out sync); return sync; } /// <summary> /// Allocate a new synchronous channel (returning a value of type <c>R</c> and taking no argument) on <see cref="Join"/> instance <paramref name="owner"/> . /// This is an alternative to <c>Initialize(out channel)</c> /// that does not use an <c>out</c> parameter. /// </summary> /// <param name="owner"> the join instance that owns the new channel.</param> /// <returns> a new channel owned by <paramref name="owner"/>.</returns> /// <exception cref = "JoinException"> when owner <paramref name="owner"/> is null. </exception> public static Synchronous<R>.Channel CreateChannel(Join owner) { if (owner == null) JoinException.OwnerNull(); Synchronous<R>.Channel sync; owner.Initialize(out sync); return sync; } /// <summary> /// Access the ChannelTarget underlying a channel. /// </summary> /// <typeparam name="A">The message type of the channel.</typeparam> /// <param name="ch">The channel.</param> /// <returns>The underlying target.</returns> internal static IChannelTarget<A> ToChannelTarget<A>(Channel<A> ch) { if (ch == null) JoinException.UnInitializedChannelException(); IChannelTarget<A> ct = ch.Target as IChannelTarget<A>; if (ct == null) JoinException.ForeignJoinException(); return ct; } /// <summary> /// Access the ChannelTarget underlying a channel. /// </summary> /// <param name="ch">The channel.</param> /// <returns>The underlying target.</returns> internal static IChannelTarget<Unit> ToChannelTarget(Channel ch) { if (ch == null) JoinException.UnInitializedChannelException(); IChannelTarget<Unit> ct = ch.Target as IChannelTarget<Unit>; if (ct == null) JoinException.ForeignJoinException(); return ct; } /// <summary> /// Access the ChannelTargets underlying a channel array. /// </summary> /// <param name="chs">The channels.</param> /// <returns>The underlying targets.</returns> internal static IChannelTarget<A>[] ToChannelTarget<A>(Channel<A>[] chs) { if (chs == null) JoinException.UnInitializedChannelException(); var cts = new IChannelTarget<A>[chs.Length]; for (int i = 0; i < cts.Length; i++) { cts[i] = Synchronous<R>.ToChannelTarget(chs[i]); } return cts; } /// <summary> /// Access the ChannelTargets underlying a channel array. /// </summary> /// <param name="chs">The channels.</param> /// <returns>The underlying targets.</returns> internal static IChannelTarget<Unit>[] ToChannelTarget(Channel[] chs) { if (chs == null) JoinException.UnInitializedChannelException(); var cts = new IChannelTarget<Unit>[chs.Length]; for (int i = 0; i < cts.Length; i++) { cts[i] = Synchronous<R>.ToChannelTarget(chs[i]); } return cts; } } /// <summary> /// Contains nested classes for synchronous channels returning <c>void</c>. /// </summary> public static partial class Synchronous { /// <summary> /// A synchronous channel that returns void and takes one argument of type <c>A</c>. /// <para> /// A value <c>channel</c>of type <c>Synchronous.Channel&lt;A&gt;</c> allocated by some <see cref="Join"/> instance <c>j</c> /// may then be joined with other asynchronous channels initialized on <c>j</c>. /// Invoking <c>channel(a)</c> on an argument of type <c>A</c> will wait (block) until or unless some join pattern declared on <c>j</c> is enabled by zero or more pending asynchronous channel invocations. /// </para> /// </summary> /// <typeparam name="A">The type of the single argument to the delegate's implicit <c>Invoke</c> method.</typeparam> /// <param name="a">The single argument of the delegate's implicit <c>Invoke</c> method.</param> [DebuggerDisplay("{Target}")] public delegate void Channel<A>(A a); /// <summary> /// A synchronous channel that returns void and takes no arguments. /// <para> /// A value <c>channel</c>of type <c>Synchronous.Channel</c> allocated by some <see cref="Join"/> instance <c>j</c> /// may then be joined with other asynchronous channels initialised on <c>j</c>. /// Invoking <c>channel()</c> will wait (block) until or unless some join pattern declared on <c>j</c> is enabled by zero or more pending asynchronous channel invocations. /// </para> /// </summary> [DebuggerDisplay("{Target}")] public delegate void Channel(); /// <summary> /// Allocate a new synchronous channel (returning <c>void</c> and taking no argument) on <see cref="Join"/> instance <paramref name="owner"/> . /// This is an alternative to <c>Initialize(out channel)</c> /// that does not use an <c>out</c> parameter. /// </summary> /// <param name="owner"> the join instance that owns the new channel.</param> /// <returns> a new channel owned by <paramref name="owner"/>.</returns> /// <exception cref = "JoinException"> when owner <paramref name="owner"/> is null. </exception> public static Synchronous.Channel CreateChannel(Join owner) { if (owner == null) JoinException.OwnerNull(); Synchronous.Channel sync; owner.Initialize(out sync); return sync; } /// <summary> /// Allocate a new synchronous channel (returning <c>void</c> and taking one argument of type <c>A</c>) on <see cref="Join"/> instance <paramref name="owner"/> . /// This is an alternative to <c>Initialize(out channel)</c> /// that does not use an <c>out</c> parameter. /// </summary> /// <typeparam name="A"> the argument type of the channel.</typeparam> /// <param name="owner"> the join instance that owns the new channel.</param> /// <returns> a new channel owned by <paramref name="owner"/>.</returns> /// <exception cref = "JoinException"> when owner <paramref name="owner"/> is null. </exception> public static Synchronous.Channel<A> CreateChannel<A>(Join owner) { if (owner == null) JoinException.OwnerNull(); Synchronous.Channel<A> sync; owner.Initialize(out sync); return sync; } /// <summary> /// Access the ChannelTarget underlying a channel. /// </summary> /// <typeparam name="A">The message type of the channel.</typeparam> /// <param name="ch">The channel.</param> /// <returns>The underlying target.</returns> internal static IChannelTarget<A> ToChannelTarget<A>(Channel<A> ch) { if (ch == null) JoinException.UnInitializedChannelException(); IChannelTarget<A> ct = ch.Target as IChannelTarget<A>; if (ct == null) JoinException.ForeignJoinException(); return ct; } /// <summary> /// Access the ChannelTarget underlying a channel. /// </summary> /// <param name="ch">The channel.</param> /// <returns>The underlying target.</returns> internal static IChannelTarget<Unit> ToChannelTarget(Channel ch) { if (ch == null) JoinException.UnInitializedChannelException(); IChannelTarget<Unit> ct = ch.Target as IChannelTarget<Unit>; if (ct == null) JoinException.ForeignJoinException(); return ct; } /// <summary> /// Access the ChannelTargets underlying a channel array. /// </summary> /// <param name="chs">The channels.</param> /// <returns>The underlying targets.</returns> internal static IChannelTarget<A>[] ToChannelTarget<A>(Channel<A>[] chs) { if (chs == null) JoinException.UnInitializedChannelException(); var cts = new IChannelTarget<A>[chs.Length]; for (int i = 0; i < cts.Length; i++) { cts[i] = Synchronous.ToChannelTarget(chs[i]); } return cts; } /// <summary> /// Access the ChannelTargets underlying a channel array. /// </summary> /// <param name="chs">The channels.</param> /// <returns>The underlying targets.</returns> internal static IChannelTarget<Unit>[] ToChannelTarget(Channel[] chs) { if (chs == null) JoinException.UnInitializedChannelException(); var cts = new IChannelTarget<Unit>[chs.Length]; for (int i = 0; i < cts.Length; i++) { cts[i] = Synchronous.ToChannelTarget(chs[i]); } return cts; } } /// <summary> /// Contains nested classes for asynchronous channels (returning <c>void</c>). /// </summary> public static class Asynchronous { /// <summary> /// An asynchronous channel that accepts one argument of type <c>A</c> and immediately returns void. /// <para> /// A value <c>channel</c>of type <c>Asynchronous.Channel&lt;A&gt;</c> allocated by some <see cref="Join"/> instance <c>j</c> /// may then be joined with other synchronous and asynchronous channels initialised on <c>j</c>. /// Invoking <c>channel(a)</c> on an argument of type <c>A</c> queues the invocation and may enable the execution of some join pattern declared on <c>j</c>. /// </para> /// </summary> /// <typeparam name="A"> The type of the single argument to the delegate's implicit <c>Invoke</c> method.</typeparam> /// <param name="a">The single argument of the delegate's implicit <c>Invoke</c> method.</param> [DebuggerDisplay("{Target}")] public delegate void Channel<A>(A a); /// <summary> /// An asynchronous channel that takes no arguments and immediately returns void. /// <para> /// A value <c>channel</c> of type <c>Asynchronous.Channel</c> allocated by some <see cref="Join"/> instance <c>j</c> /// may then be joined with other synchronous and asynchronous channels initialised on <c>j</c>. /// Invoking <c>channel()</c> queues the invocation and may enable the execution of some join pattern declared on <c>j</c>. /// </para> /// </summary> [DebuggerDisplay("{Target}")] public delegate void Channel(); /// <summary> /// Allocate a new asynchronous channel (taking no argument) on <see cref="Join"/> instance <paramref name="owner"/>. /// This is an alternative to <c>Initialize(out channel)</c> that does not use an <c>out</c> parameter. /// </summary> /// <param name="owner"> the join instance that owns the new channel.</param> /// <returns> a new channel owned by <paramref name="owner"/>.</returns> /// <exception cref = "JoinException"> when <paramref name="owner"/> is null. </exception> public static Asynchronous.Channel CreateChannel(Join owner) { if (owner == null) JoinException.OwnerNull(); Asynchronous.Channel async; owner.Initialize(out async); return async; } /// <summary> /// Allocate a new asynchronous channel (taking one argument of type <c>A</c>) on <see cref="Join"/> instance <paramref name="owner"/>. /// This is an alternative to <c>Initialize(out channel)</c> that does not use an <c>out</c> parameter. /// </summary> /// <typeparam name="A"> the argument type of the channel.</typeparam> /// <param name="owner"> the join instance that owns the new channel.</param> /// <returns> a new channel owned by <paramref name="owner"/>.</returns> /// <exception cref = "JoinException"> when <paramref name="owner"/> is null. </exception> public static Asynchronous.Channel<A> CreateChannel<A>(Join owner) { if (owner == null) JoinException.OwnerNull(); Asynchronous.Channel<A> async; owner.Initialize(out async); return async; } /// <summary> /// Allocate a new array of new asynchronous channels (each taking no argument) on <see cref="Join"/> instance <paramref name="owner"/> . /// This is an alternative to <c>Initialize(out channels, length)</c> /// that does not use an <c>out</c> parameter. /// </summary> /// <param name="owner"> the join instance that owns the new channels.</param> /// <param name="length"> the number of distinct channels to create.</param> /// <returns> an array of <paramref name="length"/> distinct channels</returns> /// <exception cref = "JoinException"> when <paramref name="owner"/> is null. </exception> public static Asynchronous.Channel[] CreateChannels(Join owner,int length) { if (owner == null) JoinException.OwnerNull(); Asynchronous.Channel[] asyncs; owner.Initialize(out asyncs, length); return asyncs; } /// <summary> /// Allocate a new array of new asynchronous channels (each taking one argument of type <c>A</c>) on <see cref="Join"/> instance <paramref name="owner"/> . /// This is an alternative to <c>Initialize(out channels, length)</c> /// that does not use an <c>out</c> parameter. /// </summary> /// <typeparam name="A"> the argument type of each channel.</typeparam> /// <param name="owner"> the join instance that owns the new channels.</param> /// <param name="length"> the number of distinct channels to create.</param> /// <returns> an array of <paramref name="length"/> distinct channels</returns> /// <exception cref = "JoinException"> when <paramref name="owner"/> is null. </exception> public static Asynchronous.Channel<A>[] CreateChannels<A>(Join owner, int length) { if (owner == null) JoinException.OwnerNull(); Asynchronous.Channel<A>[] asyncs; owner.Initialize(out asyncs, length); return asyncs; } /// <summary> /// Access the ChannelTarget underlying a channel. /// </summary> /// <typeparam name="A">The message type of the channel.</typeparam> /// <param name="ch">The channel.</param> /// <returns>The underlying target.</returns> internal static IChannelTarget<A> ToChannelTarget<A>(Channel<A> ch) { if (ch == null) JoinException.UnInitializedChannelException(); IChannelTarget<A> ct = ch.Target as IChannelTarget<A>; if (ct == null) JoinException.ForeignJoinException(); return ct; } /// <summary> /// Access the ChannelTarget underlying a channel. /// </summary> /// <param name="ch">The channel.</param> /// <returns>The underlying target.</returns> internal static IChannelTarget<Unit> ToChannelTarget(Channel ch) { if (ch == null) JoinException.UnInitializedChannelException(); IChannelTarget<Unit> ct = ch.Target as IChannelTarget<Unit>; if (ct == null) JoinException.ForeignJoinException(); return ct; } /// <summary> /// Access the ChannelTargets underlying a channel array. /// </summary> /// <param name="chs">The channels.</param> /// <returns>The underlying targets.</returns> internal static IChannelTarget<Unit>[] ToChannelTarget(Channel[] chs) { if (chs == null) JoinException.UnInitializedChannelException(); var cts = new IChannelTarget<Unit>[chs.Length]; for (int i = 0; i < cts.Length; i++) { cts[i] = Asynchronous.ToChannelTarget(chs[i]); } return cts; } /// <summary> /// Access the ChannelTargets underlying a channel array. /// </summary> /// <param name="chs">The channels.</param> /// <returns>The underlying targets.</returns> internal static IChannelTarget<A>[] ToChannelTarget<A>(Channel<A>[] chs) { if (chs == null) JoinException.UnInitializedChannelException(); var cts = new IChannelTarget<A>[chs.Length]; for (int i = 0; i < cts.Length; i++) { cts[i] = Asynchronous.ToChannelTarget(chs[i]); } return cts; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Messages.Messages File: Currency.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Messages { using System; using System.Runtime.Serialization; using Ecng.Common; /// <summary> /// Currency. /// </summary> [DataContract] [Serializable] public class Currency : Equatable<Currency> { static Currency() { Converter.AddTypedConverter<Currency, decimal>(input => (decimal)input); Converter.AddTypedConverter<decimal, Currency>(input => input); } /// <summary> /// Initializes a new instance of the <see cref="Currency"/>. /// </summary> public Currency() { Type = CurrencyTypes.RUB; } /// <summary> /// Currency type. The default is <see cref="CurrencyTypes.RUB"/>. /// </summary> [DataMember] public CurrencyTypes Type { get; set; } /// <summary> /// Absolute value in <see cref="CurrencyTypes"/>. /// </summary> [DataMember] public decimal Value { get; set; } /// <summary> /// Create a copy of <see cref="Currency"/>. /// </summary> /// <returns>Copy.</returns> public override Currency Clone() { return new Currency { Type = Type, Value = Value }; } /// <summary> /// Compare <see cref="Currency"/> on the equivalence. /// </summary> /// <param name="other">Another value with which to compare.</param> /// <returns><see langword="true" />, if the specified object is equal to the current object, otherwise, <see langword="false" />.</returns> protected override bool OnEquals(Currency other) { return Type == other.Type && Value == other.Value; } /// <summary> /// Get the hash code of the object <see cref="Currency"/>. /// </summary> /// <returns>A hash code.</returns> public override int GetHashCode() { return Type.GetHashCode() ^ Value.GetHashCode(); } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"{Value} {Type}"; } /// <summary> /// Cast <see cref="decimal"/> object to the type <see cref="Currency"/>. /// </summary> /// <param name="value"><see cref="decimal"/> value.</param> /// <returns>Object <see cref="Currency"/>.</returns> public static implicit operator Currency(decimal value) { return new Currency { Value = value }; } /// <summary> /// Cast object from <see cref="Currency"/> to <see cref="decimal"/>. /// </summary> /// <param name="unit">Object <see cref="Currency"/>.</param> /// <returns><see cref="decimal"/> value.</returns> public static explicit operator decimal(Currency unit) { if (unit == null) throw new ArgumentNullException(nameof(unit)); return unit.Value; } /// <summary> /// Add the two objects <see cref="Currency"/>. /// </summary> /// <param name="c1">First object <see cref="Currency"/>.</param> /// <param name="c2">Second object <see cref="Currency"/>.</param> /// <returns>The result of addition.</returns> /// <remarks> /// The values must be the same <see cref="Currency.Type"/>. /// </remarks> public static Currency operator +(Currency c1, Currency c2) { if (c1 == null) throw new ArgumentNullException(nameof(c1)); if (c2 == null) throw new ArgumentNullException(nameof(c2)); return (decimal)c1 + (decimal)c2; } /// <summary> /// Subtract one value from another value. /// </summary> /// <param name="c1">First object <see cref="Currency"/>.</param> /// <param name="c2">Second object <see cref="Currency"/>.</param> /// <returns>The result of the subtraction.</returns> public static Currency operator -(Currency c1, Currency c2) { if (c1 == null) throw new ArgumentNullException(nameof(c1)); if (c2 == null) throw new ArgumentNullException(nameof(c2)); return (decimal)c1 - (decimal)c2; } /// <summary> /// Multiply one value to another. /// </summary> /// <param name="c1">First object <see cref="Currency"/>.</param> /// <param name="c2">Second object <see cref="Currency"/>.</param> /// <returns>The result of the multiplication.</returns> public static Currency operator *(Currency c1, Currency c2) { if (c1 == null) throw new ArgumentNullException(nameof(c1)); if (c2 == null) throw new ArgumentNullException(nameof(c2)); return (decimal)c1 * (decimal)c2; } /// <summary> /// Divide one value to another. /// </summary> /// <param name="c1">First object <see cref="Currency"/>.</param> /// <param name="c2">Second object <see cref="Currency"/>.</param> /// <returns>The result of the division.</returns> public static Currency operator /(Currency c1, Currency c2) { if (c1 == null) throw new ArgumentNullException(nameof(c1)); if (c2 == null) throw new ArgumentNullException(nameof(c2)); return (decimal)c1 / (decimal)c2; } } /// <summary> /// Extension class for <see cref="Currency"/>. /// </summary> public static class CurrencyHelper { /// <summary> /// Cast <see cref="decimal"/> to <see cref="Currency"/>. /// </summary> /// <param name="value">Currency value.</param> /// <param name="type">Currency type.</param> /// <returns>Currency.</returns> public static Currency ToCurrency(this decimal value, CurrencyTypes type) { return new Currency { Type = type, Value = value }; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using VkNet.Enums.Filters; using VkNet.Enums.SafetyEnums; using VkNet.Model; using VkNet.Model.RequestParams; using VkNet.Utils; namespace VkNet.Categories { public partial class MessagesCategory { /// <inheritdoc /> public Task<bool> AddChatUserAsync(long chatId, long userId) { return TypeHelper.TryInvokeMethodAsync(func: () => AddChatUser(chatId: chatId, userId: userId)); } /// <inheritdoc /> public Task<bool> AllowMessagesFromGroupAsync(long groupId, string key) { return TypeHelper.TryInvokeMethodAsync(func: () => AllowMessagesFromGroup(groupId: groupId, key: key)); } /// <inheritdoc /> public Task<long> CreateChatAsync(IEnumerable<ulong> userIds, string title) { return TypeHelper.TryInvokeMethodAsync(func: () => CreateChat(userIds: userIds, title: title)); } /// <inheritdoc /> public Task<IDictionary<ulong, bool>> DeleteAsync(IEnumerable<ulong> messageIds, bool spam, bool deleteForAll) { return TypeHelper.TryInvokeMethodAsync(func: () => Delete(messageIds: messageIds, spam: spam, deleteForAll: deleteForAll)); } /// <inheritdoc /> public Task<Chat> DeleteChatPhotoAsync(ulong chatId) { return TypeHelper.TryInvokeMethodAsync(func: () => DeleteChatPhoto(messageId: out var _, chatId: chatId)); } /// <inheritdoc /> public Task<bool> DeleteConversationAsync(long? userId, long? peerId = null, uint? offset = null, uint? count = null, long? groupId = null) { return TypeHelper.TryInvokeMethodAsync(func: () => DeleteConversation(userId, peerId, offset, count, groupId)); } /// <inheritdoc /> public async Task<ConversationResultObject> GetConversationsByIdAsync(IEnumerable<long> peerIds, IEnumerable<string> fields, bool? extended = null, ulong? groupId = null) { return await TypeHelper.TryInvokeMethodAsync(() => GetConversationsById(peerIds, fields, extended, groupId)); } /// <inheritdoc /> public async Task<GetConversationsResult> GetConversationsAsync(GetConversationsParams getConversationsParams) { return await TypeHelper.TryInvokeMethodAsync(() => GetConversations(getConversationsParams)); } /// <inheritdoc /> public async Task<GetConversationMembersResult> GetConversationMembersAsync(long peerId, IEnumerable<string> fields, ulong? groupId = null) { return await TypeHelper.TryInvokeMethodAsync(() => GetConversationMembers(peerId, fields, groupId)); } /// <inheritdoc /> public async Task<GetByConversationMessageIdResult> GetByConversationMessageIdAsync(long peerId, IEnumerable<ulong> conversationMessageIds, IEnumerable<string> fields, bool? extended = null, ulong? groupId = null) { return await TypeHelper.TryInvokeMethodAsync(() => GetByConversationMessageId(peerId, conversationMessageIds, fields, extended, groupId)); } /// <inheritdoc /> public async Task<SearchConversationsResult> SearchConversationsAsync(string q, IEnumerable<string> fields, ulong? count = null, bool? extended = null, ulong? groupId = null) { return await TypeHelper.TryInvokeMethodAsync(() => SearchConversations(q, fields, count, extended, groupId)); } /// <inheritdoc /> public Task<bool> DeleteDialogAsync(long? userId, long? peerId = null, uint? offset = null, uint? count = null) { return TypeHelper.TryInvokeMethodAsync(func: () => DeleteDialog(userId: userId, peerId: peerId, offset: offset, count: count)); } /// <inheritdoc /> public Task<bool> DenyMessagesFromGroupAsync(long groupId) { return TypeHelper.TryInvokeMethodAsync(func: () => DenyMessagesFromGroup(groupId: groupId)); } /// <inheritdoc /> public Task<bool> EditChatAsync(long chatId, string title) { return TypeHelper.TryInvokeMethodAsync(func: () => EditChat(chatId: chatId, title: title)); } /// <inheritdoc /> public Task<MessagesGetObject> GetAsync(MessagesGetParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => Get(@params: @params)); } /// <inheritdoc /> public Task<VkCollection<Message>> GetByIdAsync(IEnumerable<ulong> messageIds, uint? previewLength = null) { return TypeHelper.TryInvokeMethodAsync(func: () => GetById(messageIds: messageIds, previewLength: previewLength)); } /// <inheritdoc /> public Task<SearchDialogsResponse> SearchDialogsAsync(string query, ProfileFields fields = null, uint? limit = null) { return TypeHelper.TryInvokeMethodAsync(func: () => SearchDialogs(query: query, fields: fields, limit: limit)); } /// <inheritdoc /> public Task<VkCollection<Message>> SearchAsync(MessagesSearchParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => Search(@params: @params)); } /// <inheritdoc /> public Task<long> SendAsync(MessagesSendParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => Send(@params: @params)); } /// <inheritdoc /> public Task<ReadOnlyCollection<MessagesSendResult>> SendToUserIdsAsync(MessagesSendParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => SendToUserIds(@params: @params)); } /// <inheritdoc /> public Task<bool> RestoreAsync(ulong messageId) { return TypeHelper.TryInvokeMethodAsync(func: () => Restore(messageId: messageId)); } /// <inheritdoc /> public Task<bool> MarkAsReadAsync(IEnumerable<long> messageIds, string peerId, long? startMessageId = null) { return TypeHelper.TryInvokeMethodAsync(func: () => MarkAsRead(messageIds: messageIds, peerId: peerId, startMessageId: startMessageId)); } /// <inheritdoc /> public Task<bool> SetActivityAsync(long userId, long? peerId = null, string type = "typing") { return TypeHelper.TryInvokeMethodAsync(func: () => SetActivity(userId: userId, peerId: peerId, type: type)); } /// <inheritdoc /> public Task<LastActivity> GetLastActivityAsync(long userId) { return TypeHelper.TryInvokeMethodAsync(func: () => GetLastActivity(userId: userId)); } /// <inheritdoc /> public Task<Chat> GetChatAsync(long chatId, ProfileFields fields = null, NameCase nameCase = null) { return TypeHelper.TryInvokeMethodAsync(func: () => GetChat(chatId: chatId, fields: fields, nameCase: nameCase)); } /// <inheritdoc /> public Task<ReadOnlyCollection<Chat>> GetChatAsync(IEnumerable<long> chatIds , ProfileFields fields = null , NameCase nameCase = null) { return TypeHelper.TryInvokeMethodAsync(func: () => GetChat(chatIds: chatIds, fields: fields, nameCase: nameCase)); } /// <inheritdoc /> public Task<ChatPreview> GetChatPreviewAsync(string link, ProfileFields fields) { return TypeHelper.TryInvokeMethodAsync(func: () => GetChatPreview(link: link, fields: fields)); } /// <inheritdoc /> public Task<ReadOnlyCollection<User>> GetChatUsersAsync(IEnumerable<long> chatIds, UsersFields fields, NameCase nameCase) { return TypeHelper.TryInvokeMethodAsync(func: () => GetChatUsers(chatIds: chatIds, fields: fields, nameCase: nameCase)); } /// <inheritdoc /> public Task<MessagesGetObject> GetDialogsAsync(MessagesDialogsGetParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => GetDialogs(@params: @params)); } /// <inheritdoc /> public Task<MessagesGetObject> GetHistoryAsync(MessagesGetHistoryParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => GetHistory(@params: @params)); } /// <inheritdoc /> public Task<bool> RemoveChatUserAsync(long chatId, long userId) { return TypeHelper.TryInvokeMethodAsync(func: () => RemoveChatUser(chatId: chatId, userId: userId)); } /// <inheritdoc /> public Task<LongPollServerResponse> GetLongPollServerAsync(bool needPts = false, uint lpVersion = 2) { return TypeHelper.TryInvokeMethodAsync(func: () => GetLongPollServer(needPts: needPts, lpVersion: lpVersion)); } /// <inheritdoc /> public Task<LongPollHistoryResponse> GetLongPollHistoryAsync(MessagesGetLongPollHistoryParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => GetLongPollHistory(@params: @params)); } /// <inheritdoc /> public Task<long> SetChatPhotoAsync(string file) { return TypeHelper.TryInvokeMethodAsync(func: () => SetChatPhoto(messageId: out var _, file: file)); } /// <inheritdoc /> public Task<ReadOnlyCollection<long>> MarkAsImportantAsync(IEnumerable<long> messageIds, bool important = true) { return TypeHelper.TryInvokeMethodAsync(func: () => MarkAsImportant(messageIds: messageIds, important: important)); } /// <inheritdoc /> public Task<long> SendStickerAsync(MessagesSendStickerParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => SendSticker(@params: @params)); } /// <inheritdoc /> public Task<ReadOnlyCollection<HistoryAttachment>> GetHistoryAttachmentsAsync(MessagesGetHistoryAttachmentsParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => GetHistoryAttachments(@params: @params, nextFrom: out var _)); } /// <inheritdoc /> public Task<string> GetInviteLinkAsync(ulong peerId, bool reset) { return TypeHelper.TryInvokeMethodAsync(func: () => GetInviteLink(peerId: peerId, reset: reset)); } /// <inheritdoc /> public Task<bool> IsMessagesFromGroupAllowedAsync(ulong groupId, ulong userId) { return TypeHelper.TryInvokeMethodAsync(func: () => IsMessagesFromGroupAllowed(groupId: groupId, userId: userId)); } /// <inheritdoc /> public Task<long> JoinChatByInviteLinkAsync(string link) { return TypeHelper.TryInvokeMethodAsync(func: () => JoinChatByInviteLink(link: link)); } public Task<bool> MarkAsAnsweredConversationAsync(long peerId, bool answered = true) { throw new NotImplementedException(); } /// <inheritdoc /> public Task<bool> MarkAsAnsweredDialogAsync(long peerId, bool answered = true) { return TypeHelper.TryInvokeMethodAsync(func: () => MarkAsAnsweredDialog(peerId: peerId, answered: answered)); } /// <inheritdoc /> public Task<bool> MarkAsImportantConversationAsync(long peerId, bool important = true) { return TypeHelper.TryInvokeMethodAsync(func: () => MarkAsImportantConversation(peerId: peerId, important: important)); } /// <inheritdoc /> public Task<bool> MarkAsImportantDialogAsync(long peerId, bool important = true) { return TypeHelper.TryInvokeMethodAsync(func: () => MarkAsImportantDialog(peerId: peerId, important: important)); } /// <inheritdoc /> public Task<bool> EditAsync(MessageEditParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () => Edit(@params: @params)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; using System.Threading.Tasks; namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using YamlDotNet.Serialization; using Microsoft.DocAsCode.Common.EntityMergers; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.DataContracts.ManagedReference; public class MetadataItem : ICloneable { [YamlIgnore] [JsonIgnore] public bool IsInvalid { get; set; } [YamlIgnore] [JsonIgnore] public bool IsExtraDoc { get; set; } [YamlIgnore] [JsonIgnore] public string ExtraDocFilePath { get; set; } [YamlIgnore] [JsonIgnore] public string RawComment { get; set; } [JsonProperty(Constants.PropertyName.IsEii)] [YamlMember(Alias = Constants.PropertyName.IsEii)] public bool IsExplicitInterfaceImplementation { get; set; } [YamlMember(Alias = "isExtensionMethod")] [JsonProperty("isExtensionMethod")] public bool IsExtensionMethod { get; set; } [YamlMember(Alias = Constants.PropertyName.Id)] [JsonProperty(Constants.PropertyName.Id)] public string Name { get; set; } [YamlMember(Alias = Constants.PropertyName.CommentId)] [JsonProperty(Constants.PropertyName.CommentId)] public string CommentId { get; set; } [YamlMember(Alias = "language")] [JsonProperty("language")] public SyntaxLanguage Language { get; set; } [YamlMember(Alias = "name")] [JsonProperty("name")] public SortedList<SyntaxLanguage, string> DisplayNames { get; set; } [YamlMember(Alias = "nameWithType")] [JsonProperty("nameWithType")] public SortedList<SyntaxLanguage, string> DisplayNamesWithType { get; set; } [YamlMember(Alias = "qualifiedName")] [JsonProperty("qualifiedName")] public SortedList<SyntaxLanguage, string> DisplayQualifiedNames { get; set; } [YamlMember(Alias = "parent")] [JsonProperty("parent")] public MetadataItem Parent { get; set; } [YamlMember(Alias = Constants.PropertyName.Type)] [JsonProperty(Constants.PropertyName.Type)] public MemberType Type { get; set; } [YamlMember(Alias = "assemblies")] [JsonProperty("assemblies")] public List<string> AssemblyNameList { get; set; } [YamlMember(Alias = "namespace")] [JsonProperty("namespace")] public string NamespaceName { get; set; } [YamlMember(Alias = Constants.PropertyName.Source)] [JsonProperty(Constants.PropertyName.Source)] public SourceDetail Source { get; set; } [YamlMember(Alias = Constants.PropertyName.Documentation)] [JsonProperty(Constants.PropertyName.Documentation)] public SourceDetail Documentation { get; set; } public List<LayoutItem> Layout { get; set; } [YamlMember(Alias = "summary")] [JsonProperty("summary")] public string Summary { get; set; } [YamlMember(Alias = "remarks")] [JsonProperty("remarks")] public string Remarks { get; set; } [YamlMember(Alias = "example")] [JsonProperty("example")] public List<string> Examples { get; set; } [YamlMember(Alias = "syntax")] [JsonProperty("syntax")] public SyntaxDetail Syntax { get; set; } [YamlMember(Alias = "overload")] [JsonProperty("overload")] public string Overload { get; set; } [YamlMember(Alias = "overridden")] [JsonProperty("overridden")] public string Overridden { get; set; } [YamlMember(Alias = "exceptions")] [JsonProperty("exceptions")] public List<ExceptionInfo> Exceptions { get; set; } [YamlMember(Alias = "see")] [JsonProperty("see")] public List<LinkInfo> Sees { get; set; } [YamlMember(Alias = "seealso")] [JsonProperty("seealso")] public List<LinkInfo> SeeAlsos { get; set; } [YamlMember(Alias = "inheritance")] [JsonProperty("inheritance")] public List<string> Inheritance { get; set; } [YamlMember(Alias = "derivedClasses")] [JsonProperty("derivedClasses")] public List<string> DerivedClasses { get; set; } [YamlMember(Alias = "implements")] [JsonProperty("implements")] public List<string> Implements { get; set; } [YamlMember(Alias = "inheritedMembers")] [JsonProperty("inheritedMembers")] public List<string> InheritedMembers { get; set; } [YamlMember(Alias = "extensionMethods")] [JsonProperty("extensionMethods")] public List<string> ExtensionMethods { get; set; } [YamlMember(Alias = "attributes")] [JsonProperty("attributes")] [MergeOption(MergeOption.Ignore)] public List<AttributeInfo> Attributes { get; set; } [YamlMember(Alias = "modifiers")] [JsonProperty("modifiers")] public SortedList<SyntaxLanguage, List<string>> Modifiers { get; set; } = new SortedList<SyntaxLanguage, List<string>>(); [YamlMember(Alias = "items")] [JsonProperty("items")] public List<MetadataItem> Items { get; set; } [YamlMember(Alias = "references")] [JsonProperty("references")] public Dictionary<string, ReferenceItem> References { get; set; } [YamlIgnore] [JsonIgnore] public string InheritDoc { get; set; } [YamlIgnore] [JsonIgnore] public TripleSlashCommentModel CommentModel { get; set; } public override string ToString() { return Type + ": " + Name; } public object Clone() { return MemberwiseClone(); } public void CopyInheritedData(MetadataItem src) { if (src == null) throw new ArgumentNullException(nameof(src)); if (Summary == null) Summary = src.Summary; if (Remarks == null) Remarks = src.Remarks; if (Exceptions == null && src.Exceptions != null) Exceptions = src.Exceptions.Select(e => e.Clone()).ToList(); if (Sees == null && src.Sees != null) Sees = src.Sees.Select(s => s.Clone()).ToList(); if (SeeAlsos == null && src.SeeAlsos != null) SeeAlsos = src.SeeAlsos.Select(s => s.Clone()).ToList(); if (Examples == null && src.Examples != null) Examples = new List<string>(src.Examples); if (CommentModel != null && src.CommentModel != null) CommentModel.CopyInheritedData(src.CommentModel); if (Syntax != null && src.Syntax != null) Syntax.CopyInheritedData(src.Syntax); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace JiebaNet.Segmenter.FinalSeg { public class Viterbi : IFinalSeg { private static readonly Lazy<Viterbi> Lazy = new Lazy<Viterbi>(() => new Viterbi()); private static readonly char[] States = {'B', 'M', 'E', 'S'}; private static readonly Regex RegexChinese = new Regex(@"([\u4E00-\u9FA5]+)", RegexOptions.Compiled); private static readonly Regex RegexSkip = new Regex(@"(\d+\.\d+|[a-zA-Z0-9]+)", RegexOptions.Compiled); private static IDictionary<char, IDictionary<char, Double>> _emitProbs; private static IDictionary<char, Double> _startProbs; private static IDictionary<char, IDictionary<char, Double>> _transProbs; private static IDictionary<char, char[]> _prevStatus; private Viterbi() { LoadModel(); } // TODO: synchronized public static Viterbi Instance { get { return Lazy.Value; } } public IEnumerable<string> Cut(String sentence) { var tokens = new List<string>(); foreach (var blk in RegexChinese.Split(sentence)) { if (RegexChinese.IsMatch(blk)) { tokens.AddRange(ViterbiCut(blk)); } else { var segments = RegexSkip.Split(blk).Where(seg => !string.IsNullOrEmpty(seg)); tokens.AddRange(segments); } } return tokens; } #region Private Helpers private void LoadModel() { long s = DateTime.Now.Millisecond; _prevStatus = new Dictionary<char, char[]>(); _prevStatus['B'] = new char[] {'E', 'S'}; _prevStatus['M'] = new char[] {'M', 'B'}; _prevStatus['S'] = new char[] {'S', 'E'}; _prevStatus['E'] = new char[] {'B', 'M'}; _startProbs = new Dictionary<char, Double>(); _startProbs['B'] = -0.26268660809250016; _startProbs['E'] = -3.14e+100; _startProbs['M'] = -3.14e+100; _startProbs['S'] = -1.4652633398537678; _transProbs = new Dictionary<char, IDictionary<char, Double>>(); IDictionary<char, Double> transB = new Dictionary<char, Double>(); transB['E'] = -0.510825623765990; transB['M'] = -0.916290731874155; _transProbs['B'] = transB; IDictionary<char, Double> transE = new Dictionary<char, Double>(); transE['B'] = -0.5897149736854513; transE['S'] = -0.8085250474669937; _transProbs['E'] = transE; IDictionary<char, Double> transM = new Dictionary<char, Double>(); transM['E'] = -0.33344856811948514; transM['M'] = -1.2603623820268226; _transProbs['M'] = transM; IDictionary<char, Double> transS = new Dictionary<char, Double>(); transS['B'] = -0.7211965654669841; transS['S'] = -0.6658631448798212; _transProbs['S'] = transS; var probEmitPath = ConfigManager.ProbEmitFile; _emitProbs = new Dictionary<char, IDictionary<char, double>>(); try { var lines = File.ReadAllLines(probEmitPath, Encoding.UTF8); IDictionary<char, double> values = null; foreach (var line in lines) { var tokens = line.Split('\t'); // If a new state starts. if (tokens.Length == 1) { values = new Dictionary<char, double>(); _emitProbs[tokens[0][0]] = values; } else { values[tokens[0][0]] = double.Parse(tokens[1]); } } } catch (IOException ex) { Console.Error.WriteLine("{0}: loading model from file {1} failure!", ex.Message, probEmitPath); } Console.WriteLine("model loading finished, time elapsed {0} ms.", DateTime.Now.Millisecond - s); } private IEnumerable<string> ViterbiCut(string sentence) { var v = new List<IDictionary<char, Double>>(); IDictionary<char, Node> path = new Dictionary<char, Node>(); // Init weights and paths. v.Add(new Dictionary<char, Double>()); foreach (var state in States) { var emP = _emitProbs[state].GetDefault(sentence[0], Constants.MinProb); v[0][state] = _startProbs[state] + emP; path[state] = new Node(state, null); } // For each remaining char for (var i = 1; i < sentence.Length; ++i) { IDictionary<char, Double> vv = new Dictionary<char, Double>(); v.Add(vv); IDictionary<char, Node> newPath = new Dictionary<char, Node>(); foreach (var y in States) { var emp = _emitProbs[y].GetDefault(sentence[i], Constants.MinProb); Pair<char> candidate = new Pair<char>('\0', Constants.MinProb); foreach (var y0 in _prevStatus[y]) { var tranp = _transProbs[y0].GetDefault(y, Constants.MinProb); tranp = v[i - 1][y0] + tranp + emp; if (candidate.Freq <= tranp) { candidate.Freq = tranp; candidate.Key = y0; } } vv[y] = candidate.Freq; newPath[y] = new Node(y, path[candidate.Key]); } path = newPath; } var probE = v[sentence.Length - 1]['E']; var probS = v[sentence.Length - 1]['S']; var finalPath = probE < probS ? path['S'] : path['E']; var posList = new List<char>(sentence.Length); while (finalPath != null) { posList.Add(finalPath.Value); finalPath = finalPath.Parent; } posList.Reverse(); var tokens = new List<string>(); int begin = 0, next = 0; for (var i = 0; i < sentence.Length; i++) { var pos = posList[i]; if (pos == 'B') begin = i; else if (pos == 'E') { tokens.Add(sentence.Sub(begin, i + 1)); next = i + 1; } else if (pos == 'S') { tokens.Add(sentence.Sub(i, i + 1)); next = i + 1; } } if (next < sentence.Length) { tokens.Add(sentence.Substring(next)); } return tokens; } #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 MS.Utility; using System; using System.Windows; using System.Windows.Media; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using MS.Internal.Ink; using MS.Internal; using MS.Internal.PresentationCore; namespace System.Windows.Ink { /// <summary> /// The Renderer class is used to render a stroke collection. /// This class listens to stroke added and removed events on the /// stroke collection and updates the internal visual tree. /// It also listens to the Invalidated event on Stroke (fired when /// DrawingAttributes changes, packet data changes, DrawingAttributes /// replaced, as well as Stroke developer calls Stroke.OnInvalidated) /// and updates the visual state as necessary. /// </summary> /// [FriendAccessAllowed] // Built into Core, also used by Framework. internal class Renderer { #region StrokeVisual /// <summary> /// A retained visual for rendering a single stroke in a stroke collection view /// </summary> private class StrokeVisual : System.Windows.Media.DrawingVisual { /// <summary> /// Constructor /// </summary> /// <param name="stroke">a stroke to render into this visual</param> /// <param name="renderer">a renderer associated to this visual</param> internal StrokeVisual(Stroke stroke, Renderer renderer) : base() { Debug.Assert(renderer != null); if (stroke == null) { throw new System.ArgumentNullException("stroke"); } _stroke = stroke; _renderer = renderer; // The original value of the color and IsHighlighter are cached so // when Stroke.Invalidated is fired, Renderer knows whether re-arranging // the visual tree is needed. _cachedColor = stroke.DrawingAttributes.Color; _cachedIsHighlighter = stroke.DrawingAttributes.IsHighlighter; // Update the visual contents Update(); } /// <summary> /// The Stroke rendedered into this visual. /// </summary> internal Stroke Stroke { get { return _stroke; } } /// <summary> /// Updates the contents of the visual. /// </summary> internal void Update() { using (DrawingContext drawingContext = RenderOpen()) { bool highContrast = _renderer.IsHighContrast(); if (highContrast == true && _stroke.DrawingAttributes.IsHighlighter) { // we don't render highlighters in high contrast return; } DrawingAttributes da; if (highContrast) { da = _stroke.DrawingAttributes.Clone(); da.Color = _renderer.GetHighContrastColor(); } else if (_stroke.DrawingAttributes.IsHighlighter == true) { // Get the drawing attributes to use for a highlighter stroke. This can be a copied DA with color.A // overridden if color.A != 255. da = StrokeRenderer.GetHighlighterAttributes(_stroke, _stroke.DrawingAttributes); } else { // Otherwise, usethe DA on this stroke da = _stroke.DrawingAttributes; } // Draw selected stroke as hollow _stroke.DrawInternal (drawingContext, da, _stroke.IsSelected ); } } /// <summary> /// StrokeVisual should not be hittestable as it interferes with event routing /// </summary> protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParams) { return null; } /// <summary> /// The previous value of IsHighlighter /// </summary> internal bool CachedIsHighlighter { get {return _cachedIsHighlighter;} set {_cachedIsHighlighter = value;} } /// <summary> /// The previous value of Color /// </summary> internal Color CachedColor { get {return _cachedColor;} set {_cachedColor = value;} } private Stroke _stroke; private bool _cachedIsHighlighter; private Color _cachedColor; private Renderer _renderer; } /// <summary> /// Private helper that helps reverse map the highlighter dictionary /// </summary> private class HighlighterContainerVisual : ContainerVisual { internal HighlighterContainerVisual(Color color) { _color = color; } /// <summary> /// The Color of the strokes in this highlighter container visual /// </summary> internal Color Color { get { return _color; } } private Color _color; } #endregion #region Internal interface /// <summary> /// Public Constructor /// </summary> internal Renderer() { // Initialize the data members. // We intentionally don't use lazy initialization for the core members to avoid // hidden bug situations when one thing has been created while another not. // If the user is looking for lazy initialization, she should do that on her // own and create Renderer only when there's a need for it. // Create visuals that'll be the containers for all other visuals // created by the Renderer. This visuals are created once and are // not supposed to be replaced nor destroyed while the Renderer is alive. _rootVisual = new ContainerVisual(); _highlightersRoot = new ContainerVisual(); _regularInkVisuals = new ContainerVisual(); _incrementalRenderingVisuals = new ContainerVisual(); // Highlighters go to the bottom, then regular ink, and regular // ink' incremental rendering in on top. VisualCollection rootChildren = _rootVisual.Children; rootChildren.Add(_highlightersRoot); rootChildren.Add(_regularInkVisuals); rootChildren.Add(_incrementalRenderingVisuals); // Set the default value of highcontrast to be false. _highContrast = false; // Create a stroke-visual dictionary _visuals = new Dictionary<Stroke, StrokeVisual>(); } /// <summary> /// Returns a reference to a visual tree that can be used to render the ink. /// This property may be either a single visual or a container visual with /// children. The element uses this visual as a child visual and arranges /// it with respects to the other siblings. /// Note: No visuals are actually generated until the application gets /// this property for the first time. If no strokes are set then an empty /// visual is returned. /// </summary> internal Visual RootVisual { get { return _rootVisual; } } /// <summary> /// Set the strokes property to the collection of strokes to be rendered. /// The Renderer will then listen to changes to the StrokeCollection /// and update its state to reflect the changes. /// </summary> internal StrokeCollection Strokes { get { // We should never return a null value. if ( _strokes == null ) { _strokes = new StrokeCollection(); // Start listening on events from the stroke collection. _strokes.StrokesChangedInternal += new StrokeCollectionChangedEventHandler(OnStrokesChanged); } return _strokes; } set { if (value == null) { throw new System.ArgumentNullException("value"); } if (value == _strokes) { return; } // Detach the current stroke collection if (null != _strokes) { // Stop listening on events from the stroke collection. _strokes.StrokesChangedInternal -= new StrokeCollectionChangedEventHandler(OnStrokesChanged); foreach (StrokeVisual visual in _visuals.Values) { StopListeningOnStrokeEvents(visual.Stroke); // Detach the visual from the tree DetachVisual(visual); } _visuals.Clear(); } // Set it. _strokes = value; // Create visuals foreach (Stroke stroke in _strokes) { // Create a visual per stroke StrokeVisual visual = new StrokeVisual(stroke, this); // Store the stroke-visual pair in the dictionary _visuals.Add(stroke, visual); StartListeningOnStrokeEvents(visual.Stroke); // Attach it to the visual tree AttachVisual(visual, true/*buildingStrokeCollection*/); } // Start listening on events from the stroke collection. _strokes.StrokesChangedInternal += new StrokeCollectionChangedEventHandler(OnStrokesChanged); } } /// <summary> /// User supposed to use this method to attach IncrementalRenderer's root visual /// to the visual tree of a stroke collection view. /// </summary> /// <param name="visual">visual to attach</param> /// <param name="drawingAttributes">drawing attributes that used in the incremental rendering</param> internal void AttachIncrementalRendering(Visual visual, DrawingAttributes drawingAttributes) { // Check the input parameters if (visual == null) { throw new System.ArgumentNullException("visual"); } if (drawingAttributes == null) { throw new System.ArgumentNullException("drawingAttributes"); } //harden against eaten exceptions bool exceptionRaised = false; // Verify that the visual hasn't been attached already if (_attachedVisuals != null) { foreach(Visual alreadyAttachedVisual in _attachedVisuals) { if (visual == alreadyAttachedVisual) { exceptionRaised = true; throw new System.InvalidOperationException(SR.Get(SRID.CannotAttachVisualTwice)); } } } else { // Create the list to register attached visuals in _attachedVisuals = new List<Visual>(); } if (!exceptionRaised) { // The position of the visual in the tree depends on the drawingAttributes // Find the appropriate parent visual to attach this visual to. ContainerVisual parent = drawingAttributes.IsHighlighter ? GetContainerVisual(drawingAttributes) : _incrementalRenderingVisuals; // Attach the visual to the tree parent.Children.Add(visual); // Put the visual into the list of visuals attached via this method _attachedVisuals.Add(visual); } } /// <summary> /// Detaches a visual previously attached via AttachIncrementalRendering /// </summary> /// <param name="visual">the visual to detach</param> internal void DetachIncrementalRendering(Visual visual) { if (visual == null) { throw new System.ArgumentNullException("visual"); } // Remove the visual in the list of attached via AttachIncrementalRendering if ((_attachedVisuals == null) || (_attachedVisuals.Remove(visual) == false)) { throw new System.InvalidOperationException(SR.Get(SRID.VisualCannotBeDetached)); } // Detach it from the tree DetachVisual(visual); } /// <summary> /// Internal helper used to indicate if a visual was previously attached /// via a call to AttachIncrementalRendering /// </summary> internal bool ContainsAttachedIncrementalRenderingVisual(Visual visual) { if (visual == null || _attachedVisuals == null) { return false; } return _attachedVisuals.Contains(visual); } /// <summary> /// Internal helper used to determine if a visual is in the right spot in the visual tree /// </summary> internal bool AttachedVisualIsPositionedCorrectly(Visual visual, DrawingAttributes drawingAttributes) { if (visual == null || drawingAttributes == null || _attachedVisuals == null || !_attachedVisuals.Contains(visual)) { return false; } ContainerVisual correctParent = drawingAttributes.IsHighlighter ? GetContainerVisual(drawingAttributes) : _incrementalRenderingVisuals; ContainerVisual currentParent = VisualTreeHelper.GetParent(visual) as ContainerVisual; if (currentParent == null || correctParent != currentParent) { return false; } return true; } /// <summary> /// TurnOnHighContrast turns on the HighContrast rendering mode /// </summary> /// <param name="strokeColor">The stroke color under high contrast</param> internal void TurnHighContrastOn(Color strokeColor) { if ( !_highContrast || strokeColor != _highContrastColor ) { _highContrast = true; _highContrastColor = strokeColor; UpdateStrokeVisuals(); } } /// <summary> /// ResetHighContrast turns off the HighContrast mode /// </summary> internal void TurnHighContrastOff() { if ( _highContrast ) { _highContrast = false; UpdateStrokeVisuals(); } } /// <summary> /// Indicates whether the renderer is in high contrast mode. /// </summary> /// <returns></returns> internal bool IsHighContrast() { return _highContrast; } /// <summary> /// returns the stroke color for the high contrast rendering. /// </summary> /// <returns></returns> public Color GetHighContrastColor() { return _highContrastColor; } #endregion #region Event handlers /// <summary> /// StrokeCollectionChanged event handler /// </summary> private void OnStrokesChanged(object sender, StrokeCollectionChangedEventArgs eventArgs) { System.Diagnostics.Debug.Assert(sender == _strokes); // Read the args StrokeCollection added = eventArgs.Added; StrokeCollection removed = eventArgs.Removed; // Add new strokes foreach (Stroke stroke in added) { // Verify that it's not a dupe if (_visuals.ContainsKey(stroke)) { throw new System.ArgumentException(SR.Get(SRID.DuplicateStrokeAdded)); } // Create a visual for the new stroke and add it to the dictionary StrokeVisual visual = new StrokeVisual(stroke, this); _visuals.Add(stroke, visual); // Start listening on the stroke events StartListeningOnStrokeEvents(visual.Stroke); // Attach it to the visual tree AttachVisual(visual, false/*buildingStrokeCollection*/); } // Deal with removed strokes first foreach (Stroke stroke in removed) { // Verify that the event is in sync with the view StrokeVisual visual = null; if (_visuals.TryGetValue(stroke, out visual)) { // get rid of both the visual and the stroke DetachVisual(visual); StopListeningOnStrokeEvents(visual.Stroke); _visuals.Remove(stroke); } else { throw new System.ArgumentException(SR.Get(SRID.UnknownStroke3)); } } } /// <summary> /// Stroke Invalidated event handler /// </summary> private void OnStrokeInvalidated(object sender, EventArgs eventArgs) { System.Diagnostics.Debug.Assert(_strokes.IndexOf(sender as Stroke) != -1); // Find the visual associated with the changed stroke. StrokeVisual visual; Stroke stroke = (Stroke)sender; if (_visuals.TryGetValue(stroke, out visual) == false) { throw new System.ArgumentException(SR.Get(SRID.UnknownStroke1)); } // The original value of IsHighligher and Color are cached in StrokeVisual. // if (IsHighlighter value changed or (IsHighlighter == true and not changed and color changed) // detach and re-attach the corresponding visual; // otherwise Invalidate the corresponding StrokeVisual if (visual.CachedIsHighlighter != stroke.DrawingAttributes.IsHighlighter || (stroke.DrawingAttributes.IsHighlighter && StrokeRenderer.GetHighlighterColor(visual.CachedColor) != StrokeRenderer.GetHighlighterColor(stroke.DrawingAttributes.Color))) { // The change requires reparenting the visual in the tree. DetachVisual(visual); AttachVisual(visual, false/*buildingStrokeCollection*/); // Update the cached values visual.CachedIsHighlighter = stroke.DrawingAttributes.IsHighlighter; visual.CachedColor = stroke.DrawingAttributes.Color; } // Update the visual. visual.Update(); } #endregion #region Helper methods /// <summary> /// Update the stroke visuals /// </summary> private void UpdateStrokeVisuals() { foreach ( StrokeVisual strokeVisual in _visuals.Values ) { strokeVisual.Update(); } } /// <summary> /// Attaches a stroke visual to the tree based on the stroke's /// drawing attributes and/or its z-order (index in the collection). /// </summary> private void AttachVisual(StrokeVisual visual, bool buildingStrokeCollection) { System.Diagnostics.Debug.Assert(_strokes != null); if (visual.Stroke.DrawingAttributes.IsHighlighter) { // Find or create a container visual for highlighter strokes of the color ContainerVisual parent = GetContainerVisual(visual.Stroke.DrawingAttributes); Debug.Assert(visual is StrokeVisual); //insert StrokeVisuals under any non-StrokeVisuals used for dynamic inking int i = 0; for (int j = parent.Children.Count - 1; j >= 0; j--) { if (parent.Children[j] is StrokeVisual) { i = j + 1; break; } } parent.Children.Insert(i, visual); } else { // For regular ink we have to respect the z-order of the strokes. // The implementation below is not optimal in a generic case, but the // most simple and should work ok in most common scenarios. // Find the nearest non-highlighter stroke with a lower z-order // and insert the new visual right next to the visual of that stroke. StrokeVisual precedingVisual = null; int i = 0; if (buildingStrokeCollection) { Stroke visualStroke = visual.Stroke; //we're building up a stroke collection, no need to start at IndexOf, i = Math.Min(_visuals.Count, _strokes.Count); //not -1, we're about to decrement while (--i >= 0) { if (object.ReferenceEquals(_strokes[i], visualStroke)) { break; } } } else { i = _strokes.IndexOf(visual.Stroke); } while (--i >= 0) { Stroke stroke = _strokes[i]; if ((stroke.DrawingAttributes.IsHighlighter == false) && (_visuals.TryGetValue(stroke, out precedingVisual) == true) && (VisualTreeHelper.GetParent(precedingVisual) != null)) { VisualCollection children = ((ContainerVisual)(VisualTreeHelper.GetParent(precedingVisual))).Children; int index = children.IndexOf(precedingVisual); children.Insert(index + 1, visual); break; } } // If found no non-highlighter strokes with a lower z-order, insert // the stroke at the very bottom of the regular ink visual tree. if (i < 0) { ContainerVisual parent = GetContainerVisual(visual.Stroke.DrawingAttributes); parent.Children.Insert(0, visual); } } } /// <summary> /// Detaches a visual from the tree, also removes highligher parents if empty /// when true is passed /// </summary> private void DetachVisual(Visual visual) { ContainerVisual parent = (ContainerVisual)(VisualTreeHelper.GetParent(visual)); if (parent != null) { VisualCollection children = parent.Children; children.Remove(visual); // If the parent is a childless highlighter, detach it too. HighlighterContainerVisual hcVisual = parent as HighlighterContainerVisual; if (hcVisual != null && hcVisual.Children.Count == 0 && _highlighters != null && _highlighters.ContainsValue(hcVisual)) { DetachVisual(hcVisual); _highlighters.Remove(hcVisual.Color); } } } /// <summary> /// Attaches event handlers to stroke events /// </summary> private void StartListeningOnStrokeEvents(Stroke stroke) { System.Diagnostics.Debug.Assert(stroke != null); stroke.Invalidated += new EventHandler(OnStrokeInvalidated); } /// <summary> /// Detaches event handlers from stroke /// </summary> private void StopListeningOnStrokeEvents(Stroke stroke) { System.Diagnostics.Debug.Assert(stroke != null); stroke.Invalidated -= new EventHandler(OnStrokeInvalidated); } /// <summary> /// Finds a container for a new visual based on the drawing attributes /// of the stroke rendered into that visual. /// </summary> /// <param name="drawingAttributes">drawing attributes</param> /// <returns>visual</returns> private ContainerVisual GetContainerVisual(DrawingAttributes drawingAttributes) { System.Diagnostics.Debug.Assert(drawingAttributes != null); HighlighterContainerVisual hcVisual; if (drawingAttributes.IsHighlighter) { // For a highlighter stroke, the color.A is neglected. Color color = StrokeRenderer.GetHighlighterColor(drawingAttributes.Color); if ((_highlighters == null) || (_highlighters.TryGetValue(color, out hcVisual) == false)) { if (_highlighters == null) { _highlighters = new Dictionary<Color, HighlighterContainerVisual>(); } hcVisual = new HighlighterContainerVisual(color); hcVisual.Opacity = StrokeRenderer.HighlighterOpacity; _highlightersRoot.Children.Add(hcVisual); _highlighters.Add(color, hcVisual); } else if (VisualTreeHelper.GetParent(hcVisual) == null) { _highlightersRoot.Children.Add(hcVisual); } return hcVisual; } else { return _regularInkVisuals; } } #endregion #region Fields // The renderer's top level container visuals private ContainerVisual _rootVisual; private ContainerVisual _highlightersRoot; private ContainerVisual _incrementalRenderingVisuals; private ContainerVisual _regularInkVisuals; // Stroke-to-visual map private Dictionary<Stroke, StrokeVisual> _visuals; // Color-to-visual map for highlighter ink container visuals private Dictionary<Color, HighlighterContainerVisual> _highlighters = null; // Collection of strokes this Renderer renders private StrokeCollection _strokes = null; // List of visuals attached via AttachIncrementalRendering private List<Visual> _attachedVisuals = null; // When true, will render in high contrast mode private bool _highContrast; private Color _highContrastColor = Colors.White; #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using AutoMapper; using Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Network; using System; using System.Collections; using System.Collections.Generic; using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.New, "AzureRmVirtualNetworkGateway", SupportsShouldProcess = true), OutputType(typeof(PSVirtualNetworkGateway))] public class NewAzureVirtualNetworkGatewayCommand : VirtualNetworkGatewayBaseCmdlet { [Alias("ResourceName")] [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name.")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ValidateNotNullOrEmpty] public virtual string ResourceGroupName { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "location.")] [ValidateNotNullOrEmpty] public string Location { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The IpConfigurations for Virtual network gateway.")] [ValidateNotNullOrEmpty] public List<PSVirtualNetworkGatewayIpConfiguration> IpConfigurations { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of this virtual network gateway: Vpn, ExoressRoute")] [ValidateSet( MNM.VirtualNetworkGatewayType.Vpn, MNM.VirtualNetworkGatewayType.ExpressRoute, IgnoreCase = true)] public string GatewayType { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of the Vpn:PolicyBased/RouteBased")] [ValidateSet( MNM.VpnType.PolicyBased, MNM.VpnType.RouteBased, IgnoreCase = true)] public string VpnType { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "EnableBgp Flag")] public bool EnableBgp { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of the Vpn:PolicyBased/RouteBased")] [ValidateSet( MNM.VirtualNetworkGatewaySkuTier.Basic, MNM.VirtualNetworkGatewaySkuTier.Standard, MNM.VirtualNetworkGatewaySkuTier.HighPerformance, IgnoreCase = true)] public string GatewaySku { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetByResource", HelpMessage = "GatewayDefaultSite")] public PSLocalNetworkGateway GatewayDefaultSite { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "P2S VpnClient AddressPool")] [ValidateNotNullOrEmpty] public List<string> VpnClientAddressPool { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of VpnClientRootCertificates to be added.")] public List<PSVpnClientRootCertificate> VpnClientRootCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of VpnClientCertificates to be revoked.")] public List<PSVpnClientRevokedCertificate> VpnClientRevokedCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The virtual network gateway's ASN for BGP over VPN")] public uint Asn { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The weight added to routes learned over BGP from this virtual network gateway")] public int PeerWeight { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable which represents resource tags.")] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, HelpMessage = "Do not ask for confirmation if you want to overrite a resource")] public SwitchParameter Force { get; set; } public override void Execute() { base.Execute(); WriteWarning("The output object type of this cmdlet will be modified in a future release."); var present = this.IsVirtualNetworkGatewayPresent(this.ResourceGroupName, this.Name); ConfirmAction( Force.IsPresent, string.Format(Properties.Resources.OverwritingResource, Name), Properties.Resources.CreatingResourceMessage, Name, () => { var virtualNetworkGateway = CreateVirtualNetworkGateway(); WriteObject(virtualNetworkGateway); }, () => present); } private PSVirtualNetworkGateway CreateVirtualNetworkGateway() { var vnetGateway = new PSVirtualNetworkGateway(); vnetGateway.Name = this.Name; vnetGateway.ResourceGroupName = this.ResourceGroupName; vnetGateway.Location = this.Location; if (this.IpConfigurations != null) { vnetGateway.IpConfigurations = this.IpConfigurations; } vnetGateway.GatewayType = this.GatewayType; vnetGateway.VpnType = this.VpnType; vnetGateway.EnableBgp = this.EnableBgp; if (this.GatewayDefaultSite != null) { vnetGateway.GatewayDefaultSite = new PSResourceId(); vnetGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id; } else { vnetGateway.GatewayDefaultSite = null; } if (this.GatewaySku != null) { vnetGateway.Sku = new PSVirtualNetworkGatewaySku(); vnetGateway.Sku.Tier = this.GatewaySku; vnetGateway.Sku.Name = this.GatewaySku; } else { vnetGateway.Sku = null; } if (this.VpnClientAddressPool != null || this.VpnClientRootCertificates != null || this.VpnClientRevokedCertificates != null) { vnetGateway.VpnClientConfiguration = new PSVpnClientConfiguration(); if (this.VpnClientAddressPool != null) { // Make sure passed Virtual Network gateway type is RouteBased if P2S VpnClientAddressPool is specified. if (this.VpnType == null || !this.VpnType.Equals(MNM.VpnType.RouteBased)) { throw new ArgumentException("Virtual Network Gateway VpnType should be :{0} when P2S VpnClientAddressPool is specified."); } vnetGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace(); vnetGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool; } if (this.VpnClientRootCertificates != null) { vnetGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates; } if (this.VpnClientRevokedCertificates != null) { vnetGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates; } } else { vnetGateway.VpnClientConfiguration = null; } if (this.Asn > 0 || this.PeerWeight > 0) { vnetGateway.BgpSettings = new PSBgpSettings(); vnetGateway.BgpSettings.BgpPeeringAddress = null; // We block modifying the gateway's BgpPeeringAddress (CA) if (this.Asn > 0) { vnetGateway.BgpSettings.Asn = this.Asn; } if (this.PeerWeight > 0) { vnetGateway.BgpSettings.PeerWeight = this.PeerWeight; } else if (this.PeerWeight < 0) { throw new ArgumentException("PeerWeight must be a positive integer"); } } // Map to the sdk object var vnetGatewayModel = Mapper.Map<MNM.VirtualNetworkGateway>(vnetGateway); vnetGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true); // Execute the Create VirtualNetwork call this.VirtualNetworkGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, vnetGatewayModel); var getVirtualNetworkGateway = this.GetVirtualNetworkGateway(this.ResourceGroupName, this.Name); return getVirtualNetworkGateway; } } }
// // PictureTile.cs // // Author: // Stephane Delcroix <sdelcroix*novell.com> // // Copyright (C) 2008 Novell, Inc. // Copyright (C) 2008 Stephane Delcroix // // 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.IO; using System.Collections; using System.Globalization; using Gtk; using FSpot; using FSpot.Extensions; using FSpot.Widgets; using FSpot.Filters; using FSpot.UI.Dialog; using Hyena; using Mono.Unix; namespace PictureTileExtension { public class PictureTile: ICommand { [Glade.Widget] Gtk.Dialog picturetile_dialog; [Glade.Widget] Gtk.SpinButton x_max_size; [Glade.Widget] Gtk.SpinButton y_max_size; [Glade.Widget] Gtk.SpinButton space_between_images; [Glade.Widget] Gtk.SpinButton outside_border; [Glade.Widget] Gtk.ComboBox background_color; [Glade.Widget] Gtk.SpinButton image_scale; [Glade.Widget] Gtk.CheckButton uniform_images; [Glade.Widget] Gtk.RadioButton jpeg_radio; [Glade.Widget] Gtk.RadioButton tiff_radio; [Glade.Widget] Gtk.SpinButton pages; [Glade.Widget] Gtk.SpinButton jpeg_quality; string dir_tmp; string destfile_tmp; string [] colors = {"white", "black"}; Tag [] photo_tags; public void Run (object o, EventArgs e) { Log.Information ("Executing PictureTile extension"); if (App.Instance.Organizer.SelectedPhotos ().Length == 0) { InfoDialog (Catalog.GetString ("No selection available"), Catalog.GetString ("This tool requires an active selection. Please select one or more pictures and try again"), Gtk.MessageType.Error); return; } else { //Check for PictureTile executable string output = ""; try { System.Diagnostics.Process mp_check = new System.Diagnostics.Process (); mp_check.StartInfo.RedirectStandardOutput = true; mp_check.StartInfo.RedirectStandardError = true; mp_check.StartInfo.UseShellExecute = false; mp_check.StartInfo.FileName = "picturetile.pl"; mp_check.Start (); mp_check.WaitForExit (); StreamReader sroutput = mp_check.StandardError; output = sroutput.ReadLine (); } catch (System.Exception) { } if (!System.Text.RegularExpressions.Regex.IsMatch (output, "^picturetile")) { InfoDialog (Catalog.GetString ("PictureTile not available"), Catalog.GetString ("The picturetile.pl executable was not found in path. Please check that you have it installed and that you have permissions to execute it"), Gtk.MessageType.Error); return; } ShowDialog (); } } public void ShowDialog () { Glade.XML xml = new Glade.XML (null, "PictureTile.glade", "picturetile_dialog", "f-spot"); xml.Autoconnect (this); picturetile_dialog.Modal = true; picturetile_dialog.TransientFor = null; picturetile_dialog.Response += OnDialogReponse; jpeg_radio.Active = true; jpeg_radio.Toggled += HandleFormatRadioToggled; HandleFormatRadioToggled (null, null); PopulateCombo (); picturetile_dialog.ShowAll (); } void OnDialogReponse (object obj, ResponseArgs args) { if (args.ResponseId == ResponseType.Ok) { CreatePhotoWall (); } picturetile_dialog.Destroy (); } void CreatePhotoWall () { dir_tmp = System.IO.Path.GetTempFileName (); System.IO.File.Delete (dir_tmp); System.IO.Directory.CreateDirectory (dir_tmp); dir_tmp += "/"; //Prepare the pictures ProgressDialog progress_dialog = null; progress_dialog = new ProgressDialog (Catalog.GetString ("Preparing selected pictures"), ProgressDialog.CancelButtonType.Stop, App.Instance.Organizer.SelectedPhotos ().Length, picturetile_dialog); FilterSet filters = new FilterSet (); filters.Add (new JpegFilter ()); uint counter = 0; ArrayList all_tags = new ArrayList (); foreach (Photo p in App.Instance.Organizer.SelectedPhotos ()) { if (progress_dialog.Update (String.Format (Catalog.GetString ("Processing \"{0}\""), p.Name))) { progress_dialog.Destroy (); DeleteTmp (); return; } //Store photo tags, to attach them later on import foreach (Tag tag in p.Tags) { if (! all_tags.Contains (tag)) all_tags.Add (tag); } //FIXME should switch to retry/skip if (!GLib.FileFactory.NewForUri (p.DefaultVersion.Uri).Exists) { Log.WarningFormat ("Couldn't access photo {0} while creating mosaics", p.DefaultVersion.Uri.LocalPath); continue; } using (FilterRequest freq = new FilterRequest (p.DefaultVersion.Uri)) { filters.Convert (freq); File.Copy (freq.Current.LocalPath, String.Format ("{0}{1}.jpg", dir_tmp, counter ++)); } } if (progress_dialog != null) progress_dialog.Destroy (); photo_tags = (Tag []) all_tags.ToArray (typeof (Tag)); string uniform = ""; if (uniform_images.Active) uniform = "--uniform"; string output_format = "jpeg"; if (tiff_radio.Active) output_format = "tiff"; string scale = String.Format (CultureInfo.InvariantCulture, "{0,4}", (double) image_scale.Value / (double) 100); destfile_tmp = String.Format ("{0}.{1}", System.IO.Path.GetTempFileName (), output_format); //Execute picturetile string picturetile_command = String.Format ("--size {0}x{1} " + "--directory {2} " + "--scale {3} " + "--margin {4} " + "--border {5} " + "--background {6} " + "--pages {7} " + "{8} " + "{9}", x_max_size.Text, y_max_size.Text, dir_tmp, scale, space_between_images.Text, outside_border.Text, colors [background_color.Active], pages.Text, uniform, destfile_tmp); Log.Debug ("Executing: picturetile.pl " + picturetile_command); System.Diagnostics.Process pt_exe = System.Diagnostics.Process.Start ("picturetile.pl", picturetile_command); pt_exe.WaitForExit (); // Handle multiple files generation (pages). // If the user wants 2 pages (images), and the output filename is out.jpg, picturetile will create // /tmp/out1.jpg and /tmp/out2.jpg. System.IO.DirectoryInfo di = new System.IO.DirectoryInfo (System.IO.Path.GetDirectoryName (destfile_tmp)); string filemask = System.IO.Path.GetFileNameWithoutExtension (destfile_tmp) + "*" + System.IO.Path.GetExtension (destfile_tmp); FileInfo [] fi = di.GetFiles (filemask); // Move generated files to f-spot photodir string [] photo_import_list = new string [fi.Length]; counter = 0; foreach (FileInfo f in fi) { string orig = System.IO.Path.Combine (f.DirectoryName, f.Name); photo_import_list [counter ++] = MoveFile (orig); } //Add the pic(s) to F-Spot! Db db = App.Instance.Database; ImportCommand command = new ImportCommand (null); if (command.ImportFromPaths (db.Photos, photo_import_list, photo_tags) > 0) { InfoDialog (Catalog.GetString ("PhotoWall generated!"), Catalog.GetString ("Your photo wall have been generated and imported in F-Spot. Select the last roll to see it"), Gtk.MessageType.Info); } else { InfoDialog (Catalog.GetString ("Error importing photowall"), Catalog.GetString ("An error occurred while importing the newly generated photowall to F-Spot"), Gtk.MessageType.Error); } DeleteTmp (); } private void HandleFormatRadioToggled (object o, EventArgs e) { jpeg_quality.Sensitive = jpeg_radio.Active; } private void DeleteTmp () { //Clean temp workdir DirectoryInfo dir = new DirectoryInfo(dir_tmp); FileInfo[] tmpfiles = dir.GetFiles(); foreach (FileInfo f in tmpfiles) { if (System.IO.File.Exists(dir_tmp + f.Name)) { System.IO.File.Delete (dir_tmp + f.Name); } } if (System.IO.Directory.Exists(dir_tmp)) { System.IO.Directory.Delete(dir_tmp); } } private void PopulateCombo () { foreach (string c in colors) { background_color.AppendText (c); } background_color.Active = 0; } private string MoveFile (string orig) { string dest = FileImportBackend.ChooseLocation (orig); System.IO.File.Move (orig, dest); return dest; } private void InfoDialog (string title, string msg, Gtk.MessageType type) { HigMessageDialog md = new HigMessageDialog (App.Instance.Organizer.Window, DialogFlags.DestroyWithParent, type, ButtonsType.Ok, title, msg); md.Run (); md.Destroy (); } } }
//============================================================================= // System : Sandcastle Help File Builder Utilities // File : ConvertConceptualContent.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 09/28/2008 // Note : Copyright 2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a class used to convert conceptual content settings in // version 1.7.0.0 and prior SHFB project files to the new MSBuild format. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.8.0.0 07/24/2008 EFW Created the code //============================================================================= using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; using SandcastleBuilder.Utils.BuildEngine; using SandcastleBuilder.Utils.ConceptualContent; namespace SandcastleBuilder.Utils.Conversion { /// <summary> /// This class is used to convert conceptual content settings in version /// 1.7.0.0 and prior SHFB project files to the new MSBuild format. /// </summary> public class ConvertConceptualContent { #region Private data members //===================================================================== private ConvertFromShfbFile converter; private static Regex reFindHead = new Regex(@"</head>", RegexOptions.IgnoreCase); private static Regex reFindTopic = new Regex(@"<topic ", RegexOptions.IgnoreCase); #endregion #region Constructor //===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="projectConverter">The project converter object</param> public ConvertConceptualContent(ConvertFromShfbFile projectConverter) { converter = projectConverter; } #endregion #region Methods //===================================================================== /// <summary> /// This is used to convert the conceptual content from the old project /// into the format required by the new project. /// </summary> public void ConvertContent() { XmlTextReader xr = converter.Reader; // Add code snippets file if defined string dest, file = xr.GetAttribute("snippetFile"); if(file != null && file.Trim().Length > 0) { dest = Path.Combine(converter.ProjectFolder, Path.GetFileName( file)); dest = Path.ChangeExtension(dest, ".snippets"); converter.Project.AddFileToProject(converter.FullPath(file), dest); } if(!xr.IsEmptyElement) while(!xr.EOF && xr.NodeType != XmlNodeType.EndElement) { if(xr.NodeType == XmlNodeType.Element && xr.Name == "tokens" && !xr.IsEmptyElement) this.CreateTokenFile(); if(xr.NodeType == XmlNodeType.Element && xr.Name == "images" && !xr.IsEmptyElement) this.AddImageFiles(); if(xr.NodeType == XmlNodeType.Element && xr.Name == "topics" && !xr.IsEmptyElement) this.CreateContentFile(); xr.Read(); } } /// <summary> /// This converts the token entries to a token file and adds it to /// the project. /// </summary> private void CreateTokenFile() { XmlReader xr = converter.Reader; StreamWriter sw = null; string tokenFile = Path.Combine(converter.ProjectFolder, Path.GetFileNameWithoutExtension(converter.Project.Filename) + ".tokens"); // Create an empty token file try { sw = File.CreateText(tokenFile); sw.WriteLine("<content/>"); } finally { if(sw != null) sw.Close(); } FileItem fileItem = converter.Project.AddFileToProject(tokenFile, tokenFile); TokenCollection tokens = new TokenCollection(fileItem); while(!xr.EOF && xr.NodeType != XmlNodeType.EndElement) { if(xr.NodeType == XmlNodeType.Element && xr.Name == "token") tokens.Add(new Token(xr.GetAttribute("name"), xr.GetAttribute("value"))); xr.Read(); } tokens.Save(); } /// <summary> /// This adds all image files to the project /// </summary> private void AddImageFiles() { XmlReader xr = converter.Reader; SandcastleProject project = converter.Project; FileItem fileItem; string sourceFile, id, altText, destFile, oldFolder = converter.OldFolder, projectFolder = converter.ProjectFolder; bool alwaysCopy; while(!xr.EOF && xr.NodeType != XmlNodeType.EndElement) { if(xr.NodeType == XmlNodeType.Element && xr.Name == "image") { id = xr.GetAttribute("id"); if(id == null || id.Trim().Length == 0) id = Guid.NewGuid().ToString(); sourceFile = xr.GetAttribute("file"); if(sourceFile == null || sourceFile.Trim().Length == 0) sourceFile = "Unknown.jpg"; sourceFile = converter.FullPath(sourceFile); // Maintain any additional path info beyond the old base // project folder. if(sourceFile.StartsWith(oldFolder, StringComparison.OrdinalIgnoreCase)) destFile = projectFolder + sourceFile.Substring( oldFolder.Length); else destFile = Path.Combine(projectFolder, Path.GetFileName(sourceFile)); altText = xr.GetAttribute("altText"); alwaysCopy = Convert.ToBoolean(xr.GetAttribute( "alwaysCopy"), CultureInfo.InvariantCulture); fileItem = project.AddFileToProject(sourceFile, destFile); fileItem.BuildAction = BuildAction.Image; fileItem.ProjectElement.SetMetadata("ImageId", id); if(!String.IsNullOrEmpty(altText)) fileItem.ProjectElement.SetMetadata("AlternateText", altText); if(alwaysCopy) fileItem.ProjectElement.SetMetadata("CopyToMedia", "True"); } xr.Read(); } } /// <summary> /// This converts the topic entries to a content file and adds it to /// the project. /// </summary> private void CreateContentFile() { SandcastleProject project = converter.Project; XmlReader xr = converter.Reader; XmlWriterSettings settings = new XmlWriterSettings(); XmlWriter xw = null; string contentFilename, attr; try { settings.Indent = true; settings.CloseOutput = true; contentFilename = Path.Combine(converter.ProjectFolder, Path.GetFileNameWithoutExtension( converter.Project.Filename) + ".content"); xw = XmlWriter.Create(contentFilename, settings); xw.WriteStartDocument(); xw.WriteStartElement("Topics"); // Add the default topic and split TOC attributes if present attr = xr.GetAttribute("defaultTopic"); if(!String.IsNullOrEmpty(attr)) xw.WriteAttributeString("defaultTopic", attr); attr = xr.GetAttribute("splitTOCTopic"); if(!String.IsNullOrEmpty(attr)) xw.WriteAttributeString("splitTOCTopic", attr); while(!xr.EOF && xr.NodeType != XmlNodeType.EndElement) { if(xr.NodeType == XmlNodeType.Element && xr.Name == "topic") this.ConvertTopic(xr, xw, project); xr.Read(); } xw.WriteEndElement(); // </Topics> xw.WriteEndDocument(); } finally { if(xw != null) xw.Close(); } converter.Project.AddFileToProject(contentFilename, contentFilename); } /// <summary> /// Convert a conceptual content topic and all of its children /// </summary> /// <param name="xr">The XML reader containing the topics</param> /// <param name="xw">The XML writer to which they are written</param> /// <param name="project">The project to which the files are added</param> private void ConvertTopic(XmlReader xr, XmlWriter xw, SandcastleProject project) { FileItem newFile = null; string id, file, title, tocTitle, linkText, destFile, ext, name, value, oldFolder = converter.OldFolder, projectFolder = converter.ProjectFolder; bool visible; int revision; id = xr.GetAttribute("id"); // If not set, an ID will be created when needed if(id == null || id.Trim().Length == 0) id = new Guid(id).ToString(); file = xr.GetAttribute("file"); title = xr.GetAttribute("title"); tocTitle = xr.GetAttribute("tocTitle"); linkText = xr.GetAttribute("linkText"); if(!Int32.TryParse(xr.GetAttribute("revision"), out revision) || revision < 1) revision = 1; if(!Boolean.TryParse(xr.GetAttribute("visible"), out visible)) visible = true; // Add the topic to the content file and the project xw.WriteStartElement("Topic"); xw.WriteAttributeString("id", id); if(file != null && file.Trim().Length > 0) { file = converter.FullPath(file); // Maintain any additional path info beyond the old base // project folder. if(file.StartsWith(oldFolder, StringComparison.OrdinalIgnoreCase)) destFile = projectFolder + file.Substring(oldFolder.Length); else destFile = Path.Combine(projectFolder, Path.GetFileName(file)); ext = Path.GetExtension(destFile).ToLower( CultureInfo.InvariantCulture); // Change the extension on .xml files to .aml and add the // root topic element. if(ext == ".xml") { destFile = Path.ChangeExtension(destFile, ".aml"); ConvertTopic(file, destFile, id, revision); file = destFile; } // Add meta elements for the ID and revision number if(ext == ".htm" || ext == ".html" || ext == ".topic") { ConvertTopic(file, destFile, id, revision); file = destFile; } newFile = project.AddFileToProject(file, destFile); newFile.BuildAction = BuildAction.None; } else xw.WriteAttributeString("noFile", "True"); if(title != null) xw.WriteAttributeString("title", title); if(tocTitle != null) xw.WriteAttributeString("tocTitle", tocTitle); if(linkText != null) xw.WriteAttributeString("linkText", linkText); xw.WriteAttributeString("visible", visible.ToString(CultureInfo.InvariantCulture)); // Add child elements, if any if(!xr.IsEmptyElement) while(!xr.EOF) { xr.Read(); if(xr.NodeType == XmlNodeType.EndElement && xr.Name == "topic") break; if(xr.NodeType == XmlNodeType.Element) if(xr.Name == "helpAttributes") { xw.WriteStartElement("HelpAttributes"); while(!xr.EOF && xr.NodeType != XmlNodeType.EndElement) { if(xr.NodeType == XmlNodeType.Element && xr.Name == "helpAttribute") { name = xr.GetAttribute("name"); value = xr.GetAttribute("value"); if(!String.IsNullOrEmpty(name)) { xw.WriteStartElement("HelpAttribute"); xw.WriteAttributeString("name", name); xw.WriteAttributeString("value", value); xw.WriteEndElement(); } } xr.Read(); } xw.WriteEndElement(); } else if(xr.Name == "helpKeywords") { xw.WriteStartElement("HelpKeywords"); while(!xr.EOF && xr.NodeType != XmlNodeType.EndElement) { if(xr.NodeType == XmlNodeType.Element && xr.Name == "helpKeyword") { name = xr.GetAttribute("index"); value = xr.GetAttribute("term"); if(!String.IsNullOrEmpty(name)) { xw.WriteStartElement("HelpKeyword"); xw.WriteAttributeString("index", name); xw.WriteAttributeString("term", value); xw.WriteEndElement(); } } xr.Read(); } xw.WriteEndElement(); } else if(xr.Name == "topic") this.ConvertTopic(xr, xw, project); } xw.WriteEndElement(); } /// <summary> /// Convert a conceptual topic to the new format /// </summary> /// <param name="source">The source file</param> /// <param name="dest">The destination file</param> /// <param name="id">The topic ID</param> /// <param name="revision">The revision number</param> private static void ConvertTopic(string source, string dest, string id, int revision) { XmlDocument doc; XmlNode root; XmlAttribute attr; Encoding enc = Encoding.Default; Match m; string content; if(!Directory.Exists(Path.GetDirectoryName(dest))) Directory.CreateDirectory(Path.GetDirectoryName(dest)); if(dest.EndsWith(".aml", StringComparison.OrdinalIgnoreCase)) { doc = new XmlDocument(); doc.Load(source); // Already there? root = doc.SelectSingleNode("topic"); if(root != null) { if(root.Attributes["id"] == null || root.Attributes["revisionNumber"] == null) throw new FormatException(source + " contains a " + "root topic element without an id and/or " + "revision attribute"); doc.Save(dest); return; } // Add the root node root = doc.CreateElement("topic"); attr = doc.CreateAttribute("id"); attr.Value = id; root.Attributes.Append(attr); attr = doc.CreateAttribute("revisionNumber"); attr.Value = revision.ToString(CultureInfo.InvariantCulture); root.Attributes.Append(attr); root.AppendChild(doc.ChildNodes[1]); doc.AppendChild(root); doc.Save(dest); return; } content = BuildProcess.ReadWithEncoding(source, ref enc); if(!source.EndsWith(".topic", StringComparison.OrdinalIgnoreCase)) { m = reFindHead.Match(content); if(!m.Success) throw new FormatException(source + " does not contain a " + "<head> element"); content = content.Insert(m.Index, String.Format( CultureInfo.InvariantCulture, "<meta name=\"id\" " + "content=\"{0}\">\r\n<meta name=\"revisionNumber\" " + "content=\"{1}\">\r\n", id, revision)); } else { m = reFindTopic.Match(content); if(!m.Success) throw new FormatException(source + " does not contain a " + "<topic> element"); content = content.Insert(m.Index + m.Length, String.Format( CultureInfo.InvariantCulture, " id=\"{0}\" " + "revisionNumber=\"{1}\" ", id, revision)); } // Write the file back out with the appropriate encoding using(StreamWriter sw = new StreamWriter(dest, false, enc)) { sw.Write(content); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq.Expressions; using Xunit; namespace System.Linq.Tests { public class GroupByTests : EnumerableBasedTests { public static void AssertGroupingCorrect<TKey, TElement>(IQueryable<TKey> keys, IQueryable<TElement> elements, IQueryable<IGrouping<TKey, TElement>> grouping) { AssertGroupingCorrect<TKey, TElement>(keys, elements, grouping, EqualityComparer<TKey>.Default); } public static void AssertGroupingCorrect<TKey, TElement>(IQueryable<TKey> keys, IQueryable<TElement> elements, IQueryable<IGrouping<TKey, TElement>> grouping, IEqualityComparer<TKey> keyComparer) { if (grouping == null) { Assert.Null(elements); Assert.Null(keys); return; } Assert.NotNull(elements); Assert.NotNull(keys); Dictionary<TKey, List<TElement>> dict = new Dictionary<TKey, List<TElement>>(keyComparer); List<TElement> groupingForNullKeys = new List<TElement>(); using (IEnumerator<TElement> elEn = elements.GetEnumerator()) using (IEnumerator<TKey> keyEn = keys.GetEnumerator()) { while (keyEn.MoveNext()) { Assert.True(elEn.MoveNext()); TKey key = keyEn.Current; if (key == null) { groupingForNullKeys.Add(elEn.Current); } else { List<TElement> list; if (!dict.TryGetValue(key, out list)) dict.Add(key, list = new List<TElement>()); list.Add(elEn.Current); } } Assert.False(elEn.MoveNext()); } foreach (IGrouping<TKey, TElement> group in grouping) { Assert.NotEmpty(group); TKey key = group.Key; List<TElement> list; if (key == null) { Assert.Equal(groupingForNullKeys, group); groupingForNullKeys.Clear(); } else { Assert.True(dict.TryGetValue(key, out list)); Assert.Equal(list, group); dict.Remove(key); } } Assert.Empty(dict); Assert.Empty(groupingForNullKeys); } public struct Record { public string Name; public int Score; } [Fact] public void SingleNullKeySingleNullElement() { string[] key = { null }; string[] element = { null }; AssertGroupingCorrect(key.AsQueryable(), element.AsQueryable(), new string[] { null }.AsQueryable().GroupBy(e => e, e => e, EqualityComparer<string>.Default), EqualityComparer<string>.Default); } [Fact] public void EmptySource() { Assert.Empty(new Record[] { }.AsQueryable().GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void SourceIsNull() { IQueryable<Record> source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score)); Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name)); Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum())); Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score))); Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer())); } [Fact] public void KeySelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<Record, string>> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, e => e.Score, new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score, (k, es) => es.Sum())); Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score)); Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score, (k, es) => es.Sum())); Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, (k, es) => es.Sum(e => e.Score))); Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector)); } [Fact] public void ElementSelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<Record, int>> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector)); Assert.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum())); Assert.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum(), new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNull() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<string, IEnumerable<int>, long>> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, e => e.Score, resultSelector, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNullNoComparer() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<string, IEnumerable<int>, long>> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, e => e.Score, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelector() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<string, IEnumerable<Record>, long>> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelectorCustomComparer() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Expression<Func<string, IEnumerable<Record>, long>> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, resultSelector, new AnagramEqualityComparer())); } [Fact] public void EmptySourceWithResultSelector() { Assert.Empty(new Record[] { }.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void DuplicateKeysCustomComparer() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 240, 365, -600, 63 }; Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void NullComparer() { string[] key = { "Tim", null, null, "Robert", "Chris", "miT" }; int[] element = { 55, 49, 9, -100, 24, 25 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = null, Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = null, Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 165, 58, -600, 120, 75 }; Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null)); } [Fact] public void SingleNonNullElement() { string[] key = { "Tim" }; Record[] source = { new Record { Name = key[0], Score = 60 } }; AssertGroupingCorrect(key.AsQueryable(), source.AsQueryable(), source.AsQueryable().GroupBy(e => e.Name)); } [Fact] public void AllElementsSameKey() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] scores = { 60, -10, 40, 100 }; var source = key.Zip(scores, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key.AsQueryable(), source.AsQueryable(), source.AsQueryable().GroupBy(e => e.Name, new AnagramEqualityComparer()), new AnagramEqualityComparer()); } [Fact] public void AllElementsSameKeyResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; long[] expected = { 570 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] } }; Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), new AnagramEqualityComparer())); } [Fact] public void NullComparerResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] }, }; long[] expected = { 150, 420 }; Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), null)); } [Fact] public void GroupBy1() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy2() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy3() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy4() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy5() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, (k, g) => k).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy6() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, (k, g) => k).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy7() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, (k, g) => k, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy8() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, (k, g) => k, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.MethodInfos; using Internal.Reflection.Core.Execution; using Internal.Reflection.Core.NonPortable; using Internal.Reflection.Tracing; using Internal.Reflection.Augments; using EnumInfo = Internal.Runtime.Augments.EnumInfo; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // Abstract base class for all TypeInfo's implemented by the runtime. // // This base class performs several services: // // - Provides default implementations whenever possible. Some of these // return the "common" error result for narrowly applicable properties (such as those // that apply only to generic parameters.) // // - Inverts the DeclaredMembers/DeclaredX relationship (DeclaredMembers is auto-implemented, others // are overriden as abstract. This ordering makes more sense when reading from metadata.) // // - Overrides many "NotImplemented" members in TypeInfo with abstracts so failure to implement // shows up as build error. // [DebuggerDisplay("{_debugName}")] internal abstract partial class RuntimeTypeInfo : TypeInfo, ITraceableTypeMember, ICloneable, IRuntimeImplemented { protected RuntimeTypeInfo() { } public abstract override bool IsTypeDefinition { get; } public abstract override bool IsGenericTypeDefinition { get; } protected abstract override bool HasElementTypeImpl(); protected abstract override bool IsArrayImpl(); public abstract override bool IsSZArray { get; } public abstract override bool IsVariableBoundArray { get; } protected abstract override bool IsByRefImpl(); protected abstract override bool IsPointerImpl(); public abstract override bool IsGenericParameter { get; } public abstract override bool IsGenericTypeParameter { get; } public abstract override bool IsGenericMethodParameter { get; } public abstract override bool IsConstructedGenericType { get; } public abstract override bool IsByRefLike { get; } public sealed override bool IsCollectible => false; public abstract override Assembly Assembly { get; } public sealed override string AssemblyQualifiedName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_AssemblyQualifiedName(this); #endif string fullName = FullName; if (fullName == null) // Some Types (such as generic parameters) return null for FullName by design. return null; string assemblyName = InternalFullNameOfAssembly; return fullName + ", " + assemblyName; } } public sealed override Type AsType() { return this; } public sealed override Type BaseType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_BaseType(this); #endif // If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata. RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) { RuntimeTypeHandle baseTypeHandle; if (ReflectionCoreExecution.ExecutionEnvironment.TryGetBaseType(typeHandle, out baseTypeHandle)) return Type.GetTypeFromHandle(baseTypeHandle); } Type baseType = BaseTypeWithoutTheGenericParameterQuirk; if (baseType != null && baseType.IsGenericParameter) { // Desktop quirk: a generic parameter whose constraint is another generic parameter reports its BaseType as System.Object // unless that other generic parameter has a "class" constraint. GenericParameterAttributes genericParameterAttributes = baseType.GenericParameterAttributes; if (0 == (genericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint)) baseType = CommonRuntimeTypes.Object; } return baseType; } } public abstract override bool ContainsGenericParameters { get; } public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; } // // Left unsealed as generic parameter types must override. // public override MethodBase DeclaringMethod { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } // // Equals()/GetHashCode() // // RuntimeTypeInfo objects are interned to preserve the app-compat rule that Type objects (which are the same as TypeInfo objects) // can be compared using reference equality. // // We use weak pointers to intern the objects. This means we can use instance equality to implement Equals() but we cannot use // the instance hashcode to implement GetHashCode() (otherwise, the hash code will not be stable if the TypeInfo is released and recreated.) // Thus, we override and seal Equals() here but defer to a flavor-specific hash code implementation. // public sealed override bool Equals(object obj) { return object.ReferenceEquals(this, obj); } public sealed override bool Equals(Type o) { return object.ReferenceEquals(this, o); } public sealed override int GetHashCode() { return InternalGetHashCode(); } public abstract override string FullName { get; } // // Left unsealed as generic parameter types must override. // public override GenericParameterAttributes GenericParameterAttributes { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } // // Left unsealed as generic parameter types must override this. // public override int GenericParameterPosition { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } public sealed override Type[] GenericTypeArguments { get { return InternalRuntimeGenericTypeArguments.CloneTypeArray(); } } public sealed override MemberInfo[] GetDefaultMembers() { string defaultMemberName = GetDefaultMemberName(); return defaultMemberName != null ? GetMember(defaultMemberName) : Array.Empty<MemberInfo>(); } public sealed override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_InterfaceMap); } // // Implements the correct GUID behavior for all "constructed" types (i.e. returning an all-zero GUID.) Left unsealed // so that RuntimeNamedTypeInfo can override. // public override Guid GUID { get { return Guid.Empty; } } public abstract override bool HasSameMetadataDefinitionAs(MemberInfo other); public sealed override IEnumerable<Type> ImplementedInterfaces { get { LowLevelListWithIList<Type> result = new LowLevelListWithIList<Type>(); bool done = false; // If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata. RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) { IEnumerable<RuntimeTypeHandle> implementedInterfaces = ReflectionCoreExecution.ExecutionEnvironment.TryGetImplementedInterfaces(typeHandle); if (implementedInterfaces != null) { done = true; foreach (RuntimeTypeHandle th in implementedInterfaces) { result.Add(Type.GetTypeFromHandle(th)); } } } if (!done) { TypeContext typeContext = this.TypeContext; Type baseType = this.BaseTypeWithoutTheGenericParameterQuirk; if (baseType != null) result.AddRange(baseType.GetInterfaces()); foreach (QTypeDefRefOrSpec directlyImplementedInterface in this.TypeRefDefOrSpecsForDirectlyImplementedInterfaces) { Type ifc = directlyImplementedInterface.Resolve(typeContext); if (result.Contains(ifc)) continue; result.Add(ifc); foreach (Type indirectIfc in ifc.GetInterfaces()) { if (result.Contains(indirectIfc)) continue; result.Add(indirectIfc); } } } return result.AsNothingButIEnumerable(); } } public sealed override bool IsAssignableFrom(TypeInfo typeInfo) => IsAssignableFrom((Type)typeInfo); public sealed override bool IsAssignableFrom(Type c) { if (c == null) return false; if (object.ReferenceEquals(c, this)) return true; c = c.UnderlyingSystemType; Type typeInfo = c; RuntimeTypeInfo toTypeInfo = this; if (typeInfo == null || !typeInfo.IsRuntimeImplemented()) return false; // Desktop compat: If typeInfo is null, or implemented by a different Reflection implementation, return "false." RuntimeTypeInfo fromTypeInfo = typeInfo.CastToRuntimeTypeInfo(); if (toTypeInfo.Equals(fromTypeInfo)) return true; RuntimeTypeHandle toTypeHandle = toTypeInfo.InternalTypeHandleIfAvailable; RuntimeTypeHandle fromTypeHandle = fromTypeInfo.InternalTypeHandleIfAvailable; bool haveTypeHandles = !(toTypeHandle.IsNull() || fromTypeHandle.IsNull()); if (haveTypeHandles) { // If both types have type handles, let MRT handle this. It's not dependent on metadata. if (ReflectionCoreExecution.ExecutionEnvironment.IsAssignableFrom(toTypeHandle, fromTypeHandle)) return true; // Runtime IsAssignableFrom does not handle casts from generic type definitions: always returns false. For those, we fall through to the // managed implementation. For everyone else, return "false". // // Runtime IsAssignableFrom does not handle pointer -> UIntPtr cast. if (!(fromTypeInfo.IsGenericTypeDefinition || fromTypeInfo.IsPointer)) return false; } // If we got here, the types are open, or reduced away, or otherwise lacking in type handles. Perform the IsAssignability check in managed code. return Assignability.IsAssignableFrom(this, typeInfo); } public sealed override bool IsEnum { get { return 0 != (Classification & TypeClassification.IsEnum); } } public sealed override MemberTypes MemberType { get { if (IsPublic || IsNotPublic) return MemberTypes.TypeInfo; else return MemberTypes.NestedType; } } // // Left unsealed as there are so many subclasses. Need to be overriden by EcmaFormatRuntimeNamedTypeInfo and RuntimeConstructedGenericTypeInfo // public abstract override int MetadataToken { get; } public sealed override Module Module { get { return Assembly.ManifestModule; } } public abstract override string Namespace { get; } public sealed override Type[] GenericTypeParameters { get { return RuntimeGenericTypeParameters.CloneTypeArray(); } } // // Left unsealed as array types must override this. // public override int GetArrayRank() { Debug.Assert(!IsArray); throw new ArgumentException(SR.Argument_HasToBeArrayClass); } public sealed override Type GetElementType() { return InternalRuntimeElementType; } // // Left unsealed as generic parameter types must override. // public override Type[] GetGenericParameterConstraints() { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } // // Left unsealed as IsGenericType types must override this. // public override Type GetGenericTypeDefinition() { Debug.Assert(!IsGenericType); throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); } public sealed override Type MakeArrayType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeArrayType(this); #endif // Do not implement this as a call to MakeArrayType(1) - they are not interchangable. MakeArrayType() returns a // vector type ("SZArray") while MakeArrayType(1) returns a multidim array of rank 1. These are distinct types // in the ECMA model and in CLR Reflection. return this.GetArrayType(); } public sealed override Type MakeArrayType(int rank) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeArrayType(this, rank); #endif if (rank <= 0) throw new IndexOutOfRangeException(); return this.GetMultiDimArrayType(rank); } public sealed override Type MakeByRefType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeByRefType(this); #endif return this.GetByRefType(); } public sealed override Type MakeGenericType(params Type[] typeArguments) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeGenericType(this, typeArguments); #endif if (typeArguments == null) throw new ArgumentNullException(nameof(typeArguments)); if (!IsGenericTypeDefinition) throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); // We intentionally don't validate the number of arguments or their suitability to the generic type's constraints. // In a pay-for-play world, this can cause needless MissingMetadataExceptions. There is no harm in creating // the Type object for an inconsistent generic type - no EEType will ever match it so any attempt to "invoke" it // will throw an exception. bool foundSignatureType = false; RuntimeTypeInfo[] runtimeTypeArguments = new RuntimeTypeInfo[typeArguments.Length]; for (int i = 0; i < typeArguments.Length; i++) { RuntimeTypeInfo runtimeTypeArgument = runtimeTypeArguments[i] = typeArguments[i] as RuntimeTypeInfo; if (runtimeTypeArgument == null) { if (typeArguments[i] == null) throw new ArgumentNullException(); if (typeArguments[i].IsSignatureType) { foundSignatureType = true; } else { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MakeGenericType); // "PlatformNotSupported" because on desktop, passing in a foreign type is allowed and creates a RefEmit.TypeBuilder } } } if (foundSignatureType) return ReflectionAugments.MakeGenericSignatureType(this, typeArguments); for (int i = 0; i < typeArguments.Length; i++) { RuntimeTypeInfo runtimeTypeArgument = runtimeTypeArguments[i]; // Desktop compatibility: Treat generic type definitions as a constructed generic type using the generic parameters as type arguments. if (runtimeTypeArgument.IsGenericTypeDefinition) runtimeTypeArgument = runtimeTypeArguments[i] = runtimeTypeArgument.GetConstructedGenericType(runtimeTypeArgument.RuntimeGenericTypeParameters); if (runtimeTypeArgument.IsByRefLike) throw new TypeLoadException(SR.CannotUseByRefLikeTypeInInstantiation); } return this.GetConstructedGenericType(runtimeTypeArguments); } public sealed override Type MakePointerType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakePointerType(this); #endif return this.GetPointerType(); } public sealed override Type DeclaringType { get { return this.InternalDeclaringType; } } public sealed override string Name { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Name(this); #endif Type rootCauseForFailure = null; string name = InternalGetNameIfAvailable(ref rootCauseForFailure); if (name == null) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(rootCauseForFailure); return name; } } public sealed override Type ReflectedType { get { // Desktop compat: For types, ReflectedType == DeclaringType. Nested types are always looked up as BindingFlags.DeclaredOnly was passed. // For non-nested types, the concept of a ReflectedType doesn't even make sense. return DeclaringType; } } public abstract override StructLayoutAttribute StructLayoutAttribute { get; } public abstract override string ToString(); public sealed override RuntimeTypeHandle TypeHandle { get { RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) return typeHandle; // If a constructed type doesn't have an type handle, it's either because the reducer tossed it (in which case, // we would thrown a MissingMetadataException when attempting to construct the type) or because one of // component types contains open type parameters. Since we eliminated the first case, it must be the second. // Throwing PlatformNotSupported since the desktop does, in fact, create type handles for open types. if (HasElementType || IsConstructedGenericType || IsGenericParameter) throw new PlatformNotSupportedException(SR.PlatformNotSupported_NoTypeHandleForOpenTypes); // If got here, this is a "plain old type" that has metadata but no type handle. We can get here if the only // representation of the type is in the native metadata and there's no EEType at the runtime side. // If you squint hard, this is a missing metadata situation - the metadata is missing on the runtime side - and // the action for the user to take is the same: go mess with RD.XML. throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override Type UnderlyingSystemType { get { return this; } } protected abstract override TypeAttributes GetAttributeFlagsImpl(); protected sealed override TypeCode GetTypeCodeImpl() { return ReflectionAugments.GetRuntimeTypeCode(this); } protected abstract int InternalGetHashCode(); protected sealed override bool IsCOMObjectImpl() { return ReflectionCoreExecution.ExecutionEnvironment.IsCOMObject(this); } protected sealed override bool IsPrimitiveImpl() { return 0 != (Classification & TypeClassification.IsPrimitive); } protected sealed override bool IsValueTypeImpl() { return 0 != (Classification & TypeClassification.IsValueType); } String ITraceableTypeMember.MemberName { get { string name = InternalNameIfAvailable; return name ?? string.Empty; } } Type ITraceableTypeMember.ContainingType { get { return this.InternalDeclaringType; } } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // a base class and interface list based on its constraints. // internal virtual RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { return null; } } internal EnumInfo EnumInfo => Cache.EnumInfo; internal abstract Type InternalDeclaringType { get; } // // Return the full name of the "defining assembly" for the purpose of computing TypeInfo.AssemblyQualifiedName; // internal abstract string InternalFullNameOfAssembly { get; } public abstract override string InternalGetNameIfAvailable(ref Type rootCauseForFailure); // // Left unsealed as HasElement types must override this. // internal virtual RuntimeTypeInfo InternalRuntimeElementType { get { Debug.Assert(!HasElementType); return null; } } // // Left unsealed as constructed generic types must override this. // internal virtual RuntimeTypeInfo[] InternalRuntimeGenericTypeArguments { get { Debug.Assert(!IsConstructedGenericType); return Array.Empty<RuntimeTypeInfo>(); } } internal abstract RuntimeTypeHandle InternalTypeHandleIfAvailable { get; } internal bool IsDelegate { get { return 0 != (Classification & TypeClassification.IsDelegate); } } // // Returns true if it's possible to ask for a list of members and the base type without triggering a MissingMetadataException. // internal abstract bool CanBrowseWithoutMissingMetadataExceptions { get; } // // The non-public version of TypeInfo.GenericTypeParameters (does not array-copy.) // internal virtual RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { Debug.Assert(!(this is RuntimeNamedTypeInfo)); return Array.Empty<RuntimeTypeInfo>(); } } // // Normally returns empty: Overridden by array types to return constructors. // internal virtual IEnumerable<RuntimeConstructorInfo> SyntheticConstructors { get { return Empty<RuntimeConstructorInfo>.Enumerable; } } // // Normally returns empty: Overridden by array types to return the "Get" and "Set" methods. // internal virtual IEnumerable<RuntimeMethodInfo> SyntheticMethods { get { return Empty<RuntimeMethodInfo>.Enumerable; } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // // If you override this method, there is no need to override BaseTypeWithoutTheGenericParameterQuirk. // internal virtual QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { return QTypeDefRefOrSpec.Null; } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal virtual QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { return Array.Empty<QTypeDefRefOrSpec>(); } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal virtual TypeContext TypeContext { get { return new TypeContext(null, null); } } // // Note: This can be (and is) called multiple times. We do not do this work in the constructor as calling ToString() // in the constructor causes some serious recursion issues. // internal void EstablishDebugName() { bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled; #if DEBUG populateDebugNames = true; #endif if (!populateDebugNames) return; if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. String debugName; #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) debugName = this.GetTraceString(); // If tracing on, call this.GetTraceString() which only gives you useful strings when metadata is available but doesn't pollute the ETW trace. else #endif debugName = this.ToString(); if (debugName == null) debugName = ""; _debugName = debugName; } return; } // // This internal method implements BaseType without the following desktop quirk: // // class Foo<X,Y> // where X:Y // where Y:MyReferenceClass // // The desktop reports "X"'s base type as "System.Object" rather than "Y", even though it does // report any interfaces that are in MyReferenceClass's interface list. // // This seriously messes up the implementation of RuntimeTypeInfo.ImplementedInterfaces which assumes // that it can recover the transitive interface closure by combining the directly mentioned interfaces and // the BaseType's own interface closure. // // To implement this with the least amount of code smell, we'll implement the idealized version of BaseType here // and make the special-case adjustment in the public version of BaseType. // // If you override this method, there is no need to overrride TypeRefDefOrSpecForBaseType. // // This method is left unsealed so that RuntimeCLSIDTypeInfo can override. // internal virtual Type BaseTypeWithoutTheGenericParameterQuirk { get { QTypeDefRefOrSpec baseTypeDefRefOrSpec = TypeRefDefOrSpecForBaseType; RuntimeTypeInfo baseType = null; if (!baseTypeDefRefOrSpec.IsValid) { baseType = baseTypeDefRefOrSpec.Resolve(this.TypeContext); } return baseType; } } private string GetDefaultMemberName() { Type defaultMemberAttributeType = typeof(DefaultMemberAttribute); for (Type type = this; type != null; type = type.BaseType) { foreach (CustomAttributeData attribute in type.CustomAttributes) { if (attribute.AttributeType == defaultMemberAttributeType) { // NOTE: Neither indexing nor cast can fail here. Any attempt to use fewer than 1 argument // or a non-string argument would correctly trigger MissingMethodException before // we reach here as that would be an attempt to reference a non-existent DefaultMemberAttribute // constructor. Debug.Assert(attribute.ConstructorArguments.Count == 1 && attribute.ConstructorArguments[0].Value is string); string memberName = (string)(attribute.ConstructorArguments[0].Value); return memberName; } } } return null; } // // Returns a latched set of flags indicating the value of IsValueType, IsEnum, etc. // private TypeClassification Classification { get { if (_lazyClassification == 0) { TypeClassification classification = TypeClassification.Computed; Type baseType = this.BaseType; if (baseType != null) { Type enumType = CommonRuntimeTypes.Enum; Type valueType = CommonRuntimeTypes.ValueType; if (baseType.Equals(enumType)) classification |= TypeClassification.IsEnum | TypeClassification.IsValueType; if (baseType.Equals(CommonRuntimeTypes.MulticastDelegate)) classification |= TypeClassification.IsDelegate; if (baseType.Equals(valueType) && !(this.Equals(enumType))) { classification |= TypeClassification.IsValueType; foreach (Type primitiveType in ReflectionCoreExecution.ExecutionDomain.PrimitiveTypes) { if (this.Equals(primitiveType)) { classification |= TypeClassification.IsPrimitive; break; } } } } _lazyClassification = classification; } return _lazyClassification; } } [Flags] private enum TypeClassification { Computed = 0x00000001, // Always set (to indicate that the lazy evaluation has occurred) IsValueType = 0x00000002, IsEnum = 0x00000004, IsPrimitive = 0x00000008, IsDelegate = 0x00000010, } object ICloneable.Clone() { return this; } private volatile TypeClassification _lazyClassification; private String _debugName; } }
using System; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] public class PostEffectsBase : MonoBehaviour { protected bool supportHDRTextures = true; protected bool supportDX11 = false; protected bool isSupported = true; protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create) { if (!s) { Debug.Log("Missing shader in " + ToString ()); enabled = false; return null; } if (s.isSupported && m2Create && m2Create.shader == s) return m2Create; if (!s.isSupported) { NotSupported (); Debug.Log("The shader " + s.ToString() + " on effect "+ToString()+" is not supported on this platform!"); return null; } else { m2Create = new Material (s); m2Create.hideFlags = HideFlags.DontSave; if (m2Create) return m2Create; else return null; } } protected Material CreateMaterial (Shader s, Material m2Create) { if (!s) { Debug.Log ("Missing shader in " + ToString ()); return null; } if (m2Create && (m2Create.shader == s) && (s.isSupported)) return m2Create; if (!s.isSupported) { return null; } else { m2Create = new Material (s); m2Create.hideFlags = HideFlags.DontSave; if (m2Create) return m2Create; else return null; } } void OnEnable () { isSupported = true; } protected bool CheckSupport () { return CheckSupport (false); } public virtual bool CheckResources () { Debug.LogWarning ("CheckResources () for " + ToString() + " should be overwritten."); return isSupported; } protected void Start () { CheckResources (); } protected bool CheckSupport (bool needDepth) { isSupported = true; supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf); supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; if (!SystemInfo.supportsImageEffects) { NotSupported (); return false; } if (needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth)) { NotSupported (); return false; } if (needDepth) GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth; return true; } protected bool CheckSupport (bool needDepth, bool needHdr) { if (!CheckSupport(needDepth)) return false; if (needHdr && !supportHDRTextures) { NotSupported (); return false; } return true; } public bool Dx11Support () { return supportDX11; } protected void ReportAutoDisable () { Debug.LogWarning ("The image effect " + ToString() + " has been disabled as it's not supported on the current platform."); } // deprecated but needed for old effects to survive upgrading bool CheckShader (Shader s) { Debug.Log("The shader " + s.ToString () + " on effect "+ ToString () + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package."); if (!s.isSupported) { NotSupported (); return false; } else { return false; } } protected void NotSupported () { enabled = false; isSupported = false; return; } protected void DrawBorder (RenderTexture dest, Material material) { float x1; float x2; float y1; float y2; RenderTexture.active = dest; bool invertY = true; // source.texelSize.y < 0.0ff; // Set up the simple Matrix GL.PushMatrix(); GL.LoadOrtho(); for (int i = 0; i < material.passCount; i++) { material.SetPass(i); float y1_; float y2_; if (invertY) { y1_ = 1.0f; y2_ = 0.0f; } else { y1_ = 0.0f; y2_ = 1.0f; } // left x1 = 0.0f; x2 = 0.0f + 1.0f/(dest.width*1.0f); y1 = 0.0f; y2 = 1.0f; GL.Begin(GL.QUADS); GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // right x1 = 1.0f - 1.0f/(dest.width*1.0f); x2 = 1.0f; y1 = 0.0f; y2 = 1.0f; GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // top x1 = 0.0f; x2 = 1.0f; y1 = 0.0f; y2 = 0.0f + 1.0f/(dest.height*1.0f); GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // bottom x1 = 0.0f; x2 = 1.0f; y1 = 1.0f - 1.0f/(dest.height*1.0f); y2 = 1.0f; GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); GL.End(); } GL.PopMatrix(); } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using XenAdmin.Actions; using XenAdmin.Core; using XenAdmin.Model; using XenAdmin.Properties; using XenAPI; namespace XenAdmin.Dialogs.HealthCheck { public partial class HealthCheckSettingsDialog : XenDialogBase { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly Pool pool; private HealthCheckSettings healthCheckSettings; private bool authenticationRequired; private bool authenticated; private string authenticationToken; private string diagnosticToken; private string xsUserName; private string xsPassword; internal override string HelpName { get { return "HealthCheckSettingsDialog"; } } public HealthCheckSettingsDialog(Pool pool, bool enrollNow) :base(pool.Connection) { this.pool = pool; healthCheckSettings = pool.HealthCheckSettings(); if (enrollNow) healthCheckSettings.Status = HealthCheckStatus.Enabled; authenticated = healthCheckSettings.TryGetExistingTokens(pool.Connection, out authenticationToken, out diagnosticToken); authenticationRequired = !authenticated; xsUserName = healthCheckSettings.GetSecretyInfo(pool.Connection, HealthCheckSettings.UPLOAD_CREDENTIAL_USER_SECRET); xsPassword = healthCheckSettings.GetSecretyInfo(pool.Connection, HealthCheckSettings.UPLOAD_CREDENTIAL_PASSWORD_SECRET); InitializeComponent(); PopulateControls(); InitializeControls(); UpdateButtons(); } private void PopulateControls() { var list = BuildDays(); var ds = new BindingSource(list, null); dayOfWeekComboBox.DataSource = ds; dayOfWeekComboBox.ValueMember = "key"; dayOfWeekComboBox.DisplayMember = "value"; var list1 = BuildHours(); var ds1 = new BindingSource(list1, null); timeOfDayComboBox.DataSource = ds1; timeOfDayComboBox.ValueMember = "key"; timeOfDayComboBox.DisplayMember = "value"; } private Dictionary<int, string> BuildDays() { Dictionary<int, string> days = new Dictionary<int, string>(); foreach (var dayOfWeek in Enum.GetValues(typeof(DayOfWeek))) { days.Add((int)dayOfWeek, HelpersGUI.DayOfWeekToString((DayOfWeek)dayOfWeek, true)); } return days; } private SortedDictionary<int, string> BuildHours() { SortedDictionary<int, string> hours = new SortedDictionary<int, string>(); for (int hour = 0; hour <= 23; hour++) { DateTime time = new DateTime(1900, 1, 1, hour, 0, 0); hours.Add(hour, HelpersGUI.DateTimeToString(time, Messages.DATEFORMAT_HM, true)); } return hours; } private void InitializeControls() { Text = String.Format(Messages.HEALTHCHECK_ENROLLMENT_TITLE, pool.Name()); string noAuthTokenMessage = string.Format(Messages.HEALTHCHECK_AUTHENTICATION_RUBRIC_NO_TOKEN, Messages.MY_CITRIX_CREDENTIALS_URL); string existingAuthTokenMessage = Messages.HEALTHCHECK_AUTHENTICATION_RUBRIC_EXISTING_TOKEN; string authenticationRubricLabelText = authenticationRequired ? noAuthTokenMessage : existingAuthTokenMessage; if (authenticationRubricLabelText == noAuthTokenMessage) { authRubricTextLabel.Visible = false; authRubricLinkLabel.Text = noAuthTokenMessage; authRubricLinkLabel.LinkArea = new System.Windows.Forms.LinkArea(authenticationRubricLabelText.IndexOf(Messages.MY_CITRIX_CREDENTIALS_URL), Messages.MY_CITRIX_CREDENTIALS_URL.Length); } else { authRubricLinkLabel.Visible = false; authRubricTextLabel.Text = existingAuthTokenMessage; } enrollmentCheckBox.Checked = healthCheckSettings.Status != HealthCheckStatus.Disabled; frequencyNumericBox.Value = healthCheckSettings.IntervalInWeeks; dayOfWeekComboBox.SelectedValue = (int)healthCheckSettings.DayOfWeek; timeOfDayComboBox.SelectedValue = healthCheckSettings.TimeOfDay; existingAuthenticationRadioButton.Enabled = existingAuthenticationRadioButton.Checked = !authenticationRequired; newAuthenticationRadioButton.Checked = authenticationRequired; SetMyCitrixCredentials(existingAuthenticationRadioButton.Checked); bool useCurrentXsCredentials = string.IsNullOrEmpty(xsUserName) || xsUserName == pool.Connection.Username; newXsCredentialsRadioButton.Checked = !useCurrentXsCredentials; currentXsCredentialsRadioButton.Checked = useCurrentXsCredentials; SetXSCredentials(currentXsCredentialsRadioButton.Checked); } private bool ChangesMade() { if (enrollmentCheckBox.Checked && healthCheckSettings.Status != HealthCheckStatus.Enabled) return true; if (!enrollmentCheckBox.Checked && healthCheckSettings.Status != HealthCheckStatus.Disabled) return true; if (frequencyNumericBox.Value != healthCheckSettings.IntervalInWeeks) return true; if (dayOfWeekComboBox.SelectedIndex != (int)healthCheckSettings.DayOfWeek) return true; if (timeOfDayComboBox.SelectedIndex != healthCheckSettings.TimeOfDay) return true; if (authenticationToken != healthCheckSettings.GetSecretyInfo(pool.Connection, HealthCheckSettings.UPLOAD_TOKEN_SECRET)) return true; if (textboxXSUserName.Text != xsUserName) return true; if (textboxXSPassword.Text != xsPassword) return true; return false; } private void UpdateButtons() { okButton.Enabled = m_ctrlError.PerformCheck(CheckCredentialsEntered) && !errorLabel.Visible; } private void okButton_Click(object sender, EventArgs e) { okButton.Enabled = false; if (enrollmentCheckBox.Checked && newAuthenticationRadioButton.Checked && !m_ctrlError.PerformCheck(CheckUploadAuthentication)) { okButton.Enabled = true; return; } if (ChangesMade()) { var newHealthCheckSettings = new HealthCheckSettings(pool.health_check_config); newHealthCheckSettings.Status = enrollmentCheckBox.Checked ? HealthCheckStatus.Enabled : HealthCheckStatus.Disabled; newHealthCheckSettings.IntervalInDays = (int)(frequencyNumericBox.Value * 7); newHealthCheckSettings.DayOfWeek = (DayOfWeek)dayOfWeekComboBox.SelectedValue; newHealthCheckSettings.TimeOfDay = (int)timeOfDayComboBox.SelectedValue; newHealthCheckSettings. RetryInterval = HealthCheckSettings.DEFAULT_RETRY_INTERVAL; new SaveHealthCheckSettingsAction(pool, newHealthCheckSettings, authenticationToken, diagnosticToken, textboxXSUserName.Text.Trim(), textboxXSPassword.Text, false).RunAsync(); new TransferHealthCheckSettingsAction(pool, newHealthCheckSettings, textboxXSUserName.Text.Trim(), textboxXSPassword.Text, true).RunAsync(); } okButton.Enabled = true; DialogResult = DialogResult.OK; Close(); } private void cancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void enrollmentCheckBox_CheckedChanged(object sender, EventArgs e) { if (!enrollmentCheckBox.Checked) HideTestCredentialsStatus(); UpdateButtons(); } private void newAuthenticationRadioButton_CheckedChanged(object sender, EventArgs e) { SetMyCitrixCredentials(existingAuthenticationRadioButton.Checked); } private void radioButton2_CheckedChanged(object sender, EventArgs e) { SetXSCredentials(currentXsCredentialsRadioButton.Checked); testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked && !string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) && !string.IsNullOrEmpty(textboxXSPassword.Text); UpdateButtons(); } private void SetXSCredentials(bool useCurrent) { if (useCurrent) { textboxXSUserName.Text = pool.Connection.Username; textboxXSPassword.Text = pool.Connection.Password; textboxXSUserName.Enabled = false; textboxXSPassword.Enabled = false; } else { textboxXSUserName.Text = xsUserName; textboxXSPassword.Text = xsPassword; textboxXSUserName.Enabled = true; textboxXSPassword.Enabled = true; } } private void SetMyCitrixCredentials(bool useExisting) { if (useExisting) { //textBoxMyCitrixUsername.Text = String.Empty; //textBoxMyCitrixPassword.Text = String.Empty; textBoxMyCitrixUsername.Enabled = false; textBoxMyCitrixPassword.Enabled = false; } else { //textBoxMyCitrixUsername.Text = String.Empty; //textBoxMyCitrixPassword.Text = String.Empty; textBoxMyCitrixUsername.Enabled = true; textBoxMyCitrixPassword.Enabled = true; } } private bool CheckCredentialsEntered() { if (!enrollmentCheckBox.Checked) return true; if (newAuthenticationRadioButton.Checked && (string.IsNullOrEmpty(textBoxMyCitrixUsername.Text.Trim()) || string.IsNullOrEmpty(textBoxMyCitrixPassword.Text))) return false; if (newXsCredentialsRadioButton.Checked && (string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) || string.IsNullOrEmpty(textboxXSPassword.Text))) return false; return true; } private bool CheckCredentialsEntered(out string error) { error = string.Empty; return CheckCredentialsEntered(); } private bool CheckUploadAuthentication(out string error) { error = string.Empty; if (!CheckCredentialsEntered()) return false; var action = new HealthCheckAuthenticationAction(textBoxMyCitrixUsername.Text.Trim(), textBoxMyCitrixPassword.Text.Trim(), Registry.HealthCheckIdentityTokenDomainName, Registry.HealthCheckUploadGrantTokenDomainName, Registry.HealthCheckUploadTokenDomainName, Registry.HealthCheckDiagnosticDomainName, Registry.HealthCheckProductKey, 0, false); try { action.RunExternal(null); } catch { error = action.Exception != null ? action.Exception.Message : Messages.ERROR_UNKNOWN; authenticationToken = null; authenticated = false; return authenticated; } authenticationToken = action.UploadToken; // curent upload token diagnosticToken = action.DiagnosticToken; // curent diagnostic token authenticated = !String.IsNullOrEmpty(authenticationToken) && !String.IsNullOrEmpty(diagnosticToken); return authenticated; } private void credentials_TextChanged(object sender, EventArgs e) { UpdateButtons(); } private void xsCredentials_TextChanged(object sender, EventArgs e) { testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked && !string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) && !string.IsNullOrEmpty(textboxXSPassword.Text); HideTestCredentialsStatus(); } private void PolicyStatementLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { new HealthCheckPolicyStatementDialog().ShowDialog(this); } private void testCredentialsButton_Click(object sender, EventArgs e) { okButton.Enabled = false; CheckXenServerCredentials(); } private void CheckXenServerCredentials() { if (string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) || string.IsNullOrEmpty(textboxXSPassword.Text)) return; bool passedRbacChecks = false; DelegatedAsyncAction action = new DelegatedAsyncAction(connection, Messages.CREDENTIALS_CHECKING, "", "", delegate { Session elevatedSession = null; try { elevatedSession = connection.ElevatedSession(textboxXSUserName.Text.Trim(), textboxXSPassword.Text); if (elevatedSession != null && (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession, Role.ValidRoleList("pool.set_health_check_config", connection)))) passedRbacChecks = true; } catch (Failure f) { if (f.ErrorDescription.Count > 0 && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { // we use a different error message here from the standard one in friendly names throw new Exception(Messages.HEALTH_CHECK_USER_HAS_NO_PERMISSION_TO_CONNECT); } throw; } finally { if (elevatedSession != null) { elevatedSession.Connection.Logout(elevatedSession); elevatedSession = null; } } }, true); action.Completed += delegate { log.DebugFormat("Logging with the new credentials returned: {0} ", passedRbacChecks); Program.Invoke(Program.MainWindow, () => { if (passedRbacChecks) { ShowTestCredentialsStatus(Resources._000_Tick_h32bit_16, null); okButton.Enabled = true; } else { okButton.Enabled = false; ShowTestCredentialsStatus(Resources._000_error_h32bit_16, action.Exception != null ? action.Exception.Message : Messages.HEALTH_CHECK_USER_NOT_AUTHORIZED); } textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked; }); }; log.Debug("Testing logging in with the new credentials"); ShowTestCredentialsStatus(Resources.ajax_loader, null); textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = false; action.RunAsync(); } private void ShowTestCredentialsStatus(Image image, string errorMessage) { testCredentialsStatusImage.Visible = true; testCredentialsStatusImage.Image = image; errorLabel.Text = errorMessage; errorLabel.Visible = !string.IsNullOrEmpty(errorMessage); } private void HideTestCredentialsStatus() { testCredentialsStatusImage.Visible = false; errorLabel.Visible = false; } private bool SessionAuthorized(Session s, List<Role> authorizedRoles) { UserDetails ud = s.CurrentUserDetails; foreach (Role r in s.Roles) { if (authorizedRoles.Contains(r)) { log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserName ?? ud.UserSid); return true; } } log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserName ?? ud.UserSid); return false; } private void existingAuthenticationRadioButton_CheckedChanged(object sender, EventArgs e) { UpdateButtons(); } private void authRubricLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Program.OpenURL(Messages.MY_CITRIX_CREDENTIALS_URL); } } }
// ------------------------------------------------------------------------------------------- // <copyright file="VirtualProductsCrawler.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // ------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // 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 Sitecore.Ecommerce.Search { using System.Collections.Generic; using System.Linq; using Catalogs; using Configuration; using Data; using Diagnostics; using DomainModel.Catalogs; using Globalization; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Search; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Search; using Sites; using Utils; /// <summary> /// Virtual products database crawler /// </summary> public class VirtualProductsCrawler : DatabaseCrawler { /// <summary> /// Product catalog template ID /// </summary> private static readonly string productCatalogTemplateId = "{BD5B78E1-107E-4572-90DD-3F11F8A7534E}"; /// <summary> /// Indexes the virtual products. /// </summary> /// <param name="catalogItem">The catalog item.</param> /// <param name="productItems">The product items.</param> /// <param name="context">The context.</param> protected virtual void AddVirtualProducts(Item catalogItem, IEnumerable<Item> productItems, IndexUpdateContext context) { foreach (Item itm in productItems) { foreach (Language language in itm.Languages) { Item latestVersion = itm.Database.GetItem(itm.ID, language, Version.Latest); if (latestVersion != null) { foreach (Item version in latestVersion.Versions.GetVersions(false)) { this.AddVirtualProduct(catalogItem, version, latestVersion, context); } } } } } /// <summary> /// Adds the virtual product. /// </summary> /// <param name="catalogItem">The catalog item.</param> /// <param name="version">The version.</param> /// <param name="latestVersion">The latest version.</param> /// <param name="context">The context.</param> protected virtual void AddVirtualProduct(Item catalogItem, Item version, Item latestVersion, IndexUpdateContext context) { this.IndexVersion(version, latestVersion, context, catalogItem); } /// <summary> /// Adds the item to the index. /// </summary> /// <param name="item">The Sitecore item to index.</param> /// <param name="latestVersion">The latest version.</param> /// <param name="context">The context.</param> protected override void IndexVersion(Item item, Item latestVersion, IndexUpdateContext context) { this.IndexVersion(item, latestVersion, context, null); if (this.IsCatalogItem(item)) { string siteName = SiteUtils.GetSiteByItem(item); if (!string.IsNullOrEmpty(siteName)) { using (new SiteContextSwitcher(Factory.GetSite(siteName))) { using (new SiteIndependentDatabaseSwitcher(item.Database)) { this.AddVirtualProducts(item, this.GetVirtualProductsForIndexing(item), context); } } } } } /// <summary> /// Indexes the version. /// </summary> /// <param name="item">The item to proceed.</param> /// <param name="latestVersion">The latest version.</param> /// <param name="context">The context.</param> /// <param name="catalogItem">The catalog item.</param> protected virtual void IndexVersion(Item item, Item latestVersion, IndexUpdateContext context, Item catalogItem) { Assert.ArgumentNotNull(item, "item"); Assert.ArgumentNotNull(latestVersion, "latestVersion"); Assert.ArgumentNotNull(context, "context"); Document document = new Document(); this.AddVersionIdentifiers(item, latestVersion, document); this.AddAllFields(document, item, true); this.AddSpecialFields(document, item); this.AdjustBoost(document, item); if (catalogItem != null) { this.AddVirtualProductIdentifiers(document, item, catalogItem); } context.AddDocument(document); } /// <summary> /// Deletes the specific version information from the index. /// </summary> /// <param name="id">The item id.</param> /// <param name="language">The language.</param> /// <param name="version">The version.</param> /// <param name="context">The context.</param> protected override void DeleteVersion(ID id, string language, string version, IndexDeleteContext context) { base.DeleteVersion(id, language, version, context); ItemUri versionUri = new ItemUri(id, Language.Parse(language), Version.Parse(version), Factory.GetDatabase(this.Database)); Item versionItem = Sitecore.Data.Database.GetItem(versionUri); if (versionItem != null && this.IsCatalogItem(versionItem)) { context.DeleteDocuments(context.Search(new PreparedQuery(this.GetVirtualProductsQuery(versionItem)), int.MaxValue).Ids); } } /// <summary> /// Gets the virtual products query. /// </summary> /// <param name="catalogItem">The catalog item.</param> /// <returns>Returns virtual products query.</returns> protected virtual Lucene.Net.Search.Query GetVirtualProductsQuery(Item catalogItem) { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(BuiltinFields.CatalogItemUri, catalogItem.Uri.ToString())), Occur.MUST); this.AddMatchCriteria(query); return query; } /// <summary> /// Adds the virtual product identifiers. /// </summary> /// <param name="document">The document.</param> /// <param name="productItem">The product item.</param> /// <param name="catalogItem">The catalog item.</param> protected virtual void AddVirtualProductIdentifiers(Document document, Item productItem, Item catalogItem) { document.Add(CreateDataField(BuiltinFields.CatalogItemUri, catalogItem.Uri.ToString())); ////replacing product path to catalog item child path Field pathField = document.GetField(Sitecore.Search.BuiltinFields.Path); string productId = _shortenGuid.Replace(productItem.ID.ToString(), string.Empty).ToLowerInvariant(); string path = string.Format("{0} {1}", this.GetItemPath(catalogItem), productId); pathField.SetValue(path); } /// <summary> /// Gets the virtual products. /// </summary> /// <param name="catalogItem">The catalog item.</param> /// <returns>Returns list of virtual products</returns> protected virtual IEnumerable<Item> GetVirtualProductsForIndexing(Item catalogItem) { string selectedMethod = catalogItem["Product Selection Method"]; if (string.IsNullOrEmpty(selectedMethod) || !ID.IsID(selectedMethod)) { return new List<Item>(); } Item selectionMethodItem = catalogItem.Database.GetItem(selectedMethod); if (selectionMethodItem != null) { string selectionMethodName = selectionMethodItem["Code"]; var catalogProductResolveStrategy = Context.Entity.Resolve<ICatalogProductResolveStrategy>(selectionMethodName); var catalogProductResolveStrategyBase = catalogProductResolveStrategy as CatalogProductResolveStrategyBase; if (catalogProductResolveStrategyBase != null) { return catalogProductResolveStrategyBase.GetCatalogProductItems(catalogItem); } } else { Log.Warn(string.Format("Product Selection Method was noe found in item {0}", catalogItem.ID), this); } return new List<Item>(); } /// <summary> /// Determines whether [is catalog item] [the specified item]. /// </summary> /// <param name="item">The item to proceed.</param> /// <returns> /// <c>true</c> if [is catalog item] [the specified item]; otherwise, <c>false</c>. /// </returns> protected virtual bool IsCatalogItem(Item item) { if (item.TemplateID.ToString() == productCatalogTemplateId) { return true; } return item.Template.BaseTemplates.Any(tp => tp.ID.ToString() == productCatalogTemplateId); } } }
// Copyright 2013 Howling Moon Software. All rights reserved. // See http://chipmunk2d.net/legal.php for more information. using UnityEngine; using System.Collections; using System; using System.Runtime.InteropServices; public class PlatformerCollisionManager : ChipmunkCollisionManager { protected void Start(){ // Turning down the timestep can smooth things out significantly. // Chipmunk is also pretty fast so you don't need to worry about the performance so much. // Not really necessary, but helps in several subtle ways. Time.fixedDeltaTime = 1f/180f; Chipmunk.gravity = new Vector2(0f, -100f); } protected bool ChipmunkPreSolve_player_oneway(ChipmunkArbiter arbiter) { // If we're pressing the down arrow key. if (Input.GetAxis("Vertical") < -0.5f) { // Fall through the floor arbiter.Ignore(); return false; } if(arbiter.GetNormal(0).y > -0.7f){ arbiter.Ignore(); return false; } return true; } protected bool ChipmunkBegin_player_bumpable(ChipmunkArbiter arbiter){ if(arbiter.GetNormal(0).y > 0.9f){ ChipmunkShape player, bonusBlock; arbiter.GetShapes(out player, out bonusBlock); bonusBlock.SendMessage("Bump"); } return true; } protected bool ChipmunkBegin_player_pit(ChipmunkArbiter arbiter){ ChipmunkShape player, pit; arbiter.GetShapes(out player, out pit); player.SendMessage("OnFellInPit"); return true; } protected bool ChipmunkBegin_player_jumpshroom(ChipmunkArbiter arbiter){ ChipmunkShape player, shroom; arbiter.GetShapes(out player, out shroom); if(arbiter.GetNormal(0).y < -0.9f){ ChipmunkBody body = player.GetComponent<ChipmunkBody>(); body.velocity = new Vector2(body.velocity.x, 50f); return false; } else { return true; } } // ----------- float FLUID_DENSITY = 1f; float FLUID_DRAG = 3f; protected float Cross(Vector2 v1, Vector2 v2){ return v1.x*v2.y - v1.y*v2.x; } protected float AreaForPoly(int count, Vector2[] verts){ float area = 0.0f; for(int i=0; i<count; i++){ area += Cross(verts[i], verts[(i+1)%count]); } return -area/2.0f; } protected Vector2 CentroidForPoly(int count, Vector2[] verts){ float sum = 0f; Vector2 vsum = Vector2.zero; for(int i=0; i<count; i++){ Vector2 v1 = verts[i]; Vector2 v2 = verts[(i+1)%count]; float cross = Cross(v1, v2); sum += cross; vsum = vsum + (v1 + v2)*cross; } return vsum/(3f*sum); } protected float KScalarBody(ChipmunkBody body, Vector2 r, Vector2 n){ float rcn = Cross(r, n); return 1f/body.mass + rcn*rcn/body.moment; } protected Vector2 NormalizeSafe(Vector2 v){ return v/(v.magnitude + float.MinValue); } protected float MomentForPoly(float m, int numVerts, Vector2[] verts, Vector2 offset){ float sum1 = 0.0f; float sum2 = 0.0f; for(int i=0; i<numVerts; i++){ Vector2 v1 = verts[i] +offset; Vector2 v2 = verts[(i+1)%numVerts] + offset; float a = Cross(v2, v1); float b = Vector2.Dot(v1, v1) + Vector2.Dot(v1, v2) + Vector2.Dot(v2, v2); sum1 += a*b; sum2 += a; } return (m*sum1)/(6.0f*sum2); } protected void ApplyImpulse(ChipmunkBody body, Vector2 j, Vector2 r){ body.velocity += j/body.mass; body.angularVelocity += Cross(r, j)/body.moment; } protected bool ChipmunkPreSolve_water_crate(ChipmunkArbiter arbiter){ ChipmunkShape water, poly; arbiter.GetShapes(out water, out poly); ChipmunkBody body = poly.body; // Sanity check if(water._handle == IntPtr.Zero || poly._handle == IntPtr.Zero){ Debug.LogError("Invalid shape references. This is likely be a Chipmunk2D bug."); return false; } // Get the top of the water sensor bounding box to use as the water level. // Chipmunk bounding boxes aren't exposed by ChipmunkShape yet. // They are rarely useful, though this makes a pretty good case for it. float level = ChipmunkBinding._cpShapeGetBB(water._handle).t; // Clip the polygon against the water level int count = ChipmunkBinding.cpPolyShapeGetNumVerts(poly._handle); int clippedCount = 0; Vector2[] clipped = new Vector2[count + 1]; for(int i=0, j=count-1; i<count; j=i, i++){ Vector2 a = ChipmunkBinding._cpBodyLocal2World(body._handle, ChipmunkBinding.cpPolyShapeGetVert(poly._handle, j)); Vector2 b = ChipmunkBinding._cpBodyLocal2World(body._handle, ChipmunkBinding.cpPolyShapeGetVert(poly._handle, i)); if(a.y < level){ clipped[clippedCount] = a; clippedCount++; } float a_level = a.y - level; float b_level = b.y - level; if(a_level*b_level < 0.0f){ float t = Mathf.Abs(a_level)/(Mathf.Abs(a_level) + Mathf.Abs(b_level)); clipped[clippedCount] = Vector2.Lerp(a, b, t); clippedCount++; } } // Calculate buoyancy from the clipped polygon area float clippedArea = AreaForPoly(clippedCount, clipped); float displacedMass = clippedArea*FLUID_DENSITY; Vector2 centroid = CentroidForPoly(clippedCount, clipped); Vector2 r = centroid - body.position; for(int i=0, j=clippedCount-1; i<clippedCount; j=i, i++){ Vector2 a = clipped[i]; Vector2 b = clipped[j]; Debug.DrawLine(a, b, Color.green); } // ChipmunkDebugDrawPolygon(clippedCount, clipped, RGBAColor(0, 0, 1, 1), RGBAColor(0, 0, 1, 0.1f)); // ChipmunkDebugDrawPoints(5, 1, &centroid, RGBAColor(0, 0, 1, 1)); float dt = Time.fixedDeltaTime; Vector2 g = Chipmunk.gravity; // Apply the buoyancy force as an impulse. ApplyImpulse(body, g*(-displacedMass*dt), r); // Apply linear damping for the fluid drag. Vector2 v_centroid = body.velocity + (new Vector2(-r.y, r.x))*body.angularVelocity; float k = KScalarBody(body, r, NormalizeSafe(v_centroid)); float damping = clippedArea*FLUID_DRAG*FLUID_DENSITY; float v_coef = Mathf.Exp(-damping*dt*k); // linear drag // float v_coef = 1.0/(1.0 + damping*dt*cpvlength(v_centroid)*k); // quadratic drag ApplyImpulse(body, (v_centroid*v_coef - v_centroid)/k, r); // Apply angular damping for the fluid drag. float w_damping = MomentForPoly(FLUID_DRAG*FLUID_DENSITY*clippedArea, clippedCount, clipped, -body.position); body.angularVelocity *= Mathf.Exp(-w_damping*dt/body.moment); return false; } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. [SerializeField] private float allowedRange = 10f; private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView (); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown ("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine (m_JumpBob.DoBobCycle ()); PlayLandingSound (); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.Encodings.Web; using System.Text.Unicode; using Xunit; namespace Microsoft.Framework.WebEncoders { public unsafe class UnicodeHelpersTests { private const int UnicodeReplacementChar = '\uFFFD'; private static readonly UTF8Encoding _utf8EncodingThrowOnInvalidBytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); // To future refactorers: // The following GetScalarValueFromUtf16_* tests must not be done as a [Theory]. If done via [InlineData], the invalid // code points will get sanitized with replacement characters before they even reach the test, as the strings are parsed // from the attributes in reflection. And if done via [MemberData], the XmlWriter used by xunit will throw exceptions // when it attempts to write out the test arguments, due to the invalid text. [Fact] public void GetScalarValueFromUtf16_NormalBMPChar_EndOfString() { GetScalarValueFromUtf16("a", 'a'); } [Fact] public void GetScalarValueFromUtf16_NormalBMPChar_NotEndOfString() { GetScalarValueFromUtf16("ab", 'a'); } [Fact] public void GetScalarValueFromUtf16_TrailingSurrogate_EndOfString() { GetScalarValueFromUtf16("\uDFFF", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_TrailingSurrogate_NotEndOfString() { GetScalarValueFromUtf16("\uDFFFx", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_LeadingSurrogate_EndOfString() { GetScalarValueFromUtf16("\uD800", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_LeadingSurrogate_NotEndOfString() { GetScalarValueFromUtf16("\uD800x", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_LeadingSurrogate_NotEndOfString_FollowedByLeadingSurrogate() { GetScalarValueFromUtf16("\uD800\uD800", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_LeadingSurrogate_NotEndOfString_FollowedByTrailingSurrogate() { GetScalarValueFromUtf16("\uD800\uDFFF", 0x103FF); } private void GetScalarValueFromUtf16(string input, int expectedResult) { fixed (char* pInput = input) { Assert.Equal(expectedResult, UnicodeHelpers.GetScalarValueFromUtf16(pInput, endOfString: (input.Length == 1))); } } [Fact] public void GetUtf8RepresentationForScalarValue() { for (int i = 0; i <= 0x10FFFF; i++) { if (i <= 0xFFFF && Char.IsSurrogate((char)i)) { continue; // no surrogates } // Arrange byte[] expectedUtf8Bytes = _utf8EncodingThrowOnInvalidBytes.GetBytes(Char.ConvertFromUtf32(i)); // Act List<byte> actualUtf8Bytes = new List<byte>(4); uint asUtf8 = unchecked((uint)UnicodeHelpers.GetUtf8RepresentationForScalarValue((uint)i)); do { actualUtf8Bytes.Add(unchecked((byte)asUtf8)); } while ((asUtf8 >>= 8) != 0); // Assert Assert.Equal(expectedUtf8Bytes, actualUtf8Bytes); } } [Fact] public void IsCharacterDefined() { Assert.All(ReadListOfDefinedCharacters().Select((defined, idx) => new { defined, idx }), c => Assert.Equal(c.defined, UnicodeHelpers.IsCharacterDefined((char)c.idx))); } private static bool[] ReadListOfDefinedCharacters() { HashSet<string> allowedCategories = new HashSet<string>(); // Letters allowedCategories.Add("Lu"); allowedCategories.Add("Ll"); allowedCategories.Add("Lt"); allowedCategories.Add("Lm"); allowedCategories.Add("Lo"); // Marks allowedCategories.Add("Mn"); allowedCategories.Add("Mc"); allowedCategories.Add("Me"); // Numbers allowedCategories.Add("Nd"); allowedCategories.Add("Nl"); allowedCategories.Add("No"); // Punctuation allowedCategories.Add("Pc"); allowedCategories.Add("Pd"); allowedCategories.Add("Ps"); allowedCategories.Add("Pe"); allowedCategories.Add("Pi"); allowedCategories.Add("Pf"); allowedCategories.Add("Po"); // Symbols allowedCategories.Add("Sm"); allowedCategories.Add("Sc"); allowedCategories.Add("Sk"); allowedCategories.Add("So"); // Separators // With the exception of U+0020 SPACE, these aren't allowed // Other // We only allow one category of 'other' characters allowedCategories.Add("Cf"); HashSet<string> seenCategories = new HashSet<string>(); bool[] retVal = new bool[0x10000]; string[] allLines = new StreamReader(typeof(UnicodeHelpersTests).GetTypeInfo().Assembly.GetManifestResourceStream("UnicodeData.8.0.txt")).ReadAllLines(); uint startSpanCodepoint = 0; foreach (string line in allLines) { string[] splitLine = line.Split(';'); uint codePoint = UInt32.Parse(splitLine[0], NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if (codePoint >= retVal.Length) { continue; // don't care about supplementary chars } if (codePoint == (uint)' ') { retVal[codePoint] = true; // we allow U+0020 SPACE as our only valid Zs (whitespace) char } else { string category = splitLine[2]; if (allowedCategories.Contains(category)) { retVal[codePoint] = true; // chars in this category are allowable seenCategories.Add(category); if (splitLine[1].EndsWith("First>")) { startSpanCodepoint = codePoint; } else if (splitLine[1].EndsWith("Last>")) { for (uint spanCounter = startSpanCodepoint; spanCounter < codePoint; spanCounter++) { retVal[spanCounter] = true; // chars in this category are allowable } } } } } // Finally, we need to make sure we've seen every category which contains // allowed characters. This provides extra defense against having a typo // in the list of categories. Assert.Equal(allowedCategories.OrderBy(c => c), seenCategories.OrderBy(c => c)); return retVal; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Coda { /// <summary> /// Used to quantify if a frame is on beat, early, or late. /// </summary> public enum Timing { early = -1, onBeat = 0, late = 1, } /// <summary> /// Maestro singleton class. Tracks the beatmap and directs subscribed MusicBehaviour listeners. /// </summary> [RequireComponent(typeof(AudioSource))] public class Maestro : MonoBehaviour { public static Maestro current = null; public TextAsset beatmapFile; private BeatMap beatmap; private AudioSource _audio; public bool loopAudio; public delegate void OnBeatDelegate(); public OnBeatDelegate onBeat; public OnBeatDelegate lateOnBeat; List<MusicBehaviour> listeners; private bool _audioClipExists; private bool _beatMapExists; private double _beatTimer; private Beat _prevBeat; private Beat _nextBeat; private int _beatIndex; private bool _songEnded; private bool _beatFrame; private float _averageTimeBetweenBeats = -1f; private float _minTimeBetweenBeats = -1f; private float _maxTimeBetweenBeats = -1f; /// <summary> /// Returns the average time between beats. /// </summary> public float averageTimeBetweenBeats { get { if (_averageTimeBetweenBeats == -1f) { if (beatmap.beats.Count > 1) { _averageTimeBetweenBeats = (float)((beatmap.beats[beatmap.beats.Count - 1].timeStamp - beatmap.beats[0].timeStamp) / (beatmap.beats.Count - 1)); } } return _averageTimeBetweenBeats; } } /// <summary> /// Returns the minimum time between beats. /// </summary> public float minTimeBetweenBeats { get { if (_minTimeBetweenBeats == -1f) { if (beatmap.beats.Count > 1) { float minTime = Mathf.Infinity; for (int i = 1; i < beatmap.beats.Count; i++) { if ((float)(beatmap.beats[i].timeStamp - beatmap.beats[i-1].timeStamp) < minTime) { minTime = (float)(beatmap.beats[i].timeStamp - beatmap.beats[i-1].timeStamp); } } _minTimeBetweenBeats = minTime; } } return _minTimeBetweenBeats; } } /// <summary> /// Returns the minimum time between beats. /// </summary> public float maxTimeBetweenBeats { get { if (_maxTimeBetweenBeats == -1f) { if (beatmap.beats.Count > 1) { float maxTime = 0f; for (int i = 1; i < beatmap.beats.Count; i++) { if ((float)(beatmap.beats[i].timeStamp - beatmap.beats[i-1].timeStamp) > maxTime) { maxTime = (float)(beatmap.beats[i].timeStamp - beatmap.beats[i-1].timeStamp); } } _maxTimeBetweenBeats = maxTime; } } return _maxTimeBetweenBeats; } } /// <summary> /// Returns the time until the next beat as a float. /// </summary> public float timeUntilNextBeat { get { if (_nextBeat == default(Beat)) { return -1f; } else { return (float)(_nextBeat.timeStamp - _beatTimer); } } } /// <summary> /// Returns the time until the next beat as a double-precision float. /// </summary> public double timeUntilNextBeat_Double { get { if (_nextBeat == default(Beat)) { return -1; } else { return _nextBeat.timeStamp - _beatTimer; } } } /// <summary> /// Returns the time until the previous beat as a float. /// </summary> public float timeSincePreviousBeat { get { if (_prevBeat == default(Beat)) { return (float)_beatTimer; } else { return (float)(_prevBeat.timeStamp - _beatTimer); } } } /// <summary> /// Returns the time until the previous beat as a double-precision float. /// </summary> public double timeSincePreviousBeat_Double { get { if (_prevBeat == default(Beat)) { return _beatTimer; } else { return _prevBeat.timeStamp - _beatTimer; } } } /// <summary> /// Returns the time to the closest beat as a float. /// </summary> public float timeToClosestBeat { get { return Mathf.Min(timeSincePreviousBeat, timeUntilNextBeat); } } /// <summary> /// Returns the time to the closest beat as a double-precision float. /// </summary> public double timeToClosestBeat_Double { get { return System.Math.Min(timeSincePreviousBeat_Double, timeUntilNextBeat_Double); } } /// <summary> /// Gets the previous beat. /// </summary> public Beat previousBeat { get { return _prevBeat; } } /// <summary> /// Gets the next beat. /// </summary> public Beat nextBeat { get { return _nextBeat; } } /// <summary> /// Gets the beat which is closest to the current frame. /// </summary> public Beat closestBeat { get { if (Mathf.Abs((float)(_nextBeat.timeStamp - _beatTimer)) < Mathf.Abs((float)(_prevBeat.timeStamp - _beatTimer))) { return _nextBeat; } else { return _prevBeat; } } } /// <summary> /// Gets the index of the next beat. /// </summary> public int nextBeatIndex { get { return _beatIndex; } } /// <summary> /// Gets the index of the previous beat. /// </summary> public int prevBeatIndex { get { return _beatIndex - 1; } } /// <summary> /// Gets the index of the beat which is closest to the current frame. /// </summary> public int closestBeatIndex { get { if (Mathf.Abs((float)(_nextBeat.timeStamp - _beatTimer)) < Mathf.Abs((float)(_prevBeat.timeStamp - _beatTimer))) { return nextBeatIndex; } else { return prevBeatIndex; } } } /// <summary> /// Makes a coroutine wait until the next beat. /// </summary> public WaitForSeconds WaitForNextBeat () { return new WaitForSeconds(timeUntilNextBeat); } /// <summary> /// Checks if the current frame is on a beat. /// </summary> public bool IsOnBeat () { return _beatFrame; } /// <summary> /// Checks if the current frame is on a beat. /// </summary> /// <param name="timing">Will return the timing of the current beat (Timing.early, Timing.onBeat, or Timing.late).</param> public bool IsOnBeat (out Timing timing) { if (_beatFrame) { timing = Timing.onBeat; return true; } float prevDist = Mathf.Abs((float)(_beatTimer - _prevBeat.timeStamp)); float nextDist = Mathf.Abs((float)(_beatTimer - _nextBeat.timeStamp)); if (nextDist < prevDist) { timing = Timing.early; } else { timing = Timing.late; } return false; } /// <summary> /// Checks if the current frame is within a given number of seconds from the closest beat. /// </summary> /// <param name="precision">How many seconds from the beat count as "on beat".</param> public bool IsOnBeat (float precision) { if (_beatFrame) { return true; } float prevDist = Mathf.Abs((float)(_beatTimer - _prevBeat.timeStamp)); float nextDist = Mathf.Abs((float)(_beatTimer - _nextBeat.timeStamp)); if (Mathf.Min(nextDist, prevDist) <= precision) { return true; } return false; } /// <summary> /// Checks if the current frame is within a given number of seconds from the closest beat. /// </summary> /// <param name="precision">How many seconds from the beat count as "on beat".</param> /// <param name="timeDifference">Returns the number of seconds to the closest beat.</param> public bool IsOnBeat (float precision, out float timeDifference) { if (_beatFrame) { timeDifference = 0f; return true; } float prevDist = Mathf.Abs((float)(_beatTimer - _prevBeat.timeStamp)); float nextDist = Mathf.Abs((float)(_beatTimer - _nextBeat.timeStamp)); timeDifference = Mathf.Min(prevDist, nextDist); return (timeDifference <= precision); } /// <summary> /// Checks if the current frame is within a given number of seconds from the closest beat. /// </summary> /// <param name="precision">How many seconds from the beat count as "on beat".</param> /// <param name="timing">Will return the timing of the current beat (Timing.early, Timing.onBeat, or Timing.late).</param> public bool IsOnBeat (float precision, out Timing timing) { if (_beatFrame) { timing = Timing.onBeat; return true; } float prevDist = Mathf.Abs((float)(_beatTimer - _prevBeat.timeStamp)); float nextDist = Mathf.Abs((float)(_beatTimer - _nextBeat.timeStamp)); if (nextDist < prevDist) { timing = Timing.early; } else { timing = Timing.late; } if (Mathf.Min(nextDist, prevDist) <= precision) { return true; } return false; } /// <summary> /// Checks if the current frame is within a given number of seconds from the closest beat. /// </summary> /// <param name="precision">How many seconds from the beat count as "on beat".</param> /// <param name="timeDifference">Returns the number of seconds to the closest beat.</param> /// <param name="timing">Will return the timing of the current beat (Timing.early, Timing.onBeat, or Timing.late).</param> public bool IsOnBeat (float precision, out float timeDifference, out Timing timing) { if (_beatFrame) { timeDifference = 0f; timing = Timing.onBeat; return true; } float prevDist = Mathf.Abs((float)(_beatTimer - _prevBeat.timeStamp)); float nextDist = Mathf.Abs((float)(_beatTimer - _nextBeat.timeStamp)); if (nextDist < prevDist) { timing = Timing.early; } else { timing = Timing.late; } timeDifference = Mathf.Min(prevDist, nextDist); return (timeDifference <= precision); } void Awake() { if (current == null) { current = this; } _beatMapExists = true; _audioClipExists = true; _audio = GetComponent<AudioSource>(); if (_audio.clip == null) { _audioClipExists = false; Debug.LogError("Maestro: No Audio Clip!"); } else { if ("BeatMap_" + _audio.clip.name.Replace(".mp3", "") != beatmapFile.name) { Debug.LogWarning("Maestro: Audio Clip and Beatmap File name mismatch!"); } } _beatIndex = 0; onBeat = OnBeat; lateOnBeat = LateOnBeat; listeners = new List<MusicBehaviour>(); beatmap = BeatMapSerializer.BeatMapReader.ReadBeatMap(beatmapFile); } void Start () { if (_audioClipExists) { _audio.Play(); } if (!StartTracking()) { _beatMapExists = false; Debug.LogError("Maestro: Beatmap has zero beats!"); } } void Update () { if (_beatMapExists) { if (TrackBeats()) { onBeat(); } } } void LateUpdate () { if (_beatFrame) { lateOnBeat(); } } /// <summary> /// Starts tracking the audio and beatmap. /// </summary> /// <returns><c>true</c>, if tracking was started successfully, <c>false</c> otherwise.</returns> bool StartTracking () { if (beatmap == null || beatmap.beats.Count == 0) { return false; } _songEnded = false; _nextBeat = beatmap.beats[0]; _beatTimer = 0.0; return true; } /// <summary> /// Tracks the beats. /// </summary> /// <returns><c>true</c>, if there was a beat this frame, <c>false</c> otherwise.</returns> bool TrackBeats () { if (!(_songEnded && !loopAudio)) { _beatTimer += Time.deltaTime; } else { _beatFrame = false; return false; } if (_songEnded) { if (_beatTimer >= (double)beatmap.songLength) { if (_audioClipExists) { _audio.Stop(); } StartTracking(); if (_audioClipExists) { _audio.Play(); } } } else if (_nextBeat.timeStamp <= _beatTimer) { _beatIndex++; if (_beatIndex == beatmap.beats.Count) { _songEnded = true; if (loopAudio) { _nextBeat = beatmap.beats[0]; } } else { _prevBeat = _nextBeat; _nextBeat = beatmap.beats[_beatIndex % beatmap.beats.Count]; } _beatFrame = true; return true; } _beatFrame = false; return false; } /// <summary> /// Activates during every beat on the beatmap. /// </summary> void OnBeat () { //Debug.Log("Beat."); } void LateOnBeat () { //Debug.Log("Late Update Beat."); } /// <summary> /// Subscribe the specified listener to the Maestro. /// </summary> /// <param name="listener">Listener (should be a subclass of MusicBehaviour).</param> public void Subscribe (MusicBehaviour listener) { if (!listeners.Contains(listener)) { listeners.Add(listener); onBeat += listener.OnBeat; lateOnBeat += listener.LateOnBeat; } } /// <summary> /// Unsubscribe the specified listener to the Maestro. /// </summary> /// <param name="listener">Listener (should be a subclass of MusicBehaviour).</param> public void Unsubscribe (MusicBehaviour listener) { if (listeners.Contains(listener)) { listeners.Remove(listener); onBeat -= listener.OnBeat; lateOnBeat -= listener.LateOnBeat; } } } }
using System; using NDatabase.Api; using NDatabase.Tool.Wrappers; using NUnit.Framework; namespace Test.NDatabase.Odb.Test.Index { [TestFixture] public class TestCreateObjectAfterInsert : ODBTest { /// <summary> /// Test the creation of an index after having created objects. /// </summary> /// <remarks> /// Test the creation of an index after having created objects. In this case /// ODB should creates the index and update it with already existing objects /// </remarks> /// <exception cref="System.Exception">System.Exception</exception> [Test] public virtual void Test1000Objects() { var OdbFileName = "index2.test1.odb"; IOdb odb = null; var size = 1000; var start = OdbTime.GetCurrentTimeInMs(); try { DeleteBase(OdbFileName); odb = Open(OdbFileName); for (var i = 0; i < size; i++) { var io = new IndexedObject("name" + i, i, new DateTime()); odb.Store(io); } odb.Close(); Println("\n\n END OF INSERT \n\n"); odb = Open(OdbFileName); var names = new[] {"name"}; odb.IndexManagerFor<IndexedObject>().AddUniqueIndexOn("index1", names); Println("\n\n after create index\n\n"); var query = odb.Query<IndexedObject>(); query.Descend("name").Constrain((object) "name0").Equal(); var objects = query.Execute<IndexedObject>(true); Println("\n\nafter get Objects\n\n"); AssertEquals(1, objects.Count); var query2 = odb.Query<IndexedObject>(); query2.Descend("duration").Constrain((object) 9).Equal(); objects = query2.Execute<IndexedObject>(true); AssertEquals(1, objects.Count); objects = odb.Query<IndexedObject>().Execute<IndexedObject>(true); AssertEquals(size, objects.Count); } finally { var end = OdbTime.GetCurrentTimeInMs(); Println((end - start) + "ms"); odb.Close(); } } /// <summary> /// Test the creation of an index after having created objects. /// </summary> /// <remarks> /// Test the creation of an index after having created objects. In this case /// ODB should creates the index and update it with already existing objects /// </remarks> /// <exception cref="System.Exception">System.Exception</exception> [Test] public virtual void Test100ObjectsIntiNdex() { var OdbFileName = "index2.test2.odb"; IOdb odb = null; var size = 100; var start = OdbTime.GetCurrentTimeInMs(); try { DeleteBase(OdbFileName); odb = Open(OdbFileName); for (var i = 0; i < size; i++) { var io = new IndexedObject("name" + i, i, new DateTime()); odb.Store(io); } odb.Close(); Println("\n\n END OF INSERT \n\n"); odb = Open(OdbFileName); var names = new[] {"duration"}; odb.IndexManagerFor<IndexedObject>().AddUniqueIndexOn("index1", names); Println("\n\n after create index\n\n"); var query = odb.Query<IndexedObject>(); query.Descend("name").Constrain((object) "name0").Equal(); var objects = query.Execute<IndexedObject>(true); Println("\n\nafter get Objects\n\n"); AssertEquals(1, objects.Count); var query2 = odb.Query<IndexedObject>(); query2.Descend("duration").Constrain((object) 10).Equal(); objects = query2.Execute<IndexedObject>(true); AssertEquals(1, objects.Count); objects = odb.Query<IndexedObject>().Execute<IndexedObject>(true); AssertEquals(size, objects.Count); } finally { var end = OdbTime.GetCurrentTimeInMs(); Println((end - start) + "ms"); } } /// <summary> /// Test the creation of an index after having created objects. /// </summary> /// <remarks> /// Test the creation of an index after having created objects. In this case /// ODB should creates the index and update it with already existing objects /// </remarks> /// <exception cref="System.Exception">System.Exception</exception> [Test] public virtual void Test1Object() { const string odbFileName = "index2.test3.odb"; DeleteBase(odbFileName); using (var odb = Open(odbFileName)) { var io = new IndexedObject("name", 5, new DateTime()); odb.Store(io); } using (var odb = Open(odbFileName)) { var names = new[] {"name"}; odb.IndexManagerFor<IndexedObject>().AddUniqueIndexOn("index1", names); var query = odb.Query<IndexedObject>(); query.Descend("name").Constrain((object) "name").Equal(); var objects = query.Execute<IndexedObject>(true); AssertEquals(1, objects.Count); } } /// <summary> /// Test the creation of an index after having created objects. /// </summary> /// <remarks> /// Test the creation of an index after having created objects. In this case /// ODB should creates the index and update it with already existing objects /// </remarks> /// <exception cref="System.Exception">System.Exception</exception> [Test] public virtual void Test2000Objects() { var OdbFileName = "index2.test4.odb"; var start = OdbTime.GetCurrentTimeInMs(); IOdb odb = null; var size = 2000; try { DeleteBase(OdbFileName); odb = Open(OdbFileName); for (var i = 0; i < size; i++) { var io = new IndexedObject("name" + i, i, new DateTime()); odb.Store(io); } odb.Close(); odb = Open(OdbFileName); var names = new[] {"name"}; odb.IndexManagerFor<IndexedObject>().AddUniqueIndexOn("index1", names); var query = odb.Query<IndexedObject>(); query.Descend("name").Constrain((object) "name0").Equal(); var objects = query.Execute<IndexedObject>(true); AssertEquals(1, objects.Count); objects = odb.Query<IndexedObject>().Execute<IndexedObject>(true); AssertEquals(size, objects.Count); } finally { if (odb != null) odb.Close(); var end = OdbTime.GetCurrentTimeInMs(); Println((end - start) + "ms"); } } } }
using System; using System.ComponentModel; using System.Collections; using System.Diagnostics; using System.Windows.Forms; using System.Text; using System.Runtime.InteropServices; using System.Reflection; using System.Drawing.Imaging; using System.Drawing; using System.IO; using System.Threading; using System.Xml; using System.Xml.Serialization; namespace MbUnit.Forms { using MbUnit.Core; using MbUnit.Core.Collections; using MbUnit.Framework; using MbUnit.Core.Invokers; using MbUnit.Core.Config; using MbUnit.Core.Reports; using MbUnit.Core.Reports.Serialization; using MbUnit.Core.Remoting; using MbUnit.Core.Monitoring; public delegate void DefaultDelegate(); /// <summary> /// Summary description for ReflectorTreeView. /// </summary> public class ReflectorTreeView : System.Windows.Forms.UserControl, IMessageFilter, IUnitTreeNodeFactory { private ReflectionImageList reflectionImageList = null; private TreeTestDomainCollection testDomains = null; private TestTreeNodeFacade treeNodeFacade=null; private UnitTreeViewState state=null; private TimeMonitor testTimer = new TimeMonitor(); private string infoMessage = ""; private UnitTreeNodeCreatorDelegate createNode; private AddChildNodeDelegate addChildNode; private System.Windows.Forms.TreeView typeTree; private System.Windows.Forms.ImageList treeImageList; private System.Windows.Forms.ToolTip treeToolTip; private System.Windows.Forms.ContextMenu treeContextMenu; private System.Windows.Forms.MenuItem addAssemblyItem; private System.Windows.Forms.MenuItem removeAssembliesItem; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem loadConfigItem; private System.Windows.Forms.MenuItem saveConfigItem; private System.ComponentModel.IContainer components; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.MenuItem menuItemGenerateXml; private System.Windows.Forms.MenuItem menuItemGenerateHtml; private System.Windows.Forms.MenuItem runNCoverMenuItem; private System.Windows.Forms.MenuItem createNAntTaskMenuItem; private System.Windows.Forms.MenuItem createMSBuildTaskMenuItem; private System.Windows.Forms.MenuItem menuItem3; private System.Windows.Forms.MenuItem menuItem4; private System.Windows.Forms.MenuItem nocoverToClipboard; private System.Windows.Forms.MenuItem stopTestsMenuItem; private System.Windows.Forms.MenuItem menuItem6; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem reloadAssembliesMenuItem; private System.Windows.Forms.MenuItem textReportMenuItem; private System.Windows.Forms.MenuItem doxReportMenuItem; private Thread workerThread = null; public ReflectorTreeView() { this.testDomains=new TreeTestDomainCollection(this); // This call is required by the Windows.Forms Form Designer. InitializeComponent(); Application.AddMessageFilter(this); DragAcceptFiles(this.Handle, true); this.state = new UnitTreeViewState(this.typeTree, new UnitTreeViewState.UpdateTreeNodeDelegate(this.UpdateNode) ); this.treeNodeFacade= new TestTreeNodeFacade(); this.reflectionImageList = new ReflectionImageList(this.treeImageList); this.createNode = new UnitTreeNodeCreatorDelegate(this.CreateNode); this.addChildNode = new AddChildNodeDelegate(this.AddChildNode); this.testDomains.Watcher.AssemblyChangedEvent+=new MbUnit.Core.Remoting.AssemblyWatcher.AssemblyChangedHandler(Watcher_AssemblyChangedEvent); this.SetStyle(ControlStyles.DoubleBuffer,true); this.SetStyle(ControlStyles.ResizeRedraw,true); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } if (this.workerThread!=null) { this.workerThread.Abort(); } } if (this.testDomains != null) { this.testDomains.Watcher.AssemblyChangedEvent -= new MbUnit.Core.Remoting.AssemblyWatcher.AssemblyChangedHandler(Watcher_AssemblyChangedEvent); this.testDomains.Dispose(); this.testDomains = null; } base.Dispose( disposing ); } #region Properties public TreeTestDomainCollection TestDomains { get { return this.testDomains; } } public TestTreeNodeFacade Facade { get { return this.treeNodeFacade; } } public TreeView TypeTree { get { return this.typeTree; } } public TreeNodeCollection Nodes { get { return this.typeTree.Nodes; } } #endregion public event TreeViewEventHandler AfterSelect; #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.typeTree = new System.Windows.Forms.TreeView(); this.treeContextMenu = new System.Windows.Forms.ContextMenu(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.stopTestsMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem6 = new System.Windows.Forms.MenuItem(); this.addAssemblyItem = new System.Windows.Forms.MenuItem(); this.removeAssembliesItem = new System.Windows.Forms.MenuItem(); this.reloadAssembliesMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem4 = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.loadConfigItem = new System.Windows.Forms.MenuItem(); this.saveConfigItem = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.menuItemGenerateXml = new System.Windows.Forms.MenuItem(); this.menuItemGenerateHtml = new System.Windows.Forms.MenuItem(); this.textReportMenuItem = new System.Windows.Forms.MenuItem(); this.doxReportMenuItem = new System.Windows.Forms.MenuItem(); this.runNCoverMenuItem = new System.Windows.Forms.MenuItem(); this.nocoverToClipboard = new System.Windows.Forms.MenuItem(); this.createNAntTaskMenuItem = new System.Windows.Forms.MenuItem(); this.createMSBuildTaskMenuItem = new System.Windows.Forms.MenuItem(); this.treeImageList = new System.Windows.Forms.ImageList(this.components); this.treeToolTip = new System.Windows.Forms.ToolTip(this.components); this.SuspendLayout(); // // typeTree // this.typeTree.ContextMenu = this.treeContextMenu; this.typeTree.Dock = System.Windows.Forms.DockStyle.Fill; this.typeTree.HideSelection = false; this.typeTree.ImageIndex = 0; this.typeTree.ImageList = this.treeImageList; this.typeTree.Location = new System.Drawing.Point(0, 0); this.typeTree.Name = "typeTree"; this.typeTree.SelectedImageIndex = 0; this.typeTree.Size = new System.Drawing.Size(488, 344); this.typeTree.Sorted = true; this.typeTree.TabIndex = 0; this.typeTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.typeTree_AfterSelect); // // treeContextMenu // this.treeContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem5, this.menuItem6, this.menuItem4, this.menuItem3, this.menuItem2, this.runNCoverMenuItem, this.createNAntTaskMenuItem, this.createMSBuildTaskMenuItem}); // // menuItem5 // this.menuItem5.Index = 0; this.menuItem5.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1, this.stopTestsMenuItem}); this.menuItem5.Text = "Tests"; // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.Text = "Start Tests"; this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click); // // stopTestsMenuItem // this.stopTestsMenuItem.Index = 1; this.stopTestsMenuItem.Text = "Stop Tests"; this.stopTestsMenuItem.Click += new System.EventHandler(this.stopTestsMenuItem_Click); // // menuItem6 // this.menuItem6.Index = 1; this.menuItem6.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.addAssemblyItem, this.removeAssembliesItem, this.reloadAssembliesMenuItem}); this.menuItem6.Text = "Assemblies"; // // addAssemblyItem // this.addAssemblyItem.Index = 0; this.addAssemblyItem.Text = "Add Assemblies..."; this.addAssemblyItem.Click += new System.EventHandler(this.addAssemblyItem_Click); // // removeAssembliesItem // this.removeAssembliesItem.Index = 1; this.removeAssembliesItem.Text = "Remove Assemblies"; this.removeAssembliesItem.Click += new System.EventHandler(this.removeAssembliesItem_Click); // // reloadAssembliesMenuItem // this.reloadAssembliesMenuItem.Index = 2; this.reloadAssembliesMenuItem.Text = "ReLoad Assemblies"; this.reloadAssembliesMenuItem.Click += new System.EventHandler(this.reloadAssembliesMenuItem_Click); // // menuItem4 // this.menuItem4.Index = 2; this.menuItem4.Text = "Clear Results"; this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click); // // menuItem3 // this.menuItem3.Index = 3; this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.loadConfigItem, this.saveConfigItem}); this.menuItem3.Text = "Config"; // // loadConfigItem // this.loadConfigItem.Index = 0; this.loadConfigItem.Text = "Load Config..."; this.loadConfigItem.Click += new System.EventHandler(this.loadConfigItem_Click); // // saveConfigItem // this.saveConfigItem.Index = 1; this.saveConfigItem.Text = "Save Config..."; this.saveConfigItem.Click += new System.EventHandler(this.saveConfigItem_Click); // // menuItem2 // this.menuItem2.Index = 4; this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItemGenerateXml, this.menuItemGenerateHtml, this.textReportMenuItem, this.doxReportMenuItem}); this.menuItem2.Text = "Report"; // // menuItemGenerateXml // this.menuItemGenerateXml.Index = 0; this.menuItemGenerateXml.Text = "XML"; this.menuItemGenerateXml.Click += new System.EventHandler(this.menuItemGenerateXml_Click); // // menuItemGenerateHtml // this.menuItemGenerateHtml.Index = 1; this.menuItemGenerateHtml.Text = "HTML"; this.menuItemGenerateHtml.Click += new System.EventHandler(this.menuItemGenerateHtml_Click); // // textReportMenuItem // this.textReportMenuItem.Index = 2; this.textReportMenuItem.Text = "&Text"; this.textReportMenuItem.Click += new System.EventHandler(this.textReportMenuItem_Click); // // doxReportMenuItem // this.doxReportMenuItem.Index = 3; this.doxReportMenuItem.Text = "&Dox"; this.doxReportMenuItem.Click += new System.EventHandler(this.doxReportMenuItem_Click); // // runNCoverMenuItem // this.runNCoverMenuItem.Index = 5; this.runNCoverMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.nocoverToClipboard}); this.runNCoverMenuItem.Text = "NCover"; // // nocoverToClipboard // this.nocoverToClipboard.Index = 0; this.nocoverToClipboard.Text = "Run"; this.nocoverToClipboard.Click += new System.EventHandler(this.nocoverToClipboard_Click); // // createNAntTaskMenuItem // this.createNAntTaskMenuItem.Index = 6; this.createNAntTaskMenuItem.Text = "Create NAnt task (Clipboard)"; this.createNAntTaskMenuItem.Click += new System.EventHandler(this.createNAntTaskMenuItem_Click); // // createMSBuildTaskMenuItem // this.createMSBuildTaskMenuItem.Index = 7; this.createMSBuildTaskMenuItem.Text = "Create MSBuild task (Clipboard)"; this.createMSBuildTaskMenuItem.Click += new System.EventHandler(this.createMSBuildTaskMenuItem_Click); // // treeImageList // this.treeImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; this.treeImageList.ImageSize = new System.Drawing.Size(16, 16); this.treeImageList.TransparentColor = System.Drawing.Color.Transparent; // // ReflectorTreeView // this.Controls.Add(this.typeTree); this.Name = "ReflectorTreeView"; this.Size = new System.Drawing.Size(488, 344); this.ResumeLayout(false); } #endregion #region Drag & Drop support [DllImport("shell32.dll")] private static extern int DragQueryFile(IntPtr hdrop, int ifile, StringBuilder fname, int fnsize); [DllImport("shell32.dll")] private static extern int DragAcceptFiles(IntPtr hwnd, bool accept); [DllImport("shell32.dll")] private static extern void DragFinish(IntPtr hdrop); private const int WM_DROPFILES = 563; public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_DROPFILES) { int nFiles = DragQueryFile(m.WParam,-1,null,0); for(int i=0;i<nFiles;++i) { StringBuilder sb = new StringBuilder(256); DragQueryFile(m.WParam, i, sb, 256); HandleDroppedFile(sb.ToString()); } DragFinish(m.WParam); ThreadedPopulateTree(true); return true; } return false; } private void HandleDroppedFile(string file) { if (file!=null && file.Length>0) AddAssembly(file); } #endregion #region Assembly handling public void AddAssembliesByDialog() { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Assemblies or Executables (*.dll,*.exe)|*.dll;*.exe|All files (*.*)|*.*||"; dlg.FilterIndex = 0; dlg.Multiselect = true; if (dlg.ShowDialog() != DialogResult.OK) return; foreach(string file in dlg.FileNames) AddAssembly(file); this.ThreadedPopulateTree(true); } public void RemoveAssemblies() { this.AbortWorkerThread(); this.TestDomains.Clear(); this.ThreadedPopulateTree(false); } public void AddAssembly(string file) { if (this.TestDomains.ContainsTestAssembly(file)) { MessageBox.Show(String.Format("The file {0} is already loaded.",file),"File already loaded error"); } else { this.TestDomains.Add(file); this.TestDomains.Watcher.Start(); } } public void Watcher_AssemblyChangedEvent(string fullPath) { this.infoMessage = String.Format("{0} modified, reloading",fullPath); this.ReloadAssemblies(); } public void ReloadAssemblies() { this.AbortWorkerThread(); this.ClearReports(); this.ThreadedPopulateTree(true); } public void NewConfig() { this.AbortWorkerThread(); this.RemoveAssemblies(); this.ClearTree(); } public void ClearReports() { MbUnit.GUI.MbUnitForm parent = (MbUnit.GUI.MbUnitForm) this.ParentForm; parent.ClearReports(); } #endregion #region Tree population public UnitTreeNode CreateUnitTreeNode(string name, TestNodeType nodeType, Guid domainIdentifier, Guid testIdentifier) { return (UnitTreeNode)this.Invoke(this.createNode, new Object[]{name,nodeType,domainIdentifier,testIdentifier} ); } public void AddChildUnitTreeNode(TreeNode node, TreeNode childNode) { this.Invoke(this.addChildNode,new Object[]{node,childNode}); } public void AddChildNode(TreeNode node, TreeNode childNode) { node.Nodes.Add(childNode); } public UnitTreeNode CreateNode(string name, TestNodeType nodeType, Guid domainIdentifier, Guid testIdentifier) { return new UnitTreeNode(name, nodeType, domainIdentifier, testIdentifier); } public void UpdateNode(TreeNodeState old, UnitTreeNode node) { if (old.IsVisible) node.EnsureVisible(); if (old.IsExpanded) node.Expand(); if (old.IsSelected) this.typeTree.SelectedNode = node; } public void ClearTree() { this.typeTree.Nodes.Clear(); this.treeNodeFacade.Clear(); this.MessageOnStatusBar("Tree Cleared"); OnTreeCleared(); } public void PopulateTree() { try { this.OnBeginLoadTests(); this.Invoke(new DefaultDelegate(this.ClearTree)); this.MessageOnStatusBar("Reloading assemblies"); this.TestDomains.Reload(); this.MessageOnStatusBar("Build facade"); this.TestDomains.PopulateFacade(this.treeNodeFacade); this.MessageOnStatusBar("Populate tree"); this.typeTree.Invoke(new MethodInvoker(this.typeTree.BeginUpdate)); this.TestDomains.PopulateChildTree(this.typeTree,this.Facade); this.typeTree.Invoke(new MethodInvoker(this.typeTree.EndUpdate)); this.MessageOnStatusBar("Tree populated"); this.state.Load(); this.MessageOnStatusBar("Previous state loaded"); OnTreePopulated(); this.MessageOnStatusBar(""); } catch (System.Runtime.Remoting.RemotingException remote) { MessageBox.Show("Could not load test domain. Please ensure you have referenced the installed version of MbUnit.Framework within your test assembly. \r\n\r\n The error message was: \r\n" + remote.Message, "Error loading test assembly", MessageBoxButtons.OK, MessageBoxIcon.Error); NewConfig(); } catch(Exception ex) { if (ex is System.Threading.ThreadAbortException) return; MessageBox.Show(ex.ToString()); } } public void ThreadedPopulateTree(bool saveTreeState) { if (saveTreeState) SaveTreeState(); this.AbortWorkerThread(); this.workerThread =new Thread(new ThreadStart(this.PopulateTree)); this.workerThread.Start(); } private void SaveTreeState() { if (InvokeRequired) Invoke(new MethodInvoker(SaveTreeState)); else state.Save(); } public event EventHandler TreeCleared; protected void OnTreeCleared() { if (this.TreeCleared!=null) TreeCleared(this, new EventArgs()); } public event EventHandler BeginLoadTests; protected void OnBeginLoadTests() { if (this.BeginLoadTests != null) BeginLoadTests(this, new EventArgs()); } public event EventHandler TreePopulated; protected void OnTreePopulated() { if (this.TreePopulated!=null) TreePopulated(this, new EventArgs()); } public void ExpandAllFailures() { this.typeTree.BeginUpdate(); foreach(UnitTreeNode node in this.typeTree.Nodes) ExpandState(node,TestState.Failure); this.typeTree.EndUpdate(); } public void ExpandAllIgnored() { this.typeTree.BeginUpdate(); foreach(UnitTreeNode node in this.typeTree.Nodes) ExpandState(node,TestState.Ignored); this.typeTree.EndUpdate(); } public void ExpandCurrentFailures() { this.ExpandState((UnitTreeNode)this.TypeTree.SelectedNode,TestState.Failure); } public void ExpandCurrentIgnored() { this.ExpandState((UnitTreeNode)this.TypeTree.SelectedNode,TestState.Failure); } public void ExpandState(UnitTreeNode node, TestState state) { if (node==null) return; if (node.TestState==state) node.EnsureVisible(); foreach(UnitTreeNode child in node.Nodes) ExpandState(child,state); } #endregion #region Status bar handling protected virtual void MessageOnStatusBar(string message, params Object[] args) { this.infoMessage=String.Format(message,args); } #endregion #region Test Running public string InfoMessage { get { return this.infoMessage; } } public bool WorkerThreadAlive { get { return this.workerThread!=null && this.workerThread.IsAlive; } } public double TestDuration { get { return this.testTimer.Now; } } public void RunTests() { try { // clearing nodes this.MessageOnStatusBar("Clearing results"); this.Invoke(new MethodInvoker(this.ClearSelectedResults)); OnStartTests(); this.MessageOnStatusBar("Starting tests"); UnitTreeNode selectedNode = (UnitTreeNode) this.Invoke(new UnitTreeNodeMethodInvoker(this.GetSelectTreeNode)); if (selectedNode==null) this.TestDomains.RunPipes(); else this.TestDomains.RunPipes(selectedNode); this.MessageOnStatusBar("Finished tests"); } catch(Exception ex) { if (ex is System.Threading.ThreadAbortException) return; MessageBox.Show(ex.ToString()); this.MessageOnStatusBar("Test execution failed: " + ex.Message); } finally { OnFinishTests(); } } public void ThreadedRunTests() { this.AbortWorkerThread(); this.workerThread =new Thread(new ThreadStart(this.RunTests)); this.workerThread.IsBackground=true; this.workerThread.Priority=ThreadPriority.Lowest; this.MessageOnStatusBar("Launching worker thread"); this.workerThread.Start(); } public void AbortWorkerThread() { if (this.workerThread!=null) { try { this.MessageOnStatusBar("Aborting worker thread"); this.testDomains.Stop(); this.workerThread.Join(1000); this.workerThread.Abort(); this.workerThread.Join(2000); this.workerThread = null; this.MessageOnStatusBar("Worker thread aborted"); } catch (Exception ex) { if (ex is System.Threading.ThreadAbortException) return; } } } private void typeTree_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { if (this.AfterSelect!=null) AfterSelect(this,e); } public delegate UnitTreeNode UnitTreeNodeMethodInvoker(); protected UnitTreeNode GetSelectTreeNode() { return this.typeTree.SelectedNode as UnitTreeNode; } public void ClearSelectedResults() { if (this.typeTree.SelectedNode != null) { this.clearNodeResults((UnitTreeNode)this.typeTree.SelectedNode); this.MessageOnStatusBar("Results cleared"); } else this.ClearAllResults(); } public void ClearAllResults() { foreach(UnitTreeNode node in this.Nodes) this.ClearResults(node); this.MessageOnStatusBar("Results cleared"); } public void ClearResults(UnitTreeNode node) { if (node==null) return; this.clearNodeResults(node); } private void clearNodeResults(UnitTreeNode node) { if (node==null) return; node.TestState = TestState.NotRun; foreach(UnitTreeNode child in node.Nodes) this.clearNodeResults(child); } public event EventHandler StartTests; protected void OnStartTests() { this.testTimer.Start(); if (this.StartTests!=null) StartTests(this,new EventArgs()); } public event EventHandler FinishTests; protected void OnFinishTests() { this.testTimer.Stop(); if (this.FinishTests!=null) FinishTests(this,new EventArgs()); } #endregion #region Context menu private void addAssemblyItem_Click(object sender, System.EventArgs e) { this.AddAssembliesByDialog(); } private void removeAssembliesItem_Click(object sender, System.EventArgs e) { this.RemoveAssemblies(); } private void menuItem1_Click(object sender, System.EventArgs e) { this.ThreadedRunTests(); } private void stopTestsMenuItem_Click(object sender, System.EventArgs e) { this.AbortWorkerThread(); } private void loadConfigItem_Click(object sender, System.EventArgs e) { this.LoadProjectByDialog(); } private void saveConfigItem_Click(object sender, System.EventArgs e) { this.SaveProjectByDialog(); } private void menuItemGenerateXml_Click(object sender, System.EventArgs e) { this.GenerateXmlReport(); } private void menuItemGenerateHtml_Click(object sender, System.EventArgs e) { this.GenerateHtmlReport(); } private void textReportMenuItem_Click(object sender, System.EventArgs e) { this.GenerateTextReport(); } private void doxReportMenuItem_Click(object sender, System.EventArgs e) { this.GenerateDoxReport(); } private void createNAntTaskMenuItem_Click(object sender, System.EventArgs e) { this.CreateNAntTask(); } private void createMSBuildTaskMenuItem_Click(object sender, System.EventArgs e) { this.CreateMSBuildTask(); } private void reloadAssembliesMenuItem_Click(object sender, System.EventArgs e) { this.ReloadAssemblies(); } private void menuItem4_Click(object sender, System.EventArgs e) { this.ClearAllResults(); } private void nocoverToClipboard_Click(object sender, System.EventArgs e) { this.CreateNCoverTask(); } #endregion #region Projects public void LoadProjectByDialog() { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Load MbUnit Project file"; dlg.Multiselect = false; dlg.Filter = "MbUnit project files (*.mbunit)|*.mbunit|Xml files (*.xml)|*.xml|All files (*.*)|*.*"; if (dlg.ShowDialog() != DialogResult.OK) return; LoadProject(dlg.FileName, false); // populate tree this.ThreadedPopulateTree(false); } public void LoadProject(string fileName, bool silent) { if (!File.Exists(fileName)) { if (!silent) { MessageBox.Show("Could not find file"); } return; } try { this.MessageOnStatusBar("Loading {0}",fileName); MbUnitProject project = MbUnitProject.Load(fileName); // removing assemblies this.RemoveAssemblies(); // adding assemblies foreach(string testFilePath in project.Assemblies) { this.AddAssembly(testFilePath); } // setting state this.state.Load(project.TreeState); } catch(Exception ex) { if (ex is System.Threading.ThreadAbortException) return; MessageBox.Show(ex.ToString()); } } public void SaveProjectByDialog() { SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = "Save Configuration file"; dlg.Filter = "MbUnit project files (*.mbunit)|*.mbunit|Xml files (*.xml)|*.xml|All files (*.*)|*.*"; dlg.DefaultExt="mbunit"; if (dlg.ShowDialog() != DialogResult.OK) return; SaveProject(dlg.FileName); } public void SaveProject(string fileName) { MbUnitProject project = new MbUnitProject(); foreach(TestDomain domain in this.TestDomains) project.Assemblies.Add(domain.TestFilePath); this.state.Save(); project.TreeState = this.state.GetTreeViewState(); project.Save(fileName); } #endregion #region Reports public void GenerateXmlReport() { // create report string outputPath = XmlReport.RenderToXml(this.TestDomains.GetReport()); try { System.Diagnostics.Process.Start(outputPath); } catch (Win32Exception) { MessageBox.Show("An error has occurred while trying to load the default xml viewer. Please ensure the viewer is setup correctly.", "Viewer loading error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void GenerateHtmlReport() { string outputPath = HtmlReport.RenderToHtml(this.TestDomains.GetReport()); try { System.Diagnostics.Process.Start(outputPath); } catch (Win32Exception) { MessageBox.Show("An error has occurred while trying to load the default browswer. Please ensure the browser is setup correctly.", "Browser loading error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void GenerateTextReport() { string outputPath = TextReport.RenderToText(this.TestDomains.GetReport()); System.Diagnostics.Process.Start(outputPath); } public void GenerateDoxReport() { string outputPath = DoxReport.RenderToDox(this.TestDomains.GetReport()); System.Diagnostics.Process.Start(outputPath); } #endregion #region NAnt, NCover, etc... public void CreateNAntTask() { XmlDocument doc = new XmlDocument(); // create project XmlElement project = doc.CreateElement("project"); project.SetAttribute("default", "tests"); doc.AppendChild(project); XmlElement target = doc.CreateElement("target"); target.SetAttribute("name", "tests"); project.AppendChild(target); // root element XmlElement mbunit = doc.CreateElement("mbunit"); target.AppendChild(mbunit); // add fileset XmlElement fileset = doc.CreateElement("assemblies"); mbunit.SetAttribute("report-types", "html"); mbunit.AppendChild(fileset); // add include for each assembly foreach(string testFilePath in this.TestDomains.TestFilePaths) { XmlElement includes = doc.CreateElement("includes"); includes.SetAttribute("asis","true"); includes.SetAttribute("name",testFilePath); fileset.AppendChild(includes); } // render to clipboard StringWriter writer = new StringWriter(); XmlTextWriter xWriter = new XmlTextWriter(writer); xWriter.Formatting = Formatting.Indented; doc.Save(xWriter); Clipboard.SetDataObject(writer.ToString(),true); } public void CreateMSBuildTask() { XmlDocument doc = new XmlDocument(); // create project XmlElement project = doc.CreateElement("Project"); project.SetAttribute("xmlns", "http://schemas.microsoft.com/developer/msbuild/2003"); doc.AppendChild(project); // add using task XmlElement usingTask = doc.CreateElement("UsingTask"); usingTask.SetAttribute("TaskName", "MbUnit.MSBuild.Tasks.MbUnit"); usingTask.SetAttribute("AssemblyFile", "MbUnit.MSBuild.Tasks.dll"); project.AppendChild(usingTask); XmlElement itemGroup = doc.CreateElement("ItemGroup"); project.AppendChild(itemGroup); // add include for each assembly foreach (string testFilePath in this.TestDomains.TestFilePaths) { XmlElement includes = doc.CreateElement("TestAssemblies"); includes.SetAttribute("Include", testFilePath); itemGroup.AppendChild(includes); } XmlElement target = doc.CreateElement("Target"); target.SetAttribute("Name", "Tests"); project.AppendChild(target); // root element XmlElement mbunit = doc.CreateElement("MbUnit"); mbunit.SetAttribute("Assemblies", "@(TestAssemblies)"); mbunit.SetAttribute("ReportTypes", "Html"); target.AppendChild(mbunit); // render to clipboard StringWriter writer = new StringWriter(); XmlTextWriter xWriter = new XmlTextWriter(writer); xWriter.Formatting = Formatting.Indented; doc.Save(xWriter); Clipboard.SetDataObject(writer.ToString(), true); } public void CreateNCoverTask() { throw new NotImplementedException(); } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MainMenu.cs" company="Exit Games GmbH"> // Part of: Photon Unity Networking // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections; using UnityEngine; public class Connect1B : MonoBehaviour { private string roomName = "myRoom"; private Vector2 scrollPos = Vector2.zero; private bool connectFailed = false; private void Awake() { // Connect to the main photon server. if (!PhotonNetwork.connected) { PhotonNetwork.ConnectUsingSettings("1.0"); } //Load our name from PlayerPrefs PhotonNetwork.playerName = "Guest" + Random.Range(1, 9999); } private void OnGUI() { if (!PhotonNetwork.connected) { GUI_Disconnected(); } else { if (PhotonNetwork.room != null) { GUI_Connected_Room(); } else { GUI_Connected_Lobby(); } } } void GUI_Disconnected() { if (PhotonNetwork.connecting) { GUILayout.Label("Connecting..."); } else { GUILayout.Label("Not connected. Check console output. (" + PhotonNetwork.connectionState + ")"); } if (this.connectFailed) { GUILayout.Label("Connection failed. Check setup and use Setup Wizard to fix configuration."); GUILayout.Label(string.Format("Server: {0}", PhotonNetwork.PhotonServerSettings.ServerAddress)); GUILayout.Label(string.Format("AppId: {0}", PhotonNetwork.PhotonServerSettings.AppID)); if (GUILayout.Button("Try Again", GUILayout.Width(100))) { this.connectFailed = false; PhotonNetwork.ConnectUsingSettings("1.0"); } } } void GUI_Connected_Lobby() { GUILayout.BeginArea(new Rect((Screen.width - 400) / 2, (Screen.height - 300) / 2, 400, 300)); GUILayout.Label("Main Menu"); // Player name GUILayout.BeginHorizontal(); GUILayout.Label("Player name:", GUILayout.Width(150)); PhotonNetwork.playerName = GUILayout.TextField(PhotonNetwork.playerName); if (GUI.changed) { PlayerPrefs.SetString("playerName" + Application.platform, PhotonNetwork.playerName); } GUILayout.EndHorizontal(); GUILayout.Space(15); // Join room by title GUILayout.BeginHorizontal(); GUILayout.Label("JOIN ROOM:", GUILayout.Width(150)); this.roomName = GUILayout.TextField(this.roomName); if (GUILayout.Button("GO")) { PhotonNetwork.JoinRoom(this.roomName); } GUILayout.EndHorizontal(); // Create a room (fails if already exists!) GUILayout.BeginHorizontal(); GUILayout.Label("CREATE ROOM:", GUILayout.Width(150)); this.roomName = GUILayout.TextField(this.roomName); if (GUILayout.Button("GO")) { PhotonNetwork.CreateRoom(this.roomName, new RoomOptions() { maxPlayers = 10}, null); } GUILayout.EndHorizontal(); // Join random room (there must be at least 1 room) GUILayout.BeginHorizontal(); GUILayout.Label("JOIN RANDOM ROOM:", GUILayout.Width(150)); if (PhotonNetwork.GetRoomList().Length == 0) { GUILayout.Label("..no games available..."); } else { if (GUILayout.Button("GO")) { PhotonNetwork.JoinRandomRoom(); } } GUILayout.EndHorizontal(); GUILayout.Space(30); //Show a list of all current rooms GUILayout.Label("ROOM LISTING:"); if (PhotonNetwork.GetRoomList().Length == 0) { GUILayout.Label("..no games available.."); } else { // Room listing: simply call GetRoomList: no need to fetch/poll whatever! this.scrollPos = GUILayout.BeginScrollView(this.scrollPos); foreach (RoomInfo game in PhotonNetwork.GetRoomList()) { GUILayout.BeginHorizontal(); GUILayout.Label(game.name + " " + game.playerCount + "/" + game.maxPlayers); if (GUILayout.Button("JOIN")) { PhotonNetwork.JoinRoom(game.name); } GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); } GUILayout.EndArea(); } void GUI_Connected_Room() { GUILayout.Label("We are connected to room: "+PhotonNetwork.room); GUILayout.Label("Players: "); foreach (PhotonPlayer player in PhotonNetwork.playerList) { GUILayout.Label("ID: "+player.ID+" Name: "+player.name); } if (GUILayout.Button("Leave room")) { PhotonNetwork.LeaveRoom(); } } // We have two options here: we either joined(by title, list or random) or created a room. private void OnJoinedRoom() { Debug.Log("We have joined a room."); StartCoroutine(MoveToGameScene()); } private void OnCreatedRoom() { Debug.Log("We have created a room."); //When creating a room, OnJoinedRoom is also called, so we don't have to do anything here. } private void OnFailedToConnectToPhoton(object parameters) { this.connectFailed = true; Debug.Log("OnFailedToConnectToPhoton. StatusCode: " + parameters); } private IEnumerator MoveToGameScene() { //Wait for the while (PhotonNetwork.room == null) { yield return 0; } Debug.LogWarning("Normally we would load the game scene right now."); /* PhotonNetwork.LoadLevel( LEVEL TO LOAD); */ } //CALLBACKS - for debug info only // ROOMS void OnLeftRoom() { Debug.Log("This client has left a game room."); } void OnPhotonCreateRoomFailed() { Debug.Log("A CreateRoom call failed, most likely the room name is already in use."); } void OnPhotonJoinRoomFailed() { Debug.Log("A JoinRoom call failed, most likely the room name does not exist or is full."); } void OnPhotonRandomJoinFailed() { Debug.Log("A JoinRandom room call failed, most likely there are no rooms available."); } // LOBBY EVENTS void OnJoinedLobby() { Debug.Log("We joined the lobby."); } void OnLeftLobby() { Debug.Log("We left the lobby."); } // ROOMLIST void OnReceivedRoomList() { Debug.Log("We received a new room list, total rooms: " + PhotonNetwork.GetRoomList().Length); } void OnReceivedRoomListUpdate() { Debug.Log("We received a room list update, total rooms now: " + PhotonNetwork.GetRoomList().Length); } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Windows.Forms; using FTD2XX_NET; using System.Collections; namespace WeblinkCommunication { class DriverFTDI_D2XX { public FTDI device; FTDI.FT_STATUS ftStatus; UInt32 ftdiDeviceCount; private IDLspecs IdatalinkInfo; // used by function private uint b = 0; // nNb Byte already r/w private byte[] cmd = new byte[2]; // Command to send private byte[] data = new byte[16]; // Data to received private byte[] ack = new byte[1]; // Ack to received private Thread keepAlive; private volatile bool inKeepAlive; private volatile bool isInRdOrWr; private uint baudRate; public DriverFTDI_D2XX(uint baudRate, IDLspecs info) { IdatalinkInfo = info; this.baudRate = baudRate; Preload(); } /// <summary> /// Set D2XX setting /// </summary> private void Preload() { // USB Section ftStatus = FTDI.FT_STATUS.FT_OK; ftdiDeviceCount = 0; device = new FTDI(); device.SetBaudRate(this.baudRate); ftStatus = device.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE); device.SetLatency(1); // Latency = 1ms device.SetTimeouts(1000, 1000); } /// <summary> /// Try to detect module and start a communication on USB driver /// Return true if module is detected /// </summary> public bool Init() { string temp = ""; // Determine the number of FTDI devices connected to the machine ftStatus = device.GetNumberOfDevices(ref ftdiDeviceCount); // If no devices available, return if (ftdiDeviceCount == 0) { IdatalinkInfo.info = "No port detected!"; return false; } // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = device.GetDeviceList(ftdiDeviceList); if (ftStatus == FTDI.FT_STATUS.FT_OK) { // for each FTDI device found get only weblink device for (uint i = 0; i < ftdiDeviceList.Length; i++) { // Check for a weblink device if ("ADS Weblink Interface" == ftdiDeviceList[i].Description) { //MessageBox.Show(ftdiDeviceList[i].Description + " : " + i); ftStatus = device.OpenByIndex(i); // check for detecting device.... // ftStatus = device.ResetPort(); ftStatus = device.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); if (ftStatus == FTDI.FT_STATUS.FT_OK) { // Check for a module response if (InitModule()) { // good port device.GetDescription(out temp); IdatalinkInfo.portName = temp; IdatalinkInfo.info = "Device detected on USB : " + IdatalinkInfo.portName + " : (FTD2XX driver used)"; return true; } } } } } else { IdatalinkInfo.info = " USB device not ready"; InitModule(); } return false; } // public bool InitLogExtractionModule() { ftStatus = device.SetDTR(false); Thread.Sleep(50); if (ftStatus != FTDI.FT_STATUS.FT_OK) return false; ftStatus = device.SetBaudRate(57600); if (ftStatus != FTDI.FT_STATUS.FT_OK) return false; // set DTR and wait 400ms ftStatus = device.SetDTR(true); if (ftStatus != FTDI.FT_STATUS.FT_OK) return false; Thread.Sleep(400); ////////// Handshake ////////// // Receive 0xAA ftStatus = device.Read(data, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (data[0] != 0x00)) { Close(); return false; } // Response with 0xBB data[0] = 0xBB; ftStatus = device.Write(data, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { Close(); return false; } // Receive 0xCC data[1] = 0x00;//init ftStatus = device.Read(data, 2, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (data[0] != 0xCC)) { Close(); return false; } return true; } /// <summary> /// This function try to start a communication with direct USB driver (D2XX) with idatalink device on the weblink /// </summary> /// <returns> /// true: if a communication success with the device /// false: if a error occur during the communication /// </returns> public bool InitModule() { ftStatus = device.SetDTR(false); Thread.Sleep(50); if (ftStatus != FTDI.FT_STATUS.FT_OK) return false; ftStatus = device.SetBaudRate(9600); if (ftStatus != FTDI.FT_STATUS.FT_OK) return false; // set DTR and wait 400ms ftStatus = device.SetDTR(true); if (ftStatus != FTDI.FT_STATUS.FT_OK) return false; Thread.Sleep(400); ////////// Handshake ////////// // Receive 0x00 ftStatus = device.Read(data, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (data[0] != 0x00)) { Close(); return false; } // Response with 0x01 data[0] = 0x01; ftStatus = device.Write(data, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { Close(); return false; } // Receive 0x02 and bootloader version data[1] = 0x00;//init ftStatus = device.Read(data, 2, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 2) || (data[0] != 0x02)) { Close(); return false; } // Note: IdatalinkInfo.BootloaderVersion = data[1]; if ((IdatalinkInfo.BootloaderVersion == 0x00) || (IdatalinkInfo.BootloaderVersion == 0xFF)) // invalid bootloader { Close(); // when opened, should be closed to complete the loop MessageBox.Show("Invalid bootloader version"); return false; } else { // Change speed for supported device if ((IdatalinkInfo.BootloaderVersion != 1) && (IdatalinkInfo.BootloaderVersion != 2)) { //ChangeSpeed(IdlSpeed.SPEED_57600); } IdatalinkInfo.EepromLength = IdatalinkInfo.EepromSize[IdatalinkInfo.BootloaderVersion]; } /////////////////////////////// keepAlive = new Thread(new ThreadStart(KeepModuleAlive)); keepAlive.Start(); return true; } public void WriteByte(byte[] buffer, uint timeout) { while (inKeepAlive) ; isInRdOrWr = true; device.SetTimeouts(timeout, timeout); ftStatus = device.Write(buffer, buffer.Length, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != buffer.Length)) { Close(); } isInRdOrWr = false; } public void WriteLine(string text, uint timeout) { while (inKeepAlive) ; isInRdOrWr = true; ftStatus = device.SetTimeouts(timeout, timeout); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Close(); return; } ftStatus = device.Write(text, text.Length, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != (uint)text.Length)) { Close(); return; } isInRdOrWr = false; } public byte ReadByte(uint timeout) { ftStatus = device.SetTimeouts(timeout, timeout); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Close(); throw new Exception("Unable to read USB device"); } ftStatus = device.Read(data, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { Close(); throw new Exception("Unable to read USB device"); } return data[0]; } public byte[] ReadByte(uint NbByteToRead, uint timeout) { byte[] dat = new byte[NbByteToRead]; ftStatus = device.SetTimeouts(timeout, timeout); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Close(); throw new Exception("Unable to read USB device"); } ftStatus = device.Read(dat, NbByteToRead, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != NbByteToRead)) { Close(); throw new Exception("Unable to read USB device"); } return dat; } public string ReadLine(uint timeout) { string line = ""; ftStatus = device.SetTimeouts(timeout, timeout); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Close(); throw new Exception("Unable to read USB device"); } ftStatus = device.Read(out line, 20, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK)) { Close(); throw new Exception("Unable to read USB device"); } return line; } public void KeepModuleAlive() { Thread.Sleep(500); while ((device != null) && (device.IsOpen)) { // wait between the read and write sequence while (isInRdOrWr) ; // wait the end of the read/write inKeepAlive = true; // prevent read/write while the keep alive // KeepAlive 0x04 data[0] = (byte)Cmd.KEEP_ALIVE; ftStatus = device.Write(data, 1, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { //MessageBox.Show("KA Time out"); Close(); throw new Exception("Unable to write USB device"); } // Receive 0x55 ftStatus = device.Read(ack, 1, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (ack[0] != (byte)Cmd.ACK)) { //MessageBox.Show("KA Time out"); Close(); throw new Exception("Keepalive Time out!\r\n"); } inKeepAlive = false; // permit read/write // do the keepalive every 500ms Thread.Sleep(500); } //MessageBox.Show("No more KA"); } #region Bootloader // Read Eeprom page public byte[] ReadEepromPage(byte page) { cmd[0] = (byte)Cmd.READ_EEPROM_PAGE; cmd[1] = page; // wait the end of keepalive and avoid it while (inKeepAlive) ; isInRdOrWr = true; // set time out ftStatus = device.SetTimeouts(500, 500); if ((ftStatus != FTDI.FT_STATUS.FT_OK)) { Close(); //MessageBox.Show("E0"); throw new Exception("Unable set USB port Timeout"); } // Send cmd and page ftStatus = device.Write(cmd, 2, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 2)) { Close(); //MessageBox.Show("E1"); throw new Exception("Unable to write on USB device"); } // Read the page ftStatus = device.Read(data, 16, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 16)) { Close(); //MessageBox.Show("E2"); throw new Exception("Unable to read on USB device"); } // Read the ack ftStatus = device.Read(ack, 1, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (ack[0] != (byte)Cmd.ACK)) { Close(); //MessageBox.Show("E4"); throw new Exception("Unable to read on USB device"); } // permit the keepalive isInRdOrWr = false; return data; } public void SendCTR(byte[] ctr) { cmd[0] = (byte)Cmd.SEND_CTR; // wait the end of keepalive and avoid it while (inKeepAlive) ; isInRdOrWr = true; // set time out ftStatus = device.SetTimeouts(500, 500); if ((ftStatus != FTDI.FT_STATUS.FT_OK)) { Close(); //MessageBox.Show("E0"); throw new Exception("Unable set USB port Timeout"); } // Send cmd ftStatus = device.Write(cmd, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { Close(); //MessageBox.Show("E1"); throw new Exception("Unable to write on USB device"); } // Send ctr ftStatus = device.Write(ctr, 14, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 14)) { Close(); //MessageBox.Show("E1"); throw new Exception("Unable to write CTR on USB device"); } // Read ACK ftStatus = device.Read(data, 1, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (ack[0] != (byte)Cmd.ACK)) { Close(); //MessageBox.Show("E2"); throw new Exception("Unable to read on USB device"); } // permit the keepalive isInRdOrWr = false; } public void SendMAC(byte[] mac) { cmd[0] = (byte)Cmd.SEND_MAC; // wait the end of keepalive and avoid it while (inKeepAlive) ; isInRdOrWr = true; // set time out ftStatus = device.SetTimeouts(500, 500); if ((ftStatus != FTDI.FT_STATUS.FT_OK)) { Close(); //MessageBox.Show("E0"); throw new Exception("Unable set USB port Timeout"); } // Send cmd ftStatus = device.Write(cmd, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { Close(); //MessageBox.Show("E1"); throw new Exception("Unable to write on USB device"); } // Send mac ftStatus = device.Write(mac, 16, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 16)) { Close(); //MessageBox.Show("E1"); throw new Exception("Unable to write MAC on USB device"); } // Read ACK ftStatus = device.Read(data, 1, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (ack[0] != (byte)Cmd.ACK)) { Close(); //MessageBox.Show("E2"); throw new Exception("Unable to read on USB device"); } // permit the keepalive isInRdOrWr = false; } public void SendFlashPage(byte[] FlashPage) { cmd[0] = (byte)Cmd.WRITE_FLASH_PAGE; // wait the end of keepalive and avoid it while (inKeepAlive) ; isInRdOrWr = true; // set time out ftStatus = device.SetTimeouts(500, 500); if ((ftStatus != FTDI.FT_STATUS.FT_OK)) { Close(); //MessageBox.Show("E0"); throw new Exception("Unable set USB port Timeout"); } // Send cmd ftStatus = device.Write(cmd, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { Close(); //MessageBox.Show("E1"); throw new Exception("Unable to write on USB device"); } // Send flash page ftStatus = device.Write(FlashPage, FlashPage.Length, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != FlashPage.Length)) { Close(); //MessageBox.Show("E1"); throw new Exception("Unable to write FLASH PAGE on USB device"); } // Read ACK ftStatus = device.Read(data, 1, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (ack[0] != (byte)Cmd.ACK)) { Close(); //MessageBox.Show("E2"); throw new Exception("Unable to read on USB device"); } // permit the keepalive isInRdOrWr = false; } public void ChangeSpeed(IdlSpeed speed) { cmd[0] = (byte)Cmd.SET_SPEED_TO_57600; // wait the end of keepalive and avoid it while (inKeepAlive) ; isInRdOrWr = true; // Send cmd ftStatus = device.Write(cmd, 1, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { Close(); throw new Exception("Unable to write on USB device"); } // Read the ack ftStatus = device.Read(ack, 1, ref b); //test if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (ack[0] != (byte)Cmd.ACK)) { Close(); throw new Exception("Unable to change device speed"); } if (speed == IdlSpeed.SPEED_9600) { device.SetBaudRate(9600); } if (speed == IdlSpeed.SPEED_57600) { device.SetBaudRate(57600); } // permit the keepalive isInRdOrWr = false; } #endregion Bootloader #region LogReader /// <summary> /// Init communication for LogReader application only /// </summary> public void InitLogReader(IdlSpeed speed) { // set DTR /* serialPort.DtrEnable = false; System.Threading.Thread.Sleep(50); serialPort.DtrEnable = true; System.Threading.Thread.Sleep(400); serialPort.BaudRate = 57600; // Convert.ToInt16(speed); serialPort.ReadTimeout = 5000; serialPort.WriteTimeout = 5000; */ device.SetTimeouts(5000,5000); ftStatus = device.SetDTR(false); Thread.Sleep(50); //if (ftStatus != FTDI.FT_STATUS.FT_OK) // throw new Exception("Unable to init the communication"); ftStatus = device.SetBaudRate(57600); //if (ftStatus != FTDI.FT_STATUS.FT_OK) // throw new Exception("Unable to init the communication"); // set DTR and wait 400ms ftStatus = device.SetDTR(true); Thread.Sleep(400); //if (ftStatus != FTDI.FT_STATUS.FT_OK) // throw new Exception("Unable to init the communication"); ////////// Handshake ////////// // Receive 0xAA ftStatus = device.Read(data, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1) || (data[0] != 0xAA)) { Close(); throw new Exception("Unable to init the communication"); } // Response with 0xBB data[0] = 0xBB; ftStatus = device.Write(data, 1, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 1)) { Close(); throw new Exception("Unable to init the communication"); } // Receive 0xCC and bootloader version data[1] = 0xCC;//init ftStatus = device.Read(data, 2, ref b); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (b != 2) || (data[0] != 0xCC)) { Close(); throw new Exception("Unable to init the communication"); } } /// <summary> /// To erase info of a log bank /// </summary> /// <param name="Bank">Bank # to read</param> public byte[] ReadLogBankInfo(byte Bank) { byte[] info = new byte[4]; return info; } /// <summary> /// To erase info of a log bank /// </summary> /// <param name="Bank">Bank # to read</param> public void EraseLogBankInfo(byte Bank) { } /// <summary> /// To read the page size /// (log2 of page size) 256->8, 512->9, 1024->10 .... /// </summary> /// <param name="Log2PageSize"> </param> /// <returns>return number of page in the buffer</returns> public byte ReadLog2PageSize() { return 0; } /// <summary> /// To read the number of page in the buffer /// </summary> /// <returns>return number of page in the buffer</returns> public byte ReadNbPagePerBuffer() { return 0; } /// <summary> /// To read a full bank of datalog /// </summary> /// <param name="Bank">Bank # to read</param> /// <param name="BufferSize"></param> /// <param name="Buffer"></param> public ArrayList ReadFlashBuffer(byte Bank, uint BufferSize) { //byte[] buffer = new byte[BufferSize]; ArrayList buffer = new ArrayList((int)BufferSize); return buffer; } /// <summary> /// To read the number of bank available /// </summary> /// <returns>return the number of bank available</returns> public byte ReadNbBank() { return 0; } /// <summary> /// /// </summary> public void ExitLogMode() { } #endregion LogReader /// <summary> /// Close all the Port and running thread for device communication /// </summary> public void Close() { isInRdOrWr = false; inKeepAlive = false; if ((device != null) && device.IsOpen) { ftStatus = device.SetDTR(false); ftStatus = device.SetRTS(false); ftStatus = device.Close(); while (ftStatus != FTDI.FT_STATUS.FT_OK) ; } if ((keepAlive != null) && (keepAlive.ThreadState != ThreadState.Stopped)) { keepAlive.Abort(); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Ros_CSharp; using Color = Microsoft.Xna.Framework.Color; using Game = Microsoft.Xna.Framework.Game; using Image = Messages.sensor_msgs.Image; using Matrix = Microsoft.Xna.Framework.Matrix; using Point = Microsoft.Xna.Framework.Point; using Rectangle = Microsoft.Xna.Framework.Rectangle; namespace WindowsGameTest { public class TheGame : Game { private Quad[] quad; private Texture2D texture; private Texture2D next_texture; private BasicEffect effect; private Camera camera; #region ROS stuff private Mutex padlock = new Mutex(); private NodeHandle nh; private Subscriber<Messages.sensor_msgs.Image> imgSub; private TextureUtils util = new TextureUtils(); #endregion private GraphicsDeviceManager manager; public TheGame() : base() { manager = new GraphicsDeviceManager(this); } protected override void Initialize() { quad = new Quad[6]; quad[0] = new Quad(Vector3.Backward, Vector3.Backward, Vector3.Up, 2, 2); quad[1] = new Quad(Vector3.Left, Vector3.Left, Vector3.Up, 2, 2); quad[2] = new Quad(Vector3.Right, Vector3.Right, Vector3.Up, 2, 2); quad[3] = new Quad(Vector3.Forward, Vector3.Forward, Vector3.Up, 2, 2); quad[4] = new Quad(Vector3.Down, Vector3.Down, Vector3.Right, 2, 2); quad[5] = new Quad(Vector3.Up, Vector3.Up, Vector3.Left, 2, 2); nh = new NodeHandle(); imgSub = nh.subscribe<Messages.sensor_msgs.Image>("/camera/rgb/image_rect_color", 1, (img) => { if (padlock.WaitOne(10)) { if (next_texture == null) { next_texture = new Texture2D(GraphicsDevice, (int) img.width, (int) img.height); } util.UpdateImage(GraphicsDevice, img.data, new Size((int)img.width, (int)img.height), ref next_texture, img.encoding.data); padlock.ReleaseMutex(); } }); base.Initialize(); } protected override void LoadContent() { // Initialize the BasicEffect effect = new BasicEffect(GraphicsDevice); camera = new Camera(this, new Vector3(0, 0, 5), Vector3.Zero, Vector3.Up); Components.Add(camera); base.LoadContent(); } protected override void UnloadContent() { base.UnloadContent(); } protected override void Update(GameTime gameTime) { if (padlock.WaitOne(10)) { if (next_texture != null) { if (texture != null) { effect.Texture.Dispose(); effect.Texture = null; texture.Dispose(); texture = null; } texture = next_texture; next_texture = null; effect.Texture = texture; effect.TextureEnabled = true; } padlock.ReleaseMutex(); } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); float amount = 0.5f+(float)Math.Sin((double)gameTime.TotalGameTime.TotalSeconds / 4.0)/2f; effect.World = Matrix.CreateRotationX(MathHelper.Lerp(-(float)Math.PI, (float)Math.PI, amount))* Matrix.CreateRotationY(MathHelper.Lerp(-(float)Math.PI, (float)Math.PI, amount)) * Matrix.CreateRotationZ(MathHelper.Lerp(-(float)Math.PI, (float)Math.PI, amount)); effect.View = camera.view; effect.Projection = camera.projection; // Begin effect and draw for each pass foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); for(int i=0;i<quad.Length;i++) GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList,quad[i].Vertices, 0, 4,quad[i].Indexes, 0, 2); } base.Draw(gameTime); } } /// <summary> /// This is a game component that implements IUpdateable. /// </summary> public class Camera : GameComponent { public Matrix view { get; protected set; } public Matrix projection { get; protected set; } public Camera(Game g, Vector3 position, Vector3 target, Vector3 up) : base(g) { view = Matrix.CreateLookAt(position, target, up); projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, (float)g.Window.ClientBounds.Width / g.Window.ClientBounds.Height, 1, 100); } /// <summary> /// Called when the GameComponent needs to be updated. Override this method with component-specific update code. /// </summary> /// <param name="gameTime">Time elapsed since the last call to Update</param> public override void Update(GameTime gameTime) { base.Update(gameTime); } } public class Quad { public VertexPositionNormalTexture[] Vertices; public short[] Indexes; private Vector3 Origin, Normal, Up, Left, UpperLeft, UpperRight, LowerLeft, LowerRight; public Quad(Vector3 origin, Vector3 normal, Vector3 up, float width, float height) { Vertices = new VertexPositionNormalTexture[4]; Indexes = new short[6]; Origin = origin; Normal = normal; Up = up; // Calculate the quad corners Left = Vector3.Cross(normal, Up); Vector3 uppercenter = (Up * height / 2) + origin; UpperLeft = uppercenter + (Left * width / 2); UpperRight = uppercenter - (Left * width / 2); LowerLeft = UpperLeft - (Up * height); LowerRight = UpperRight - (Up * height); FillVertices(); } private void FillVertices() { // Fill in texture coordinates to display full texture // on quad Vector2 textureUpperLeft = new Vector2( 0.0f, 0.0f ); Vector2 textureUpperRight = new Vector2( 1.0f, 0.0f ); Vector2 textureLowerLeft = new Vector2( 0.0f, 1.0f ); Vector2 textureLowerRight = new Vector2( 1.0f, 1.0f ); // Provide a normal for each vertex for (int i = 0; i < Vertices.Length; i++) { Vertices[i].Normal = Normal; } // Set the position and texture coordinate for each // vertex Vertices[0].Position = LowerLeft; Vertices[0].TextureCoordinate = textureLowerLeft; Vertices[1].Position = UpperLeft; Vertices[1].TextureCoordinate = textureUpperLeft; Vertices[2].Position = LowerRight; Vertices[2].TextureCoordinate = textureLowerRight; Vertices[3].Position = UpperRight; Vertices[3].TextureCoordinate = textureUpperRight; // Set the index buffer for each vertex, using // clockwise winding Indexes[0] = 0; Indexes[1] = 1; Indexes[2] = 2; Indexes[3] = 2; Indexes[4] = 1; Indexes[5] = 3; } } public class TextureUtils { /// <summary> /// Looks up the bitmaps dress, then starts passing the image around as a Byte[] and a System.Media.Size to the /// overloaded UpdateImages that make this work /// </summary> /// <param name="bmp"> /// </param> public void UpdateImage(GraphicsDevice dev, Bitmap bmp, ref Texture2D target) { try { // look up the image's dress BitmapData bData = bmp.LockBits(new System.Drawing.Rectangle(new System.Drawing.Point(), bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); // d.Imaging.PixelFormat.Format32bppArgb); int byteCount = bData.Stride*bmp.Height; byte[] rgbData = new byte[byteCount]; // turn the bitmap into a byte[] Marshal.Copy(bData.Scan0, rgbData, 0, byteCount); bmp.UnlockBits(bData); // starts the overload cluster-mess to show the image UpdateImage(dev, rgbData, SizeConverter(bmp.Size), ref target); // get that stuff out of memory so it doesn't mess our day up. bmp.Dispose(); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// same as the one above, but allows for 3 bpp bitmaps to be drawn without failing... like the surroundings. /// </summary> /// <param name="bmp"> /// </param> /// <param name="bpp"> /// </param> public void UpdateImage(GraphicsDevice dev, Bitmap bmp, int bpp, ref Texture2D target) { if (bpp == 4) { UpdateImage(dev, bmp, ref target); } if (bpp == 3) { try { // look up the image's dress BitmapData bData = bmp.LockBits(new System.Drawing.Rectangle(new System.Drawing.Point(), bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); int byteCount = bData.Stride*bmp.Height; byte[] rgbData = new byte[byteCount]; // turn the bitmap into a byte[] Marshal.Copy(bData.Scan0, rgbData, 0, byteCount); bmp.UnlockBits(bData); // starts the overload cluster-mess to show the image UpdateImage(dev, rgbData, SizeConverter(bmp.Size), ref target); // get that stuff out of memory so it doesn't mess our day up. bmp.Dispose(); } catch (Exception e) { Console.WriteLine(e); } } else Console.WriteLine("non-fatal BPP mismatch. If you see images, then you should go to vegas and bet your life savings on black."); } /// <summary> /// if hasHeader is true, then UpdateImage(byte[]) is called /// otherwise, the size is compared to lastSize, /// if they differ or header is null, a header is created, and concatinated with data, then UpdateImage(byte[]) is /// called /// </summary> /// <param name="data"> /// image data /// </param> /// <param name="size"> /// image size /// </param> /// <param name="hasHeader"> /// whether or not a header needs to be concatinated /// </param> public void UpdateImage(GraphicsDevice dev, byte[] data, Size size, ref Texture2D target, string encoding = null) { if (data != null) { byte[] correcteddata; switch (encoding) { case "rgb8": correcteddata = new byte[(int) Math.Round(4d*data.Length/3d)]; for (int i = 0, ci = 0; i < data.Length; i += 3, ci += 4) { correcteddata[ci] = data[i]; correcteddata[ci+1] = data[i+1]; correcteddata[ci+2] = data[i+2]; correcteddata[ci+3] = 0xFF; } break; default: throw new Exception("Unhandled texture conversion input, " + encoding); break; } // stick it on the bitmap data try { UpdateImage(dev, correcteddata, ref target); } catch (Exception e) { Console.WriteLine(e); } data = null; correcteddata = null; } } /// <summary> /// Uses a memory stream to turn a byte array into a BitmapImage via helper method, BytesToImage, then passes the image /// to UpdateImage(BitmapImage) /// </summary> /// <param name="data"> /// </param> public void UpdateImage(GraphicsDevice dev, byte[] data, ref Texture2D target) { int[] imgData = new int[target.Width * target.Height]; if (data.Length/4 != imgData.Length) throw new Exception("Invalid input data size! Texture data must be RGBA w/32bpp"); IntPtr addr = Marshal.AllocHGlobal(data.Length); Marshal.Copy(data, 0, addr, data.Length); Marshal.Copy(addr, imgData, 0, imgData.Length); target.SetData(imgData); Marshal.FreeHGlobal(addr); imgData = null; } /// <summary> /// turns a System.Drawing.Size into the WPF double,double version /// </summary> /// <param name="s"> /// </param> /// <returns> /// </returns> protected static Size SizeConverter(System.Drawing.Size s) { return new Size(s.Width, s.Height); } } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2009 Jason Booth Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; namespace Cocos2D { /// <summary> /// Helper class to handle file operations /// </summary> public class CCFileUtils { protected static bool s_bPopupNotify = true; /// <summary> /// Set/Get whether pop-up a message box when the image load failed /// </summary> public static bool IsPopupNotify { get { return s_bPopupNotify; } set { s_bPopupNotify = value; } } public static Stream GetFileStream(string fileName) { fileName = Path.Combine(CCContentManager.SharedContentManager.RootDirectory, fileName); return TitleContainer.OpenStream(fileName); } /// <summary> /// @brief Get resource file data /// @param[in] pszFileName The resource file name which contain the path /// @param[in] pszMode The read mode of the file /// @param[out] pSize If get the file data succeed the it will be the data size,or it will be 0 /// @return if success,the pointer of data will be returned,or NULL is returned /// @warning If you get the file data succeed,you must delete it after used. /// </summary> /// <param name="pszFileName"></param> /// <returns></returns> public static string GetFileData(string pszFileName) { return CCContentManager.SharedContentManager.Load<string>(pszFileName); } public static byte[] GetFileBytes(string pszFileName) { pszFileName = System.IO.Path.Combine(CCContentManager.SharedContentManager.RootDirectory, pszFileName); using (var stream = TitleContainer.OpenStream(pszFileName)) { var buffer = new byte[1024]; var ms = new MemoryStream(); int readed = 0; readed = stream.Read(buffer, 0, 1024); while (readed > 0) { ms.Write(buffer, 0, readed); readed = stream.Read(buffer, 0, 1024); } return ms.ToArray(); } } /// <summary> /// @brief Get resource file data from zip file /// @param[in] pszFileName The resource file name which contain the relative path of zip file /// @param[out] pSize If get the file data succeed the it will be the data size,or it will be 0 /// @return if success,the pointer of data will be returned,or NULL is returned /// @warning If you get the file data succeed,you must delete it after used. /// </summary> /// <param name="pszZipFilePath"></param> /// <param name="pszFileName"></param> /// <param name="pSize"></param> /// <returns></returns> public static char[] GetFileDataFromZip(string pszZipFilePath, string pszFileName, UInt64 pSize) { throw new NotImplementedException("Cannot load zip files for this method has not been realized !"); } /// <summary> /// removes the HD suffix from a path /// @returns const char * without the HD suffix /// @since v0.99.5 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string CCRemoveHDSuffixFromFile(string path) { throw new NotImplementedException("Remove hd picture !"); } /// <summary> /// @brief Generate the absolute path of the file. /// @param pszRelativePath The relative path of the file. /// @return The absolute path of the file. /// @warning We only add the ResourcePath before the relative path of the file. /// If you have not set the ResourcePath,the function add "/NEWPLUS/TDA_DATA/UserData/" as default. /// You can set ResourcePath by function void setResourcePath(const char *pszResourcePath); /// </summary> /// <param name="pszRelativePath"></param> /// <returns></returns> public static string FullPathFromRelativePath(string pszRelativePath) { // todo: return self now return pszRelativePath; // throw new NotImplementedException("win32 only definition does not realize !"); } /// <summary> /// extracts the directory from the pszRelativeFile and uses that directory path as the /// path for the pszFilename. /// </summary> public static string FullPathFromRelativeFile(string pszFilename, string pszRelativeFile) { string path = Path.GetDirectoryName(pszRelativeFile); return Path.Combine(path, RemoveExtension(pszFilename)); } public static string RemoveExtension(string fileName) { int len = fileName.LastIndexOf('.'); if (len != -1) { return fileName.Substring(0, len); } return fileName; } /// <summary> /// @brief Set the ResourcePath,we will find resource in this path /// @param pszResourcePath The absolute resource path /// @warning Don't call this function in android and iOS, it has not effect. /// In android, if you want to read file other than apk, you shoud use invoke getFileData(), and pass the /// absolute path. /// </summary> /// <param name="?"></param> public static void SetResourcePath(string pszResourcePath) { throw new NotSupportedException ("Not supported in XNA"); } /// <summary> /// @brief Generate a CCDictionary pointer by file /// @param pFileName The file name of *.plist file /// @return The CCDictionary pointer generated from the file /// </summary> /// <typeparam name="?"></typeparam> /// <typeparam name="?"></typeparam> /// <param name="?"></param> /// <returns></returns> public static Dictionary<string, object> DictionaryWithContentsOfFile(string pFileName) { CCDictMaker tMaker = new CCDictMaker(); return tMaker.DictionaryWithContentsOfFile(pFileName); } /// <summary> /// @brief Get the writeable path /// @return The path that can write/read file /// </summary> /// <returns></returns> public static string GetWriteablePath() { throw new NotSupportedException("Use IsolatedStorage in XNA"); } /////////////////////////////////////////////////// // interfaces on wophone /////////////////////////////////////////////////// /// <summary> /// @brief Set the resource zip file name /// @param pszZipFileName The relative path of the .zip file /// </summary> /// <param name="pszZipFileName"></param> public static void SetResource(string pszZipFileName) { throw new NotImplementedException("win32 only definition does not realize !"); } /////////////////////////////////////////////////// // interfaces on ios /////////////////////////////////////////////////// public static int CCLoadFileIntoMemory(string filename, out char[] file) { throw new NotImplementedException("win32 only definition does not realize !"); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.AppEngine.V1 { /// <summary>Settings for <see cref="AuthorizedCertificatesClient"/> instances.</summary> public sealed partial class AuthorizedCertificatesSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AuthorizedCertificatesSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AuthorizedCertificatesSettings"/>.</returns> public static AuthorizedCertificatesSettings GetDefault() => new AuthorizedCertificatesSettings(); /// <summary> /// Constructs a new <see cref="AuthorizedCertificatesSettings"/> object with default settings. /// </summary> public AuthorizedCertificatesSettings() { } private AuthorizedCertificatesSettings(AuthorizedCertificatesSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListAuthorizedCertificatesSettings = existing.ListAuthorizedCertificatesSettings; GetAuthorizedCertificateSettings = existing.GetAuthorizedCertificateSettings; CreateAuthorizedCertificateSettings = existing.CreateAuthorizedCertificateSettings; UpdateAuthorizedCertificateSettings = existing.UpdateAuthorizedCertificateSettings; DeleteAuthorizedCertificateSettings = existing.DeleteAuthorizedCertificateSettings; OnCopy(existing); } partial void OnCopy(AuthorizedCertificatesSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AuthorizedCertificatesClient.ListAuthorizedCertificates</c> and /// <c>AuthorizedCertificatesClient.ListAuthorizedCertificatesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListAuthorizedCertificatesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AuthorizedCertificatesClient.GetAuthorizedCertificate</c> and /// <c>AuthorizedCertificatesClient.GetAuthorizedCertificateAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetAuthorizedCertificateSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AuthorizedCertificatesClient.CreateAuthorizedCertificate</c> and /// <c>AuthorizedCertificatesClient.CreateAuthorizedCertificateAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateAuthorizedCertificateSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AuthorizedCertificatesClient.UpdateAuthorizedCertificate</c> and /// <c>AuthorizedCertificatesClient.UpdateAuthorizedCertificateAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings UpdateAuthorizedCertificateSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AuthorizedCertificatesClient.DeleteAuthorizedCertificate</c> and /// <c>AuthorizedCertificatesClient.DeleteAuthorizedCertificateAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteAuthorizedCertificateSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AuthorizedCertificatesSettings"/> object.</returns> public AuthorizedCertificatesSettings Clone() => new AuthorizedCertificatesSettings(this); } /// <summary> /// Builder class for <see cref="AuthorizedCertificatesClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class AuthorizedCertificatesClientBuilder : gaxgrpc::ClientBuilderBase<AuthorizedCertificatesClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AuthorizedCertificatesSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AuthorizedCertificatesClientBuilder() { UseJwtAccessWithScopes = AuthorizedCertificatesClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AuthorizedCertificatesClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AuthorizedCertificatesClient> task); /// <summary>Builds the resulting client.</summary> public override AuthorizedCertificatesClient Build() { AuthorizedCertificatesClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AuthorizedCertificatesClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AuthorizedCertificatesClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AuthorizedCertificatesClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AuthorizedCertificatesClient.Create(callInvoker, Settings); } private async stt::Task<AuthorizedCertificatesClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AuthorizedCertificatesClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AuthorizedCertificatesClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AuthorizedCertificatesClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AuthorizedCertificatesClient.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>AuthorizedCertificates client wrapper, for convenient use.</summary> /// <remarks> /// Manages SSL certificates a user is authorized to administer. A user can /// administer any SSL certificates applicable to their authorized domains. /// </remarks> public abstract partial class AuthorizedCertificatesClient { /// <summary> /// The default endpoint for the AuthorizedCertificates service, which is a host of "appengine.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "appengine.googleapis.com:443"; /// <summary>The default AuthorizedCertificates scopes.</summary> /// <remarks> /// The default AuthorizedCertificates scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/appengine.admin</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform.read-only</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/appengine.admin", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", }); 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="AuthorizedCertificatesClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="AuthorizedCertificatesClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AuthorizedCertificatesClient"/>.</returns> public static stt::Task<AuthorizedCertificatesClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AuthorizedCertificatesClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AuthorizedCertificatesClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="AuthorizedCertificatesClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AuthorizedCertificatesClient"/>.</returns> public static AuthorizedCertificatesClient Create() => new AuthorizedCertificatesClientBuilder().Build(); /// <summary> /// Creates a <see cref="AuthorizedCertificatesClient"/> 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="AuthorizedCertificatesSettings"/>.</param> /// <returns>The created <see cref="AuthorizedCertificatesClient"/>.</returns> internal static AuthorizedCertificatesClient Create(grpccore::CallInvoker callInvoker, AuthorizedCertificatesSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AuthorizedCertificates.AuthorizedCertificatesClient grpcClient = new AuthorizedCertificates.AuthorizedCertificatesClient(callInvoker); return new AuthorizedCertificatesClientImpl(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 AuthorizedCertificates client</summary> public virtual AuthorizedCertificates.AuthorizedCertificatesClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Lists all SSL certificates the user is authorized to administer. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="AuthorizedCertificate"/> resources.</returns> public virtual gax::PagedEnumerable<ListAuthorizedCertificatesResponse, AuthorizedCertificate> ListAuthorizedCertificates(ListAuthorizedCertificatesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists all SSL certificates the user is authorized to administer. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="AuthorizedCertificate"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListAuthorizedCertificatesResponse, AuthorizedCertificate> ListAuthorizedCertificatesAsync(ListAuthorizedCertificatesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the specified SSL certificate. /// </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 AuthorizedCertificate GetAuthorizedCertificate(GetAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the specified SSL certificate. /// </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<AuthorizedCertificate> GetAuthorizedCertificateAsync(GetAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the specified SSL certificate. /// </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<AuthorizedCertificate> GetAuthorizedCertificateAsync(GetAuthorizedCertificateRequest request, st::CancellationToken cancellationToken) => GetAuthorizedCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Uploads the specified SSL certificate. /// </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 AuthorizedCertificate CreateAuthorizedCertificate(CreateAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Uploads the specified SSL certificate. /// </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<AuthorizedCertificate> CreateAuthorizedCertificateAsync(CreateAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Uploads the specified SSL certificate. /// </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<AuthorizedCertificate> CreateAuthorizedCertificateAsync(CreateAuthorizedCertificateRequest request, st::CancellationToken cancellationToken) => CreateAuthorizedCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Updates the specified SSL certificate. To renew a certificate and maintain /// its existing domain mappings, update `certificate_data` with a new /// certificate. The new certificate must be applicable to the same domains as /// the original certificate. The certificate `display_name` may also be /// updated. /// </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 AuthorizedCertificate UpdateAuthorizedCertificate(UpdateAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Updates the specified SSL certificate. To renew a certificate and maintain /// its existing domain mappings, update `certificate_data` with a new /// certificate. The new certificate must be applicable to the same domains as /// the original certificate. The certificate `display_name` may also be /// updated. /// </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<AuthorizedCertificate> UpdateAuthorizedCertificateAsync(UpdateAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Updates the specified SSL certificate. To renew a certificate and maintain /// its existing domain mappings, update `certificate_data` with a new /// certificate. The new certificate must be applicable to the same domains as /// the original certificate. The certificate `display_name` may also be /// updated. /// </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<AuthorizedCertificate> UpdateAuthorizedCertificateAsync(UpdateAuthorizedCertificateRequest request, st::CancellationToken cancellationToken) => UpdateAuthorizedCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the specified SSL certificate. /// </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 void DeleteAuthorizedCertificate(DeleteAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified SSL certificate. /// </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 DeleteAuthorizedCertificateAsync(DeleteAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the specified SSL certificate. /// </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 DeleteAuthorizedCertificateAsync(DeleteAuthorizedCertificateRequest request, st::CancellationToken cancellationToken) => DeleteAuthorizedCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AuthorizedCertificates client wrapper implementation, for convenient use.</summary> /// <remarks> /// Manages SSL certificates a user is authorized to administer. A user can /// administer any SSL certificates applicable to their authorized domains. /// </remarks> public sealed partial class AuthorizedCertificatesClientImpl : AuthorizedCertificatesClient { private readonly gaxgrpc::ApiCall<ListAuthorizedCertificatesRequest, ListAuthorizedCertificatesResponse> _callListAuthorizedCertificates; private readonly gaxgrpc::ApiCall<GetAuthorizedCertificateRequest, AuthorizedCertificate> _callGetAuthorizedCertificate; private readonly gaxgrpc::ApiCall<CreateAuthorizedCertificateRequest, AuthorizedCertificate> _callCreateAuthorizedCertificate; private readonly gaxgrpc::ApiCall<UpdateAuthorizedCertificateRequest, AuthorizedCertificate> _callUpdateAuthorizedCertificate; private readonly gaxgrpc::ApiCall<DeleteAuthorizedCertificateRequest, wkt::Empty> _callDeleteAuthorizedCertificate; /// <summary> /// Constructs a client wrapper for the AuthorizedCertificates service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AuthorizedCertificatesSettings"/> used within this client. /// </param> public AuthorizedCertificatesClientImpl(AuthorizedCertificates.AuthorizedCertificatesClient grpcClient, AuthorizedCertificatesSettings settings) { GrpcClient = grpcClient; AuthorizedCertificatesSettings effectiveSettings = settings ?? AuthorizedCertificatesSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListAuthorizedCertificates = clientHelper.BuildApiCall<ListAuthorizedCertificatesRequest, ListAuthorizedCertificatesResponse>(grpcClient.ListAuthorizedCertificatesAsync, grpcClient.ListAuthorizedCertificates, effectiveSettings.ListAuthorizedCertificatesSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListAuthorizedCertificates); Modify_ListAuthorizedCertificatesApiCall(ref _callListAuthorizedCertificates); _callGetAuthorizedCertificate = clientHelper.BuildApiCall<GetAuthorizedCertificateRequest, AuthorizedCertificate>(grpcClient.GetAuthorizedCertificateAsync, grpcClient.GetAuthorizedCertificate, effectiveSettings.GetAuthorizedCertificateSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetAuthorizedCertificate); Modify_GetAuthorizedCertificateApiCall(ref _callGetAuthorizedCertificate); _callCreateAuthorizedCertificate = clientHelper.BuildApiCall<CreateAuthorizedCertificateRequest, AuthorizedCertificate>(grpcClient.CreateAuthorizedCertificateAsync, grpcClient.CreateAuthorizedCertificate, effectiveSettings.CreateAuthorizedCertificateSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callCreateAuthorizedCertificate); Modify_CreateAuthorizedCertificateApiCall(ref _callCreateAuthorizedCertificate); _callUpdateAuthorizedCertificate = clientHelper.BuildApiCall<UpdateAuthorizedCertificateRequest, AuthorizedCertificate>(grpcClient.UpdateAuthorizedCertificateAsync, grpcClient.UpdateAuthorizedCertificate, effectiveSettings.UpdateAuthorizedCertificateSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callUpdateAuthorizedCertificate); Modify_UpdateAuthorizedCertificateApiCall(ref _callUpdateAuthorizedCertificate); _callDeleteAuthorizedCertificate = clientHelper.BuildApiCall<DeleteAuthorizedCertificateRequest, wkt::Empty>(grpcClient.DeleteAuthorizedCertificateAsync, grpcClient.DeleteAuthorizedCertificate, effectiveSettings.DeleteAuthorizedCertificateSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteAuthorizedCertificate); Modify_DeleteAuthorizedCertificateApiCall(ref _callDeleteAuthorizedCertificate); 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_ListAuthorizedCertificatesApiCall(ref gaxgrpc::ApiCall<ListAuthorizedCertificatesRequest, ListAuthorizedCertificatesResponse> call); partial void Modify_GetAuthorizedCertificateApiCall(ref gaxgrpc::ApiCall<GetAuthorizedCertificateRequest, AuthorizedCertificate> call); partial void Modify_CreateAuthorizedCertificateApiCall(ref gaxgrpc::ApiCall<CreateAuthorizedCertificateRequest, AuthorizedCertificate> call); partial void Modify_UpdateAuthorizedCertificateApiCall(ref gaxgrpc::ApiCall<UpdateAuthorizedCertificateRequest, AuthorizedCertificate> call); partial void Modify_DeleteAuthorizedCertificateApiCall(ref gaxgrpc::ApiCall<DeleteAuthorizedCertificateRequest, wkt::Empty> call); partial void OnConstruction(AuthorizedCertificates.AuthorizedCertificatesClient grpcClient, AuthorizedCertificatesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AuthorizedCertificates client</summary> public override AuthorizedCertificates.AuthorizedCertificatesClient GrpcClient { get; } partial void Modify_ListAuthorizedCertificatesRequest(ref ListAuthorizedCertificatesRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetAuthorizedCertificateRequest(ref GetAuthorizedCertificateRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_CreateAuthorizedCertificateRequest(ref CreateAuthorizedCertificateRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_UpdateAuthorizedCertificateRequest(ref UpdateAuthorizedCertificateRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteAuthorizedCertificateRequest(ref DeleteAuthorizedCertificateRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Lists all SSL certificates the user is authorized to administer. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="AuthorizedCertificate"/> resources.</returns> public override gax::PagedEnumerable<ListAuthorizedCertificatesResponse, AuthorizedCertificate> ListAuthorizedCertificates(ListAuthorizedCertificatesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListAuthorizedCertificatesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListAuthorizedCertificatesRequest, ListAuthorizedCertificatesResponse, AuthorizedCertificate>(_callListAuthorizedCertificates, request, callSettings); } /// <summary> /// Lists all SSL certificates the user is authorized to administer. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="AuthorizedCertificate"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListAuthorizedCertificatesResponse, AuthorizedCertificate> ListAuthorizedCertificatesAsync(ListAuthorizedCertificatesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListAuthorizedCertificatesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListAuthorizedCertificatesRequest, ListAuthorizedCertificatesResponse, AuthorizedCertificate>(_callListAuthorizedCertificates, request, callSettings); } /// <summary> /// Gets the specified SSL certificate. /// </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 AuthorizedCertificate GetAuthorizedCertificate(GetAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAuthorizedCertificateRequest(ref request, ref callSettings); return _callGetAuthorizedCertificate.Sync(request, callSettings); } /// <summary> /// Gets the specified SSL certificate. /// </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<AuthorizedCertificate> GetAuthorizedCertificateAsync(GetAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAuthorizedCertificateRequest(ref request, ref callSettings); return _callGetAuthorizedCertificate.Async(request, callSettings); } /// <summary> /// Uploads the specified SSL certificate. /// </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 AuthorizedCertificate CreateAuthorizedCertificate(CreateAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateAuthorizedCertificateRequest(ref request, ref callSettings); return _callCreateAuthorizedCertificate.Sync(request, callSettings); } /// <summary> /// Uploads the specified SSL certificate. /// </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<AuthorizedCertificate> CreateAuthorizedCertificateAsync(CreateAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateAuthorizedCertificateRequest(ref request, ref callSettings); return _callCreateAuthorizedCertificate.Async(request, callSettings); } /// <summary> /// Updates the specified SSL certificate. To renew a certificate and maintain /// its existing domain mappings, update `certificate_data` with a new /// certificate. The new certificate must be applicable to the same domains as /// the original certificate. The certificate `display_name` may also be /// updated. /// </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 AuthorizedCertificate UpdateAuthorizedCertificate(UpdateAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UpdateAuthorizedCertificateRequest(ref request, ref callSettings); return _callUpdateAuthorizedCertificate.Sync(request, callSettings); } /// <summary> /// Updates the specified SSL certificate. To renew a certificate and maintain /// its existing domain mappings, update `certificate_data` with a new /// certificate. The new certificate must be applicable to the same domains as /// the original certificate. The certificate `display_name` may also be /// updated. /// </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<AuthorizedCertificate> UpdateAuthorizedCertificateAsync(UpdateAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UpdateAuthorizedCertificateRequest(ref request, ref callSettings); return _callUpdateAuthorizedCertificate.Async(request, callSettings); } /// <summary> /// Deletes the specified SSL certificate. /// </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 void DeleteAuthorizedCertificate(DeleteAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteAuthorizedCertificateRequest(ref request, ref callSettings); _callDeleteAuthorizedCertificate.Sync(request, callSettings); } /// <summary> /// Deletes the specified SSL certificate. /// </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 DeleteAuthorizedCertificateAsync(DeleteAuthorizedCertificateRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteAuthorizedCertificateRequest(ref request, ref callSettings); return _callDeleteAuthorizedCertificate.Async(request, callSettings); } } public partial class ListAuthorizedCertificatesRequest : gaxgrpc::IPageRequest { } public partial class ListAuthorizedCertificatesResponse : gaxgrpc::IPageResponse<AuthorizedCertificate> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<AuthorizedCertificate> GetEnumerator() => Certificates.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
using Moq; using ScriptCs.Contracts; using Should; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using Xunit; namespace ScriptCs.ComponentModel.Composition.Test { public class ScriptCsCatalogFacts { public class InitializeScriptsFiles { [Fact] public void ShouldWorkWithSimpleScript() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert mefHost.Plugins.ShouldNotBeNull(); mefHost.Plugins.Count.ShouldEqual(1); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); } [Fact] public void ShouldWorkWithSimpleScriptAndReference() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName }, GetOptions( fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScriptWithoutReference).Object, references: new[] { typeof(IDoSomething) })); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert mefHost.Plugins.ShouldNotBeNull(); mefHost.Plugins.Count.ShouldEqual(1); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); } [Fact] public void ShouldWorkWithMultipleScripts() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\DoubleScript.csx"; var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName, scriptName2 }, GetOptions(fileSystem: GetMockFileSystem(new[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert mefHost.Plugins.ShouldNotBeNull(); mefHost.Plugins.Count.ShouldEqual(2); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); mefHost.Plugins[1].DoSomething().ShouldEqual("Double"); } [Fact] public void ShouldWorkWithMultipleScriptsNotMerged() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\DoubleScript.csx"; var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName, scriptName2 }, GetOptions(fileSystem: GetMockFileSystem(new[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object, keepScriptsSeparated: true)); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert mefHost.Plugins.ShouldNotBeNull(); mefHost.Plugins.Count.ShouldEqual(2); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); mefHost.Plugins[1].DoSomething().ShouldEqual("Double"); } [Fact] public void ShouldThrowExceptionIfNullPassedForScriptsFiles() { // act var exception = Assert.Throws<ArgumentNullException>(() => new ScriptCsCatalog((IEnumerable<string>)null)); // assert exception.ParamName.ShouldEqual("scriptFiles"); } [Fact] public void ShouldThrowExceptionIfNoScriptsFilesArePassed() { // act var exception = Assert.Throws<ArgumentNullException>(() => new ScriptCsCatalog(new string[0])); // assert exception.ParamName.ShouldEqual("scriptFiles"); } [Fact] public void ShouldThrowExceptionIfNullPassedForOptions() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; // act var exception = Assert.Throws<ArgumentNullException>(() => new ScriptCsCatalog(new[] { scriptName }, null)); // assert exception.ParamName.ShouldEqual("options"); } [Fact] public void ShouldThrowExceptionIfScriptFileDoesntExists() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; // act var exception = Assert.Throws<FileNotFoundException>(() => new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(new string[0], new string[0]).Object))); // assert exception.FileName.ShouldEqual(@"c:\workingdirectory\SimpleScript.csx"); exception.Message.ShouldEqual(@"Script: 'c:\workingdirectory\SimpleScript.csx' does not exist"); } [Fact] public void ShouldThrowExceptionIfScriptDoesntCompile() { // arrange var scriptName = @"c:\workingdirectory\Script.csx"; // act try { new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.CompileExceptionScript).Object)); } catch (Exception exception) { // assert exception.Message.ShouldEqual(@"c:\workingdirectory\Script.csx(6,24): error CS1002: ; expected"); } } [Fact] public void ShouldThrowExceptionIfScriptThrowExceptionDuringExecution() { // arrange var scriptName = @"c:\workingdirectory\Script.csx"; // act var exception = Assert.Throws<Exception>(() => new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.ExecutionExceptionScript).Object))); // assert exception.Message.ShouldEqual(@"Exception from script execution"); } } public class InitializeFolder { [Fact] public void ShouldWorkWithRelativeFolder() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\_plugins\DoubleScript.csx"; var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(new string[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert mefHost.Plugins.ShouldNotBeNull(); mefHost.Plugins.Count.ShouldEqual(2); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); mefHost.Plugins[1].DoSomething().ShouldEqual("Double"); } [Fact] public void ShouldWorkWithAbsoluteFolder() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\_plugins\DoubleScript.csx"; var scriptCsCatalog = new ScriptCsCatalog(@"c:\workingdirectory\_plugins", GetOptions(fileSystem: GetMockFileSystem(new string[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert mefHost.Plugins.ShouldNotBeNull(); mefHost.Plugins.Count.ShouldEqual(2); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); mefHost.Plugins[1].DoSomething().ShouldEqual("Double"); } [Fact] public void ShouldWorkWithReferences() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScriptWithoutReference).Object, references: new[] { typeof(IDoSomething) })); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert mefHost.Plugins.ShouldNotBeNull(); mefHost.Plugins.Count.ShouldEqual(1); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); } [Fact] public void ShouldWorkWithSearchPattern() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.script"; var scriptName2 = @"c:\workingdirectory\_plugins\DoubleScript.script"; var scriptCsCatalog = new ScriptCsCatalog("_plugins", "*.script", GetOptions(fileSystem: GetMockFileSystem(new string[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert mefHost.Plugins.ShouldNotBeNull(); mefHost.Plugins.Count.ShouldEqual(2); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); mefHost.Plugins[1].DoSomething().ShouldEqual("Double"); } [Fact] public void ShouldThrowExceptionIfNullPassedForFileSystem() { // act var exception = Assert.Throws<ArgumentNullException>(() => new ScriptCsCatalog("_plugins", "*.csx", null)); // assert exception.ParamName.ShouldEqual("options"); } [Fact] public void ShouldThrowExceptionIfNullPassedForPath() { // act var exception = Assert.Throws<ArgumentNullException>(() => new ScriptCsCatalog((string)null)); // assert exception.ParamName.ShouldEqual("path"); } [Fact] public void ShouldThrowExceptionIfEmptyStringPassedForPath() { // act var exception = Assert.Throws<ArgumentNullException>(() => new ScriptCsCatalog(string.Empty)); // assert exception.ParamName.ShouldEqual("path"); } [Fact] public void ShouldThrowExceptionIfNullPassedForSearchPattern() { // act var exception = Assert.Throws<ArgumentNullException>(() => new ScriptCsCatalog("_plugins", (string)null)); // assert exception.ParamName.ShouldEqual("searchPattern"); } [Fact] public void ShouldThrowExceptionIfEmptyStringPassedForSearchPattern() { // act var exception = Assert.Throws<ArgumentNullException>(() => new ScriptCsCatalog("_plugins", string.Empty)); // assert exception.ParamName.ShouldEqual("searchPattern"); } [Fact] public void ShouldThrowExceptionIfFolderDoesntExists() { // act var exception = Assert.Throws<DirectoryNotFoundException>(() => new ScriptCsCatalog("fakeFolder", GetOptions(fileSystem: GetMockFileSystem(new string[0], new string[0]).Object))); // assert exception.Message.ShouldEqual(@"Scripts folder: 'c:\workingdirectory\fakeFolder' does not exist"); } } public class ToStringMethod { [Fact] public void ShouldReturnNameAndPath_ScriptsFiles() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.ToString().ShouldEqual("ScriptCsCatalog (Path=\"\")"); } [Fact] public void ShouldReturnNameAndPath_ScriptsFolder() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.ToString().ShouldEqual("ScriptCsCatalog (Path=\"_plugins\")"); } } public class DisplayNameProperty { [Fact] public void ShouldReturnNameAndPath_ScriptsFiles() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.DisplayName.ShouldEqual("ScriptCsCatalog (Path=\"\")"); } [Fact] public void ShouldReturnNameAndPath_ScriptsFolder() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.DisplayName.ShouldEqual("ScriptCsCatalog (Path=\"_plugins\")"); } } public class OriginProperty { [Fact] public void ShouldReturnNull() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.Origin.ShouldBeNull(); } } public class FullPathProperty { [Fact] public void ShouldReturnNullIfScriptsFilesAreProvided() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.FullPath.ShouldBeNull(); } [Fact] public void ShouldReturnFullPathIfFolderIsProvided() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.FullPath.ShouldEqual(@"c:\workingdirectory\_plugins"); } } public class PathProperty { [Fact] public void ShouldReturnNullIfScriptsFilesAreProvided() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.Path.ShouldBeNull(); } [Fact] public void ShouldReturnPathIfFolderIsProvided() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.Path.ShouldEqual("_plugins"); } } public class SearchPatternProperty { [Fact] public void ShouldReturnNullIfScriptsFilesAreProvided() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName }, GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.SearchPattern.ShouldBeNull(); } [Fact] public void ShouldReturnDefaultSearchPatternIfFolderIsProvided() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.SearchPattern.ShouldEqual("*.csx"); } [Fact] public void ShouldReturnSearchPatternIfFolderAndSearchPatternAreProvided() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", "*.script", GetOptions(fileSystem: GetMockFileSystem(scriptName, Scripts.SimpleScript).Object)); // assert scriptCsCatalog.SearchPattern.ShouldEqual("*.script"); } } public class LoadedFilesProperty { [Fact] public void ShouldReturnAllScriptsFilesIfScriptsFilesAreProvided() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\DoubleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName, scriptName2 }, GetOptions(fileSystem: GetMockFileSystem(new string[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); // assert scriptCsCatalog.LoadedFiles.Count.ShouldEqual(2); scriptCsCatalog.LoadedFiles[0].ShouldEqual(@"c:\workingdirectory\SimpleScript.csx"); scriptCsCatalog.LoadedFiles[1].ShouldEqual(@"c:\workingdirectory\DoubleScript.csx"); } [Fact] public void ShouldReturnAllScriptsFilesIfFolderIsProvided() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\_plugins\DoubleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(new string[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); // assert scriptCsCatalog.LoadedFiles.Count.ShouldEqual(2); scriptCsCatalog.LoadedFiles[0].ShouldEqual(@"c:\workingdirectory\_plugins\SimpleScript.csx"); scriptCsCatalog.LoadedFiles[1].ShouldEqual(@"c:\workingdirectory\_plugins\DoubleScript.csx"); } } public class GetEnumeratorMethod { [Fact] public void ShouldEnumerateAllPartsIfScriptsFilesAreProvided() { // arrange var scriptName = @"c:\workingdirectory\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\DoubleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog(new[] { scriptName, scriptName2 }, GetOptions(fileSystem: GetMockFileSystem(new string[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); // assert var enumerator = scriptCsCatalog.GetEnumerator(); enumerator.ShouldNotBeNull(); enumerator.Current.ShouldBeNull(); enumerator.MoveNext().ShouldBeTrue(); enumerator.Current.ShouldNotBeNull(); enumerator.Current.ToString().ShouldEqual("Submission#0+SimpleSomething"); enumerator.MoveNext().ShouldBeTrue(); enumerator.Current.ShouldNotBeNull(); enumerator.Current.ToString().ShouldEqual("Submission#0+DoubleSomething"); enumerator.MoveNext().ShouldBeFalse(); enumerator.Current.ShouldBeNull(); } [Fact] public void ShouldEnumerateAllPartsFilesIfFolderIsProvided() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\_plugins\DoubleScript.csx"; // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(new string[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); // assert var enumerator = scriptCsCatalog.GetEnumerator(); enumerator.ShouldNotBeNull(); enumerator.Current.ShouldBeNull(); enumerator.MoveNext().ShouldBeTrue(); enumerator.Current.ShouldNotBeNull(); enumerator.Current.ToString().ShouldEqual("Submission#0+SimpleSomething"); enumerator.MoveNext().ShouldBeTrue(); enumerator.Current.ShouldNotBeNull(); enumerator.Current.ToString().ShouldEqual("Submission#0+DoubleSomething"); enumerator.MoveNext().ShouldBeFalse(); enumerator.Current.ShouldBeNull(); } [Theory] [InlineData(false)] [InlineData(true)] public void ShouldNotThrowExceptionIfFolderProvidedIsEmpty(bool keepScriptSeparated) { // act var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(new string[0], new string[0]).Object, keepScriptsSeparated: keepScriptSeparated)); // assert var enumerator = scriptCsCatalog.GetEnumerator(); enumerator.ShouldNotBeNull(); enumerator.Current.ShouldBeNull(); enumerator.MoveNext().ShouldBeFalse(); } } public class RefresheMethod { [Fact] public void ShouldThrowExceptionIfAlreadyDisposed() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\_plugins\DoubleScript.csx"; var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: GetMockFileSystem(new[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }).Object)); scriptCsCatalog.Dispose(); // act var exception = Assert.Throws<ObjectDisposedException>(() => scriptCsCatalog.Refresh()); exception.ObjectName.ShouldEqual("ScriptCsCatalog"); } [Theory] [InlineData(false)] [InlineData(true)] public void ShouldRefreshPartsIfScriptsAreAdded(bool keepScriptSeparated) { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var scriptName2 = @"c:\workingdirectory\_plugins\DoubleScript.csx"; var fileSystem = GetMockFileSystem(new string[0], new string[0]); var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: fileSystem.Object, keepScriptsSeparated: keepScriptSeparated)); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert scriptCsCatalog.LoadedFiles.Count.ShouldEqual(0); mefHost.Plugins.Count.ShouldEqual(0); // arrange UpdateFileSystem(fileSystem, new[] { scriptName, scriptName2 }, new[] { Scripts.SimpleScript, Scripts.DoubleScript }); // act scriptCsCatalog.Refresh(); // assert scriptCsCatalog.LoadedFiles.Count.ShouldEqual(2); mefHost.Plugins.Count.ShouldEqual(2); } [Fact] public void ShouldRefreshPartsIfScriptIsModified() { // arrange var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var fileSystem = GetMockFileSystem(scriptName, Scripts.SimpleScript); var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: fileSystem.Object)); // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert scriptCsCatalog.LoadedFiles.Count.ShouldEqual(1); mefHost.Plugins.Count.ShouldEqual(1); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); // arrange UpdateFileSystem(fileSystem, new[] { scriptName }, new[] { Scripts.DoubleScript }); // act scriptCsCatalog.Refresh(); // assert scriptCsCatalog.LoadedFiles.Count.ShouldEqual(1); mefHost.Plugins.Count.ShouldEqual(1); mefHost.Plugins[0].DoSomething().ShouldEqual("Double"); } [Fact] public void ShouldRaiseOnchangedAndOnChanging() { // arrange bool onChangedCalled = false; bool onChangingCalled = false; ComposablePartCatalogChangeEventArgs onChangedEventArgs = null; ComposablePartCatalogChangeEventArgs onChangingEventArgs = null; var scriptName = @"c:\workingdirectory\_plugins\SimpleScript.csx"; var fileSystem = GetMockFileSystem(scriptName, Scripts.SimpleScript); var scriptCsCatalog = new ScriptCsCatalog("_plugins", GetOptions(fileSystem: fileSystem.Object)); scriptCsCatalog.Changing += (object sender, ComposablePartCatalogChangeEventArgs e) => { onChangingCalled = true; onChangingEventArgs = e; }; scriptCsCatalog.Changed += (object sender, ComposablePartCatalogChangeEventArgs e) => { onChangedCalled = true; onChangedEventArgs = e; }; // act var mefHost = GetComposedMefHost(scriptCsCatalog); // assert scriptCsCatalog.LoadedFiles.Count.ShouldEqual(1); mefHost.Plugins.Count.ShouldEqual(1); mefHost.Plugins[0].DoSomething().ShouldEqual("Simple"); // arrange UpdateFileSystem(fileSystem, new[] { scriptName }, new[] { Scripts.DoubleScript }); // act scriptCsCatalog.Refresh(); // assert scriptCsCatalog.LoadedFiles.Count.ShouldEqual(1); mefHost.Plugins.Count.ShouldEqual(1); mefHost.Plugins[0].DoSomething().ShouldEqual("Double"); onChangingCalled.ShouldBeTrue(); onChangingEventArgs.ShouldNotBeNull(); onChangingEventArgs.AtomicComposition.ShouldNotBeNull(); onChangingEventArgs.AddedDefinitions.ShouldNotBeNull(); onChangingEventArgs.AddedDefinitions.ShouldNotBeEmpty(); onChangingEventArgs.AddedDefinitions.Count().ShouldEqual(1); onChangingEventArgs.AddedDefinitions.First().ToString().ShouldEqual("Submission#0+DoubleSomething"); onChangingEventArgs.RemovedDefinitions.ShouldNotBeNull(); onChangingEventArgs.RemovedDefinitions.ShouldNotBeEmpty(); onChangingEventArgs.RemovedDefinitions.Count().ShouldEqual(1); onChangingEventArgs.RemovedDefinitions.First().ToString().ShouldEqual("Submission#0+SimpleSomething"); onChangedCalled.ShouldBeTrue(); onChangedEventArgs.ShouldNotBeNull(); onChangedEventArgs.AtomicComposition.ShouldBeNull(); onChangedEventArgs.AddedDefinitions.ShouldNotBeNull(); onChangedEventArgs.AddedDefinitions.ShouldNotBeEmpty(); onChangedEventArgs.AddedDefinitions.Count().ShouldEqual(1); onChangedEventArgs.AddedDefinitions.First().ToString().ShouldEqual("Submission#0+DoubleSomething"); onChangedEventArgs.RemovedDefinitions.ShouldNotBeNull(); onChangedEventArgs.RemovedDefinitions.ShouldNotBeEmpty(); onChangedEventArgs.RemovedDefinitions.Count().ShouldEqual(1); onChangedEventArgs.RemovedDefinitions.First().ToString().ShouldEqual("Submission#0+SimpleSomething"); } } private static MEFHost GetComposedMefHost(ScriptCsCatalog catalog) { // arrange var container = new CompositionContainer(catalog); var batch = new CompositionBatch(); var mefHost = new MEFHost(); batch.AddPart(mefHost); // act container.Compose(batch); return mefHost; } private static ScriptCsCatalogOptions GetOptions(string[] scriptArgs = null, Type[] references = null, IFileSystem fileSystem = null, bool keepScriptsSeparated = false) { return new ScriptCsCatalogOptions { FileSystem = fileSystem, References = references, ScriptArgs = scriptArgs, KeepScriptsSeparated = keepScriptsSeparated }; } private static Mock<IFileSystem> GetMockFileSystem(string fileName, string fileContent) { return GetMockFileSystem(new[] { fileName }, new string[] { fileContent }); } private static Mock<IFileSystem> GetMockFileSystem(string[] fileNames, string[] fileContents) { var fileSystem = new Mock<IFileSystem>(); fileSystem.SetupGet(f => f.PackagesFile).Returns("scriptcs_packages.config"); fileSystem.SetupGet(f => f.PackagesFolder).Returns("scriptcs_packages"); fileSystem.SetupGet(f => f.BinFolder).Returns("scriptcs_bin"); fileSystem.SetupGet(f => f.DllCacheFolder).Returns(".scriptcs_cache"); fileSystem.SetupGet(f => f.NugetFile).Returns("scriptcs_nuget.config"); fileSystem.SetupGet(f => f.GlobalFolder).Returns(@"c:\workingdirectory"); fileSystem.SetupGet(f => f.HostBin).Returns(Environment.CurrentDirectory); fileSystem.SetupGet(f => f.CurrentDirectory).Returns(@"c:\workingdirectory"); fileSystem.Setup(f => f.GetWorkingDirectory(It.IsAny<string>())).Returns(@"c:\workingdirectory"); fileSystem.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns<string>((directory) => directory.EndsWith("_plugins")); fileSystem.SetupGet(f => f.NewLine).Returns(Environment.NewLine); fileSystem.Setup(f => f.GetFullPath(It.IsAny<string>())).Returns<string>((path) => path); fileSystem.Setup(f => f.SplitLines(It.IsAny<string>())).Returns<string>((file) => file.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)); fileSystem.Setup(f => f.EnumerateFiles(@"c:\workingdirectory\_plugins", It.IsAny<string>(), SearchOption.AllDirectories)) .Returns<string, string, SearchOption>((directory, searchPattern, searchOption) => fileNames.Where(file => file.EndsWith(Path.GetExtension(searchPattern)))); for (int i = 0; i < fileNames.Length; i++) { fileSystem.Setup(f => f.FileExists(fileNames[i])).Returns(true); fileSystem.Setup(f => f.ReadFileLines(fileNames[i])).Returns(fileContents[i].Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)); } return fileSystem; } private static void UpdateFileSystem(Mock<IFileSystem> fileSystem, string[] fileNames, string[] fileContents) { fileSystem.Setup(f => f.EnumerateFiles(@"c:\workingdirectory\_plugins", It.IsAny<string>(), SearchOption.AllDirectories)) .Returns<string, string, SearchOption>((directory, searchPattern, searchOption) => fileNames.Where(file => file.EndsWith(Path.GetExtension(searchPattern)))); for (int i = 0; i < fileNames.Length; i++) { fileSystem.Setup(f => f.FileExists(fileNames[i])).Returns(true); fileSystem.Setup(f => f.ReadFileLines(fileNames[i])).Returns(fileContents[i].Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)); } } } }
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 Mobet.Demo.ApiDocument.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections; using System.IO; using System.Xml; using System.Xml.Serialization; namespace Lewis.SST.SQLObjects { /// <summary> /// Collection of Column Objects. Includes a method to serialize the entire collection. <seealso cref="COLUMN"/> /// </summary> [Serializable()] public class ColumnCollection : CollectionBase { private string _tableName; private Lewis.SST.SQLObjects.COLUMN.ColumnAction _action; /// <summary> /// Initializes a new instance of the <see cref="ColumnCollection"/> class. Default constructor required for serialization. /// </summary> public ColumnCollection(){// Default constructor required for serialization } /// <summary> /// Creates the ColumnCollection instance with a passed in tablename /// </summary> /// <param name="tableName">String value for the SQL table name.</param> public ColumnCollection(string tableName) { _tableName = tableName; } /// <summary> /// Gets or sets the Tablename for the ColumnCollection object /// </summary> public string TableName { get {return _tableName; } set {_tableName = value;} } /// <summary> /// Gets or sets the SchemaAction Enum for the ColumnCollection object. /// This is used in the serialization to create an Action attribute for each table object. /// </summary> public Lewis.SST.SQLObjects.COLUMN.ColumnAction SchemaAction { get{return _action;} set{_action = value;} } /// <summary> /// Adds a Column object to the ColumnCollection. /// </summary> /// <param name="_column">Column Object to add</param> public void Add(COLUMN _column) { List.Add( _column ); } /// <summary> /// Gets the current Column object index from the ColumnCollection. /// </summary> public COLUMN this[int Index] { get{return (COLUMN)List[Index];} } /// <summary> /// Checks to see if the Column object is contained in the ColumnCollection. /// </summary> /// <param name="value">Column Object to check for.</param> /// <returns>returns true if Column object is in the ColumnCollection.</returns> public bool Contains( COLUMN value ) { // If value is not of type Column, this will return false. return( List.Contains( value ) ); } /// <summary> /// Provides a method to serialize the entire column collection /// </summary> /// <param name="doc">Parent XMLDoc that the returned XML node will be appended to.</param> /// <returns>XMLNode that contains the serialized ColumnCollection.</returns> public XmlNode SerializeAsXmlNode(XmlDocument doc) { System.IO.MemoryStream ms = new MemoryStream(); XmlSerializer serializer = new XmlSerializer(typeof(ColumnCollection)); XmlTextReader xRead = null; XmlNode xTable = null; try { xTable = doc.CreateNode(XmlNodeType.Element, "TABLE", doc.NamespaceURI); // create child nodes to hold information from source xTable.AppendChild(doc.CreateNode(XmlNodeType.Element, "TABLE_NAME", doc.NamespaceURI)); xTable.AppendChild(doc.CreateNode(XmlNodeType.Element, "TABLE_OWNER", doc.NamespaceURI)); xTable.AppendChild(doc.CreateNode(XmlNodeType.Element, "TABLE_FILEGROUP", doc.NamespaceURI)); xTable.AppendChild(doc.CreateNode(XmlNodeType.Element, "TABLE_REFERENCE", doc.NamespaceURI)); xTable.AppendChild(doc.CreateNode(XmlNodeType.Element, "TABLE_CONSTRAINTS", doc.NamespaceURI)); xTable.AppendChild(doc.CreateNode(XmlNodeType.Element, "TABLE_ORIG_CONSTRAINTS", doc.NamespaceURI)); xTable.AppendChild(doc.CreateNode(XmlNodeType.Element, "TABLE_ORIG_REFERENCE", doc.NamespaceURI)); xTable.Attributes.Append((XmlAttribute)doc.CreateNode(XmlNodeType.Attribute, "Action", doc.NamespaceURI)); xTable.SelectSingleNode("TABLE_NAME").InnerXml = _tableName; xTable.Attributes["Action"].Value = _action.ToString(); serializer.Serialize(ms, this); ms.Position = 0; xRead = new XmlTextReader( ms ); xRead.MoveToContent(); string test = xRead.ReadInnerXml(); XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); docFrag.InnerXml = test; xTable.AppendChild(docFrag); } catch(Exception ex) { throw new Exception("ColumnCollection Serialization Error.", ex); } finally { ms.Close(); if (xRead != null) xRead.Close(); } return xTable; } } /// <summary> /// The Column Class, for creating an object that represents a single SQL table column's schema information. <seealso cref="ColumnCollection"/> /// </summary> [Serializable()] public class COLUMN { /// <summary> /// Column Action enumeration used to create an XML attribute for XML table nodes and column nodes. /// </summary> public enum ColumnAction { /// <summary> /// Indicates that this object/node should be added to the destination SQL server database. /// </summary> Add = 0, /// <summary> /// Indicates that this object/node should be altered or changed to the destination SQL server database. /// </summary> Alter, /// <summary> /// Indicates that this object/node should be dropped or removed to the destination SQL server database. /// </summary> Drop, /// <summary> /// Indicates that this object/node has no differences on the destination SQL server database from the source. /// </summary> UnChanged } private ColumnAction _action; private string _table_Name; private string _column_Name; private string _type; private string _base_type; private string _collation; private string _default_orig_name; private string _default_orig_value; private string _default_name; private string _default_owner; private string _default_value; private string _rule_name; private string _rule_owner; private string _rule_orig_name; private string _rule_orig_owner; private string _calc_Text; private string _computed; private string _identity; private string _rowguidcol; private string _ORIG_rowguidcol; private string _nullable; private string _notforrepl; private string _full_text; private string _ansipad; private int _length; private int _prec; private int _scale; private int _seed; private int _increment; /// <summary> /// main entry point to instantiate the column class object /// </summary> public COLUMN() { } /// <summary> /// main entry point to instantiate the column class object with a string Column_Name /// </summary> /// <param name="Column_Name"></param> public COLUMN(string Column_Name) { _column_Name = Column_Name; } /// <summary> /// Converts an XML node with the expected layout into a valid column object. /// </summary> /// <param name="xn">The XML column node to be converted into a column object.</param> /// <returns>The Column object result of the conversion process.</returns> public COLUMN Convert(XmlNode xn) { try { foreach(XmlNode x in xn.ChildNodes) { switch(x.Name.ToLower()) { case "table_name": { this.TABLE_NAME = x.InnerXml == null ? "" : x.InnerXml; break; } case "column_name": { this.Column_Name = x.InnerXml == null ? "" : x.InnerXml; break; } case "type": { this.Type = x.InnerXml == null ? "" : x.InnerXml; break; } case "collation": { this.Collation = x.InnerXml == null ? "" : x.InnerXml; break; } case "base_type": { this.Base_Type = x.InnerXml == null ? "" : x.InnerXml; break; } case "default_orig_name": { this.Default_Orig_Name = x.InnerXml == null ? "" : x.InnerXml; break; } case "default_name": { this.Default_Name = x.InnerXml == null ? "" : x.InnerXml; break; } case "default_owner": { this.Default_Owner = x.InnerXml == null ? "" : x.InnerXml; break; } case "default_value": { this.Default_Value = x.InnerXml == null ? "" : x.InnerXml; break; } case "default_orig_value": { this.Default_Orig_Value = x.InnerXml == null ? "" : x.InnerXml; break; } case "rule_name": { this.Rule_Name = x.InnerXml == null ? "" : x.InnerXml; break; } case "rule_owner": { this.Rule_Owner = x.InnerXml == null ? "" : x.InnerXml; break; } case "rule_orig_name": { this.Rule_Orig_Name = x.InnerXml == null ? "" : x.InnerXml; break; } case "rule_orig_owner": { this.Rule_Orig_Owner = x.InnerXml == null ? "" : x.InnerXml; break; } case "calc_text": { this.Calc_Text = x.InnerXml == null ? "" : x.InnerXml; break; } case "iscomputed": { this.isComputed = x.InnerXml.ToLower(); break; } case "isidentity": { this.isIdentity = x.InnerXml.ToLower(); break; } case "isrowguidcol": { this.isRowGuidCol = x.InnerXml.ToLower(); break; } case "orig_rowguidcol": { this.ORIG_RowGuidCol = x.InnerXml.ToLower(); break; } case "isnullable": { this.isNullable = x.InnerXml.ToLower(); break; } case "notforrepl": { this.NotforRepl = x.InnerXml.ToLower(); break; } case "fulltext": { this.FullText = x.InnerXml.ToLower(); break; } case "ansipad": { this.AnsiPad = x.InnerXml.ToLower(); break; } case "length": { this.Length = System.Convert.ToInt32( x.InnerXml.Length > 0 ? x.InnerXml : null ); break; } case "prec": { this.Prec = System.Convert.ToInt32( x.InnerXml.Length > 0 ? x.InnerXml : null ); break; } case "scale": { this.Scale = System.Convert.ToInt32( x.InnerXml.Length > 0 ? x.InnerXml : null ); break; } case "seed": { this.Seed = System.Convert.ToInt32( x.InnerXml.Length > 0 ? x.InnerXml : null ); break; } case "increment": { this.Increment = System.Convert.ToInt32( x.InnerXml.Length > 0 ? x.InnerXml : null ); break; } } } } catch(Exception ex) { throw new Exception("Column Conversion Error.", ex); } return this; } /// <summary> /// Gets or sets the Column Object's ColumnAction property. /// </summary> public ColumnAction Action { get{return _action;} set{_action = value;} } /// <summary> /// Gets or sets the Column Object's TABLE_NAME property. /// </summary> public string TABLE_NAME { get{return _table_Name;} set{_table_Name = value;} } /// <summary> /// Gets or sets the Column Object's Column_Name property. /// </summary> public string Column_Name { get{return _column_Name;} set{_column_Name = value;} } /// <summary> /// Gets or sets the Column Object's Type property. /// The Type property is the same as a UDDT type or /// if there is no UDDT bound to the Column, the type /// will be the same as the Base_Type. /// </summary> public string Type { get{return _type;} set{_type = value;} } /// <summary> /// Gets or sets the Column Object's Base_Type property. /// </summary> public string Base_Type { get{return _base_type;} set{_base_type = value;} } /// <summary> /// Gets or sets the Column Object's Length property. /// </summary> public int Length { get{return _length;} set{_length = value;} } /// <summary> /// Gets or sets the Column Object's Prec (precision) property. /// </summary> public int Prec { get{return _prec;} set{_prec = value;} } /// <summary> /// Gets or sets the Column Object's Scale property. /// </summary> public int Scale { get{return _scale;} set{_scale = value;} } /// <summary> /// Gets or sets the Column Object's Seed property. /// </summary> public int Seed { get{return _seed;} set{_seed = value;} } /// <summary> /// Gets or sets the Column Object's Increment property. /// </summary> public int Increment { get{return _increment;} set{_increment = value;} } /// <summary> /// Gets or sets the Column Object's isNullable property. /// </summary> public string isNullable { get{return _nullable;} set{_nullable = value;} } /// <summary> /// Gets or sets the Column Object's isIdentity property. /// </summary> public string isIdentity { get{return _identity;} set{_identity = value;} } /// <summary> /// Gets or sets the Column Object's isComputed property. /// </summary> public string isComputed { get{return _computed;} set{_computed = value;} } // /// <summary> // /// Gets or sets the Column Object's isIndexable property. // /// </summary> // public bool isIndexable // { // get{return _indexable;} // set{_indexable = value;} // } /// <summary> /// Gets or sets the Column Object's Default_Orig_Name property. /// This property is used to find the original default name so /// that it can be removed when altering or dropping the column. /// </summary> public string Default_Orig_Name { get{return _default_orig_name;} set{_default_orig_name = value;} } /// <summary> /// Gets or sets the Column Object's Default_Name property. /// </summary> public string Default_Name { get{return _default_name;} set{_default_name = value;} } /// <summary> /// Gets or sets the Column Object's Rule_Name property. /// </summary> public string Rule_Name { get{return _rule_name;} set{_rule_name = value;} } /// <summary> /// Gets or sets the Column Object's Rule_Owner property. /// </summary> public string Rule_Owner { get{return _rule_owner;} set{_rule_owner = value;} } /// <summary> /// Gets or sets the Column Object's Rule_Orig_Name property. /// </summary> public string Rule_Orig_Name { get{return _rule_orig_name;} set{_rule_orig_name = value;} } /// <summary> /// Gets or sets the Column Object's Rule_Orig_Owner property. /// </summary> public string Rule_Orig_Owner { get{return _rule_orig_owner;} set{_rule_orig_owner = value;} } /// <summary> /// Gets or sets the Column Object's Default_Owner property. /// </summary> public string Default_Owner { get{return _default_owner;} set{_default_owner = value;} } /// <summary> /// Gets or sets the Column Object's Default_Value property. /// </summary> public string Default_Value { get{return _default_value;} set{_default_value = value;} } /// <summary> /// Gets or sets the Column Object's Default_Orig_Value property. /// </summary> public string Default_Orig_Value { get{return _default_orig_value;} set{_default_orig_value = value;} } /// <summary> /// Gets or sets the Column Object's NotforRepl property. /// </summary> public string NotforRepl { get{return _notforrepl;} set{_notforrepl = value;} } /// <summary> /// Gets or sets a value indicating whether [row GUID col]. /// </summary> /// <value><c>true</c> if [row GUID col]; otherwise, <c>false</c>.</value> public string isRowGuidCol { get{return _rowguidcol;} set{_rowguidcol = value;} } /// <summary> /// Gets or sets a bool value indicating ORIG_isRowGuidCol is <c>true</c> or <c>false</c>. /// </summary> /// <value>if ORIG_RowGuidCol <c>true</c>; otherwise, <c>false</c>.</value> public string ORIG_RowGuidCol { get{return _ORIG_rowguidcol;} set{_ORIG_rowguidcol = value;} } /// <summary> /// Gets or sets the Column Object's FullText property. /// </summary> public string FullText { get{return _full_text;} set{_full_text = value;} } /// <summary> /// Gets or sets the Column Object's AnsiPad property. /// </summary> public string AnsiPad { get{return _ansipad;} set{_ansipad = value;} } /// <summary> /// Gets or sets the Column Object's Collation property. /// </summary> public string Collation { get{return _collation;} set{_collation = value;} } /// <summary> /// Gets or sets the calc_ text. /// </summary> /// <value>The calc_ text.</value> public string Calc_Text { get{return _calc_Text;} set{_calc_Text = value;} } } }
namespace Nancy.Diagnostics { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Bootstrapper; using Cookies; using Cryptography; using Helpers; using ModelBinding; using Nancy.Localization; using Nancy.Routing.Constraints; using Nancy.Routing.Trie; using Responses; using Responses.Negotiation; using Routing; using Nancy.Culture; public static class DiagnosticsHook { private static readonly CancellationToken CancellationToken = new CancellationToken(); private const string PipelineKey = "__Diagnostics"; internal const string ItemsKey = "DIAGS_REQUEST"; public static void Enable( DiagnosticsConfiguration diagnosticsConfiguration, IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable<IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource) { var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsConfiguration); var diagnosticsRouteCache = new RouteCache( diagnosticsModuleCatalog, new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource), new DefaultRouteSegmentExtractor(), new DefaultRouteDescriptionProvider(), cultureService, routeMetadataProviders); var diagnosticsRouteResolver = new DefaultRouteResolver( diagnosticsModuleCatalog, new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator), diagnosticsRouteCache, new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints))); var serializer = new DefaultObjectSerializer(); pipelines.BeforeRequest.AddItemToStartOfPipeline( new PipelineItem<Func<NancyContext, Response>>( PipelineKey, ctx => { if (!ctx.ControlPanelEnabled) { return null; } if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase)) { return null; } ctx.Items[ItemsKey] = true; var resourcePrefix = string.Concat(diagnosticsConfiguration.Path, "/Resources/"); if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase)) { var resourceNamespace = "Nancy.Diagnostics.Resources"; var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty; if (!string.IsNullOrEmpty(path)) { resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.')); } return new EmbeddedFileResponse( typeof(DiagnosticsHook).Assembly, resourceNamespace, Path.GetFileName(ctx.Request.Url.Path)); } RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx); return diagnosticsConfiguration.Valid ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer) : GetDiagnosticsHelpView(ctx); })); } public static void Disable(IPipelines pipelines) { pipelines.BeforeRequest.RemoveByName(PipelineKey); } private static Response GetDiagnosticsHelpView(NancyContext ctx) { return (StaticConfiguration.IsRunningDebug) ? new DiagnosticsViewRenderer(ctx)["help"] : HttpStatusCode.NotFound; } private static Response GetDiagnosticsLoginView(NancyContext ctx) { var renderer = new DiagnosticsViewRenderer(ctx); return renderer["login"]; } private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); if (session == null) { var view = GetDiagnosticsLoginView(ctx); view.AddCookie( new NancyCookie(diagnosticsConfiguration.CookieName, string.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return view; } var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Parameters; ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before); if (ctx.Response == null) { // Don't care about async here, so just get the result var task = resolveResult.Route.Invoke(resolveResult.Parameters, CancellationToken); task.Wait(); ctx.Response = task.Result; } if (ctx.Request.Method.ToUpperInvariant() == "HEAD") { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResult.After != null) { resolveResult.After.Invoke(ctx, CancellationToken); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); return ctx.Response; } private static void AddUpdateSessionCookie(DiagnosticsSession session, NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { if (context.Response == null) { return; } session.Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout); var serializedSession = serializer.Serialize(session); var encryptedSession = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(serializedSession); var hmacBytes = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession); var hmacString = Convert.ToBase64String(hmacBytes); var cookie = new NancyCookie(diagnosticsConfiguration.CookieName, string.Format("{1}{0}", encryptedSession, hmacString), true); context.Response.AddCookie(cookie); } private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { if (context.Request == null) { return null; } if (IsLoginRequest(context, diagnosticsConfiguration)) { return ProcessLogin(context, diagnosticsConfiguration, serializer); } if (!context.Request.Cookies.ContainsKey(diagnosticsConfiguration.CookieName)) { return null; } var encryptedValue = HttpUtility.UrlDecode(context.Request.Cookies[diagnosticsConfiguration.CookieName]); var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength); var encryptedSession = encryptedValue.Substring(hmacStringLength); var hmacString = encryptedValue.Substring(0, hmacStringLength); var hmacBytes = Convert.FromBase64String(hmacString); var newHmac = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession); var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength); if (!hmacValid) { return null; } var decryptedValue = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Decrypt(encryptedSession); var session = serializer.Deserialize(decryptedValue) as DiagnosticsSession; if (session == null || session.Expiry < DateTime.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password)) { return null; } return session; } private static bool SessionPasswordValid(DiagnosticsSession session, string realPassword) { var newHash = DiagnosticsSession.GenerateSaltedHash(realPassword, session.Salt); return (newHash.Length == session.Hash.Length && newHash.SequenceEqual(session.Hash)); } private static DiagnosticsSession ProcessLogin(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { string password = context.Request.Form.Password; if (!string.Equals(password, diagnosticsConfiguration.Password, StringComparison.Ordinal)) { return null; } var salt = DiagnosticsSession.GenerateRandomSalt(); var hash = DiagnosticsSession.GenerateSaltedHash(password, salt); var session = new DiagnosticsSession { Hash = hash, Salt = salt, Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout) }; return session; } private static bool IsLoginRequest(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration) { return context.Request.Method == "POST" && context.Request.Url.BasePath.TrimEnd(new[] { '/' }).EndsWith(diagnosticsConfiguration.Path) && context.Request.Url.Path == "/"; } private static void ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq) { if (resolveResultPreReq == null) { return; } var resolveResultPreReqResponse = resolveResultPreReq.Invoke(context, cancellationToken).Result; if (resolveResultPreReqResponse != null) { context.Response = resolveResultPreReqResponse; } } private static void RewriteDiagnosticsUrl(DiagnosticsConfiguration diagnosticsConfiguration, NancyContext ctx) { ctx.Request.Url.BasePath = string.Concat(ctx.Request.Url.BasePath, diagnosticsConfiguration.Path); ctx.Request.Url.Path = ctx.Request.Url.Path.Substring(diagnosticsConfiguration.Path.Length); if (ctx.Request.Url.Path.Length.Equals(0)) { ctx.Request.Url.Path = "/"; } } } }