context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Derivco.Orniscient.Proxy.Attributes; using Derivco.Orniscient.Proxy.Grains.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans; using Orleans.Core; using Orleans.Runtime; namespace Derivco.Orniscient.Proxy.Grains { public class MethodInvocationGrain : Grain, IMethodInvocationGrain { private string _grainType; private IGrainFactory _grainFactory; private List<GrainMethod> _methods = new List<GrainMethod>(); public MethodInvocationGrain() { } internal MethodInvocationGrain(string type, IGrainIdentity identity, IGrainRuntime runtime, IGrainFactory factory) : base(identity, runtime) { _grainType = type; _grainFactory = factory; } public override async Task OnActivateAsync() { if (_grainType == null) _grainType = this.GetPrimaryKeyString(); if (_grainFactory == null) _grainFactory = GrainFactory; await HydrateMethodList(); await base.OnActivateAsync(); } public Task<List<GrainMethod>> GetAvailableMethods() { return Task.FromResult(_methods); } public Task<string> GetGrainKeyType() { var grainInterface = GetGrainInterfaceType(GetTypeFromString(_grainType)); return grainInterface != null ? Task.FromResult(GetGrainKeyType(grainInterface)?.FullName) : Task.FromResult(string.Empty); } public async Task<object> InvokeGrainMethod(string id, string methodId, string parametersJson, bool invokeOnNewGrain = false) { var method = _methods.FirstOrDefault(p => p.MethodId == methodId); if (method != null) { if (invokeOnNewGrain && string.IsNullOrEmpty(id)) { id = Guid.NewGuid().ToString(); } var grain = GetGrainReference(id, method); if (grain != null) { //invoke the method in the grain. var parameters = BuildParameterObjects(JArray.Parse(parametersJson)); dynamic methodInvocation = grain.GetType() .GetMethod(method.Name, BindingFlags.Instance | BindingFlags.Public, null, method.Parameters.Select(p => GetTypeFromString(p.Type)).ToArray(), null) .Invoke(grain, parameters); return JsonConvert.SerializeObject(await methodInvocation); } } return null; } private Task HydrateMethodList() { var grainType = GetTypeFromString(_grainType); _methods = new List<GrainMethod>(); foreach (var @interface in grainType.GetInterfaces()) { if (@interface.GetInterfaces().Contains(typeof(IAddressable))) { _methods.AddRange(@interface.GetMethods() .Where( p => grainType.GetMethods() .Where(q => Attribute.IsDefined(q, typeof(OrniscientMethod))) .Any(r => r.Name == p.Name)) .Select(m => new GrainMethod { Name = m.Name, InterfaceForMethod = @interface.FullName, MethodId = Guid.NewGuid().ToString(), Parameters = m.GetParameters() .Select(p => new GrainMethodParameters { Name = p.Name, Type = p.ParameterType.ToString(), IsComplexType = !p.ParameterType.IsValueType && p.ParameterType != typeof(string) }).ToList() })); } } return TaskDone.Done; } private IGrain GetGrainReference(string id, GrainMethod method) { if (method != null) { var grainInterface = GetGrainInterfaceType(GetTypeFromString(_grainType)); var grainKeyType = GetGrainKeyType(grainInterface); var grainKey = GetGrainKeyFromType(grainKeyType, id); var grainReference = typeof(IGrainFactory) .GetMethod("GetGrain", new[] {grainKeyType, typeof(string)}) .MakeGenericMethod(grainInterface) .Invoke(_grainFactory, new[] {grainKey, null}) as IGrain; if (method.InterfaceForMethod == grainInterface.FullName) { return grainReference; } var interfaceForMethod = GetTypeFromString(method.InterfaceForMethod); return typeof(GrainExtensions) .GetMethod("AsReference") .MakeGenericMethod(interfaceForMethod) .Invoke(grainReference, new object[] {grainReference}) as IGrain; } return null; } private static object[] BuildParameterObjects(JArray parametersArray) { var parameterObjects = new List<object>(); foreach (var parameter in parametersArray) { var type = GetTypeFromString(parameter["type"].ToString()); if (!string.IsNullOrEmpty(parameter["value"].ToString())) { var value = JsonConvert.DeserializeObject(parameter["value"].ToString(), type); parameterObjects.Add(value); } else { parameterObjects.Add(null); } } return parameterObjects.ToArray(); } private static object GetGrainKeyFromType(Type grainKeyType, string id) { if (grainKeyType == typeof(Guid)) { return Guid.Parse(id); } if (grainKeyType == typeof(int)) { return int.Parse(id); } if (grainKeyType == typeof(string)) { return id; } return null; } private static Type GetTypeFromString(string typeName) { var type = System.Type.GetType(typeName); if (type == null) { foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) { type = a.GetType(typeName); if (type != null) break; } } return type; } private static Type GetGrainInterfaceType(Type grainType) { return grainType?.GetInterfaces() .FirstOrDefault( i => grainType.GetInterfaceMap(i).TargetMethods.Any(m => m.DeclaringType == grainType) && i.Name.Contains(grainType.Name)) ?? grainType?.GetInterfaces().FirstOrDefault(i => i.Name.Contains(grainType.Name)); } private static Type GetGrainKeyType(Type grainInterface) { var grainKeyInterface = grainInterface.GetInterfaces().FirstOrDefault(i => i.Name.Contains("Key")); if (grainKeyInterface != null) { if (grainKeyInterface.IsAssignableFrom(typeof(IGrainWithGuidKey))) { return typeof(Guid); } if (grainKeyInterface.IsAssignableFrom(typeof(IGrainWithIntegerKey))) { return typeof(int); } if (grainKeyInterface.IsAssignableFrom(typeof(IGrainWithStringKey))) { return typeof(string); } } return null; } } }
using J2N.Text; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Analysis.TokenAttributes { /* * 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 BytesRef = Lucene.Net.Util.BytesRef; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestCharTermAttributeImpl : LuceneTestCase { [Test] public virtual void TestResize() { CharTermAttribute t = new CharTermAttribute(); char[] content = "hello".ToCharArray(); t.CopyBuffer(content, 0, content.Length); for (int i = 0; i < 2000; i++) { t.ResizeBuffer(i); Assert.IsTrue(i <= t.Buffer.Length); Assert.AreEqual("hello", t.ToString()); } } [Test] public virtual void TestGrow() { CharTermAttribute t = new CharTermAttribute(); StringBuilder buf = new StringBuilder("ab"); for (int i = 0; i < 20; i++) { char[] content = buf.ToString().ToCharArray(); t.CopyBuffer(content, 0, content.Length); Assert.AreEqual(buf.Length, t.Length); Assert.AreEqual(buf.ToString(), t.ToString()); buf.Append(buf.ToString()); } Assert.AreEqual(1048576, t.Length); // now as a StringBuilder, first variant t = new CharTermAttribute(); buf = new StringBuilder("ab"); for (int i = 0; i < 20; i++) { t.SetEmpty().Append(buf); Assert.AreEqual(buf.Length, t.Length); Assert.AreEqual(buf.ToString(), t.ToString()); buf.Append(t); } Assert.AreEqual(1048576, t.Length); // Test for slow growth to a long term t = new CharTermAttribute(); buf = new StringBuilder("a"); for (int i = 0; i < 20000; i++) { t.SetEmpty().Append(buf); Assert.AreEqual(buf.Length, t.Length); Assert.AreEqual(buf.ToString(), t.ToString()); buf.Append("a"); } Assert.AreEqual(20000, t.Length); } [Test] public virtual void TestToString() { char[] b = new char[] { 'a', 'l', 'o', 'h', 'a' }; CharTermAttribute t = new CharTermAttribute(); t.CopyBuffer(b, 0, 5); Assert.AreEqual("aloha", t.ToString()); t.SetEmpty().Append("hi there"); Assert.AreEqual("hi there", t.ToString()); } [Test] public virtual void TestClone() { CharTermAttribute t = new CharTermAttribute(); char[] content = "hello".ToCharArray(); t.CopyBuffer(content, 0, 5); char[] buf = t.Buffer; CharTermAttribute copy = TestToken.AssertCloneIsEqual(t); Assert.AreEqual(t.ToString(), copy.ToString()); Assert.AreNotSame(buf, copy.Buffer); } [Test] public virtual void TestEquals() { CharTermAttribute t1a = new CharTermAttribute(); char[] content1a = "hello".ToCharArray(); t1a.CopyBuffer(content1a, 0, 5); CharTermAttribute t1b = new CharTermAttribute(); char[] content1b = "hello".ToCharArray(); t1b.CopyBuffer(content1b, 0, 5); CharTermAttribute t2 = new CharTermAttribute(); char[] content2 = "hello2".ToCharArray(); t2.CopyBuffer(content2, 0, 6); Assert.IsTrue(t1a.Equals(t1b)); Assert.IsFalse(t1a.Equals(t2)); Assert.IsFalse(t2.Equals(t1b)); } [Test] public virtual void TestCopyTo() { CharTermAttribute t = new CharTermAttribute(); CharTermAttribute copy = TestToken.AssertCopyIsEqual(t); Assert.AreEqual("", t.ToString()); Assert.AreEqual("", copy.ToString()); t = new CharTermAttribute(); char[] content = "hello".ToCharArray(); t.CopyBuffer(content, 0, 5); char[] buf = t.Buffer; copy = TestToken.AssertCopyIsEqual(t); Assert.AreEqual(t.ToString(), copy.ToString()); Assert.AreNotSame(buf, copy.Buffer); } [Test] public virtual void TestAttributeReflection() { CharTermAttribute t = new CharTermAttribute(); t.Append("foobar"); TestUtil.AssertAttributeReflection(t, new Dictionary<string, object>() { { typeof(ICharTermAttribute).Name + "#term", "foobar" }, { typeof(ITermToBytesRefAttribute).Name + "#bytes", new BytesRef("foobar") } }); } [Test] public virtual void TestCharSequenceInterface() { const string s = "0123456789"; CharTermAttribute t = new CharTermAttribute(); t.Append(s); Assert.AreEqual(s.Length, t.Length); Assert.AreEqual("12", t.Subsequence(1, 3 - 1).ToString()); // LUCENENET: Corrected 2nd parameter of Subsequence Assert.AreEqual(s, t.Subsequence(0, s.Length - 0).ToString()); // LUCENENET: Corrected 2nd parameter of Subsequence Assert.IsTrue(Regex.IsMatch(t.ToString(), "01\\d+")); Assert.IsTrue(Regex.IsMatch(t.Subsequence(3, 5 - 3).ToString(), "34")); // LUCENENET: Corrected 2nd parameter of Subsequence Assert.AreEqual(s.Substring(3, 4), t.Subsequence(3, 7 - 3).ToString()); // LUCENENET: Corrected 2nd parameter of Subsequence for (int i = 0; i < s.Length; i++) { Assert.IsTrue(t[i] == s[i]); } // LUCENENET specific to test indexer for (int i = 0; i < s.Length; i++) { Assert.IsTrue(t[i] == s[i]); } } [Test] public virtual void TestAppendableInterface() { CharTermAttribute t = new CharTermAttribute(); //Formatter formatter = new Formatter(t, Locale.ROOT); //formatter.format("%d", 1234); //Assert.AreEqual("1234", t.ToString()); //formatter.format("%d", 5678); // LUCENENET: We don't have a formatter in .NET, so continue from here t.Append("12345678"); // LUCENENET specific overload that accepts string Assert.AreEqual("12345678", t.ToString()); t.SetEmpty().Append("12345678".ToCharArray()); // LUCENENET specific overload that accepts char[] Assert.AreEqual("12345678", t.ToString()); t.Append('9'); Assert.AreEqual("123456789", t.ToString()); t.Append(new StringCharSequence("0")); Assert.AreEqual("1234567890", t.ToString()); t.Append(new StringCharSequence("0123456789"), 1, 3 - 1); // LUCENENET: Corrected 3rd parameter Assert.AreEqual("123456789012", t.ToString()); //t.Append((ICharSequence) CharBuffer.wrap("0123456789".ToCharArray()), 3, 5); t.Append("0123456789".ToCharArray(), 3, 5 - 3); // LUCENENET: no CharBuffer in .NET, so we test char[], start, end overload // LUCENENET: Corrected 3rd parameter Assert.AreEqual("12345678901234", t.ToString()); t.Append((ICharSequence)t); Assert.AreEqual("1234567890123412345678901234", t.ToString()); t.Append(/*(ICharSequence)*/ new StringBuilder("0123456789").ToString(), 5, 7 - 5); // LUCENENET: StringBuilder doesn't implement ICharSequence, corrected 3rd argument Assert.AreEqual("123456789012341234567890123456", t.ToString()); t.Append(/*(ICharSequence)*/ new StringBuilder(t.ToString())); Assert.AreEqual("123456789012341234567890123456123456789012341234567890123456", t.ToString()); // LUCENENET: StringBuilder doesn't implement ICharSequence // very wierd, to test if a subSlice is wrapped correct :) //CharBuffer buf = CharBuffer.wrap("0123456789".ToCharArray(), 3, 5); // LUCENENET: No CharBuffer in .NET StringBuilder buf = new StringBuilder("0123456789", 3, 5, 16); Assert.AreEqual("34567", buf.ToString()); t.SetEmpty().Append(/*(ICharSequence)*/ buf, 1, 2 - 1); // LUCENENET: StringBuilder doesn't implement ICharSequence // LUCENENET: Corrected 3rd parameter Assert.AreEqual("4", t.ToString()); ICharTermAttribute t2 = new CharTermAttribute(); t2.Append("test"); t.Append((ICharSequence)t2); Assert.AreEqual("4test", t.ToString()); t.Append((ICharSequence)t2, 1, 2 - 1); // LUCENENET: Corrected 3rd parameter Assert.AreEqual("4teste", t.ToString()); try { t.Append((ICharSequence)t2, 1, 5 - 1); // LUCENENET: Corrected 3rd parameter Assert.Fail("Should throw ArgumentOutOfRangeException"); } #pragma warning disable 168 catch (ArgumentOutOfRangeException iobe) #pragma warning restore 168 { } try { t.Append((ICharSequence)t2, 1, 0 - 1); // LUCENENET: Corrected 3rd parameter Assert.Fail("Should throw ArgumentOutOfRangeException"); } #pragma warning disable 168 catch (ArgumentOutOfRangeException iobe) #pragma warning restore 168 { } string expected = t.ToString(); t.Append((ICharSequence)null); // No-op Assert.AreEqual(expected, t.ToString()); // LUCENENET specific - test string overloads try { t.Append((string)t2.ToString(), 1, 5 - 1); // LUCENENET: Corrected 3rd parameter Assert.Fail("Should throw ArgumentOutOfRangeException"); } #pragma warning disable 168 catch (ArgumentOutOfRangeException iobe) #pragma warning restore 168 { } try { t.Append((string)t2.ToString(), 1, 0 - 1); // LUCENENET: Corrected 3rd parameter Assert.Fail("Should throw ArgumentOutOfRangeException"); } #pragma warning disable 168 catch (ArgumentOutOfRangeException iobe) #pragma warning restore 168 { } expected = t.ToString(); t.Append((string)null); // No-op Assert.AreEqual(expected, t.ToString()); // LUCENENET specific - test char[] overloads try { t.Append((char[])t2.ToString().ToCharArray(), 1, 5 - 1); // LUCENENET: Corrected 3rd parameter Assert.Fail("Should throw ArgumentOutOfRangeException"); } #pragma warning disable 168 catch (ArgumentOutOfRangeException iobe) #pragma warning restore 168 { } try { t.Append((char[])t2.ToString().ToCharArray(), 1, 0 - 1); // LUCENENET: Corrected 3rd parameter Assert.Fail("Should throw ArgumentOutOfRangeException"); } #pragma warning disable 168 catch (ArgumentOutOfRangeException iobe) #pragma warning restore 168 { } expected = t.ToString(); t.Append((char[])null); // No-op Assert.AreEqual(expected, t.ToString()); } [Test] public virtual void TestAppendableInterfaceWithLongSequences() { CharTermAttribute t = new CharTermAttribute(); t.Append("01234567890123456789012345678901234567890123456789"); // LUCENENET specific overload that accepts string assertEquals("01234567890123456789012345678901234567890123456789", t.ToString()); t.Append("01234567890123456789012345678901234567890123456789", 3, 50 - 3); // LUCENENET specific overload that accepts string, startIndex, charCount Assert.AreEqual("0123456789012345678901234567890123456789012345678934567890123456789012345678901234567890123456789", t.ToString()); t.SetEmpty(); t.Append("01234567890123456789012345678901234567890123456789".ToCharArray()); // LUCENENET specific overload that accepts char[] assertEquals("01234567890123456789012345678901234567890123456789", t.ToString()); t.Append("01234567890123456789012345678901234567890123456789".ToCharArray(), 3, 50 - 3); // LUCENENET specific overload that accepts char[], startIndex, charCount Assert.AreEqual("0123456789012345678901234567890123456789012345678934567890123456789012345678901234567890123456789", t.ToString()); t.SetEmpty(); t.Append(new StringCharSequence("01234567890123456789012345678901234567890123456789")); //t.Append((ICharSequence) CharBuffer.wrap("01234567890123456789012345678901234567890123456789".ToCharArray()), 3, 50); // LUCENENET: No CharBuffer in .NET t.Append("01234567890123456789012345678901234567890123456789".ToCharArray(), 3, 50 - 3); // LUCENENET specific overload that accepts char[], startIndex, charCount // "01234567890123456789012345678901234567890123456789" Assert.AreEqual("0123456789012345678901234567890123456789012345678934567890123456789012345678901234567890123456789", t.ToString()); t.SetEmpty().Append(/*(ICharSequence)*/ new StringBuilder("01234567890123456789"), 5, 17 - 5); // LUCENENET: StringBuilder doesn't implement ICharSequence Assert.AreEqual((ICharSequence)new StringCharSequence("567890123456"), t /*.ToString()*/); t.Append(new StringBuilder(t.ToString())); Assert.AreEqual((ICharSequence)new StringCharSequence("567890123456567890123456"), t /*.ToString()*/); // very wierd, to test if a subSlice is wrapped correct :) //CharBuffer buf = CharBuffer.wrap("012345678901234567890123456789".ToCharArray(), 3, 15); // LUCENENET: No CharBuffer in .NET StringBuilder buf = new StringBuilder("012345678901234567890123456789", 3, 15, 16); Assert.AreEqual("345678901234567", buf.ToString()); t.SetEmpty().Append(buf, 1, 14 - 1); Assert.AreEqual("4567890123456", t.ToString()); // finally use a completely custom ICharSequence that is not catched by instanceof checks const string longTestString = "012345678901234567890123456789"; t.Append(new CharSequenceAnonymousClass(this, longTestString)); Assert.AreEqual("4567890123456" + longTestString, t.ToString()); } private class CharSequenceAnonymousClass : ICharSequence { private readonly TestCharTermAttributeImpl outerInstance; private string longTestString; public CharSequenceAnonymousClass(TestCharTermAttributeImpl outerInstance, string longTestString) { this.outerInstance = outerInstance; this.longTestString = longTestString; } bool ICharSequence.HasValue => longTestString != null; // LUCENENET specific (implementation of ICharSequence) public char CharAt(int i) { return longTestString[i]; } // LUCENENET specific - Added to .NETify public char this[int i] => longTestString[i]; public int Length => longTestString.Length; public ICharSequence Subsequence(int startIndex, int length) // LUCENENET: Changed semantics to startIndex/length to match .NET { return new StringCharSequence(longTestString.Substring(startIndex, length)); } public override string ToString() { return longTestString; } } [Test] public virtual void TestNonCharSequenceAppend() { CharTermAttribute t = new CharTermAttribute(); t.Append("0123456789"); t.Append("0123456789"); Assert.AreEqual("01234567890123456789", t.ToString()); t.Append(new StringBuilder("0123456789")); Assert.AreEqual("012345678901234567890123456789", t.ToString()); ICharTermAttribute t2 = new CharTermAttribute(); t2.Append("test"); t.Append(t2); Assert.AreEqual("012345678901234567890123456789test", t.ToString()); t.Append((string)null); t.Append((StringBuilder)null); t.Append((ICharTermAttribute)null); Assert.AreEqual("012345678901234567890123456789test", t.ToString()); } [Test] public virtual void TestExceptions() { CharTermAttribute t = new CharTermAttribute(); t.Append("test"); Assert.AreEqual("test", t.ToString()); try { var _ = t[-1]; Assert.Fail("Should throw ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { } try { var _ = t[4]; Assert.Fail("Should throw ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { } try { t.Subsequence(0, 5 - 0); // LUCENENET: Corrected 2nd parameter of Subsequence Assert.Fail("Should throw ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { } try { t.Subsequence(5, 0 - 5); // LUCENENET: Corrected 2nd parameter of Subsequence Assert.Fail("Should throw ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { } } /* // test speed of the dynamic instanceof checks in append(ICharSequence), // to find the best max length for the generic while (start<end) loop: public void testAppendPerf() { CharTermAttributeImpl t = new CharTermAttributeImpl(); final int count = 32; ICharSequence[] csq = new ICharSequence[count * 6]; final StringBuilder sb = new StringBuilder(); for (int i=0,j=0; i<count; i++) { sb.append(i%10); final String testString = sb.toString(); CharTermAttribute cta = new CharTermAttributeImpl(); cta.append(testString); csq[j++] = cta; csq[j++] = testString; csq[j++] = new StringBuilder(sb); csq[j++] = new StringBuffer(sb); csq[j++] = CharBuffer.wrap(testString.toCharArray()); csq[j++] = new ICharSequence() { public char charAt(int i) { return testString.charAt(i); } public int length() { return testString.length(); } public ICharSequence subSequence(int start, int end) { return testString.subSequence(start, end); } public String toString() { return testString; } }; } Random rnd = newRandom(); long startTime = System.currentTimeMillis(); for (int i=0; i<100000000; i++) { t.SetEmpty().append(csq[rnd.nextInt(csq.length)]); } long endTime = System.currentTimeMillis(); System.out.println("Time: " + (endTime-startTime)/1000.0 + " s"); } */ } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.IO; using System.Management.Automation; using System.Xml; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell { /// <summary> /// Wraps Hitesh's xml serializer in such a way that it will select the proper serializer based on the data /// format. /// </summary> internal class Serialization { /// <summary> /// Describes the format of the data streamed between minishells, e.g. the allowed arguments to the minishell /// -outputformat and -inputformat command line parameters. /// </summary> internal enum DataFormat { /// <summary> /// Text format -- i.e. stream text just as out-default would display it. /// </summary> Text = 0, /// <summary> /// XML-serialized format. /// </summary> XML = 1, /// <summary> /// Indicates that the data should be discarded instead of processed. /// </summary> None = 2 } protected Serialization(DataFormat dataFormat, string streamName) { Dbg.Assert(!string.IsNullOrEmpty(streamName), "stream needs a name"); format = dataFormat; this.streamName = streamName; } protected static string XmlCliTag = "#< CLIXML"; protected string streamName; protected DataFormat format; } internal class WrappedSerializer : Serialization { internal WrappedSerializer(DataFormat dataFormat, string streamName, TextWriter output) : base(dataFormat, streamName) { Dbg.Assert(output != null, "output should have a value"); textWriter = output; switch (format) { case DataFormat.XML: XmlWriterSettings settings = new XmlWriterSettings(); settings.CheckCharacters = false; settings.OmitXmlDeclaration = true; _xmlWriter = XmlWriter.Create(textWriter, settings); _xmlSerializer = new Serializer(_xmlWriter); break; case DataFormat.Text: default: // do nothing; we'll just write to the TextWriter // or discard it. break; } } internal void Serialize(object o) { Serialize(o, this.streamName); } internal void Serialize(object o, string streamName) { switch (format) { case DataFormat.None: break; case DataFormat.XML: if (_firstCall) { _firstCall = false; textWriter.WriteLine(Serialization.XmlCliTag); } _xmlSerializer.Serialize(o, streamName); break; case DataFormat.Text: default: textWriter.Write(o.ToString()); break; } } internal void End() { switch (format) { case DataFormat.None: // do nothing break; case DataFormat.XML: _xmlSerializer.Done(); _xmlSerializer = null; break; case DataFormat.Text: default: // do nothing break; } } internal TextWriter textWriter; private readonly XmlWriter _xmlWriter; private Serializer _xmlSerializer; private bool _firstCall = true; } internal class WrappedDeserializer : Serialization { internal WrappedDeserializer(DataFormat dataFormat, string streamName, TextReader input) : base(dataFormat, streamName) { Dbg.Assert(input != null, "input should have a value"); // If the data format is none - do nothing... if (dataFormat == DataFormat.None) return; textReader = input; _firstLine = textReader.ReadLine(); if (string.Equals(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase)) { // format should be XML dataFormat = DataFormat.XML; } switch (format) { case DataFormat.XML: _xmlReader = XmlReader.Create(textReader, new XmlReaderSettings { XmlResolver = null }); _xmlDeserializer = new Deserializer(_xmlReader); break; case DataFormat.Text: default: // do nothing; we'll just read from the TextReader break; } } internal object Deserialize() { object o; switch (format) { case DataFormat.None: _atEnd = true; return null; case DataFormat.XML: string unused; o = _xmlDeserializer.Deserialize(out unused); break; case DataFormat.Text: default: if (_atEnd) { return null; } if (_firstLine != null) { o = _firstLine; _firstLine = null; } else { o = textReader.ReadLine(); if (o == null) { _atEnd = true; } } break; } return o; } internal bool AtEnd { get { bool result = false; switch (format) { case DataFormat.None: _atEnd = true; result = true; break; case DataFormat.XML: result = _xmlDeserializer.Done(); break; case DataFormat.Text: default: result = _atEnd; break; } return result; } } internal void End() { switch (format) { case DataFormat.None: case DataFormat.XML: case DataFormat.Text: default: // do nothing break; } } internal TextReader textReader; private readonly XmlReader _xmlReader; private readonly Deserializer _xmlDeserializer; private string _firstLine; private bool _atEnd; } } // namespace
/* Following "Sweep-line algorithm for constrained Delaunay triangulation", by Domiter and Zalik */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using SymmetricSegment = Microsoft.Msagl.Core.DataStructures.SymmetricTuple<Microsoft.Msagl.Core.Geometry.Point>; namespace Microsoft.Msagl.Routing.ConstrainedDelaunayTriangulation { ///<summary> ///triangulates the space between point, line segment and polygons in the Delaunay fashion ///</summary> public class Cdt : AlgorithmBase { readonly IEnumerable<Tuple<Point, object>> isolatedSitesWithObject; readonly IEnumerable<Point> isolatedSites; readonly IEnumerable<Polyline> obstacles; readonly List<SymmetricSegment> isolatedSegments; CdtSite P1; CdtSite P2; CdtSweeper sweeper; internal readonly Dictionary<Point, CdtSite> PointsToSites = new Dictionary<Point, CdtSite>(); List<CdtSite> allInputSites; ///<summary> ///constructor ///</summary> ///<param name="isolatedSites"></param> ///<param name="obstacles"></param> ///<param name="isolatedSegments"></param> public Cdt(IEnumerable<Point> isolatedSites, IEnumerable<Polyline> obstacles, List<SymmetricSegment> isolatedSegments) { this.isolatedSites = isolatedSites; this.obstacles = obstacles; this.isolatedSegments = isolatedSegments; } /// <summary> /// constructor /// </summary> /// <param name="isolatedSites"></param> public Cdt(IEnumerable<Tuple<Point, object>> isolatedSites) { isolatedSitesWithObject = isolatedSites; } void FillAllInputSites() { //for now suppose that the data is correct: no isolatedSites coincide with obstacles or isolatedSegments, obstacles are mutually disjoint, etc if (isolatedSitesWithObject != null) foreach (var tuple in isolatedSitesWithObject) AddSite(tuple.Item1, tuple.Item2); if (isolatedSites != null) foreach (var isolatedSite in isolatedSites) AddSite(isolatedSite, null); if (obstacles != null) foreach (var poly in obstacles) AddPolylineToAllInputSites(poly); if (isolatedSegments != null) foreach (var isolatedSegment in isolatedSegments) AddConstrainedEdge(isolatedSegment.A, isolatedSegment.B, null); AddP1AndP2(); allInputSites = new List<CdtSite>(PointsToSites.Values); } CdtSite AddSite(Point point, object relatedObject) { CdtSite site; if (PointsToSites.TryGetValue(point, out site)) { site.Owner = relatedObject;//set the owner anyway return site; } PointsToSites[point] = site = new CdtSite(point) { Owner = relatedObject }; return site; } void AddP1AndP2() { var box = Rectangle.CreateAnEmptyBox(); foreach (var site in PointsToSites.Keys) box.Add(site); var delx = box.Width / 3; var dely = box.Height / 3; P1 = new CdtSite(box.LeftBottom + new Point(-delx, -dely)); P2 = new CdtSite(box.RightBottom + new Point(delx, -dely)); } void AddPolylineToAllInputSites(Polyline poly) { for (var pp = poly.StartPoint; pp.Next != null; pp = pp.Next) AddConstrainedEdge(pp.Point, pp.Next.Point, poly); if (poly.Closed) AddConstrainedEdge(poly.EndPoint.Point, poly.StartPoint.Point, poly); } void AddConstrainedEdge(Point a, Point b, Polyline poly) { var ab = Above(a, b); Debug.Assert(ab != 0); CdtSite upperPoint; CdtSite lowerPoint; if (ab > 0) {//a is above b upperPoint = AddSite(a, poly); lowerPoint = AddSite(b, poly); } else { Debug.Assert(ab < 0); upperPoint = AddSite(b, poly); lowerPoint = AddSite(a, poly); } var edge = CreateEdgeOnOrderedCouple(upperPoint, lowerPoint); edge.Constrained = true; } static internal CdtEdge GetOrCreateEdge(CdtSite a, CdtSite b) { if (Above(a.Point, b.Point) == 1) { var e = a.EdgeBetweenUpperSiteAndLowerSite(b); if (e != null) return e; return CreateEdgeOnOrderedCouple(a, b); } else { var e = b.EdgeBetweenUpperSiteAndLowerSite(a); if (e != null) return e; return CreateEdgeOnOrderedCouple(b, a); } } static CdtEdge CreateEdgeOnOrderedCouple(CdtSite upperPoint, CdtSite lowerPoint) { Debug.Assert(Above(upperPoint.Point, lowerPoint.Point) == 1); return new CdtEdge(upperPoint, lowerPoint); } ///<summary> ///</summary> ///<returns></returns> public Set<CdtTriangle> GetTriangles() { return sweeper.Triangles; } /// <summary> /// Executes the actual algorithm. /// </summary> protected override void RunInternal() { Initialization(); SweepAndFinalize(); } void SweepAndFinalize() { sweeper = new CdtSweeper(allInputSites, P1, P2, GetOrCreateEdge); sweeper.Run(); } void Initialization() { FillAllInputSites(); allInputSites.Sort(OnComparison); } static int OnComparison(CdtSite a, CdtSite b) { return Above(a.Point, b.Point); } /// <summary> /// compare first y then -x coordinates /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns>1 if a is above b, 0 if points are the same and -1 if a is below b</returns> static public int Above(Point a, Point b) { var del = a.Y - b.Y; if (del > 0) return 1; if (del < 0) return -1; del = a.X - b.X; return del > 0 ? -1 : (del < 0 ? 1 : 0); //for a horizontal edge the point with the smaller X is the upper point } /// <summary> /// compare first y then -x coordinates /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns>1 if a is above b, 0 if points are the same and -1 if a is below b</returns> static internal int Above(CdtSite a, CdtSite b) { var del = a.Point.Y - b.Point.Y; if (del > 0) return 1; if (del < 0) return -1; del = a.Point.X - b.Point.X; return del > 0 ? -1 : (del < 0 ? 1 : 0); //for a horizontal edge the point with the smaller X is the upper point } internal void RestoreEdgeCapacities() { foreach (var site in allInputSites) foreach (var e in site.Edges) if (!e.Constrained) //do not care of constrained edges e.ResidualCapacity = e.Capacity; } ///<summary> ///</summary> public void SetInEdges() { foreach (var site in PointsToSites.Values) { var edges = site.Edges; for (int i = edges.Count - 1; i >= 0; i--) { var e = edges[i]; var oSite = e.lowerSite; Debug.Assert(oSite != site); oSite.AddInEdge(e); } } } ///<summary> ///</summary> ///<param name="point"></param> ///<returns></returns> public CdtSite FindSite(Point point) { return PointsToSites[point]; } // /// <summary> // /// returns CdtEdges crossed by the segment a.Point, b.Point // /// </summary> // /// <param name="prevA">if prevA is not a null, that means the path is passing through prevA and might need to include // /// the edge containing a.Point if such exists</param> // /// <param name="a"></param> // /// <param name="b"></param> // /// <returns></returns> // internal IEnumerable<CdtEdge> GetCdtEdgesCrossedBySegment(PolylinePoint prevA, PolylinePoint a, PolylinePoint b) { // count++; // if (dd) { // var l = new List<DebugCurve> { // new DebugCurve("red", new Ellipse(5, 5, a.Point)), // new DebugCurve("blue", new Ellipse(5, 5, b.Point)), // new DebugCurve("blue", new LineSegment(a.Point, b.Point)) // }; // // l.AddRange( // GetTriangles().Select( // tr => new DebugCurve(100, 1, "green", new Polyline(tr.Sites.Select(v => v.Point)) {Closed = true}))); // LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(l); // // } // var ret = new List<CdtEdge>(); // CdtEdge piercedEdge; // CdtTriangle t = GetFirstTriangleAndPiercedEdge(a, b, out piercedEdge); // if (ProperCrossing(a, b, piercedEdge)) // ret.Add(piercedEdge); // // ret.AddRange(ContinueThreadingThroughTriangles(a,b,t, piercedEdge)); // // return ret; // } /* static bool ProperCrossing(Point a, Point b, CdtEdge cdtEdge) { return cdtEdge != null && cdtEdge.upperSite.Owner != cdtEdge.lowerSite.Owner && CrossEdgeInterior(cdtEdge, a, b); } */ // static int count; // static bool db { get { return count == 125; }} internal IEnumerable<CdtEdge> ThreadEdgeThroughTriangles(CdtSite startSite, Point end) { CdtEdge piercedEdge; var triangle = FindFirstPiercedTriangle(startSite, end, out piercedEdge); if (triangle == null) yield break; var start = startSite.Point; foreach (var cdtEdge in ThreadThroughTriangles(start, end, triangle, piercedEdge)) yield return cdtEdge; } IEnumerable<CdtEdge> ThreadThroughTriangles(Point start, Point end, CdtTriangle triangle, CdtEdge piercedEdge) { var ret = new List<CdtEdge>(); do { if (piercedEdge.upperSite.Owner != piercedEdge.lowerSite.Owner) ret.Add(piercedEdge); } while (FindNextPierced(start, end, ref triangle, ref piercedEdge)); return ret; } bool FindNextPierced(Point start, Point end, ref CdtTriangle t, ref CdtEdge piercedEdge) { t = piercedEdge.GetOtherTriangle(t); if (t == null) return false; var i = t.Edges.Index(piercedEdge); for (int j = i + 1; j <= i + 2; j++) { var pe = t.Edges[j]; piercedEdge = PiercedEdgeQuery(pe, start, end, t); if (piercedEdge != null) { // CdtSweeper.ShowFront(trs, null, // new []{new LineSegment(e.SourcePoint,e.TargetPoint)}, new []{new LineSegment(pe.upperSite.Point,pe.lowerSite.Point)}); break; } } return !PointIsInsideOfTriangle(end, t); } /* static CdtEdge GetPiercedEdge(Point a, Point b, CdtTriangle triangle) { Debug.Assert(!triangle.Sites.Any(s=>ApproximateComparer.Close(a, s.Point))); var a0 = Point.GetTriangleOrientation(a, triangle.Sites[0].Point, triangle.Sites[1].Point); if (a0 == TriangleOrientation.Clockwise)return null; var a1 = Point.GetTriangleOrientation(a,triangle.Sites[1].Point, triangle.Sites[2].Point); if (a1 == TriangleOrientation.Clockwise)return null; var a2 = Point.GetTriangleOrientation(a,triangle.Sites[2].Point, triangle.Sites[3].Point); if (a2 == TriangleOrientation.Clockwise)return null; if (a0 == TriangleOrientation.Counterclockwise && Point.GetTriangleOrientation(b, triangle.Sites[0].Point, triangle.Sites[1].Point) == TriangleOrientation.Clockwise) return triangle.Edges[0]; if (a1 == TriangleOrientation.Counterclockwise && Point.GetTriangleOrientation(b, triangle.Sites[1].Point, triangle.Sites[2].Point) == TriangleOrientation.Clockwise) return triangle.Edges[1]; if (a2 == TriangleOrientation.Counterclockwise && Point.GetTriangleOrientation(b, triangle.Sites[2].Point, triangle.Sites[3].Point) == TriangleOrientation.Clockwise) return triangle.Edges[2]; return null; } */ /* static bool CheckIntersectionStartingFromSide(int i, CdtTriangle triangle, Point a, Point b) { var edgeDir = triangle.Sites[i + 1].Point - triangle.Sites[i].Point; var edgePerp = edgeDir.Rotate90Ccw(); return ((b - a)*edgePerp)*((triangle.Sites[i + 2].Point - a)*edgePerp) > 0; } */ internal static bool PointIsInsideOfTriangle(Point point, CdtTriangle t) { for (int i = 0; i < 3; i++) { var a = t.Sites[i].Point; var b = t.Sites[i + 1].Point; if (Point.SignedDoubledTriangleArea(point, a, b) < -ApproximateComparer.DistanceEpsilon) return false; } return true; } CdtTriangle FindFirstPiercedTriangle(CdtSite startSite, Point target, out CdtEdge piercedEdge) { if (startSite != null) { foreach (var t in startSite.Triangles) { piercedEdge = GetPiercedEdgeInSiteTriangle(t, startSite, target); if (piercedEdge != null) if (!PointIsInsideOfTriangle(target, t)) return t; } } piercedEdge = null; return null; } CdtEdge GetPiercedEdgeInSiteTriangle(CdtTriangle t, CdtSite site, Point target) { var e = t.OppositeEdge(site); return PiercedEdgeQuery(e, site.Point, target, t); } internal static bool EdgeIsPierced(CdtEdge e, Point source, Point target, CdtTriangle cdtTriangle) { var area0 = Point.SignedDoubledTriangleArea(e.upperSite.Point, source, target); var area1 = Point.SignedDoubledTriangleArea(e.lowerSite.Point, source, target); if (ApproximateComparer.Sign(area0) * ApproximateComparer.Sign(area1) > 0) return false; area0 = Point.SignedDoubledTriangleArea(e.upperSite.Point, e.lowerSite.Point, source); area1 = Point.SignedDoubledTriangleArea(e.upperSite.Point, e.lowerSite.Point, target); if (ApproximateComparer.Sign(area0) * ApproximateComparer.Sign(area1) > 0) return false; var otherT = e.GetOtherTriangle(cdtTriangle); if (otherT == null) return true; var otherSite = otherT.OppositeSite(e); area0 = Point.SignedDoubledTriangleArea(e.upperSite.Point, e.lowerSite.Point, otherSite.Point); return (ApproximateComparer.Sign(area0) * ApproximateComparer.Sign(area1) >= 0); } CdtEdge PiercedEdgeQuery(CdtEdge e, Point source, Point target, CdtTriangle cdtTriangle) { return EdgeIsPierced(e, source, target, cdtTriangle) ? e : null; } RectangleNode<CdtTriangle> cdtTree = null; internal RectangleNode<CdtTriangle> GetCdtTree() { if (cdtTree == null) { cdtTree = RectangleNode<CdtTriangle>.CreateRectangleNodeOnEnumeration(GetTriangles().Select(t => new RectangleNode<CdtTriangle>(t, t.BoundingBox()))); } return cdtTree; } } }
using System; using System.Collections; using System.Text; namespace Rainbow.Framework.Helpers { /// <summary> /// Helper for dealing with IP numbers and ranges of IP numbers. /// Copyright by Bo Norgaard, All rights reserved. /// Modified for Rainbow by Jeremy Esland (jes1111) 26/04/2005 /// </summary> public class IPList { private ArrayList ipRangeList = new ArrayList(); private SortedList maskList = new SortedList(); private ArrayList usedList = new ArrayList(); /// <summary> /// Initializes a new instance of the <see cref="T:IPList"/> class. /// </summary> public IPList() { // Initialize IP mask list and create IPArrayList into the ipRangeList uint mask = 0x00000000; for(int level = 1; level<33; level++) { mask = (mask >> 1) | 0x80000000; maskList.Add(mask,level); ipRangeList.Add(new IPArrayList(mask)); } } /// <summary> /// Parse a String IP address to a 32 bit unsigned integer /// We can't use System.Net.IPAddress as it will not parse /// our masks correctly eg. 255.255.0.0 is parsed as 65535 ! /// </summary> /// <param name="IPNumber">The IP number.</param> /// <returns></returns> private uint parseIP(string IPNumber) { uint res = 0; string[] elements = IPNumber.Split(new Char[] {'.'}); if (elements.Length==4) { res = (uint)Convert.ToInt32(elements[0])<<24; res += (uint)Convert.ToInt32(elements[1])<<16; res += (uint) Convert.ToInt32(elements[2])<<8; res += (uint) Convert.ToInt32(elements[3]); } return res; } /// <summary> /// Add a single IP number to the list as a string, ex. 10.1.1.1 /// </summary> /// <param name="ipNumber">The ip number.</param> public void Add(string ipNumber) { this.Add(parseIP(ipNumber)); } /// <summary> /// Add a single IP number to the list as a unsigned integer, ex. 0x0A010101 /// </summary> /// <param name="ip">The ip.</param> public void Add(uint ip) { ((IPArrayList)ipRangeList[31]).Add(ip); if (!usedList.Contains((int)31)) { usedList.Add((int)31); usedList.Sort(); } } /// <summary> /// Adds IP numbers using a mask for range where the mask specifies the number of /// fixed bits, ex. 172.16.0.0 255.255.0.0 will add 172.16.0.0 - 172.16.255.255 /// </summary> /// <param name="ipNumber">The ip number.</param> /// <param name="mask">The mask.</param> public void Add(string ipNumber, string mask) { this.Add(parseIP(ipNumber),parseIP(mask)); } /// <summary> /// Adds IP numbers using a mask for range where the mask specifies the number of /// fixed bits, ex. 0xAC1000 0xFFFF0000 will add 172.16.0.0 - 172.16.255.255 /// </summary> /// <param name="ip">The ip.</param> /// <param name="umask">The umask.</param> public void Add(uint ip, uint umask) { object Level = maskList[umask]; if (Level!=null) { ip = ip & umask; ((IPArrayList)ipRangeList[(int)Level-1]).Add(ip); if (!usedList.Contains((int)Level-1)) { usedList.Add((int)Level-1); usedList.Sort(); } } } /// <summary> /// Adds IP numbers using a mask for range where the mask specifies the number of /// fixed bits, ex. 192.168.1.0/24 which will add 192.168.1.0 - 192.168.1.255 /// </summary> /// <param name="ipNumber">The ip number.</param> /// <param name="maskLevel">The mask level.</param> public void Add(string ipNumber, int maskLevel) { this.Add(parseIP(ipNumber),(uint)maskList.GetKey(maskList.IndexOfValue(maskLevel))); } /// <summary> /// Adds IP numbers using a from and to IP number. The method checks the range and /// splits it into normal ip/mask blocks. /// </summary> /// <param name="fromIP">From IP.</param> /// <param name="toIP">To IP.</param> public void AddRange(string fromIP, string toIP) { this.AddRange(parseIP(fromIP),parseIP(toIP)); } /// <summary> /// Adds IP numbers using a from and to IP number. The method checks the range and /// splits it into normal ip/mask blocks. /// </summary> /// <param name="fromIP">From IP.</param> /// <param name="toIP">To IP.</param> public void AddRange(uint fromIP, uint toIP) { // If the order is not asending, switch the IP numbers. if (fromIP>toIP) { uint tempIP = fromIP; fromIP=toIP; toIP=tempIP; } if (fromIP==toIP) { this.Add(fromIP); } else { uint diff = toIP-fromIP; int diffLevel = 1; uint range = 0x80000000; if (diff<256) { diffLevel = 24; range = 0x00000100; } while (range>diff) { range = range>>1; diffLevel++; } uint mask = (uint)maskList.GetKey(maskList.IndexOfValue(diffLevel)); uint minIP = fromIP & mask; if (minIP<fromIP) minIP+=range; if (minIP>fromIP) { this.AddRange(fromIP,minIP-1); fromIP=minIP; } if (fromIP==toIP) { this.Add(fromIP); } else { if ((minIP+(range-1))<=toIP) { this.Add(minIP,mask); fromIP = minIP+range; } if (fromIP==toIP) { this.Add(toIP); } else { if (fromIP<toIP) this.AddRange(fromIP,toIP); } } } } /// <summary> /// Checks if an IP number is contained in the lists, ex. 10.0.0.1 /// </summary> /// <param name="ipNumber">The ip number.</param> /// <returns></returns> public bool CheckNumber(string ipNumber) { return this.CheckNumber(parseIP(ipNumber));; } /// <summary> /// Checks if an IP number is contained in the lists, ex. 0x0A000001 /// </summary> /// <param name="ip">The ip.</param> /// <returns></returns> public bool CheckNumber(uint ip) { bool found = false; int i=0; while (!found && i<usedList.Count) { found = ((IPArrayList)ipRangeList[(int)usedList[i]]).Check(ip); i++; } return found; } /// <summary> /// Clears all lists of IP numbers /// </summary> public void Clear() { foreach (int i in usedList) { ((IPArrayList)ipRangeList[i]).Clear(); } usedList.Clear(); } /// <summary> /// Generates a list of all IP ranges in printable format /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>. /// </returns> public override string ToString() { StringBuilder buffer = new StringBuilder(); foreach (int i in usedList) { buffer.Append("\r\nRange with mask of ").Append(i+1).Append("\r\n"); buffer.Append(((IPArrayList)ipRangeList[i]).ToString()); } return buffer.ToString(); } } /// <summary> /// Class for storing a range of IP numbers with the same IP mask /// Copyright by Bo Norgaard, All rights reserved. /// Modified for Rainbow by Jeremy Esland (jes1111) 26/04/2005 /// </summary> public sealed class IPArrayList { private bool isSorted = false; private ArrayList ipNumList = new ArrayList(); private uint ipmask; /// <summary> /// Constructor that sets the mask for the list /// </summary> /// <param name="mask">The mask.</param> public IPArrayList(uint mask) { ipmask = mask; } /// <summary> /// Add a new IP numer (range) to the list /// </summary> /// <param name="IPNum">The IP num.</param> public void Add(uint IPNum) { isSorted = false; ipNumList.Add(IPNum & ipmask); } /// <summary> /// Checks if an IP number is within the ranges included by the list /// </summary> /// <param name="IPNum">The IP num.</param> /// <returns></returns> public bool Check(uint IPNum) { bool found = false; if (ipNumList.Count>0) { if (!isSorted) { ipNumList.Sort(); isSorted=true; } IPNum = IPNum & ipmask; if (ipNumList.BinarySearch(IPNum)>=0) found=true; } return found; } /// <summary> /// Clears the list /// </summary> public void Clear() { ipNumList.Clear(); isSorted = false; } /// <summary> /// The ToString is overriden to generate a list of the IP numbers /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>. /// </returns> public override string ToString() { StringBuilder buf = new StringBuilder(); foreach (uint ipnum in ipNumList) { if (buf.Length>0) buf.Append("\r\n"); buf.Append(((int)ipnum & 0xFF000000) >> 24).Append('.'); buf.Append(((int)ipnum & 0x00FF0000) >> 16).Append('.'); buf.Append(((int)ipnum & 0x0000FF00) >> 8).Append('.'); buf.Append(((int)ipnum & 0x000000FF)); } return buf.ToString(); } /// <summary> /// The IP mask for this list of IP numbers /// </summary> /// <value>The mask.</value> public uint Mask { get { return ipmask; } } } }
// --------------------------------------------------------------------------- // Copyright (C) 2006 Microsoft Corporation All Rights Reserved // --------------------------------------------------------------------------- using System; using System.CodeDom; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; namespace System.Workflow.Activities.Rules { internal abstract class Symbol { internal abstract string Name { get; } internal abstract CodeExpression ParseRootIdentifier(Parser parser, ParserContext parserContext, bool assignIsEquality); internal abstract void RecordSymbol(ArrayList list); } // Represents a field, property, or method within "this". (Not a nested type.) internal class MemberSymbol : Symbol { private MemberInfo member; internal MemberSymbol(MemberInfo member) { this.member = member; } internal override string Name { get { return member.Name; } } internal override CodeExpression ParseRootIdentifier(Parser parser, ParserContext parserContext, bool assignIsEquality) { return parser.ParseUnadornedMemberIdentifier(parserContext, this, assignIsEquality); } internal override void RecordSymbol(ArrayList list) { list.Add(member); } } internal class NamespaceSymbol : Symbol { private string name; internal readonly NamespaceSymbol Parent; internal Dictionary<string, Symbol> NestedSymbols; internal readonly int Level; internal NamespaceSymbol(string name, NamespaceSymbol parent) { this.name = name; this.Parent = parent; this.Level = (parent == null) ? 0 : parent.Level + 1; } // For unnamed namespaces. There is only one of these. internal NamespaceSymbol() { } internal override string Name { get { return name; } } internal NamespaceSymbol AddNamespace(string nsName) { if (NestedSymbols == null) NestedSymbols = new Dictionary<string, Symbol>(); if (!NestedSymbols.TryGetValue(nsName, out Symbol ns)) { ns = new NamespaceSymbol(nsName, this); NestedSymbols.Add(nsName, ns); } return ns as NamespaceSymbol; } internal void AddType(Type type) { TypeSymbol typeSym = new TypeSymbol(type); string typeName = typeSym.Name; if (NestedSymbols == null) NestedSymbols = new Dictionary<string, Symbol>(); if (NestedSymbols.TryGetValue(typeName, out Symbol existingSymbol)) { OverloadedTypeSymbol overloadSym = existingSymbol as OverloadedTypeSymbol; if (overloadSym == null) { TypeSymbol typeSymbol = existingSymbol as TypeSymbol; System.Diagnostics.Debug.Assert(typeSymbol != null); overloadSym = new OverloadedTypeSymbol(typeName, typeSym, typeSymbol); NestedSymbols[typeName] = overloadSym; } else { overloadSym.AddLocalType(typeSym); } } else { NestedSymbols.Add(typeName, typeSym); } } internal Symbol FindMember(string memberName) { NestedSymbols.TryGetValue(memberName, out Symbol nestedSym); return nestedSym; } internal ArrayList GetMembers() { ArrayList members = new ArrayList(NestedSymbols.Count); foreach (Symbol sym in NestedSymbols.Values) sym.RecordSymbol(members); return members; } internal string GetQualifiedName() { StringBuilder sb = new StringBuilder(); Stack<string> names = new Stack<string>(); names.Push(Name); for (NamespaceSymbol currentParent = Parent; currentParent != null; currentParent = currentParent.Parent) names.Push(currentParent.Name); sb.Append(names.Pop()); while (names.Count > 0) { sb.Append('.'); sb.Append(names.Pop()); } return sb.ToString(); } internal override CodeExpression ParseRootIdentifier(Parser parser, ParserContext parserContext, bool assignIsEquality) { return parser.ParseRootNamespaceIdentifier(parserContext, this, assignIsEquality); } internal override void RecordSymbol(ArrayList list) { // Just add the name (string) to the member list. list.Add(Name); } } internal abstract class TypeSymbolBase : Symbol { internal abstract OverloadedTypeSymbol OverloadType(TypeSymbolBase typeSymBase); } internal class TypeSymbol : TypeSymbolBase { internal readonly Type Type; internal readonly int GenericArgCount; private string name; internal TypeSymbol(Type type) { this.Type = type; this.name = type.Name; if (type.IsGenericType) { int tickIx = type.Name.LastIndexOf('`'); if (tickIx > 0) { string count = type.Name.Substring(tickIx + 1); GenericArgCount = Int32.Parse(count, CultureInfo.InvariantCulture); name = type.Name.Substring(0, tickIx); } } } internal override string Name { get { return name; } } internal override OverloadedTypeSymbol OverloadType(TypeSymbolBase newTypeSymBase) { if (newTypeSymBase is OverloadedTypeSymbol newTypeOverload) { // We've encountered an overloaded type symbol over a previous simple // type symbol. return newTypeOverload.OverloadType(this); } else { // We've encountered two simple types... just create an overload for them if // possible. if (newTypeSymBase is TypeSymbol newTypeSym && this.CanOverload(newTypeSym)) return new OverloadedTypeSymbol(name, this, newTypeSym); } return null; } internal bool CanOverload(TypeSymbol typeSym) { return typeSym.GenericArgCount != this.GenericArgCount; } internal override CodeExpression ParseRootIdentifier(Parser parser, ParserContext parserContext, bool assignIsEquality) { // The root name is a type (might be generic or not). return parser.ParseRootTypeIdentifier(parserContext, this, assignIsEquality); } internal override void RecordSymbol(ArrayList list) { // Add the System.Type to the member list. list.Add(Type); } } internal class OverloadedTypeSymbol : TypeSymbolBase { internal List<TypeSymbol> TypeSymbols = new List<TypeSymbol>(); private string name; internal OverloadedTypeSymbol(string name, TypeSymbol typeSym1, TypeSymbol typeSym2) { this.name = name; AddLocalType(typeSym1); AddLocalType(typeSym2); } private OverloadedTypeSymbol(string name, List<TypeSymbol> typeSymbols) { this.name = name; this.TypeSymbols = typeSymbols; } internal override string Name { get { return name; } } // Add a local overload (within the same namespace). internal void AddLocalType(TypeSymbol typeSym) { // Since it's a local overload, we don't have to check whether it's ambiguous. TypeSymbols.Add(typeSym); } internal override OverloadedTypeSymbol OverloadType(TypeSymbolBase newTypeSymBase) { List<TypeSymbol> newOverloads = new List<TypeSymbol>(); TypeSymbol typeSym = null; if (newTypeSymBase is OverloadedTypeSymbol newTypeOverload) { newOverloads.AddRange(newTypeOverload.TypeSymbols); } else { // We've encountered a simple type... just create an overload for them if // possible. typeSym = newTypeSymBase as TypeSymbol; if (typeSym != null) newOverloads.Add(typeSym); } // If every item in this overloaded type symbol is overloadable with the new one, // add to the new list all our items. foreach (TypeSymbol thisTypeSym in this.TypeSymbols) { foreach (TypeSymbol newTypeSym in newOverloads) { if (!newTypeSym.CanOverload(thisTypeSym)) return null; // Can't overload } newOverloads.Add(thisTypeSym); } return new OverloadedTypeSymbol(name, newOverloads); } internal override CodeExpression ParseRootIdentifier(Parser parser, ParserContext parserContext, bool assignIsEquality) { return parser.ParseRootOverloadedTypeIdentifier(parserContext, this.TypeSymbols, assignIsEquality); } internal override void RecordSymbol(ArrayList list) { foreach (TypeSymbol overloadedType in TypeSymbols) list.Add(overloadedType.Type); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.CSharp.Interactive; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Scripting; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Traits = Roslyn.Test.Utilities.Traits; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostTests : AbstractInteractiveHostTests { #region Utils private SynchronizedStringWriter _synchronizedOutput; private SynchronizedStringWriter _synchronizedErrorOutput; private int[] _outputReadPosition = new int[] { 0, 0 }; internal readonly InteractiveHost Host; public InteractiveHostTests() { Host = new InteractiveHost(typeof(CSharpRepl), GetInteractiveHostPath(), ".", millisecondsTimeout: -1); RedirectOutput(); Host.ResetAsync(InteractiveHostOptions.Default).Wait(); var remoteService = Host.TryGetService(); Assert.NotNull(remoteService); remoteService.ObjectFormattingOptions = new ObjectFormattingOptions( memberFormat: MemberDisplayFormat.Inline, quoteStrings: true, useHexadecimalNumbers: false, maxOutputLength: int.MaxValue, memberIndentation: " "); // assert and remove logo: var output = ReadOutputToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); var errorOutput = ReadErrorOutputToEnd(); Assert.Equal("", errorOutput); Assert.Equal(2, output.Length); Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); // "Type "#help" for more information." Assert.Equal(FeaturesResources.TypeHelpForMoreInformation, output[1]); // remove logo: ClearOutput(); } public override void Dispose() { try { Process process = Host.TryGetProcess(); DisposeInteractiveHostProcess(Host); // the process should be terminated if (process != null && !process.HasExited) { process.WaitForExit(); } } finally { // Dispose temp files only after the InteractiveHost exits, // so that assemblies are unloaded. base.Dispose(); } } internal void RedirectOutput() { _synchronizedOutput = new SynchronizedStringWriter(); _synchronizedErrorOutput = new SynchronizedStringWriter(); ClearOutput(); Host.Output = _synchronizedOutput; Host.ErrorOutput = _synchronizedErrorOutput; } internal AssemblyLoadResult LoadReference(string reference) { return Host.TryGetService().LoadReferenceThrowing(reference, addReference: true); } internal bool Execute(string code) { var task = Host.ExecuteAsync(code); task.Wait(); return task.Result.Success; } internal bool IsShadowCopy(string path) { return Host.TryGetService().IsShadowCopy(path); } public string ReadErrorOutputToEnd() { return ReadOutputToEnd(isError: true); } public void ClearOutput() { _outputReadPosition = new int[] { 0, 0 }; _synchronizedOutput.Clear(); _synchronizedErrorOutput.Clear(); } public void RestartHost(string rspFile = null) { ClearOutput(); var initTask = Host.ResetAsync(InteractiveHostOptions.Default.WithInitializationFile(rspFile)); initTask.Wait(); } public string ReadOutputToEnd(bool isError = false) { var writer = isError ? _synchronizedErrorOutput : _synchronizedOutput; var markPrefix = '\uFFFF'; var mark = markPrefix + Guid.NewGuid().ToString(); // writes mark to the STDOUT/STDERR pipe in the remote process: Host.TryGetService().RemoteConsoleWrite(Encoding.UTF8.GetBytes(mark), isError); while (true) { var data = writer.Prefix(mark, ref _outputReadPosition[isError ? 0 : 1]); if (data != null) { return data; } Thread.Sleep(10); } } internal class CompiledFile { public string Path; public ImmutableArray<byte> Image; } internal CompiledFile CompileLibrary(TempDirectory dir, string fileName, string assemblyName, string source, params MetadataReference[] references) { const string Prefix = "RoslynTestFile_"; fileName = Prefix + fileName; assemblyName = Prefix + assemblyName; var file = dir.CreateFile(fileName); var compilation = CreateCompilation( new[] { source }, assemblyName: assemblyName, references: references.Concat(new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }), options: fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll); var image = compilation.EmitToArray(); file.WriteAllBytes(image); return new CompiledFile { Path = file.Path, Image = image }; } #endregion [Fact] // Bugs #5018, #5344 public void OutputRedirection() { Execute(@" System.Console.WriteLine(""hello-\u4567!""); System.Console.Error.WriteLine(""error-\u7890!""); 1+1 "); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("hello-\u4567!\r\n2\r\n", output); Assert.Equal("error-\u7890!\r\n", error); } [Fact] public void OutputRedirection2() { Execute(@"System.Console.WriteLine(1);"); Execute(@"System.Console.Error.WriteLine(2);"); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("1\r\n", output); Assert.Equal("2\r\n", error); RedirectOutput(); Execute(@"System.Console.WriteLine(3);"); Execute(@"System.Console.Error.WriteLine(4);"); output = ReadOutputToEnd(); error = ReadErrorOutputToEnd(); Assert.Equal("3\r\n", output); Assert.Equal("4\r\n", error); } [Fact] public void StackOverflow() { // Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) ignores SetErrorMode and shows crash dialog, which would hang the test: if (Environment.OSVersion.Version < new Version(6, 1, 0, 0)) { return; } Execute(@" int foo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9) { return foo(0,1,2,3,4,5,6,7,8,9) + foo(0,1,2,3,4,5,6,7,8,9); } foo(0,1,2,3,4,5,6,7,8,9) "); Assert.Equal("", ReadOutputToEnd()); // Hosting process exited with exit code -1073741571. Assert.Equal("Process is terminated due to StackOverflowException.\n" + string.Format(FeaturesResources.HostingProcessExitedWithExitCode, -1073741571), ReadErrorOutputToEnd().Trim()); Execute(@"1+1"); Assert.Equal("2\r\n", ReadOutputToEnd().ToString()); } private const string MethodWithInfiniteLoop = @" void foo() { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { System.Console.Error.WriteLine(""in the loop""); i = i + 1; } } } "; [Fact] public void AsyncExecute_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); Assert.True(mayTerminate.WaitOne()); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact(Skip = "529027")] public void AsyncExecute_HangingForegroundThreads() { var mayTerminate = new ManualResetEvent(false); Host.OutputReceived += (_, __) => { mayTerminate.Set(); }; var executeTask = Host.ExecuteAsync(@" using System.Threading; int i1 = 0; Thread t1 = new Thread(() => { while(true) { i1++; } }); t1.Name = ""TestThread-1""; t1.IsBackground = false; t1.Start(); int i2 = 0; Thread t2 = new Thread(() => { while(true) { i2++; } }); t2.Name = ""TestThread-2""; t2.IsBackground = true; t2.Start(); Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite)); t3.Name = ""TestThread-3""; t3.Start(); while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { } System.Console.WriteLine(""terminate!""); while(true) {} "); Assert.Equal("", ReadErrorOutputToEnd()); Assert.True(mayTerminate.WaitOne()); var service = Host.TryGetService(); Assert.NotNull(service); var process = Host.TryGetProcess(); Assert.NotNull(process); service.EmulateClientExit(); // the process should terminate with exit code 0: process.WaitForExit(); Assert.Equal(0, process.ExitCode); } [Fact] public void AsyncExecuteFile_InfiniteLoop() { var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path; var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteFileAsync(file); mayTerminate.WaitOne(); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact] public void AsyncExecuteFile_SourceKind() { var file = Temp.CreateFile().WriteAllText("1+1").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file + "(1,4):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_NonExistingFile() { var task = Host.ExecuteFileAsync("non existing file"); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.Contains("Specified file not found.", errorOut, StringComparison.Ordinal); Assert.Contains("Searched in directories:", errorOut, StringComparison.Ordinal); } [Fact] public void AsyncExecuteFile() { var file = Temp.CreateFile().WriteAllText(@" using static System.Console; public class C { public int field = 4; public int Foo(int i) { return i; } } public int Foo(int i) { return i; } WriteLine(5); ").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.True(task.Result.Success); Assert.Equal("5", ReadOutputToEnd().Trim()); Execute("Foo(2)"); Assert.Equal("2", ReadOutputToEnd().Trim()); Execute("new C().Foo(3)"); Assert.Equal("3", ReadOutputToEnd().Trim()); Execute("new C().field"); Assert.Equal("4", ReadOutputToEnd().Trim()); } [Fact] public void AsyncExecuteFile_InvalidFileContent() { var executeTask = Host.ExecuteFileAsync(typeof(Process).Assembly.Location); executeTask.Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_ScriptFileWithBuildErrors() { var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}"); Host.ExecuteFileAsync(file.Path).Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file.Path + "(1,2):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1024"), "Error output should include error CS1024"); } /// <summary> /// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be /// even invoked since we resolve the assembly via Fusion. /// </summary> [Fact(Skip = "987032")] public void UserDefinedAssemblyResolve_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); Host.TryGetService().HookMaliciousAssemblyResolve(); var executeTask = Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid()); Assert.True(mayTerminate.WaitOne()); executeTask.Wait(); Assert.True(Execute(@"1+1")); var output = ReadOutputToEnd(); Assert.Equal("2\r\n", output); } [Fact] public void AddReference_PartialName() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference("System").IsSuccessful); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [Fact] public void AddReference_PartialName_LatestVersion() { // there might be two versions of System.Data - v2 and v4, we should get the latter: Assert.True(LoadReference("System.Data").IsSuccessful); Assert.True(LoadReference("System").IsSuccessful); Assert.True(LoadReference("System.Xml").IsSuccessful); var version = (Version)Host.TryGetService().ExecuteAndWrap("new System.Data.DataSet().GetType().Assembly.GetName().Version").Unwrap(); Assert.True(version >= new Version(4, 0, 0, 0), "Actual:" + version.ToString()); } [Fact] public void AddReference_FullName() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference(typeof(Process).Assembly.FullName).IsSuccessful); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [ConditionalFact(typeof(Framework35Installed))] public void AddReference_VersionUnification1() { var location = typeof(Enumerable).Assembly.Location; // V3.5 unifies with the current Framework version: var result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.True(result.IsSuccessful, "First load"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.False(result.IsSuccessful, "Already loaded"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); result = LoadReference("System.Core"); Assert.False(result.IsSuccessful, "Already loaded"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); } // TODO: merge with previous test [Fact] public void AddReference_VersionUnification2() { var location = typeof(Enumerable).Assembly.Location; var result = LoadReference("System.Core"); Assert.True(result.IsSuccessful, "First load"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); result = LoadReference("System.Core.dll"); Assert.False(result.IsSuccessful, "Already loaded"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); } [Fact] public void AddReference_Path() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference(typeof(Process).Assembly.Location).IsSuccessful); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [Fact(Skip = "530414")] public void AddReference_ShadowCopy() { var dir = Temp.CreateDirectory(); // create C.dll var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); // load C.dll: Assert.True(LoadReference(c.Path).IsSuccessful); Assert.True(Execute("new C()")); Assert.Equal("C { }", ReadOutputToEnd().Trim()); // rewrite C.dll: File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 }); // we can still run code: var result = Execute("new C()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("C { }", ReadOutputToEnd().Trim()); Assert.True(result); } /// <summary> /// Tests that a dependency is correctly resolved and loaded at runtime. /// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded. /// </summary> [Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")] public void AddReference_Dependencies() { var dir = Temp.CreateDirectory(); var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image)); var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image)); AssemblyLoadResult result; result = LoadReference(a.Path); Assert.Equal(a.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); Assert.True(Execute("A.CallB()")); // c.dll is loaded as a dependency, so #r should be successful: result = LoadReference(c.Path); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); // c.dll was already loaded explicitly via #r so we should fail now: result = LoadReference(c.Path); Assert.False(result.IsSuccessful); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } /// <summary> /// When two files of the same version are in the same directory, prefer .dll over .exe. /// </summary> [Fact] public void AddReference_Dependencies_DllExe() { var dir = Temp.CreateDirectory(); var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }"); var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(dll.Image)); Assert.True(LoadReference(main.Path).IsSuccessful); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.SymbolsTests.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.SymbolsTests.General.C2); Assert.True(LoadReference(file1.Path).IsSuccessful); Assert.True(LoadReference(file2.Path).IsSuccessful); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.SymbolsTests.General.C2.AsImmutableOrNull())); Assert.True(LoadReference(main.Path).IsSuccessful); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("2", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_AlreadyLoadedDependencies() { var dir = Temp.CreateDirectory(); var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }"); var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }", MetadataReference.CreateFromFile(lib1.Path)); Execute("#r \"" + lib1.Path + "\""); Execute("#r \"" + lib2.Path + "\""); Execute("new C().M()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact(Skip = "530414")] public void AddReference_LoadUpdatedReference() { var dir = Temp.CreateDirectory(); var source1 = "public class C { public int X = 1; }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); // use: Execute(@" #r """ + file.Path + @""" C foo() { return new C(); } new C().X "); // update: var source2 = "public class D { public int Y = 2; }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); file.WriteAllBytes(c2.EmitToArray()); // add the reference again: Execute(@" #r """ + file.Path + @""" new D().Y "); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal( @"1 2", ReadOutputToEnd().Trim()); } [Fact(Skip = "987032")] public void AddReference_MutlipleReferencesWithSameWeakIdentity() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = "public class C1 { }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = "public class C2 { }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); Execute(@" #r """ + file1.Path + @""" #r """ + file2.Path + @""" "); Execute("new C1()"); Execute("new C2()"); Assert.Equal( @"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side. (1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) (1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); } //// TODO (987032): //// [Fact] //// public void AsyncInitializeContextWithDotNETLibraries() //// { //// var rspFile = Temp.CreateFile(); //// var rspDisplay = Path.GetFileName(rspFile.Path); //// var initScript = Temp.CreateFile(); //// rspFile.WriteAllText(@" /////r:System.Core ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Linq.Expressions; ////WriteLine(Expression.Constant(123)); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var output = ReadOutputToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("123", output[3]); //// Assert.Equal("", errorOutput); //// Host.InitializeContextAsync(rspFile.Path).Wait(); //// output = ReadOutputToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //// errorOutput = ReadErrorOutputToEnd(); //// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines."); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]); //// Assert.Equal("123", output[1]); //// Assert.Equal("", errorOutput); //// } //// [Fact] //// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries() //// { //// var dir = Temp.CreateDirectory(); //// var rspFile = Temp.CreateFile(); //// var initScript = Temp.CreateFile(); //// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); //// rspFile.WriteAllText(@" /////r:System.Numerics /////r:" + dll.Path + @" ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Numerics; ////WriteLine(new Complex(12, 6).Real + C.Main()); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal("", errorOutput); //// var output = ReadOutputToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("13", output[3]); //// } [Fact] public void ReferenceDirectives() { var task = Host.ExecuteAsync(@" #r ""System.Numerics"" #r """ + typeof(System.Linq.Expressions.Expression).Assembly.Location + @""" using static System.Console; using System.Linq.Expressions; using System.Numerics; WriteLine(Expression.Constant(1)); WriteLine(new Complex(2, 6).Real); "); task.Wait(); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n", output); } [Fact] public void ExecutesOnStaThread() { var task = Host.ExecuteAsync(@" #r ""System"" #r ""System.Xaml"" #r ""WindowsBase"" #r ""PresentationCore"" #r ""PresentationFramework"" new System.Windows.Window(); System.Console.WriteLine(""OK""); "); task.Wait(); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("OK\r\n", output); } [Fact] public void MultiModuleAssembly() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModule); dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2); dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3); var task = Host.ExecuteAsync(@" #r """ + dll.Path + @""" new object[] { new Class1(), new Class2(), new Class3() } "); task.Wait(); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output); } [Fact] public void SearchPaths1() { var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01); var srcDir = Temp.CreateDirectory(); var dllDir = Path.GetDirectoryName(dll.Path); srcDir.CreateFile("foo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");"); Func<string, string> normalizeSeparatorsAndFrameworkFolders = (s) => s.Replace("\\", "\\\\").Replace("Framework64", "Framework"); // print default: Host.ExecuteAsync(@"ReferencePaths").Wait(); var output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", ScriptOptions.Default.SearchPaths)) + "\" }\r\n", output); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultSourceSearchPaths)) + "\" }\r\n", output); // add and test if added: Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");").Wait(); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultSourceSearchPaths.Concat(new[] { srcDir.Path }))) + "\" }\r\n", output); // execute file (uses modified search paths), the file adds a reference path Host.ExecuteFileAsync("foo.csx").Wait(); Host.ExecuteAsync(@"ReferencePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", ScriptOptions.Default.SearchPaths.Concat(new[] { dllDir }))) + "\" }\r\n", output); Host.AddReferenceAsync(Path.GetFileName(dll.Path)).Wait(); Host.ExecuteAsync(@"typeof(Metadata.ICSProp)").Wait(); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); output = ReadOutputToEnd(); Assert.Equal("[Metadata.ICSProp]\r\n", output); } [Fact] public void InvalidArguments() { Assert.Throws<FileNotFoundException>(() => LoadReference("")); Assert.Throws<FileNotFoundException>(() => LoadReference("\0")); Assert.Throws<FileNotFoundException>(() => LoadReference("blah \0")); Assert.Throws<FileNotFoundException>(() => LoadReference("*.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference("*.exe")); Assert.Throws<FileNotFoundException>(() => LoadReference("http://foo.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference("blah:foo.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference("C:\\" + new string('x', 10000) + "\\foo.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference("system,mscorlib")); Assert.Throws<FileNotFoundException>(() => LoadReference(@"\\sample\sample1.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference(typeof(string).Assembly.Location + " " + typeof(string).Assembly.Location)); } #region Submission result printing - null/void/value. [Fact] public void SubmissionResult_PrintingNull() { Execute(@" string s; s "); var output = ReadOutputToEnd(); Assert.Equal("null\r\n", output); } [Fact] public void SubmissionResult_PrintingVoid() { Execute(@"System.Console.WriteLine(2)"); var output = ReadOutputToEnd(); Assert.Equal("2\r\n<void>\r\n", output); Execute(@" void foo() { } foo() "); output = ReadOutputToEnd(); Assert.Equal("<void>\r\n", output); } #endregion } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// <summary>Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, /// the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread. /// <para>This class cannot be inherited.</para> /// </summary> [SerializableAttribute] [SecurityCritical] public sealed class DiskSpaceInfo { #region Constructor /// <summary>Initializes a DiskSpaceInfo instance.</summary> /// <param name="drivePath">A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: \\server\share</param> /// <Remark>This is a Lazyloading object; call <see cref="Refresh()"/> to populate all properties first before accessing.</Remark> [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public DiskSpaceInfo(string drivePath) { if (Utils.IsNullOrWhiteSpace(drivePath)) throw new ArgumentNullException("drivePath"); if (drivePath.Length == 1) DriveName += Path.VolumeSeparatorChar; else DriveName = Path.GetPathRoot(drivePath, false); if (Utils.IsNullOrWhiteSpace(DriveName)) throw new ArgumentException("Argument must be a drive letter (\"C\"), RootDir (\"C:\\\") or UNC path (\"\\\\server\\share\")"); // MSDN: // If this parameter is a UNC name, it must include a trailing backslash (for example, "\\MyServer\MyShare\"). // Furthermore, a drive specification must have a trailing backslash (for example, "C:\"). // The calling application must have FILE_LIST_DIRECTORY access rights for this directory. DriveName = Path.AddTrailingDirectorySeparator(DriveName, false); } /// <summary>Initializes a DiskSpaceInfo instance.</summary> /// <param name="drivePath">A valid drive path or drive letter. This can be either uppercase or lowercase, 'a' to 'z' or a network share in the format: \\server\share</param> /// <param name="spaceInfoType"><see langword="null"/> gets both size- and disk cluster information. <see langword="true"/> Get only disk cluster information, <see langword="false"/> Get only size information.</param> /// <param name="refresh">Refreshes the state of the object.</param> /// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param> [SecurityCritical] public DiskSpaceInfo(string drivePath, bool? spaceInfoType, bool refresh, bool continueOnException) : this(drivePath) { if (spaceInfoType == null) _initGetSpaceInfo = _initGetClusterInfo = true; else { _initGetSpaceInfo = (bool) !spaceInfoType; _initGetClusterInfo = (bool) spaceInfoType; } _continueOnAccessError = continueOnException; if (refresh) Refresh(); } #endregion // Constructor #region Fields private readonly bool _initGetClusterInfo = true; private readonly bool _initGetSpaceInfo = true; private readonly bool _continueOnAccessError; #endregion // Fields #region Methods #region Refresh /// <summary>Refreshes the state of the object.</summary> public void Refresh() { Reset(); // ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups. using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors)) { int lastError = (int) Win32Errors.NO_ERROR; #region Get size information. if (_initGetSpaceInfo) { long freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes; if (!NativeMethods.GetDiskFreeSpaceEx(DriveName, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes)) lastError = Marshal.GetLastWin32Error(); else { FreeBytesAvailable = freeBytesAvailable; TotalNumberOfBytes = totalNumberOfBytes; TotalNumberOfFreeBytes = totalNumberOfFreeBytes; } if (!_continueOnAccessError && (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NOT_READY)) NativeError.ThrowException(DriveName); } #endregion // Get size information. #region Get cluster information. if (_initGetClusterInfo) { int sectorsPerCluster, bytesPerSector, numberOfFreeClusters; uint totalNumberOfClusters; if (!NativeMethods.GetDiskFreeSpace(DriveName, out sectorsPerCluster, out bytesPerSector, out numberOfFreeClusters, out totalNumberOfClusters)) lastError = Marshal.GetLastWin32Error(); else { BytesPerSector = bytesPerSector; NumberOfFreeClusters = numberOfFreeClusters; SectorsPerCluster = sectorsPerCluster; TotalNumberOfClusters = totalNumberOfClusters; } if (!_continueOnAccessError && (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_NOT_READY)) NativeError.ThrowException(DriveName); } #endregion // Get cluster information. } } #endregion // Refresh #region Reset /// <summary>Initializes all <see ref="Alphaleonis.Win32.Filesystem.DiskSpaceInfo"/> properties to 0.</summary> private void Reset() { if (_initGetSpaceInfo) FreeBytesAvailable = TotalNumberOfBytes = TotalNumberOfFreeBytes = 0; if (_initGetClusterInfo) { BytesPerSector = NumberOfFreeClusters = SectorsPerCluster = 0; TotalNumberOfClusters = 0; } } #endregion // Reset #region ToString /// <summary>Returns the drive name.</summary> /// <returns>A string that represents this object.</returns> public override string ToString() { return DriveName; } #endregion // ToString #endregion // Methods #region Properties /// <summary>Indicates the amount of available free space on a drive, formatted as percentage.</summary> public string AvailableFreeSpacePercent { get { return string.Format(CultureInfo.CurrentCulture, "{0:0.00}%", Utils.PercentCalculate(TotalNumberOfBytes - (TotalNumberOfBytes - TotalNumberOfFreeBytes), 0, TotalNumberOfBytes)); } } /// <summary>Indicates the amount of available free space on a drive, formatted as a unit size.</summary> public string AvailableFreeSpaceUnitSize { get { return Utils.UnitSizeToText(TotalNumberOfFreeBytes); } } /// <summary>Returns the Clusters size.</summary> public long ClusterSize { get { return SectorsPerCluster * BytesPerSector; } } /// <summary>Gets the name of a drive.</summary> /// <returns>The name of the drive.</returns> /// <remarks>This property is the name assigned to the drive, such as C:\ or E:\</remarks> public string DriveName { get; private set; } /// <summary>The total number of bytes on a disk that are available to the user who is associated with the calling thread, formatted as a unit size.</summary> public string TotalSizeUnitSize { get { return Utils.UnitSizeToText(TotalNumberOfBytes); } } /// <summary>Indicates the amount of used space on a drive, formatted as percentage.</summary> public string UsedSpacePercent { get { return string.Format(CultureInfo.CurrentCulture, "{0:0.00}%", Utils.PercentCalculate(TotalNumberOfBytes - FreeBytesAvailable, 0, TotalNumberOfBytes)); } } /// <summary>Indicates the amount of used space on a drive, formatted as a unit size.</summary> public string UsedSpaceUnitSize { get { return Utils.UnitSizeToText(TotalNumberOfBytes - FreeBytesAvailable); } } /// <summary>The total number of free bytes on a disk that are available to the user who is associated with the calling thread.</summary> public long FreeBytesAvailable { get; private set; } /// <summary>The total number of bytes on a disk that are available to the user who is associated with the calling thread.</summary> public long TotalNumberOfBytes { get; private set; } /// <summary>The total number of free bytes on a disk.</summary> public long TotalNumberOfFreeBytes { get; private set; } /// <summary>The number of bytes per sector.</summary> public int BytesPerSector { get; private set; } /// <summary>The total number of free clusters on the disk that are available to the user who is associated with the calling thread.</summary> public int NumberOfFreeClusters { get; private set; } /// <summary>The number of sectors per cluster.</summary> public int SectorsPerCluster { get; private set; } /// <summary>The total number of clusters on the disk that are available to the user who is associated with the calling thread. /// If per-user disk quotas are in use, this value may be less than the total number of clusters on the disk. /// </summary> public long TotalNumberOfClusters { get; private set; } #endregion // Properties } }
using System; using System.Threading; namespace Netduino.IP { internal class ICMPv4Handler : IDisposable { // fixed buffer for ICMP frames const int ICMP_HEADER_LENGTH = 8; const int ICMP_FRAME_BUFFER_LENGTH = 8; byte[] _icmpFrameBuffer = new byte[ICMP_FRAME_BUFFER_LENGTH]; object _icmpFrameBufferLock = new object(); byte[][] _bufferArray = new byte[2][]; int[] _indexArray = new int[2]; int[] _countArray = new int[2]; protected byte[][] _checksumBufferArray = new byte[2][]; protected int[] _checksumOffsetArray = new int[2]; protected int[] _checksumCountArray = new int[2]; object _checksumLock = new object(); IPv4Layer _ipv4Layer; bool _isDisposed = false; enum IcmpMessageType : byte { EchoReply = 0, //DestinationUnreachable = 3, Echo = 8, /* EchoRequest */ //TimeExceeded = 11, } enum IcmpMessageCode : byte { None = 0, //TimeExceeded_TtlExpiredInTransit = 0, //TimeExceeded_FragmentReassemblyTimeExceeded = 1, } struct IcmpMessage { public UInt32 DestinationIPAddress; public IcmpMessageType IcmpMessageType; public IcmpMessageCode IcmpMessageCode; public byte[] RestOfHeader; public byte[] Data; public IcmpMessage(UInt32 destinationIPAddress, IcmpMessageType icmpMessageType, IcmpMessageCode icmpMessageCode, byte[] restOfHeader, byte[] data) { this.DestinationIPAddress = destinationIPAddress; this.IcmpMessageType = icmpMessageType; this.IcmpMessageCode = icmpMessageCode; this.RestOfHeader = new byte[4]; if (restOfHeader != null) { Array.Copy(restOfHeader, this.RestOfHeader, System.Math.Min(this.RestOfHeader.Length, restOfHeader.Length)); } if (data != null) { this.Data = data; } else { this.Data = new byte[0]; } } } System.Threading.Thread _sendIcmpMessagesInBackgroundThread; AutoResetEvent _sendIcmpMessagesInBackgroundEvent = new AutoResetEvent(false); System.Collections.Queue _sendIcmpMessagesInBackgroundQueue; //struct EchoRequest //{ // public UInt32 DestinationIPAddress; // public UInt16 Identifier; // public UInt16 SequenceNumber; // public byte[] Data; // AutoResetEvent _responseReceivedEvent; // public EchoRequest(UInt32 destinationIPAddress, UInt16 identifier, UInt16 sequenceNumber, byte[] data) // { // this.DestinationIPAddress = destinationIPAddress; // this.Identifier = identifier; // this.SequenceNumber = sequenceNumber; // this.Data = data; // _responseReceivedEvent = new AutoResetEvent(false); // } // public bool WaitForResponse(Int32 millisecondsTimeout) // { // return _responseReceivedEvent.WaitOne(millisecondsTimeout, false); // } // internal void SetResponseReceived() // { // _responseReceivedEvent.Set(); // } //} //System.Collections.ArrayList _outstandingEchoRequests = new System.Collections.ArrayList(); //object _outstandingEchoRequestsLock = new object(); //UInt16 _nextEchoRequestSequenceNumber = 0; internal ICMPv4Handler(IPv4Layer ipv4Layer) { _ipv4Layer = ipv4Layer; // start our "send ICMP messages transmission" thread _sendIcmpMessagesInBackgroundQueue = new System.Collections.Queue(); _sendIcmpMessagesInBackgroundThread = new Thread(SendIcmpMessagesThread); _sendIcmpMessagesInBackgroundThread.Start(); } public void Dispose() { if (_isDisposed) return; _isDisposed = true; // shut down our icmp messages transmission thread if (_sendIcmpMessagesInBackgroundEvent != null) { _sendIcmpMessagesInBackgroundEvent.Set(); _sendIcmpMessagesInBackgroundEvent = null; } _ipv4Layer = null; _icmpFrameBuffer = null; _icmpFrameBufferLock = null; //if (_outstandingEchoRequests != null) //{ // for (int i = 0; i < _outstandingEchoRequests.Count; i++) // { // if (_outstandingEchoRequests[i] != null) // { // ((IDisposable)_outstandingEchoRequests[i]).Dispose(); // } // } //} //_outstandingEchoRequests = null; //_outstandingEchoRequestsLock = null; _bufferArray = null; _indexArray = null; _countArray = null; _checksumBufferArray = null; _checksumOffsetArray = null; _checksumCountArray = null; _checksumLock = null; } internal void OnPacketReceived(UInt32 sourceIPAddress, byte[] buffer, Int32 index, Int32 count) { if (count < ICMP_HEADER_LENGTH) return; UInt16 verifyChecksum; lock (_checksumLock) { // calculate checksum over entire ICMP frame including data _checksumBufferArray[0] = buffer; _checksumOffsetArray[0] = index; _checksumCountArray[0] = count; verifyChecksum = Utility.CalculateInternetChecksum(_checksumBufferArray, _checksumOffsetArray, _checksumCountArray, 1); } if (verifyChecksum != 0x0000) return; /* parse ICMP message */ /* Type */ IcmpMessageType icmpMessageType = (IcmpMessageType)buffer[index + 0]; /* Code (Subtype) */ IcmpMessageCode icmpMessageCode = (IcmpMessageCode)buffer[index + 1]; /* Rest of header */ byte[] restOfHeader = new byte[4]; Array.Copy(buffer, index + 4, restOfHeader, 0, restOfHeader.Length); /* Data */ byte[] data = new byte[count - 8]; Array.Copy(buffer, index + 8, data, 0, data.Length); /* process ICMP message */ switch (icmpMessageType) { case IcmpMessageType.Echo: { SendIcmpMessageInBackground(sourceIPAddress, IcmpMessageType.EchoReply, IcmpMessageCode.None, restOfHeader, data); } break; //case IcmpMessageType.EchoReply: // { // lock (_outstandingEchoRequestsLock) // { // for (int i = 0; i < _outstandingEchoRequests.Count; i++) // { // if (_outstandingEchoRequests[i] != null) // { // // check to see if this request matches // EchoRequest echoRequest = (EchoRequest)_outstandingEchoRequests[i]; // if (echoRequest.DestinationIPAddress == sourceIPAddress) // { // /* parse restOfHeader */ // UInt16 identifier = (UInt16)((restOfHeader[0] << 8) + restOfHeader[1]); // UInt16 sequenceNumber = (UInt16)((restOfHeader[2] << 8) + restOfHeader[3]); // if ((echoRequest.Identifier == identifier) && (echoRequest.SequenceNumber == sequenceNumber) && (echoRequest.Data.Length == data.Length)) // { // bool dataMatches = true; // for (int iData = 0; iData < data.Length; iData++) // { // if (data[iData] != echoRequest.Data[iData]) // { // dataMatches = false; // break; // } // } // if (dataMatches) // echoRequest.SetResponseReceived(); // } // } // } // } // } // } // break; default: break; } } ///* this function returns true if ping was success, and false if ping was not successful */ //bool PingDestinationIPAddress(UInt32 destinationIPAddress) //{ // byte[] restOfHeader = new byte[4]; // UInt16 identifier = 0x0000; // UInt16 sequenceNumber = _nextEchoRequestSequenceNumber++; // restOfHeader[0] = (byte)((identifier << 8) & 0xFF); // restOfHeader[1] = (byte)(identifier & 0xFF); // restOfHeader[2] = (byte)((sequenceNumber << 8) & 0xFF); // restOfHeader[3] = (byte)(sequenceNumber & 0xFF); // /* for data, we will include a simple 8-character array. we could alternatively send a timestamp, etc. */ // byte[] data = System.Text.Encoding.UTF8.GetBytes("abcdefgh"); // EchoRequest echoRequest = new EchoRequest(destinationIPAddress, identifier, sequenceNumber, data); // lock (_outstandingEchoRequests) // { // _outstandingEchoRequests.Add(echoRequest); // } // bool echoReplyReceived = false; // try // { // Int64 timeoutInMachineTicks = 1 * TimeSpan.TicksPerSecond; /* wait up to one second for ping to be sent */ // /* send ICMP echo request */ // SendIcmpMessage(destinationIPAddress, IcmpMessageType.Echo, IcmpMessageCode.None, restOfHeader, data, timeoutInMachineTicks); // /* wait for ICMP echo reply for up to one second */ // echoReplyReceived = echoRequest.WaitForResponse(1000); // } // finally // { // /* remove ICMP request from collection */ // lock (_outstandingEchoRequests) // { // _outstandingEchoRequests.Remove(echoRequest); // } // } // /* if we did not get a match, return false */ // return echoReplyReceived; //} void SendIcmpMessagesThread() { while (true) { _sendIcmpMessagesInBackgroundEvent.WaitOne(); // if we have been disposed, shut down our thread now. if (_isDisposed) return; while ((_sendIcmpMessagesInBackgroundQueue != null) && (_sendIcmpMessagesInBackgroundQueue.Count > 0)) { try { IcmpMessage icmpMessage = (IcmpMessage)_sendIcmpMessagesInBackgroundQueue.Dequeue(); SendIcmpMessage(icmpMessage.DestinationIPAddress, icmpMessage.IcmpMessageType, icmpMessage.IcmpMessageCode, icmpMessage.RestOfHeader, icmpMessage.Data, Int64.MaxValue); } catch (InvalidOperationException) { // reply queue was empty } // if we have been disposed, shut down our thread now. if (_isDisposed) return; } } } void SendIcmpMessageInBackground(UInt32 destinationIPAddress, IcmpMessageType icmpMessageType, IcmpMessageCode icmpMessageCode, byte[] restOfHeader, byte[] data) { IcmpMessage icmpMessage = new IcmpMessage(destinationIPAddress, icmpMessageType, icmpMessageCode, restOfHeader, data); _sendIcmpMessagesInBackgroundQueue.Enqueue(icmpMessage); _sendIcmpMessagesInBackgroundEvent.Set(); } void SendIcmpMessage(UInt32 destinationIPAddress, IcmpMessageType icmpMessageType, IcmpMessageCode icmpMessageCode, byte[] restOfHeader, byte[] data, Int64 timeoutInMachineTicks) { if (_isDisposed) return; lock (_icmpFrameBufferLock) { // configure ICMPv4 frame /* Type */ _icmpFrameBuffer[0] = (byte)icmpMessageType; /* Code (Subtype) */ _icmpFrameBuffer[1] = (byte)icmpMessageCode; /* checksum (clear this for now; we will calculate it shortly) */ Array.Clear(_icmpFrameBuffer, 2, 2); /* restOfHeader */ if (restOfHeader.Length < 4) Array.Clear(_icmpFrameBuffer, 4, 4); Array.Copy(restOfHeader, 0, _icmpFrameBuffer, 4, System.Math.Min(4, restOfHeader.Length)); UInt16 checksum; lock (_checksumLock) { // calculate checksum over entire ICMP frame including data _checksumBufferArray[0] = _icmpFrameBuffer; _checksumOffsetArray[0] = 0; _checksumCountArray[0] = ICMP_FRAME_BUFFER_LENGTH; _checksumBufferArray[1] = data; _checksumOffsetArray[1] = 0; _checksumCountArray[1] = data.Length; checksum = Utility.CalculateInternetChecksum(_checksumBufferArray, _checksumOffsetArray, _checksumCountArray, 2); } _icmpFrameBuffer[2] = (byte)((checksum >> 8) & 0xFF); _icmpFrameBuffer[3] = (byte)(checksum & 0xFF); _bufferArray[0] = _icmpFrameBuffer; _indexArray[0] = 0; _countArray[0] = ICMP_FRAME_BUFFER_LENGTH; _bufferArray[1] = data; _indexArray[1] = 0; _countArray[1] = data.Length; _ipv4Layer.Send(1 /* PROTOCOL for ICMP */, _ipv4Layer.IPAddress, destinationIPAddress, _bufferArray, _indexArray, _countArray, timeoutInMachineTicks); } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using Accord.Statistics.Models.Markov.Topology; using Accord.Statistics.Models.Markov; using Accord.Statistics.Models.Markov.Learning; using System.Threading; namespace Recognizer.HMM { public class MainForm : System.Windows.Forms.Form { #region Fields private RecognizerUtils _rec; private bool _recording; private bool _isDown; private ArrayList _points; private Queue<int> _directionalCodewordsQueue; private List<ArrayList> _pointsList; private ViewForm _viewFrm; private List<String> _directionalCodewordsList; //private String _directionalCodewords; private String _info = "null"; private HiddenMarkovClassifier _hmmc; private HiddenMarkovModel[] _hmms; //Font private Font _font; private int _maxCount = 200; //private Thread ComputingThread; #endregion #region Form Elements private System.Windows.Forms.Label lblRecord; private System.Windows.Forms.MainMenu MainMenu; private System.Windows.Forms.MenuItem Exit; private System.Windows.Forms.MenuItem LoadGesture; private System.Windows.Forms.MenuItem ViewGesture; private System.Windows.Forms.MenuItem RecordGesture; private System.Windows.Forms.MenuItem GestureMenu; private System.Windows.Forms.MenuItem ClearGestures; private System.Windows.Forms.MenuItem HelpMenu; private System.Windows.Forms.MenuItem About; private MenuItem FileMenu; private MenuItem HMMMenu; private MenuItem LoadAndTrain; private MenuItem LoadFromHMMFile; private Label lblResult; private MenuItem SaveHMMFile; private IContainer components; #endregion #region Start & Stop [STAThread] static void Main(string[] args) { Application.Run(new MainForm()); } public MainForm() { SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true); InitializeComponent(); _rec = new RecognizerUtils(); _points = new ArrayList(); _directionalCodewordsQueue = new Queue<int>(); _directionalCodewordsList = new List<string>(); _pointsList = new List<ArrayList>(); _font = new Font(FontFamily.GenericSansSerif, 8.25f); _viewFrm = null; lblResult.Text = String.Empty; this.KeyPreview = true; //ComputingThread = new Thread(new ThreadStart(this.HMMDecode)); //ComputingThread.Start(); // Spin for a while waiting for the started thread to become // alive: //while (!ComputingThread.IsAlive) ; //// Put the Main thread to sleep for 1 millisecond to allow oThread //// to do some work: //Thread.Sleep(1); } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.lblRecord = new System.Windows.Forms.Label(); this.MainMenu = new System.Windows.Forms.MainMenu(this.components); this.FileMenu = new System.Windows.Forms.MenuItem(); this.Exit = new System.Windows.Forms.MenuItem(); this.GestureMenu = new System.Windows.Forms.MenuItem(); this.RecordGesture = new System.Windows.Forms.MenuItem(); this.LoadGesture = new System.Windows.Forms.MenuItem(); this.ViewGesture = new System.Windows.Forms.MenuItem(); this.ClearGestures = new System.Windows.Forms.MenuItem(); this.HMMMenu = new System.Windows.Forms.MenuItem(); this.LoadAndTrain = new System.Windows.Forms.MenuItem(); this.LoadFromHMMFile = new System.Windows.Forms.MenuItem(); this.SaveHMMFile = new System.Windows.Forms.MenuItem(); this.HelpMenu = new System.Windows.Forms.MenuItem(); this.About = new System.Windows.Forms.MenuItem(); this.lblResult = new System.Windows.Forms.Label(); this.SuspendLayout(); // // lblRecord // this.lblRecord.BackColor = System.Drawing.Color.Transparent; this.lblRecord.Dock = System.Windows.Forms.DockStyle.Top; this.lblRecord.Font = new System.Drawing.Font("Courier New", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblRecord.ForeColor = System.Drawing.Color.Firebrick; this.lblRecord.Location = new System.Drawing.Point(0, 0); this.lblRecord.Name = "lblRecord"; this.lblRecord.Size = new System.Drawing.Size(1184, 26); this.lblRecord.TabIndex = 1; this.lblRecord.Text = "[Recording]"; this.lblRecord.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.lblRecord.Visible = false; // // MainMenu // this.MainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.FileMenu, this.GestureMenu, this.HMMMenu, this.HelpMenu}); // // FileMenu // this.FileMenu.Index = 0; this.FileMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.Exit}); this.FileMenu.Text = "&File"; // // Exit // this.Exit.Index = 0; this.Exit.Text = "E&xit"; this.Exit.Click += new System.EventHandler(this.Exit_Click); // // GestureMenu // this.GestureMenu.Index = 1; this.GestureMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.RecordGesture, this.LoadGesture, this.ViewGesture, this.ClearGestures}); this.GestureMenu.Text = "&Gestures"; this.GestureMenu.Popup += new System.EventHandler(this.GestureMenu_Popup); // // RecordGesture // this.RecordGesture.Index = 0; this.RecordGesture.Shortcut = System.Windows.Forms.Shortcut.F1; this.RecordGesture.Text = "&Record"; this.RecordGesture.Click += new System.EventHandler(this.RecordGesture_Click); // // LoadGesture // this.LoadGesture.Index = 1; this.LoadGesture.Shortcut = System.Windows.Forms.Shortcut.CtrlO; this.LoadGesture.Text = "&Load..."; this.LoadGesture.Click += new System.EventHandler(this.LoadGesture_Click); // // ViewGesture // this.ViewGesture.Index = 2; this.ViewGesture.Shortcut = System.Windows.Forms.Shortcut.CtrlV; this.ViewGesture.Text = "&View"; this.ViewGesture.Click += new System.EventHandler(this.ViewGesture_Click); // // ClearGestures // this.ClearGestures.Index = 3; this.ClearGestures.Text = "&Clear"; this.ClearGestures.Click += new System.EventHandler(this.ClearGestures_Click); // // HMMMenu // this.HMMMenu.Index = 2; this.HMMMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.LoadAndTrain, this.LoadFromHMMFile, this.SaveHMMFile}); this.HMMMenu.Text = "&HMM"; // // LoadAndTrain // this.LoadAndTrain.Index = 0; this.LoadAndTrain.Text = "&Load .xml And Train..."; this.LoadAndTrain.Click += new System.EventHandler(this.LoadAndTrain_Click); // // LoadFromHMMFile // this.LoadFromHMMFile.Index = 1; this.LoadFromHMMFile.Text = "Load From .&hmm File..."; this.LoadFromHMMFile.Click += new System.EventHandler(this.LoadFromHMMFile_Click); // // SaveHMMFile // this.SaveHMMFile.Index = 2; this.SaveHMMFile.Text = "&Save to .hmm File"; this.SaveHMMFile.Click += new System.EventHandler(this.SaveHMMFile_Click); // // HelpMenu // this.HelpMenu.Index = 3; this.HelpMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.About}); this.HelpMenu.Text = "&Help"; // // About // this.About.Index = 0; this.About.Text = "&About..."; this.About.Click += new System.EventHandler(this.About_Click); // // lblResult // this.lblResult.BackColor = System.Drawing.Color.Transparent; this.lblResult.Dock = System.Windows.Forms.DockStyle.Top; this.lblResult.Font = new System.Drawing.Font("Courier New", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblResult.ForeColor = System.Drawing.Color.Firebrick; this.lblResult.Location = new System.Drawing.Point(0, 26); this.lblResult.Name = "lblResult"; this.lblResult.Size = new System.Drawing.Size(1184, 26); this.lblResult.TabIndex = 2; this.lblResult.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.BackColor = System.Drawing.SystemColors.Window; this.ClientSize = new System.Drawing.Size(1184, 640); this.Controls.Add(this.lblResult); this.Controls.Add(this.lblRecord); this.KeyPreview = true; this.Menu = this.MainMenu; this.Name = "MainForm"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Recognizer.HMM"; this.Load += new System.EventHandler(this.MainForm_Load); this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyUp); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseDown); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseMove); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseUp); this.ResumeLayout(false); } private void MainForm_Load(object sender, EventArgs e) { } #endregion #region File Menu private void Exit_Click(object sender, System.EventArgs e) { Close(); } #endregion #region Gestures Menu private void GestureMenu_Popup(object sender, System.EventArgs e) { ViewGesture.Checked = (_viewFrm != null && !_viewFrm.IsDisposed); ClearGestures.Enabled = (_rec.NumGestures > 0); } private void LoadGesture_Click(object sender, System.EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Gestures (*.xml)|*.xml"; dlg.Title = "Load Gestures"; dlg.RestoreDirectory = false; dlg.Multiselect = true; if (dlg.ShowDialog(this) == DialogResult.OK) { for (int i = 0; i < dlg.FileNames.Length; i++) { string name = dlg.FileNames[i]; _rec.LoadGesture(name); } ReloadViewForm(); } } private void ViewGesture_Click(object sender, System.EventArgs e) { if (_viewFrm != null && !_viewFrm.IsDisposed) { _viewFrm.Close(); _viewFrm = null; } else { _viewFrm = new ViewForm(_rec.Gestures); _viewFrm.Owner = this; _viewFrm.Show(); } } private void ReloadViewForm() { if (_viewFrm != null && !_viewFrm.IsDisposed) { _viewFrm.Close(); _viewFrm = new ViewForm(_rec.Gestures); _viewFrm.Owner = this; _viewFrm.Show(); } } private void RecordGesture_Click(object sender, System.EventArgs e) { _points.Clear(); Invalidate(); _recording = !_recording; // recording will happen on mouse-up if (_recording) { RecordGesture.Text = "Stop Recording"; } else { if (_directionalCodewordsList.Count > 0) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Gestures (*.xml)|*.xml"; dlg.Title = "Save Gesture As"; dlg.AddExtension = true; dlg.RestoreDirectory = false; if (dlg.ShowDialog(this) == DialogResult.OK) { _rec.SaveDirectionalCodewords(dlg.FileName, _directionalCodewordsList); String filename = Gesture.ParseName(dlg.FileName); for (int i = 0; i < _pointsList.Count; i++) { _rec.SaveGesture(filename + i + ".xml", _pointsList[i]); } ReloadViewForm(); } dlg.Dispose(); _directionalCodewordsList.Clear(); _pointsList.Clear(); _points.Clear(); lblResult.Text = "0"; Invalidate(); RecordGesture.Text = "Record"; } } lblRecord.Visible = _recording; } private void ClearGestures_Click(object sender, System.EventArgs e) { if (MessageBox.Show(this, "This will clear all loaded gestures. (It will not delete any XML files.)", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { _rec.ClearGestures(); ReloadViewForm(); } } #endregion #region HMM Menu private void LoadAndTrain_Click(object sender, EventArgs e) { List<int> outputLabels = new List<int>(); List<int[]> inputSequences = new List<int[]>(); OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Gestures (*.xml)|*.xml"; dlg.Title = "Load Gestures"; dlg.RestoreDirectory = false; dlg.Multiselect = true; if (dlg.ShowDialog(this) == DialogResult.OK) { lblResult.Text = "Training..."; for (int i = 0; i < dlg.FileNames.Length; i++) { string name = dlg.FileNames[i]; List<int[]> inputSequencesTemp = _rec.LoadDirectionalCodewordsFile(name); for (int j = 0; j < inputSequencesTemp.Count; j++) { inputSequences.Add(inputSequencesTemp[j]); outputLabels.Add(i); } } ReloadViewForm(); } //ITopology forward = new Forward(4,3); ITopology[] forwards = new Forward[4]; forwards[0] = new Forward(5, 3); forwards[1] = new Forward(5, 3); forwards[2] = new Forward(5, 3); forwards[3] = new Forward(5, 3); _hmmc = new HiddenMarkovClassifier(4, forwards, 16); //hmmc.Models[0] = new HiddenMarkovModel(); //hmmc.Models[0].Transitions = null;kovModel(); // And create a algorithms to teach each of the inner models var teacher = new HiddenMarkovClassifierLearning(_hmmc, // We can specify individual training options for each inner model: modelIndex => new BaumWelchLearning(_hmmc.Models[modelIndex]) { Tolerance = 0.001, // iterate until log-likelihood changes less than 0.001 Iterations = 0 // don't place an upper limit on the number of iterations }); teacher.Run((int[][])inputSequences.ToArray(), (int[])outputLabels.ToArray()); _hmmc.Threshold = teacher.Threshold(); _hmmc.Sensitivity = 1; _hmms = _hmmc.Models; for (int i = 0; i < dlg.FileNames.Length; i++) { _hmms[i].Tag = Gesture.ParseName(dlg.FileNames[i]); } lblResult.Text = "Success!!"; } private void SaveHMMFile_Click(object sender, EventArgs e) { if (_hmmc != null) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Gestures (*.hmm)|*.hmm"; dlg.Title = "Save Gesture As"; dlg.AddExtension = true; dlg.RestoreDirectory = false; if (dlg.ShowDialog(this) == DialogResult.OK) { _hmmc.Save(dlg.FileName); ReloadViewForm(); } dlg.Dispose(); } } private void LoadFromHMMFile_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Gestures (*.hmm)|*.hmm"; dlg.Title = "Load Gestures"; dlg.RestoreDirectory = false; dlg.Multiselect = true; if (dlg.ShowDialog(this) == DialogResult.OK) { _hmmc = HiddenMarkovClassifier.Load(dlg.FileName); _hmms = _hmmc.Models; if (_hmmc != null) { lblResult.Text = "Success!!"; } ReloadViewForm(); } } #endregion #region About Menu private void About_Click(object sender, System.EventArgs e) { AboutForm frm = new AboutForm(_points); frm.ShowDialog(this); } #endregion #region Window Form Events private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { if (_points.Count > 0) { PointF p0 = (PointF)(PointR)_points[0]; // draw the first point bigger e.Graphics.FillEllipse(_recording ? Brushes.Firebrick : Brushes.DarkBlue, p0.X - 5f, p0.Y - 5f, 10f, 10f); } e.Graphics.DrawString(_info, _font, Brushes.Black, new PointF(20, 40)); foreach (PointR r in _points) { PointF p = (PointF)r; // cast e.Graphics.FillEllipse(_recording ? Brushes.Firebrick : Brushes.DarkBlue, p.X - 2f, p.Y - 2f, 4f, 4f); } } #endregion #region Keyboard Events private void MainForm_KeyUp(object sender, KeyEventArgs e) { //if (e.KeyCode == Keys.Up) //{ // if (hmmc != null) // { // hmmc.Sensitivity++; // info = "Sensitivity:" + hmmc.Sensitivity; // } //} //if (e.KeyCode == Keys.Down) //{ // if (hmmc != null) // { // hmmc.Sensitivity--; // info = "Sensitivity:" + hmmc.Sensitivity; // } //} } #endregion #region Mouse Events private void MainForm_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (_pointsList.Count >= 1) { _directionalCodewordsList.RemoveAt(_directionalCodewordsList.Count - 1); _pointsList.RemoveAt(_pointsList.Count - 1); _points.Clear(); if (_pointsList.Count - 1 >= 0) { foreach (PointR p in _pointsList[_pointsList.Count - 1]) { _points.Add(new PointR(p.X,p.Y)); } } _info = "Sample count:" + _directionalCodewordsList.Count; Invalidate(); } } if (e.Button == MouseButtons.Left) { _isDown = true; _points.Clear(); _points.Add(new PointR(e.X, e.Y, Environment.TickCount)); _directionalCodewordsQueue.Clear(); Invalidate(); } } private void MainForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (_isDown) { if (_points.Count >= 2) { PointR p = (PointR)_points[_points.Count - 1]; //_directionalCodewords = "" + getDirectionalCodewords(e.X, e.Y, p.X, p.Y); _directionalCodewordsQueue.Enqueue(getDirectionalCodewords(e.X, e.Y, p.X, p.Y)); if (_directionalCodewordsQueue.Count > _maxCount) { _directionalCodewordsQueue.Dequeue(); } } _points.Add(new PointR(e.X, e.Y, Environment.TickCount)); //info = info + "a"; if (_hmmc != null && _directionalCodewordsQueue.Count > 1 && !_recording) // not recording, so testing { Queue<int> directionalCodewordsQueueTemp = _directionalCodewordsQueue; while (directionalCodewordsQueueTemp.Count > 40) { //lblResult.Text = "Recognizing..."; _info = null; _info = _info + _rec.encode(_directionalCodewordsQueue.ToArray()) + "\n"; //int[] observations = _rec.decode(_directionalCodewords); int[] observations = directionalCodewordsQueueTemp.ToArray(); _info = _info + _hmmc.Compute(observations) + "\n"; string gestureName = (string)_hmms[0].Tag; double probTemp = 0; _hmmc[0].Decode(observations, out probTemp); //double probTemp = hmms[0].Evaluate(observations); foreach (HiddenMarkovModel hmm in _hmms) { //double prob = hmm.Evaluate(observations); double prob = 0; int[] viterbipath = hmm.Decode(observations, out prob); if (prob > probTemp) { gestureName = (string)hmm.Tag; probTemp = prob; } //info = info + hmm.Tag + "\t" + hmm.Evaluate(observations) + "\t"; _info = _info + hmm.Tag + "\t" + prob + "\t"; // = hmm.Decode(observations); foreach (int state in viterbipath) { _info = _info + state + " "; } _info = _info + "\n"; } double probTM = 0; int[] viterbipathTM = _hmmc.Threshold.Decode(observations, out probTM); _info = _info + "ThresholdModel\t" + probTM + "\t"; //hmmc.Threshold.Decode(observations); foreach (int state in viterbipathTM) { _info = _info + state + " "; } _info = _info + "\n"; if (probTM > probTemp) { gestureName = "Threshold"; _info = _info + "\n\n" + gestureName; } else { _info = _info + "\n\n" + gestureName; _directionalCodewordsQueue.Clear(); break; } for (int loop = 0; loop < 10; loop++) { directionalCodewordsQueueTemp.Dequeue(); } } } Invalidate(); } } //Invalidate(new Rectangle(e.X - 2, e.Y - 2, 4, 4)); } private void MainForm_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (_isDown) { _isDown = false; if (_points.Count >= 5) // require 5 points for a valid gesture { if (_recording) { //_directionalCodewords = _directionalCodewords.Substring(1, _directionalCodewords.Length - 1); _directionalCodewordsList.Add(_rec.encode(_directionalCodewordsQueue.ToArray())); //ArrayList pointsTemp = new ArrayList(); //foreach (PointR r in _points) //{ // pointsTemp.Add(new PointR(r.X, r.Y)); //} _pointsList.Add(new ArrayList(_points)); _info = "Sample count:" + _pointsList.Count; Invalidate(); } } } } } private int getDirectionalCodewords(double x, double y, double lastX, double lastY) { double angle = Math.Atan2(y - lastY, x - lastX); // keep it in radians if (angle < 0) angle += 2 * 3.1425926; return (int)(angle * (8 / 3.1425926)); // convert to <0, 16) } #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.Reflection; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; [assembly: SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Scope = "type", Target = "System.ComponentModel.BindingList`1")] namespace System.ComponentModel { [Serializable] [TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class BindingList<T> : Collection<T>, IBindingList, ICancelAddNew, IRaiseItemChangedEvents { private int addNewPos = -1; // Do not rename (binary serialization) private bool raiseListChangedEvents = true; // Do not rename (binary serialization) private bool raiseItemChangedEvents; // Do not rename (binary serialization) [NonSerialized] private PropertyDescriptorCollection _itemTypeProperties; [NonSerialized] private PropertyChangedEventHandler _propertyChangedEventHandler; [NonSerialized] private AddingNewEventHandler _onAddingNew; [NonSerialized] private ListChangedEventHandler _onListChanged; [NonSerialized] private int _lastChangeIndex = -1; private bool allowNew = true; // Do not rename (binary serialization) private bool allowEdit = true; // Do not rename (binary serialization) private bool allowRemove = true; // Do not rename (binary serialization) private bool userSetAllowNew; // Do not rename (binary serialization) #region Constructors public BindingList() => Initialize(); /// <summary> /// Constructor that allows substitution of the inner list with a custom list. /// </summary> public BindingList(IList<T> list) : base(list) { Initialize(); } private void Initialize() { // Set the default value of AllowNew based on whether type T has a default constructor allowNew = ItemTypeHasDefaultConstructor; // Check for INotifyPropertyChanged if (typeof(INotifyPropertyChanged).IsAssignableFrom(typeof(T))) { // Supports INotifyPropertyChanged raiseItemChangedEvents = true; // Loop thru the items already in the collection and hook their change notification. foreach (T item in Items) { HookPropertyChanged(item); } } } private bool ItemTypeHasDefaultConstructor { get { Type itemType = typeof(T); if (itemType.IsPrimitive) { return true; } const BindingFlags BindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance; return itemType.GetConstructor(BindingFlags, null, Array.Empty<Type>(), null) != null; } } #endregion #region AddingNew event /// <summary> /// Event that allows a custom item to be provided as the new item added to the list by AddNew(). /// </summary> public event AddingNewEventHandler AddingNew { add { bool allowNewWasTrue = AllowNew; _onAddingNew += value; if (allowNewWasTrue != AllowNew) { FireListChanged(ListChangedType.Reset, -1); } } remove { bool allowNewWasTrue = AllowNew; _onAddingNew -= value; if (allowNewWasTrue != AllowNew) { FireListChanged(ListChangedType.Reset, -1); } } } /// <summary> /// Raises the AddingNew event. /// </summary> protected virtual void OnAddingNew(AddingNewEventArgs e) => _onAddingNew?.Invoke(this, e); // Private helper method private object FireAddingNew() { AddingNewEventArgs e = new AddingNewEventArgs(null); OnAddingNew(e); return e.NewObject; } #endregion #region ListChanged event /// <summary> /// Event that reports changes to the list or to items in the list. /// </summary> public event ListChangedEventHandler ListChanged { add => _onListChanged += value; remove => _onListChanged -= value; } /// <summary> /// Raises the ListChanged event. /// </summary> protected virtual void OnListChanged(ListChangedEventArgs e) => _onListChanged?.Invoke(this, e); public bool RaiseListChangedEvents { get => raiseListChangedEvents; set => raiseListChangedEvents = value; } public void ResetBindings() => FireListChanged(ListChangedType.Reset, -1); public void ResetItem(int position) { FireListChanged(ListChangedType.ItemChanged, position); } // Private helper method private void FireListChanged(ListChangedType type, int index) { if (raiseListChangedEvents) { OnListChanged(new ListChangedEventArgs(type, index)); } } #endregion #region Collection<T> overrides // Collection<T> funnels all list changes through the four virtual methods below. // We override these so that we can commit any pending new item and fire the proper ListChanged events. protected override void ClearItems() { EndNew(addNewPos); if (raiseItemChangedEvents) { foreach (T item in Items) { UnhookPropertyChanged(item); } } base.ClearItems(); FireListChanged(ListChangedType.Reset, -1); } protected override void InsertItem(int index, T item) { EndNew(addNewPos); base.InsertItem(index, item); if (raiseItemChangedEvents) { HookPropertyChanged(item); } FireListChanged(ListChangedType.ItemAdded, index); } protected override void RemoveItem(int index) { // Need to all RemoveItem if this on the AddNew item if (!allowRemove && !(addNewPos >= 0 && addNewPos == index)) { throw new NotSupportedException(); } EndNew(addNewPos); if (raiseItemChangedEvents) { UnhookPropertyChanged(this[index]); } base.RemoveItem(index); FireListChanged(ListChangedType.ItemDeleted, index); } protected override void SetItem(int index, T item) { if (raiseItemChangedEvents) { UnhookPropertyChanged(this[index]); } base.SetItem(index, item); if (raiseItemChangedEvents) { HookPropertyChanged(item); } FireListChanged(ListChangedType.ItemChanged, index); } #endregion #region ICancelAddNew interface /// <summary> /// If item added using AddNew() is still cancellable, then remove that item from the list. /// </summary> public virtual void CancelNew(int itemIndex) { if (addNewPos >= 0 && addNewPos == itemIndex) { RemoveItem(addNewPos); addNewPos = -1; } } /// <summary> /// If item added using AddNew() is still cancellable, then commit that item. /// </summary> public virtual void EndNew(int itemIndex) { if (addNewPos >= 0 && addNewPos == itemIndex) { addNewPos = -1; } } #endregion #region IBindingList interface /// <summary> /// Adds a new item to the list. Calls <see cref="AddNewCore" /> to create and add the item. /// /// Add operations are cancellable via the <see cref="ICancelAddNew" /> interface. The position of the /// new item is tracked until the add operation is either cancelled by a call to <see cref="CancelNew" />, /// explicitly commited by a call to <see cref="EndNew" />, or implicitly commmited some other operation /// changes the contents of the list (such as an Insert or Remove). When an add operation is /// cancelled, the new item is removed from the list. /// </summary> public T AddNew() => (T)((this as IBindingList).AddNew()); object IBindingList.AddNew() { // Create new item and add it to list object newItem = AddNewCore(); // Record position of new item (to support cancellation later on) addNewPos = (newItem != null) ? IndexOf((T)newItem) : -1; // Return new item to caller return newItem; } private bool AddingNewHandled => _onAddingNew != null && _onAddingNew.GetInvocationList().Length > 0; /// <summary> /// Creates a new item and adds it to the list. /// /// The base implementation raises the AddingNew event to allow an event handler to /// supply a custom item to add to the list. Otherwise an item of type T is created. /// The new item is then added to the end of the list. /// </summary> [SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods")] protected virtual object AddNewCore() { // Allow event handler to supply the new item for us object newItem = FireAddingNew(); // If event hander did not supply new item, create one ourselves if (newItem == null) { newItem = Activator.CreateInstance(typeof(T)); } // Add item to end of list. Note: If event handler returned an item not of type T, // the cast below will trigger an InvalidCastException. This is by design. Add((T)newItem); // Return new item to caller return newItem; } public bool AllowNew { get { // If the user set AllowNew, return what they set. If we have a default constructor, allowNew will be // true and we should just return true. if (userSetAllowNew || allowNew) { return allowNew; } // Even if the item doesn't have a default constructor, the user can hook AddingNew to provide an item. // If there's a handler for this, we should allow new. return AddingNewHandled; } set { bool oldAllowNewValue = AllowNew; userSetAllowNew = true; // Note that we don't want to set allowNew only if AllowNew didn't match value, // since AllowNew can depend on onAddingNew handler allowNew = value; if (oldAllowNewValue != value) { FireListChanged(ListChangedType.Reset, -1); } } } bool IBindingList.AllowNew => AllowNew; public bool AllowEdit { get => allowEdit; set { if (allowEdit != value) { allowEdit = value; FireListChanged(ListChangedType.Reset, -1); } } } bool IBindingList.AllowEdit => AllowEdit; public bool AllowRemove { get => allowRemove; set { if (allowRemove != value) { allowRemove = value; FireListChanged(ListChangedType.Reset, -1); } } } bool IBindingList.AllowRemove => AllowRemove; bool IBindingList.SupportsChangeNotification => SupportsChangeNotificationCore; protected virtual bool SupportsChangeNotificationCore => true; bool IBindingList.SupportsSearching => SupportsSearchingCore; protected virtual bool SupportsSearchingCore => false; bool IBindingList.SupportsSorting => SupportsSortingCore; protected virtual bool SupportsSortingCore => false; bool IBindingList.IsSorted => IsSortedCore; protected virtual bool IsSortedCore => false; PropertyDescriptor IBindingList.SortProperty => SortPropertyCore; protected virtual PropertyDescriptor SortPropertyCore => null; ListSortDirection IBindingList.SortDirection => SortDirectionCore; protected virtual ListSortDirection SortDirectionCore => ListSortDirection.Ascending; void IBindingList.ApplySort(PropertyDescriptor prop, ListSortDirection direction) { ApplySortCore(prop, direction); } protected virtual void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction) { throw new NotSupportedException(); } void IBindingList.RemoveSort() => RemoveSortCore(); protected virtual void RemoveSortCore() { throw new NotSupportedException(); } int IBindingList.Find(PropertyDescriptor prop, object key) => FindCore(prop, key); protected virtual int FindCore(PropertyDescriptor prop, object key) { throw new NotSupportedException(); } void IBindingList.AddIndex(PropertyDescriptor prop) { // Not supported } void IBindingList.RemoveIndex(PropertyDescriptor prop) { // Not supported } #endregion #region Property Change Support private void HookPropertyChanged(T item) { // Note: inpc may be null if item is null, so always check. if (item is INotifyPropertyChanged inpc) { if (_propertyChangedEventHandler == null) { _propertyChangedEventHandler = new PropertyChangedEventHandler(Child_PropertyChanged); } inpc.PropertyChanged += _propertyChangedEventHandler; } } private void UnhookPropertyChanged(T item) { // Note: inpc may be null if item is null, so always check. if (item is INotifyPropertyChanged inpc && _propertyChangedEventHandler != null) { inpc.PropertyChanged -= _propertyChangedEventHandler; } } private void Child_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (RaiseListChangedEvents) { if (sender == null || e == null || string.IsNullOrEmpty(e.PropertyName)) { // Fire reset event (per INotifyPropertyChanged spec) ResetBindings(); } else { // The change event is broken should someone pass an item to us that is not // of type T. Still, if they do so, detect it and ignore. It is an incorrect // and rare enough occurrence that we do not want to slow the mainline path // with "is" checks. T item; try { item = (T)sender; } catch (InvalidCastException) { ResetBindings(); return; } // Find the position of the item. This should never be -1. If it is, // somehow the item has been removed from our list without our knowledge. int pos = _lastChangeIndex; if (pos < 0 || pos >= Count || !this[pos].Equals(item)) { pos = IndexOf(item); _lastChangeIndex = pos; } if (pos == -1) { // The item was removed from the list but we still get change notifications or // the sender is invalid and was never added to the list. UnhookPropertyChanged(item); ResetBindings(); } else { // Get the property descriptor if (null == _itemTypeProperties) { // Get Shape _itemTypeProperties = TypeDescriptor.GetProperties(typeof(T)); Debug.Assert(_itemTypeProperties != null); } PropertyDescriptor pd = _itemTypeProperties.Find(e.PropertyName, true); // Create event args. If there was no matching property descriptor, // we raise the list changed anyway. ListChangedEventArgs args = new ListChangedEventArgs(ListChangedType.ItemChanged, pos, pd); // Fire the ItemChanged event OnListChanged(args); } } } } #endregion #region IRaiseItemChangedEvents interface /// <summary> /// Returns false to indicate that BindingList&lt;T&gt; does NOT raise ListChanged events /// of type ItemChanged as a result of property changes on individual list items /// unless those items support INotifyPropertyChanged. /// </summary> bool IRaiseItemChangedEvents.RaisesItemChangedEvents => raiseItemChangedEvents; #endregion } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Data. THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Data. THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; using System.IO; using GME.MGA; namespace DynamicsTeamTest.Projects { public class RICheckerTestModelFixture : XmeImportFixture { protected override string xmeFilename { get { return Path.Combine("RICheckerTestModel", "RICheckerTestModel.xme"); } } } public partial class RICheckerTestModel : IUseFixture<RICheckerTestModelFixture> { internal string mgaFile { get { return this.fixture.mgaFile; } } private RICheckerTestModelFixture fixture { get; set; } public void SetFixture(RICheckerTestModelFixture data) { this.fixture = data; } //[Fact] //[Trait("Model", "RICheckerTestModel")] //[Trait("ProjectImport/Open", "RICheckerTestModel")] //public void ProjectXmeImport() //{ // Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); //} [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("ProjectImport/Open", "RICheckerTestModel")] public void ProjectMgaOpen() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.OpenEx(mgaReference, "CyPhyML", null); project.Close(true); Assert.True(File.Exists(mgaReference.Substring("MGA=".Length))); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_RICircuit_Missing_Uri_In_Component() { string outputDir = "CheckerTests_CA_RICircuit_Missing_Uri_In_Component"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit_Missing_Uri_In_Component|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_RICircuit_Missing_Uri_In_TestComponent() { string outputDir = "CheckerTests_CA_RICircuit_Missing_Uri_In_TestComponent"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit_Missing_Uri_In_TestComponent|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } /* MOT-171: Case can no longer occur -- Connectors are now "unrolled" [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_RICircuit_ModelicaConnector_in_CA_connected_to_Connector() { string outputDir = "CheckerTests_CA_RICircuit_ModelicaConnector_in_CA_connected_to_Connector"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit_ModelicaConnector_in_CA_connected_to_Connector|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } */ [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_RICircuit_CA_RegularModelicaConnectorsNotConnectedInComponent() { string outputDir = "CheckerTests_CA_RICircuit_CA_RegularModelicaConnectorsNotConnectedInComponent"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit_CA_RegularModelicaConnectorsNotConnectedInComponent|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } /* MOT-171 obsolete test [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CyPhy2Modelica", "RICheckerTestModel")] public void CheckerTests_CA_RICircuit_ConnectorNotConnectedInComponent() { string outputDir = "CheckerTests_CA_RICircuit_ConnectorNotConnectedInComponent"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit_ConnectorNotConnectedInComponent|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.True(result, "CyPhy2Modelica_v2 failed."); } */ [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_RICircuit_With_Space_in_Name() { string outputDir = "CheckerTests_CA_RICircuit With Space in Name"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit With Space in Name|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_() { string outputDir = "CheckerTests_CA_"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_1TB_Starts_with_character() { string outputDir = "CheckerTests_CA_1TB_Starts_with_character"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@1TB_Starts_with_character|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_for() { string outputDir = "CheckerTests_CA_for"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@for|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_RICircuit_CA_SolverSettingNegativeIntervalLength() { string outputDir = "CheckerTests_CA_RICircuit_CA_SolverSettingNegativeIntervalLength"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit_CA_SolverSettingNegativeIntervalLength|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_RICircuit_CA_SolverSettingNegativeTolerance() { string outputDir = "CheckerTests_CA_RICircuit_CA_SolverSettingNegativeTolerance"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit_CA_SolverSettingNegativeTolerance|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CheckerShouldFail", "RICheckerTestModel")] public void Fail_CheckerTests_CA_RICircuit_CA_SolverSettingNegativeNbrOfIntervals() { string outputDir = "CheckerTests_CA_RICircuit_CA_SolverSettingNegativeNbrOfIntervals"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@CheckerTests_CA|kind=Testing|relpos=0/@RICircuit_CA_SolverSettingNegativeNbrOfIntervals|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.False(result, "CyPhy2Modelica_v2 should have failed, but did not."); } [Fact] [Trait("Model", "RICheckerTestModel")] [Trait("CyPhy2Modelica", "RICheckerTestModel")] public void Tests_RICircuit_CA() { string outputDir = "Tests_RICircuit_CA"; string testBenchPath = "/@Tests|kind=Testing|relpos=0/@RICircuit_CA|kind=TestBench|relpos=0"; Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool result = CyPhy2ModelicaRunner.Run(outputDir, mgaFile, testBenchPath); Assert.True(result, "CyPhy2Modelica_v2 failed."); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osuTK; using osuTK.Input; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets.Mods; using System; using System.Linq; using System.Collections.Generic; using System.Threading; using Humanizer; using osu.Framework.Input.Events; using osu.Game.Graphics; namespace osu.Game.Overlays.Mods { public class ModSection : CompositeDrawable { private readonly Drawable header; public FillFlowContainer<ModButtonEmpty> ButtonsContainer { get; } protected IReadOnlyList<ModButton> Buttons { get; private set; } = Array.Empty<ModButton>(); public Action<Mod> Action; public Key[] ToggleKeys; public readonly ModType ModType; public IEnumerable<Mod> SelectedMods => Buttons.Select(b => b.SelectedMod).Where(m => m != null); private CancellationTokenSource modsLoadCts; protected bool SelectionAnimationRunning => pendingSelectionOperations.Count > 0; /// <summary> /// True when all mod icons have completed loading. /// </summary> public bool ModIconsLoaded { get; private set; } = true; public IEnumerable<Mod> Mods { set { var modContainers = value.Select(m => { if (m == null) return new ModButtonEmpty(); return new ModButton(m) { SelectionChanged = mod => { ModButtonStateChanged(mod); Action?.Invoke(mod); }, }; }).ToArray(); modsLoadCts?.Cancel(); if (modContainers.Length == 0) { ModIconsLoaded = true; header.Hide(); Hide(); return; } ModIconsLoaded = false; LoadComponentsAsync(modContainers, c => { ModIconsLoaded = true; ButtonsContainer.ChildrenEnumerable = c; }, (modsLoadCts = new CancellationTokenSource()).Token); Buttons = modContainers.OfType<ModButton>().ToArray(); header.FadeIn(200); this.FadeIn(200); } } protected virtual void ModButtonStateChanged(Mod mod) { } protected override bool OnKeyDown(KeyDownEvent e) { if (e.ControlPressed) return false; if (ToggleKeys != null) { var index = Array.IndexOf(ToggleKeys, e.Key); if (index > -1 && index < Buttons.Count) Buttons[index].SelectNext(e.ShiftPressed ? -1 : 1); } return base.OnKeyDown(e); } private const double initial_multiple_selection_delay = 120; private double selectionDelay = initial_multiple_selection_delay; private double lastSelection; private readonly Queue<Action> pendingSelectionOperations = new Queue<Action>(); protected override void Update() { base.Update(); if (selectionDelay == initial_multiple_selection_delay || Time.Current - lastSelection >= selectionDelay) { if (pendingSelectionOperations.TryDequeue(out var dequeuedAction)) { dequeuedAction(); // each time we play an animation, we decrease the time until the next animation (to ramp the visual and audible elements). selectionDelay = Math.Max(30, selectionDelay * 0.8f); lastSelection = Time.Current; } else { // reset the selection delay after all animations have been completed. // this will cause the next action to be immediately performed. selectionDelay = initial_multiple_selection_delay; } } } /// <summary> /// Selects all mods. /// </summary> public void SelectAll() { pendingSelectionOperations.Clear(); foreach (var button in Buttons.Where(b => !b.Selected)) pendingSelectionOperations.Enqueue(() => button.SelectAt(0)); } /// <summary> /// Deselects all mods. /// </summary> public void DeselectAll() { pendingSelectionOperations.Clear(); DeselectTypes(Buttons.Select(b => b.SelectedMod?.GetType()).Where(t => t != null)); } /// <summary> /// Deselect one or more mods in this section. /// </summary> /// <param name="modTypes">The types of <see cref="Mod"/>s which should be deselected.</param> /// <param name="immediate">Whether the deselection should happen immediately. Should only be used when required to ensure correct selection flow.</param> /// <param name="newSelection">If this deselection is triggered by a user selection, this should contain the newly selected type. This type will never be deselected, even if it matches one provided in <paramref name="modTypes"/>.</param> public void DeselectTypes(IEnumerable<Type> modTypes, bool immediate = false, Mod newSelection = null) { foreach (var button in Buttons) { if (button.SelectedMod == null) continue; if (button.SelectedMod == newSelection) continue; foreach (var type in modTypes) { if (type.IsInstanceOfType(button.SelectedMod)) { if (immediate) button.Deselect(); else pendingSelectionOperations.Enqueue(button.Deselect); } } } } /// <summary> /// Updates all buttons with the given list of selected mods. /// </summary> /// <param name="newSelectedMods">The new list of selected mods to select.</param> public void UpdateSelectedButtons(IReadOnlyList<Mod> newSelectedMods) { foreach (var button in Buttons) updateButtonSelection(button, newSelectedMods); } private void updateButtonSelection(ModButton button, IReadOnlyList<Mod> newSelectedMods) { foreach (var mod in newSelectedMods) { var index = Array.FindIndex(button.Mods, m1 => mod.GetType() == m1.GetType()); if (index < 0) continue; var buttonMod = button.Mods[index]; // as this is likely coming from an external change, ensure the settings of the mod are in sync. buttonMod.CopyFrom(mod); button.SelectAt(index, false); return; } button.Deselect(); } public ModSection(ModType type) { ModType = type; AutoSizeAxes = Axes.Y; RelativeSizeAxes = Axes.X; Origin = Anchor.TopCentre; Anchor = Anchor.TopCentre; InternalChildren = new[] { header = CreateHeader(type.Humanize(LetterCasing.Title)), ButtonsContainer = new FillFlowContainer<ModButtonEmpty> { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Origin = Anchor.BottomLeft, Anchor = Anchor.BottomLeft, Spacing = new Vector2(50f, 0f), Margin = new MarginPadding { Top = 20, }, AlwaysPresent = true }, }; } protected virtual Drawable CreateHeader(string text) => new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.Bold), Text = text }; /// <summary> /// Play out all remaining animations immediately to leave mods in a good (final) state. /// </summary> public void FlushAnimation() { while (pendingSelectionOperations.TryDequeue(out var dequeuedAction)) dequeuedAction(); } } }
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Web; using Newtonsoft.Json; using Nutritionix.Uris; namespace Nutritionix { /// <summary> /// Client interface for accessing the Nutritionix API /// </summary> public interface INutritionixClient { /// <summary> /// Sets the credentials to be used when querying the Nutritionix API. Must be called before making any requests. /// </summary> /// <param name="appId">Your developer application id</param> /// <param name="appKey">Your developer application key</param> void Initialize(string appId, string appKey); /// <summary> /// Searches Nutritionix for items matching the specified query. /// </summary> /// <param name="request">The query.</param> /// <returns>The search response from the Nutritionix API.</returns> /// <exception cref="Nutritionix.NutritionixException"/> SearchResponse SearchItems(SearchRequest request); /// <summary> /// Searches Nutritionix for items matching the specified query. /// </summary> /// <param name="request">The query.</param> /// <returns>The search response from the Nutritionix API.</returns> /// <exception cref="Nutritionix.NutritionixException"/> SearchResponse SearchItems(PowerSearchRequest request); /// <summary> /// Retrieves the specified item from Nutritionix /// </summary> /// <param name="id">The item id</param> /// <returns>The requested item or null</returns> /// <exception cref="Nutritionix.NutritionixException"></exception> Item RetrieveItem(string id); /// <summary> /// Retrieves the specified item from Nutritionix /// </summary> /// <param name="upc">The UPC</param> /// <returns>The requested item or null</returns> /// <exception cref="Nutritionix.NutritionixException"/> Item RetrieveItemByUPC(string upc); /// <summary> /// Retrieves the specified brand from Nutritionix /// </summary> /// <param name="id">The brand id</param> /// <returns>The requested brand or null</returns> /// <exception cref="Nutritionix.NutritionixException"/> Brand RetrieveBrand(string id); } /// <summary> /// Client for accessing the Nutritionix API /// </summary> public class NutritionixClient : INutritionixClient { private string _appId; private string _appKey; // ReSharper disable once InconsistentNaming private readonly Func<HttpClient> CreateHttpClient; /// <summary> /// Create a new instance of <see cref="NutritionixClient"/> /// </summary> public NutritionixClient() : this(() => new HttpClient()) { } /// <summary> /// Create a new instance of <see cref="NutritionixClient"/> /// </summary> public NutritionixClient(Func<HttpClient> createHttpClient) { CreateHttpClient = createHttpClient; } /// <summary> /// Sets the credentials to be used when querying the Nutritionix API. Must be called before making any requests. /// </summary> /// <param name="appId">Your developer application id</param> /// <param name="appKey">Your developer application key</param> public void Initialize(string appId, string appKey) { _appId = appId; _appKey = appKey; } private void CheckInitialized() { if(_appId == null && _appKey == null) { throw new NutritionixException("You must call Initialize on the NutritionixClient before executing any other commands."); } } /// <summary> /// Searches Nutritionix for items matching the specified query. /// </summary> /// <param name="request">The query.</param> /// <returns>The search response from the Nutritionix API.</returns> /// <exception cref="Nutritionix.NutritionixException"/> public SearchResponse SearchItems(SearchRequest request) { CheckInitialized(); var searchUri = new SearchUri(_appId, _appKey, request); var response = Get<SearchResponse>(searchUri); response.Results = response.Results ?? new SearchResult[0]; return response; } /// <summary> /// Searches Nutritionix for items matching the specified query. /// </summary> /// <param name="request">The query.</param> /// <returns>The search response from the Nutritionix API.</returns> /// <exception cref="Nutritionix.NutritionixException"/> public SearchResponse SearchItems(PowerSearchRequest request) { CheckInitialized(); var searchUri = new PowerSearchUri(_appId, _appKey); request.AppId = _appId; request.AppKey = _appKey; var response = Post<PowerSearchRequest, SearchResponse>(searchUri, request); response.Results = response.Results ?? new SearchResult[0]; return response; } /// <summary> /// Retrieves the specified item from the Nutritionix API /// </summary> /// <param name="id">The item id</param> /// <returns>The requested item or null</returns> /// <exception cref="Nutritionix.NutritionixException"/> public Item RetrieveItem(string id) { CheckInitialized(); var itemUri = new RetrieveItemUri(_appId, _appKey, id: id); return Get<Item>(itemUri); } /// <summary> /// Retrieves the specified item from the Nutritionix API /// </summary> /// <param name="upc">The UPC</param> /// <returns>The requested item or null</returns> /// <exception cref="Nutritionix.NutritionixException"/> public Item RetrieveItemByUPC(string upc) { CheckInitialized(); var itemUri = new RetrieveItemUri(_appId, _appKey, upc: upc); return Get<Item>(itemUri); } /// <summary> /// Retrieves the specified brand from the Nutritionix API /// </summary> /// <param name="id">The brand id</param> /// <returns>The requested brand or null</returns> /// <exception cref="Nutritionix.NutritionixException"/> public Brand RetrieveBrand(string id) { CheckInitialized(); var itemUri = new RetrieveBrandUri(_appId, _appKey, id); return Get<Brand>(itemUri); } private TResult Get<TResult>(NutritionixUri uri) where TResult : new() { using(var client = CreateHttpClient()) { HttpResponseMessage response = Get(uri, client); if(response.IsSuccessStatusCode) return ReadResponse<TResult>(response); throw CreateExceptionFromResponse(response); } } private TResult Post<TRequest, TResult>(NutritionixUri uri, TRequest request) where TResult : new() { using (var client = CreateHttpClient()) { string json = JsonConvert.SerializeObject(request, new JsonSerializerSettings{NullValueHandling = NullValueHandling.Ignore}); HttpResponseMessage response = Post(uri, client, json); if(response.IsSuccessStatusCode) return ReadResponse<TResult>(response); throw CreateExceptionFromResponse(response); } } private static Exception CreateExceptionFromResponse(HttpResponseMessage response) { var error = ReadResponse<ErrorResponse>(response); if (error != null && error.Errors != null) return new NutritionixException(error); return new HttpException((int)response.StatusCode, response.ReasonPhrase); } private static HttpResponseMessage Get(NutritionixUri uri, HttpClient client) { try { return client.GetAsync(uri.ToString()).Result; } catch { string error = string.Format("An error occurred sending a request to the Nutritionix API. Uri: {0}", uri); throw new NutritionixException(error); } } private static HttpResponseMessage Post(NutritionixUri uri, HttpClient client, string json) { try { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpContent content = new StringContent(json, new UTF8Encoding(), "application/json"); return client.PostAsync(uri.ToString(), content).Result; } catch { string error = string.Format("An error occurred sending a request to the Nutritionix API. Uri: {0}", uri); throw new NutritionixException(error); } } private static TResult ReadResponse<TResult>(HttpResponseMessage response) where TResult : new() { try { string content = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<TResult>(content); } catch { throw new NutritionixException("The response returned from the Nutritionix API contained invalid JSON."); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is used internally to create best fit behavior as per the original windows best fit behavior. // using System; using System.Globalization; using System.Text; using System.Threading; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { [Serializable] internal sealed class InternalEncoderBestFitFallback : EncoderFallback { // Our variables internal Encoding encoding = null; internal char[] arrayBestFit = null; internal InternalEncoderBestFitFallback(Encoding encoding) { // Need to load our replacement characters table. this.encoding = encoding; this.bIsMicrosoftBestFitFallback = true; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals(Object value) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if (that != null) { return (this.encoding.CodePage == that.encoding.CodePage); } return (false); } public override int GetHashCode() { return this.encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { // Our variables private char cBestFit = '\0'; private InternalEncoderBestFitFallback oFallback; private int iCount = -1; private int iSize; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Constructor public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { oFallback = fallback; if (oFallback.arrayBestFit == null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. if (oFallback.arrayBestFit == null) oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } // Fallback methods public override bool Fallback(char charUnknown, int index) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); iCount = iSize = 1; cBestFit = TryBestFit(charUnknown); if (cBestFit == '\0') cBestFit = '?'; return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); if (!Char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); Contract.EndContractBlock(); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit cBestFit = '?'; iCount = iSize = 2; return true; } // Default version is overridden in EncoderReplacementFallback.cs public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. iCount--; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (iCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (iCount == int.MaxValue) { iCount = -1; return '\0'; } // Return the best fit character return cBestFit; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if (iCount >= 0) iCount++; // Return true if we could do it. return (iCount >= 0 && iCount <= iSize); } // How many characters left to output? public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer public override unsafe void Reset() { iCount = -1; charStart = null; bFallingBack = false; } // private helper methods private char TryBestFit(char cUnknown) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = oFallback.arrayBestFit.Length; int index; // Binary search the array int iDiff; while ((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because we want to be on word boundaries. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = oFallback.arrayBestFit[index]; if (cTest == cUnknown) { // We found it Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } else if (cTest < cUnknown) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for (index = lowBound; index < highBound; index += 2) { if (oFallback.arrayBestFit[index] == cUnknown) { // We found it Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } }
/* * 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 OpenMetaverse; using System; using System.Collections.Generic; using System.Threading; using RegionFlags = OpenSim.Framework.RegionFlags; namespace OpenSim.Data.Null { public class NullRegionData : IRegionData { private static NullRegionData Instance = null; /// <summary> /// Should we use the static instance for all invocations? /// </summary> private bool m_useStaticInstance = true; // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ThreadedClasses.RwLockedDictionary<UUID, RegionData> m_regionData = new ThreadedClasses.RwLockedDictionary<UUID, RegionData>(); public NullRegionData(string connectionString, string realm) { // m_log.DebugFormat( // "[NULL REGION DATA]: Constructor got connectionString {0}, realm {1}", connectionString, realm); // The !static connection string is a hack so that regression tests can use this module without a high degree of fragility // in having to deal with the static reference in the once-loaded NullRegionData class. // // In standalone operation, we have to use only one instance of this class since the login service and // simulator have no other way of using a common data store. if (connectionString == "!static") m_useStaticInstance = false; else if (Instance == null) Instance = this; } private delegate bool Matcher(string value); public List<RegionData> Get(string regionName, UUID scopeID) { if (m_useStaticInstance && Instance != this) return Instance.Get(regionName, scopeID); // m_log.DebugFormat("[NULL REGION DATA]: Getting region {0}, scope {1}", regionName, scopeID); string cleanName = regionName.ToLower(); // Handle SQL wildcards const string wildcard = "%"; bool wildcardPrefix = false; bool wildcardSuffix = false; if (cleanName.Equals(wildcard)) { wildcardPrefix = wildcardSuffix = true; cleanName = string.Empty; } else { if (cleanName.StartsWith(wildcard)) { wildcardPrefix = true; cleanName = cleanName.Substring(1); } if (regionName.EndsWith(wildcard)) { wildcardSuffix = true; cleanName = cleanName.Remove(cleanName.Length - 1); } } Matcher queryMatch; if (wildcardPrefix && wildcardSuffix) queryMatch = delegate(string s) { return s.Contains(cleanName); }; else if (wildcardSuffix) queryMatch = delegate(string s) { return s.StartsWith(cleanName); }; else if (wildcardPrefix) queryMatch = delegate(string s) { return s.EndsWith(cleanName); }; else queryMatch = delegate(string s) { return s.Equals(cleanName); }; // Find region data List<RegionData> ret = new List<RegionData>(); m_regionData.ForEach(delegate(RegionData r) { // m_log.DebugFormat("[NULL REGION DATA]: comparing {0} to {1}", cleanName, r.RegionName.ToLower()); if (queryMatch(r.RegionName.ToLower())) ret.Add(r); }); if (ret.Count > 0) return ret; return null; } public RegionData Get(int posX, int posY, UUID scopeID) { if (m_useStaticInstance && Instance != this) return Instance.Get(posX, posY, scopeID); List<RegionData> ret = new List<RegionData>(); m_regionData.ForEach(delegate(RegionData r) { if (r.posX == posX && r.posY == posY) { ret.Add(r); } }); if (ret.Count > 0) return ret[0]; return null; } public RegionData Get(UUID regionID, UUID scopeID) { if (m_useStaticInstance && Instance != this) return Instance.Get(regionID, scopeID); try { return m_regionData[regionID]; } catch(KeyNotFoundException) { return null; } } public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID) { if (m_useStaticInstance && Instance != this) return Instance.Get(startX, startY, endX, endY, scopeID); List<RegionData> ret = new List<RegionData>(); m_regionData.ForEach(delegate(RegionData r) { if (r.posX >= startX && r.posX <= endX && r.posY >= startY && r.posY <= endY) ret.Add(r); }); return ret; } public bool Store(RegionData data) { if (m_useStaticInstance && Instance != this) return Instance.Store(data); // m_log.DebugFormat( // "[NULL REGION DATA]: Storing region {0} {1}, scope {2}", data.RegionName, data.RegionID, data.ScopeID); m_regionData[data.RegionID] = data; return true; } public bool SetDataItem(UUID regionID, string item, string value) { if (m_useStaticInstance && Instance != this) return Instance.SetDataItem(regionID, item, value); try { m_regionData[regionID].Data[item] = value; } catch(KeyNotFoundException) { return false; } return true; } public bool Delete(UUID regionID) { if (m_useStaticInstance && Instance != this) return Instance.Delete(regionID); // m_log.DebugFormat("[NULL REGION DATA]: Deleting region {0}", regionID); m_regionData.Remove(regionID); return true; } public List<RegionData> GetDefaultRegions(UUID scopeID) { return Get((int)RegionFlags.DefaultRegion, scopeID); } public List<RegionData> GetDefaultHypergridRegions(UUID scopeID) { return Get((int)RegionFlags.DefaultHGRegion, scopeID); } public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y) { List<RegionData> regions = Get((int)RegionFlags.FallbackRegion, scopeID); RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y); regions.Sort(distanceComparer); return regions; } public List<RegionData> GetHyperlinks(UUID scopeID) { return Get((int)RegionFlags.Hyperlink, scopeID); } private List<RegionData> Get(int regionFlags, UUID scopeID) { if (Instance != this) return Instance.Get(regionFlags, scopeID); List<RegionData> ret = new List<RegionData>(); m_regionData.ForEach(delegate(RegionData r) { if ((Convert.ToInt32(r.Data["flags"]) & regionFlags) != 0) ret.Add(r); }); return ret; } } }
// ---------------------------------------------------------------------------------- // // FXMaker // Created by ismoon - 2012 - ismoonto@gmail.com // // ---------------------------------------------------------------------------------- using UnityEngine; #if UNITY_EDITOR using UnityEditor; using System.Collections; using System.Collections.Generic; public class FxmInfoIndexing : MonoBehaviour { // Attribute ------------------------------------------------------------------------ public Transform m_OriginalTrans; public bool m_bRuntimeCreatedObj; public bool m_bSelected = false; public bool m_bRootSelected = false; // picking public bool m_bPicking = true; public Collider m_Collider; // wireframe public bool m_bBounds = false; public bool m_bWireframe = false; public bool m_bRoot = false; public FXMakerWireframe m_WireObject; // [HideInInspector] // static init ------------------------------------------------------------------------ public static void CreateInstanceIndexing(Transform oriTrans, Transform insTrans, bool bSameValueRecursively, bool bRuntimeCreatedObj) { if (insTrans == null) return; FxmInfoIndexing com = insTrans.gameObject.AddComponent<FxmInfoIndexing>(); com.SetOriginal(oriTrans, bRuntimeCreatedObj); com.OnAutoInitValue(); // Dup process NcDuplicator dupCom = com.GetComponent<NcDuplicator>(); if (dupCom != null) { GameObject clone = dupCom.GetCloneObject(); if (clone != null) CreateInstanceIndexing(oriTrans, clone.transform, bSameValueRecursively, false); } if (bSameValueRecursively) { for (int n = 0; n < insTrans.childCount; n++) CreateInstanceIndexing(oriTrans, insTrans.GetChild(n), bSameValueRecursively, true); } else { for (int n = 0; n < oriTrans.childCount; n++) { if (n < insTrans.childCount) CreateInstanceIndexing(oriTrans.GetChild(n), insTrans.GetChild(n), bSameValueRecursively, bRuntimeCreatedObj); } } } public static FxmInfoIndexing FindInstanceIndexing(Transform oriTrans, bool bIncludeRuntimeCreatedObj) { GameObject parentObj = FXMakerMain.inst.GetInstanceRoot(); FxmInfoIndexing[] coms = parentObj.GetComponentsInChildren<FxmInfoIndexing>(true); foreach (FxmInfoIndexing fxmInfoIndexing in coms) { if (fxmInfoIndexing.m_OriginalTrans == oriTrans && (bIncludeRuntimeCreatedObj || fxmInfoIndexing.m_bRuntimeCreatedObj == false)) return fxmInfoIndexing; } return null; } public static List<FxmInfoIndexing> FindInstanceIndexings(Transform oriTrans, bool bIncludeRuntimeCreatedObj) { GameObject parentObj = FXMakerMain.inst.GetInstanceRoot(); FxmInfoIndexing[] coms = parentObj.GetComponentsInChildren<FxmInfoIndexing>(true); List<FxmInfoIndexing> list = new List<FxmInfoIndexing>(); foreach (FxmInfoIndexing fxmInfoIndexing in coms) { if (oriTrans == null || fxmInfoIndexing.m_OriginalTrans == oriTrans && (bIncludeRuntimeCreatedObj || fxmInfoIndexing.m_bRuntimeCreatedObj == false)) list.Add(fxmInfoIndexing); } return list; } public void OnAutoInitValue() { NcEffectBehaviour[] oriComs = m_OriginalTrans.GetComponents<NcEffectBehaviour>(); foreach (NcEffectBehaviour effect in oriComs) effect.OnUpdateToolData(); NcEffectBehaviour[] insComs = transform.GetComponents<NcEffectBehaviour>(); foreach (NcEffectBehaviour effect in insComs) effect.OnUpdateToolData(); // Set particleSystem.speed // { // NcParticleSystem ncParticleScaleOri = (m_OriginalTrans.GetComponent<NcParticleSystem>()); // NcParticleSystem ncParticleScaleIns = (transform.GetComponent<NcParticleSystem>()); // if (ncParticleScaleOri != null && ncParticleScaleIns != null && ncParticleScaleOri.particleSystem != null) // { // ncParticleScaleOri.SaveShurikenSpeed(); // ncParticleScaleIns.SaveShurikenSpeed(); // } // } // Update bWorldSpace { NcParticleSystem ncParticleScaleOri = (m_OriginalTrans.GetComponent<NcParticleSystem>()); NcParticleSystem ncParticleScaleIns = (transform.GetComponent<NcParticleSystem>()); if (ncParticleScaleOri != null && ncParticleScaleIns != null) ncParticleScaleIns.m_bWorldSpace = ncParticleScaleOri.m_bWorldSpace = NgSerialized.GetSimulationSpaceWorld(ncParticleScaleOri.transform); } // Set particleEmitter.m_MinNormalVelocity, m_MaxNormalVelocity { NcParticleSystem ncParticleScaleOri = (m_OriginalTrans.GetComponent<NcParticleSystem>()); NcParticleSystem ncParticleScaleIns = (transform.GetComponent<NcParticleSystem>()); if (ncParticleScaleOri != null && ncParticleScaleOri.enabled && ncParticleScaleIns != null && ncParticleScaleOri.particleEmitter != null && ncParticleScaleOri.m_bScaleWithTransform && NgSerialized.IsMeshParticleEmitter(ncParticleScaleOri.particleEmitter)) { float fSetMinValue; float fSetMaxValue; NgSerialized.GetMeshNormalVelocity(ncParticleScaleOri.particleEmitter, out fSetMinValue, out fSetMaxValue); if (fSetMinValue != ncParticleScaleOri.GetScaleMinMeshNormalVelocity() || fSetMaxValue != ncParticleScaleOri.GetScaleMaxMeshNormalVelocity()) { NgSerialized.SetMeshNormalVelocity(ncParticleScaleOri.particleEmitter, ncParticleScaleOri.GetScaleMinMeshNormalVelocity(), ncParticleScaleOri.GetScaleMaxMeshNormalVelocity()); NgSerialized.SetMeshNormalVelocity(ncParticleScaleIns.particleEmitter, ncParticleScaleOri.GetScaleMinMeshNormalVelocity(), ncParticleScaleOri.GetScaleMaxMeshNormalVelocity()); } } } } // Property ------------------------------------------------------------------------- public void SetSelected(bool bSelected, bool bRoot) { m_bSelected = bSelected; m_bRootSelected = bRoot; } public void SetOriginal(Transform originalTrans, bool bRuntimeCreatedObj) { m_OriginalTrans = originalTrans; m_bRuntimeCreatedObj = bRuntimeCreatedObj; } public bool IsParticle() { return (particleEmitter != null || particleSystem != null); } public bool IsMesh() { MeshFilter filter = GetComponent<MeshFilter>(); return (filter != null && filter.sharedMesh != null); } public int GetParticleCount() { if (IsParticle() == false) return 0; if (m_WireObject == null) return 0; return m_WireObject.GetParticleCount(); } // Control -------------------------------------------------------------------------- public bool IsPickingParticle(Ray ray) { if (IsParticle() == false) return false; if (m_WireObject == null) return false; List<Vector4> listPos = m_WireObject.GetLastParticlePostions(); foreach (Vector4 pos in listPos) { Bounds bounds = new Bounds(new Vector3(pos.x, pos.y, pos.z), new Vector3(pos.w, pos.w, pos.w)); if (bounds.IntersectRay(ray)) return true; } return false; } // UpdateLoop ----------------------------------------------------------------------- void Start() { if (m_bPicking) InitPicking(m_bPicking); } void OnDrawGizmos() { if (m_bBounds) { if (IsParticle()) { Bounds allBounds = new Bounds(); List<Vector4> listPos = m_WireObject.GetLastParticlePostions(); for (int n=0; n < listPos.Count; n++) { Vector4 pos = listPos[n]; Bounds bounds = new Bounds(new Vector3(pos.x, pos.y, pos.z), new Vector3(pos.w, pos.w, pos.w)); // Bounds bounds = new Bounds(new Vector3(pos.x, pos.y, pos.z), new Vector3(0, 0, 0)); // Gizmos.DrawCube(bounds.center, new Vector3(0.1f, 0.1f, 0.1f)); if (n == 0) allBounds = bounds; else allBounds.Encapsulate(bounds); } Gizmos.matrix = Matrix4x4.identity; DrawBox(allBounds, (m_bRoot ? FXMakerOption.inst.m_ColorRootBoundsBox : FXMakerOption.inst.m_ColorChildBoundsBox)); } else if (renderer != null) { Gizmos.matrix = Matrix4x4.identity; DrawBox(renderer.bounds, (m_bRoot ? FXMakerOption.inst.m_ColorRootBoundsBox : FXMakerOption.inst.m_ColorChildBoundsBox)); } } } void DrawBox(Bounds bounds, Color color) { Color oldColor = Gizmos.color; Gizmos.color = color; Gizmos.DrawWireCube(bounds.center, bounds.size); Gizmos.color = oldColor; } // Event ------------------------------------------------------------------------- // Function ---------------------------------------------------------------------- bool InitPicking(bool bPicking) { if (renderer == null || bPicking == false) return false; // particle if (IsParticle()) { SetBoundsWire(m_bBounds, m_bWireframe, m_bRoot); return true; } // mesh if ((GetComponent<MeshFilter>() != null && GetComponent<MeshFilter>().sharedMesh != null)) { Mesh mesh = GetComponent<MeshFilter>().sharedMesh; bool bPlane = (mesh.bounds.size.x < 0.1f || mesh.bounds.size.y < 0.1f || mesh.bounds.size.z < 0.1f); m_bPicking = true; m_Collider = GetComponent<Collider>(); if (m_Collider == null) { if (bPlane) { m_Collider = gameObject.AddComponent<BoxCollider>(); } else { m_Collider = gameObject.AddComponent<MeshCollider>(); } } return true; } return false; } public void SetBoundsWire(bool bBounds, bool bWireframe, bool bRoot) { CreateWireObject(); m_bWireframe = m_WireObject.InitWireframe(transform, bWireframe, true, bRoot); m_bBounds = bBounds; m_bRoot = bRoot; } void CreateWireObject() { if (m_WireObject == null) { GameObject newObj = NgObject.CreateGameObject(gameObject, "WireObject"); m_WireObject = newObj.AddComponent<FXMakerWireframe>(); m_WireObject.m_ParentName = gameObject.name; } } } #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 Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01.inherit01 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(dynamic i = null) { return i ?? 1; } } public class Derived : Parent { public override int Foo(dynamic i = default(dynamic)) { return i ?? 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01a.inherit01a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(int? i = 1) { return (int)i; } } public class Derived : Parent { public override int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02.inherit02 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(dynamic i) { return 1; } } public class Derived : Parent { public override int Foo(dynamic i = null) { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02a.inherit02a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(int? i) { return (int)i; } } public class Derived : Parent { public override int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit03a.inherit03a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(int? i = 0) { return (int)1; } } public class Derived : Parent { public override int Foo(int? i) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); try { p.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04.inherit04 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual dynamic Foo(dynamic i = null) { return 0; } } public class Derived : Parent { public new dynamic Foo(dynamic i) { return 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04a.inherit04a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(int? i = 0) { return (int)i; } } public class Derived : Parent { public new int Foo(int? i) { return (int)1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05.inherit05 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual dynamic Foo(dynamic i = null) { return 1; } } public class Derived : Parent { public new dynamic Foo(dynamic i = null) { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05a.inherit05a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(int? i = 1) { return 1; } } public class Derived : Parent { public new int Foo(int? i = 0) { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06.inherit06 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual dynamic Foo(dynamic i = null) { return 1; } } public class Child : Parent { public override dynamic Foo(dynamic i = null) { return 1; } } public class Derived : Child { public override dynamic Foo(dynamic i = null) { return i ?? 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06a.inherit06a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(int? i = 0) { return 1; } } public class Child : Parent { public override int Foo(int? i = 2) { return 1; } } public class Derived : Child { public override int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07.inherit07 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual dynamic Foo(dynamic i = null) { return 1; } } public class Child : Parent { public virtual new dynamic Foo(dynamic i = null) { return 1; } } public class Derived : Child { public override dynamic Foo(dynamic i = null) { return i ?? 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07a.inherit07a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(int? i = 1) { return 1; } } public class Child : Parent { public virtual new int Foo(int? i = 20) { return 1; } } public class Derived : Child { public override int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08.inherit08 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual dynamic Foo(dynamic i = null) { return 1; } } public class Child : Parent { public override dynamic Foo(dynamic i = null) { return 1; } } public class Derived : Child { public new dynamic Foo(dynamic i = null) { return i ?? 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08a.inherit08a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Parent { public virtual int Foo(int? i = 1) { return 1; } } public class Child : Parent { public override int Foo(int? i = 1) { return 1; } } public class Derived : Child { public new int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09.inherit09 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { dynamic Foo(dynamic i = null); } public class Derived : Parent { public dynamic Foo(dynamic i = null) { return i ?? 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09a.inherit09a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 1); } public class Derived : Parent { public int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10.inherit10 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(dynamic i); } public class Derived : Parent { public int Foo(dynamic i = null) { return i ?? 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10a.inherit10a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i); } public class Derived : Parent { public int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit11a.inherit11a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 0); } public class Derived : Parent { public int Foo(int? i) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); try { p.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit12a.inherit12a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(14,17\).*CS0109</Expects> public interface Parent { int Foo(int? i = 0); } public class Derived : Parent { public new int Foo(int? i) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); try { p.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13.inherit13 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { dynamic Foo(int i = 1); } public class Derived : Parent { public dynamic Foo(int i = 0) { return i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13a.inherit13a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 1); } public class Derived : Parent { public int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14.inherit14 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { dynamic Foo(int i = 1); } public class Child : Parent { public virtual dynamic Foo(int i = 0) { return i - 2; } } public class Derived : Child { public override dynamic Foo(int i = 0) { return i + 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Child c = new Child(); Derived p = new Derived(); return p.Foo() + c.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14a.inherit14a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 1); } public class Child : Parent { public virtual int Foo(int? i = 0) { return (int)i - 2; } } public class Derived : Child { public override int Foo(int? i = 0) { return (int)i + 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new Child(); dynamic p = new Derived(); return p.Foo() + c.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15.inherit15 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(13,29\).*CS0109</Expects> public interface Parent { dynamic Foo(int i = 1); } public class Child : Parent { public virtual new dynamic Foo(int i = 1) { return 1; } } public class Derived : Child { public override dynamic Foo(int i = 0) { return i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15a.inherit15a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(13,25\).*CS0109</Expects> public interface Parent { int Foo(int? i = 1); } public class Child : Parent { public virtual new int Foo(int? i = 1) { return 1; } } public class Derived : Child { public override int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19.inherit19 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { dynamic Foo(dynamic i = null); } public struct Derived : Parent { public dynamic Foo(dynamic i = null) { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19a.inherit19a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 1); } public struct Derived : Parent { public int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20.inherit20 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { dynamic Foo(dynamic i = null); } public struct Derived : Parent { public dynamic Foo(dynamic i) { return i ?? 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20a.inherit20a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 0); } public struct Derived : Parent { public int Foo(int? i) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p1 = new Derived(); dynamic p = p1; return ((Parent)p).Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21.inherit21 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { dynamic Foo(dynamic i = null); } public class Child : Parent { public virtual dynamic Foo(dynamic i = null) { return i ?? 0 - 2; } } public class Derived : Child { public override dynamic Foo(dynamic i = null) { return i ?? 0 + 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Child c = new Child(); Derived p = new Derived(); return p.Foo() + c.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21a.inherit21a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 0); } public class Child : Parent { public virtual int Foo(int? i = 0) { return (int)i - 2; } } public class Derived : Child { public override int Foo(int? i = 0) { return (int)i + 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new Child(); dynamic p = new Derived(); return p.Foo() + c.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22.inherit22 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(dynamic i = null); } public struct Derived : Parent { public int Foo(dynamic i = null) { return 0; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Derived(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22a.inherit22a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 0); } public struct Derived : Parent { public int Foo(int? i = 0) { return (int)i; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p1 = new Derived(); dynamic p = p1; return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23.inherit23 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(dynamic i = null); } public class Derived : Parent { public int Foo(dynamic i = null) { return i - 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Derived(); return p.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23a.inherit23a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 1); } public class Derived : Parent { public int Foo(int? i = 0) { return (int)i - 1; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p1 = new Derived(); dynamic p = p1; dynamic d = 1; return p.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit24a.inherit24a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a inheritance chain with optional parameters</Description> // <Expects status=success></Expects> // <Code> public interface Parent { int Foo(int? i = 0); } public struct Derived : Parent { public int Foo(int? i) { return i.Value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Derived(); try { p.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0"); if (ret) return 0; } return 1; } } //</Code> }
using System; using System.Linq; using System.Text; using System.Web.Mvc; namespace BootstrapMvc.HtmlHelpers { public static class BootStrapExtensions { public enum ErrorMode { Alert, ClosableAlert, Panel, Modal, CollapsePanel } public class BootstrapValidationSummaryOptions { public ErrorMode DisplayMode { get; set; } public bool ShowModelErrors { get; set; } public string Title { get; set; } public string IntroductionBlock { get; set; } public AlertStyleSettings AlertDisplaySettings { get; set; } public PanelStyleSettings PanelDisplaySettings { get; set; } public ModalStyleSettings ModalDisplaySettings { get; set; } public bool EnableRequiredFieldIndicators { get; set; } public bool EnableRequiredFieldHelp { get; set; } public BootstrapValidationSummaryOptions(ErrorMode mode = ErrorMode.Alert, bool showModelErrors = true, string title = "Oops! There seems to be a problem.", string introductionBlock = "There seems to have been a problem with your request. See below: ", bool enableRequiredFieldIndicators = true, bool enableRequiredFieldHelp = true, AlertStyleSettings alertStyleSettings = null, PanelStyleSettings panelStyleSettings = null, ModalStyleSettings modalStyleSettings = null) { DisplayMode = mode; ShowModelErrors = showModelErrors; Title = title; IntroductionBlock = introductionBlock; EnableRequiredFieldIndicators = enableRequiredFieldIndicators; EnableRequiredFieldHelp = enableRequiredFieldHelp; AlertDisplaySettings = (alertStyleSettings == null) ? new AlertStyleSettings() : alertStyleSettings; PanelDisplaySettings = (panelStyleSettings == null) ? new PanelStyleSettings() : panelStyleSettings; ModalDisplaySettings = (modalStyleSettings == null) ? new ModalStyleSettings() : modalStyleSettings; } } public class BaseStyleSettings { public string ContainerClass { get; internal protected set; } public string ContainerEmphasisClass { get; internal protected set; } public string HeadingClass { get; internal protected set; } public string TitleClass { get; internal protected set; } public string BodyClass { get; internal protected set; } public string IntroductionBlockClass { get; internal protected set; } public string IntroductionBlockEmphasisClass { get; internal protected set; } public string DefaultModelErrorGroupClass { get; internal protected set; } public string DefaultModelErrorBaseItemClass { get; internal protected set; } public string DefaultModelErrorItemClass { get; internal protected set; } public string DefaultModelErrorItemAltClass { get; internal protected set; } public string AdditionalModelErrorGroupClass { get; internal protected set; } public string AdditionalModelErrorGroupEmphasis { get; internal protected set; } public BaseStyleSettings(string container, string containerEmphasis, string heading, string title, string body, string introduction, string introductionEmphasis, string defaulterrorgroup, string defaulterroritembase, string defaulterroritem, string defaulterroraltitem, string additionalerrorgroup, string additionalerrorgroupemphasis) { ContainerClass = container; ContainerEmphasisClass = containerEmphasis; HeadingClass = heading; TitleClass = title; BodyClass = body; IntroductionBlockClass = introduction; IntroductionBlockEmphasisClass = introductionEmphasis; DefaultModelErrorGroupClass = defaulterrorgroup; DefaultModelErrorBaseItemClass = defaulterroritembase; DefaultModelErrorItemClass = defaulterroritem; DefaultModelErrorItemAltClass = defaulterroraltitem; AdditionalModelErrorGroupClass = additionalerrorgroup; AdditionalModelErrorGroupEmphasis = additionalerrorgroupemphasis; } } public class AlertStyleSettings : BaseStyleSettings { public string ContainerDismissibleClass { get; internal protected set; } public string CloseButtonClass { get; internal protected set; } public AlertStyleSettings(string container = "alert", string containerEmphasis = "alert-danger", string containerDismissible = "alert-dismissible", string heading = "", string title = "", string body = "", string closebutton = "close", string introduction = "well", string introductionEmphasis = "well-sm", string defaultmodelerrorgroup = "list-group", string defaultmodelerroritembase = "list-group-item", string defaultmodelerroritem = "", string defaultmodelerroraltitem = "list-group-item-warning", string additionalmodelerrorgroup = "alert", string additionalmodelerrorgroupemphasis = "alert-danger" ) : base(container, containerEmphasis, heading, title, body, introduction, introductionEmphasis, defaultmodelerrorgroup, defaultmodelerroritembase, defaultmodelerroritem, defaultmodelerroraltitem, additionalmodelerrorgroup, additionalmodelerrorgroupemphasis) { ContainerDismissibleClass = containerDismissible; CloseButtonClass = closebutton; } } public class PanelStyleSettings : BaseStyleSettings { public PanelStyleSettings(string container = "panel", string containerEmphasis = "panel-danger", string heading = "panel-heading", string title = "panel-title", string body = "panel-body", string introduction = "well", string introductionEmphasis = "well-sm", string defaultmodelerrorgroup = "list-group", string defaultmodelerroritembase = "list-group-item", string defaultmodelerroritem = "", string defaultmodelerroraltitem = "list-group-item-warning", string additionalmodelerrorgroup = "alert", string additionalmodelerrorgroupemphasis = "alert-danger" ) : base(container, containerEmphasis, heading, title, body, introduction, introductionEmphasis, defaultmodelerrorgroup, defaultmodelerroritembase, defaultmodelerroritem, defaultmodelerroraltitem, additionalmodelerrorgroup, additionalmodelerrorgroupemphasis) { } } public class ModalStyleSettings : BaseStyleSettings { public string ModalDialogClass { get; internal protected set; } public string ModalDialogContentClass { get; internal protected set; } public string CloseButtonClass { get; internal protected set; } public ModalStyleSettings(string container = "modal", string containerEmphasis = "fade", string heading = "modal-header", string title = "modal-title", string body = "modal-body", string introduction = "well", string introductionEmphasis = "well-sm", string defaultmodelerrorgroup = "list-group", string defaultmodelerroritembase = "list-group-item", string defaultmodelerroritem = "", string defaultmodelerroraltitem = "list-group-item-warning", string additionalmodelerrorgroup = "alert", string additionalmodelerrorgroupemphasis = "alert-danger", string modaldialog = "modal-dialog", string modaldialogcontent = "modal-content", string closebutton = "close") : base(container, containerEmphasis, heading, title, body, introduction, introductionEmphasis, defaultmodelerrorgroup, defaultmodelerroritembase, defaultmodelerroritem, defaultmodelerroraltitem, additionalmodelerrorgroup, additionalmodelerrorgroupemphasis) { ModalDialogClass = modaldialog; ModalDialogContentClass = modaldialogcontent; CloseButtonClass = closebutton; } } public static MvcHtmlString BootStrapValidationSummary(this HtmlHelper helper, BootstrapValidationSummaryOptions options = null) { ///This is the full script for altering the labels on required fields. ///I have tweaked from original version to handle checkbox and text box validation. string requiredDecoratingScript = "<script>" + "$(this).ready(function () {" + "$('[data-val-required]').each(function () {" + "var label = $(\"label[for='\" + $(this).attr('id') + \"']\");" + "var isCheckbox = $(this).is(':checkbox');" + "var isTextbox = $(this).is(':text');" + "var isPassword = $(this).is(':password');" + "var isValidTextValue = true;" + "if(isTextbox || isPassword)" + "{" + "isValidTextValue = $(this).val() !== '';" + "}" + "label.removeClass(\"text-success\");" + "label.removeClass(\"text-danger\");" + "if ((" + ((helper.ViewData.ModelState.IsValid) ? "true" : "false") + "|$(this).hasClass(\"input-validation-error\") | !isValidTextValue) " + "&& !isCheckbox" + ") {" + "label.addClass(\"text-danger\");" + "}" + "else " + "{" + "if(!isCheckbox){" + "label.addClass(\"text-success\");" + "}" + "}" + "});" + "}); " + "</script>"; string requiredbox = "<div class=\"well well-sm\"><p>All labels like <strong class=\"text-danger\">this</strong> are required fields.</p>" + "<p>All labels like <strong class=\"text-success\">this</strong> are valid required fields.</p></div>"; StringBuilder stringBuilder = new StringBuilder(); if (options == null) { options = new BootstrapValidationSummaryOptions(); } if (!options.EnableRequiredFieldHelp) { requiredbox = string.Empty; } if (!options.EnableRequiredFieldIndicators) { requiredDecoratingScript = string.Empty; } // first lets check to see if we have any errors in the system. if (helper.ViewData.ModelState.IsValid) { //we have a valid model lets not do anything. return new MvcHtmlString(requiredbox + requiredDecoratingScript); } //To ensure compatability with JQuery Validate We need to wrap this up into a new validation div that will be hidden by default but will display once the system is launched //Need to see how I can do this is a nicer way without having to rewrite the entire helper. string unObtrusiveStringOpen = string.Format("<div class=\"{0}\" data-valmsg-summary=\"true\">", (helper.ViewData.ModelState.IsValid) ? "validation-summary-valid" : "validation-summary-errors"); string unObtrusiveStringEnd = string.Format("</div>"); switch (options.DisplayMode) { case ErrorMode.Alert: { stringBuilder = AlertMode(helper, false, options); break; } case ErrorMode.ClosableAlert: { stringBuilder = AlertMode(helper, true, options); break; } case ErrorMode.Modal: { stringBuilder = ModalAlertMode(helper, options); break; } case ErrorMode.Panel: { stringBuilder = PanelAlertMode(helper, options); break; } case ErrorMode.CollapsePanel: { stringBuilder = CollapsePanelAlertMode(helper, options); break; } default: { //default mode will be standard alert mode. stringBuilder = AlertMode(helper, false, options); break; } } // MvcHtmlString returnString = new MvcHtmlString(requiredbox + unObtrusiveStringOpen + stringBuilder.ToString() + unObtrusiveStringEnd + requiredDecoratingScript); MvcHtmlString returnString = new MvcHtmlString(requiredbox + stringBuilder.ToString() + requiredDecoratingScript); return returnString; } private static StringBuilder CollapsePanelAlertMode(HtmlHelper helper, BootstrapValidationSummaryOptions options) { StringBuilder builder = new StringBuilder(); //add the main panel builder.AppendFormat("<div class=\"{0} {1}\" id=\"{2}\">", options.PanelDisplaySettings.ContainerClass, options.PanelDisplaySettings.ContainerEmphasisClass, "SummaryCollapsePanel"); //add the header builder.AppendFormat("<div class=\"{0}\">", options.PanelDisplaySettings.HeadingClass); builder.AppendFormat("<div class=\"{0}\">", options.PanelDisplaySettings.TitleClass); builder.AppendFormat("<a href=\"#{0}\" data-toggle=\"collapse\" data-parent=\"#{1}\">", "SummaryErrorBody", "SummaryCollapsePanel"); builder.AppendFormat("<h4>{0} <span id=\"Errorheader-icon\" class=\"pull-right glyphicon glyphicon-plus-sign\"></span> </h4>", options.Title); builder.AppendFormat("</a>"); //close the header builder.Append("</div>"); builder.Append("</div>"); //open the panel body builder.AppendFormat("<div class=\"{0}\" id=\"{1}\">", "panel-collapse collapse in", "SummaryErrorBody"); builder.Append(AddIntroductionText(options.IntroductionBlock, options.PanelDisplaySettings)); builder.Append(AddModelErrors(helper, options.ShowModelErrors, options.PanelDisplaySettings)); //close the panel body builder.Append("</div>"); //close the panel builder.Append("</div>"); //now build in the collapse script builder.AppendFormat("<script>"); builder.Append("$(document).ready(function () {" + " $(\"#SummaryCollapsePanel\").click(function () { " + "var control = $(\"#Errorheader-icon\");" + "if (control.hasClass(\"glyphicon-plus-sign\")) {" + "control.removeClass(\"glyphicon-plus-sign\");" + "control.removeClass(\"glyphicon\");" + "control.addClass(\"glyphicon\");" + "control.addClass(\"glyphicon-minus-sign\");" + " } else {" + "control.removeClass(\"glyphicon-minus-sign\");" + "control.removeClass(\"glyphicon\");" + "control.addClass(\"glyphicon\");" + "control.addClass(\"glyphicon-plus-sign\");" + "} " + " });" + "});" ); //close the script tag builder.AppendFormat("</script>"); return builder; } private static StringBuilder PanelAlertMode(HtmlHelper helper, BootstrapValidationSummaryOptions options) { StringBuilder builder = new StringBuilder(); //add the main panel builder.AppendFormat("<div class=\"{0} {1}\">", options.PanelDisplaySettings.ContainerClass, options.PanelDisplaySettings.ContainerEmphasisClass); //add the header builder.AppendFormat("<div class=\"{0}\">", options.PanelDisplaySettings.HeadingClass); builder.AppendFormat("<h4 class=\"{0}\">{1}</h4>", options.PanelDisplaySettings.TitleClass, options.Title); //close the header builder.Append("</div>"); //open the panel body builder.AppendFormat("<div class=\"{0}\">", options.PanelDisplaySettings.BodyClass); builder.Append(AddIntroductionText(options.IntroductionBlock, options.PanelDisplaySettings)); builder.Append(AddModelErrors(helper, options.ShowModelErrors, options.PanelDisplaySettings)); //close the panel body builder.Append("</div>"); //close the panel builder.Append("</div>"); return builder; } private static StringBuilder ModalAlertMode(HtmlHelper helper, BootstrapValidationSummaryOptions options) { StringBuilder builder = new StringBuilder(); //open up the modal window builder.AppendFormat("<div class=\"{0} {1} \" id=\"SummaryErrors\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"SummaryErrorLabel\" aria-hidden=\"true\">", options.ModalDisplaySettings.ContainerClass, options.ModalDisplaySettings.ContainerEmphasisClass); //add the dialog builder.AppendFormat("<div class=\"{0}\">", options.ModalDisplaySettings.ModalDialogClass); //add the content builder.AppendFormat("<div class=\"{0}\">", options.ModalDisplaySettings.ModalDialogContentClass); //add the header builder.AppendFormat("<div class=\"{0}\">", options.ModalDisplaySettings.HeadingClass); //add button to close the modal builder.AppendFormat("<button type=\"button\" class=\"{0}\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>", options.ModalDisplaySettings.CloseButtonClass); builder.AppendFormat("<h4 class=\"{0}\" id=\"SummaryErrorLabel\">{1}</h4>", options.ModalDisplaySettings.TitleClass, options.Title); //close the header builder.Append("</div>"); //open the body builder.AppendFormat("<div class=\"{0}\">", options.ModalDisplaySettings.BodyClass); //add introduction text builder.Append(AddIntroductionText(options.IntroductionBlock, options.ModalDisplaySettings).ToString()); //add the model errors builder.Append(AddModelErrors(helper, options.ShowModelErrors, options.ModalDisplaySettings)); //close the body builder.Append("</div>"); //close the content builder.Append("</div>"); //close the dialog builder.Append("</div>"); //close the modal window builder.Append("</div>"); //add javascript to fire up the modal when the document has finished loading. builder.Append("<script>$(document).ready(function(){ $(\"#SummaryErrors\").modal(\"show\");}); </script>"); return builder; } private static StringBuilder AlertMode(this HtmlHelper helper, bool closable, BootstrapValidationSummaryOptions options) { //this is the standard alert mode box. StringBuilder builder = new StringBuilder(); if (closable) { builder.AppendFormat("<div class=\"{0} {1} {2}\">", options.AlertDisplaySettings.ContainerClass, options.AlertDisplaySettings.ContainerEmphasisClass, options.AlertDisplaySettings.ContainerDismissibleClass); builder.AppendFormat("<button type=\"{0}\" class=\"{1}\" data-dismiss=\"{2}\" aria-hidden=\"{3}\">&times;</button>", "button", options.AlertDisplaySettings.CloseButtonClass, "alert", "true"); } else { builder.AppendFormat("<div class=\"{0} {1} \">", options.AlertDisplaySettings.ContainerClass, options.AlertDisplaySettings.ContainerEmphasisClass); } builder.AppendFormat("<h4>{0}</h4>", options.Title); builder.Append(AddIntroductionText(options.IntroductionBlock, options.AlertDisplaySettings).ToString()); //add the model errors here. builder.Append(AddModelErrors(helper, options.ShowModelErrors, options.AlertDisplaySettings).ToString()); builder.Append("</div>"); return builder; } private static StringBuilder AddIntroductionText(string introductionblock, BaseStyleSettings style) { StringBuilder builder = new StringBuilder(); if (!string.IsNullOrWhiteSpace(introductionblock)) { builder.AppendFormat("<div class=\"{0} {1} \">", style.IntroductionBlockClass, style.IntroductionBlockEmphasisClass); builder.Append(introductionblock); builder.Append("</div>"); } return builder; } private static StringBuilder AddModelErrors(this HtmlHelper helper, bool showModelErrors, BaseStyleSettings style) { StringBuilder builder = new StringBuilder(); bool alternativestyle = false; if (showModelErrors && !helper.ViewData.ModelState.IsValid) { builder.AppendFormat("<ul class=\"{0}\">", style.DefaultModelErrorGroupClass); foreach (string key in helper.ViewData.ModelState.Keys) { if (key != "") { foreach (ModelError error in helper.ViewData.ModelState[key].Errors) { builder.AppendFormat("<li class=\"{0} {1}\">{2}</li>", style.DefaultModelErrorBaseItemClass, alternativestyle ? style.DefaultModelErrorItemClass : style.DefaultModelErrorItemAltClass, !string.IsNullOrWhiteSpace(error.ErrorMessage) ? error.ErrorMessage : error.Exception.Message); alternativestyle = !alternativestyle; } } } builder.Append("</ul>"); foreach (string key in helper.ViewData.ModelState.Keys) { if (key == "") { builder.AppendFormat("<div class=\"{0} {1}\">", style.AdditionalModelErrorGroupClass, style.AdditionalModelErrorGroupEmphasis); builder.Append("<strong>The following general errors have occurred:</strong>"); builder.Append("<hr/>"); foreach (ModelError error in helper.ViewData.ModelState[key].Errors) { builder.AppendFormat("<p>{0}</p>", !string.IsNullOrWhiteSpace(error.ErrorMessage) ? error.ErrorMessage : error.Exception.Message); } builder.Append("</div>"); } } } else { //builder.AppendFormat("<ul class=\"{0}\">", style.DefaultModelErrorGroupClass); //builder.Append("</ul>"); } return builder; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Settings/Master/BadgeSettings.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Settings.Master { /// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/BadgeSettings.proto</summary> public static partial class BadgeSettingsReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Settings/Master/BadgeSettings.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static BadgeSettingsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci5QT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9CYWRnZVNldHRpbmdzLnBy", "b3RvEhpQT0dPUHJvdG9zLlNldHRpbmdzLk1hc3RlchogUE9HT1Byb3Rvcy9F", "bnVtcy9CYWRnZVR5cGUucHJvdG8iZQoNQmFkZ2VTZXR0aW5ncxIvCgpiYWRn", "ZV90eXBlGAEgASgOMhsuUE9HT1Byb3Rvcy5FbnVtcy5CYWRnZVR5cGUSEgoK", "YmFkZ2VfcmFuaxgCIAEoBRIPCgd0YXJnZXRzGAMgAygFYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Enums.BadgeTypeReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.BadgeSettings), global::POGOProtos.Settings.Master.BadgeSettings.Parser, new[]{ "BadgeType", "BadgeRank", "Targets" }, null, null, null) })); } #endregion } #region Messages public sealed partial class BadgeSettings : pb::IMessage<BadgeSettings> { private static readonly pb::MessageParser<BadgeSettings> _parser = new pb::MessageParser<BadgeSettings>(() => new BadgeSettings()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<BadgeSettings> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.Master.BadgeSettingsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BadgeSettings() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BadgeSettings(BadgeSettings other) : this() { badgeType_ = other.badgeType_; badgeRank_ = other.badgeRank_; targets_ = other.targets_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BadgeSettings Clone() { return new BadgeSettings(this); } /// <summary>Field number for the "badge_type" field.</summary> public const int BadgeTypeFieldNumber = 1; private global::POGOProtos.Enums.BadgeType badgeType_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Enums.BadgeType BadgeType { get { return badgeType_; } set { badgeType_ = value; } } /// <summary>Field number for the "badge_rank" field.</summary> public const int BadgeRankFieldNumber = 2; private int badgeRank_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int BadgeRank { get { return badgeRank_; } set { badgeRank_ = value; } } /// <summary>Field number for the "targets" field.</summary> public const int TargetsFieldNumber = 3; private static readonly pb::FieldCodec<int> _repeated_targets_codec = pb::FieldCodec.ForInt32(26); private readonly pbc::RepeatedField<int> targets_ = new pbc::RepeatedField<int>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<int> Targets { get { return targets_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as BadgeSettings); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(BadgeSettings other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (BadgeType != other.BadgeType) return false; if (BadgeRank != other.BadgeRank) return false; if(!targets_.Equals(other.targets_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (BadgeType != 0) hash ^= BadgeType.GetHashCode(); if (BadgeRank != 0) hash ^= BadgeRank.GetHashCode(); hash ^= targets_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (BadgeType != 0) { output.WriteRawTag(8); output.WriteEnum((int) BadgeType); } if (BadgeRank != 0) { output.WriteRawTag(16); output.WriteInt32(BadgeRank); } targets_.WriteTo(output, _repeated_targets_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (BadgeType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) BadgeType); } if (BadgeRank != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(BadgeRank); } size += targets_.CalculateSize(_repeated_targets_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(BadgeSettings other) { if (other == null) { return; } if (other.BadgeType != 0) { BadgeType = other.BadgeType; } if (other.BadgeRank != 0) { BadgeRank = other.BadgeRank; } targets_.Add(other.targets_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { badgeType_ = (global::POGOProtos.Enums.BadgeType) input.ReadEnum(); break; } case 16: { BadgeRank = input.ReadInt32(); break; } case 26: case 24: { targets_.AddEntriesFrom(input, _repeated_targets_codec); break; } } } } } #endregion } #endregion Designer generated code
/*The MIT License(MIT) Copyright(c) 2016 Jagadeesh Govindaraj and Amulya Khare 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.*/ //Ported C# By Jagadeesh Govindaraj //TweetMe @Jaganjan using System; using Android.Graphics; using Android.Graphics.Drawables; using Android.Graphics.Drawables.Shapes; namespace Android.Ui.TextDrawable { /// <summary> /// Class TextDrawable. This class cannot be inherited. /// </summary> public sealed class TextDrawable : ShapeDrawable { /// <summary> /// The rand /// </summary> /// <summary> /// The rand /// </summary> private static readonly Random Rand = new Random(); /// <summary> /// The _shade factor /// </summary> private static readonly float ShadeFactor = 0.9f; /// <summary> /// The _bitmap /// </summary> private readonly Bitmap _bitmap; /// <summary> /// The _bordercolor /// </summary> private readonly Color _bordercolor; /// <summary> /// The _border paint /// </summary> private readonly Paint _borderPaint; /// <summary> /// The _border thickness /// </summary> private readonly int _borderThickness; /// <summary> /// The _color /// </summary> private readonly Color _color; /// <summary> /// The _font size /// </summary> private readonly int _fontSize; /// <summary> /// The _height /// </summary> private readonly int _height; /// <summary> /// The _radius /// </summary> private readonly float _radius; /// <summary> /// The _text /// </summary> private readonly string _text; /// <summary> /// The _text paint /// </summary> private readonly Paint _textPaint; /// <summary> /// The _width /// </summary> private readonly int _width; /// <summary> /// The _shape /// </summary> private RectShape _shape; /// <summary> /// Initializes a new instance of the <see cref="TextDrawable" /> class. /// </summary> /// <param name="builder">The builder.</param> private TextDrawable(Builder builder) : base(builder._shape) { // shape properties _shape = builder._shape; _height = builder._height; _width = builder._width; _radius = builder.Radius; // text and color _text = builder._toUpperCase ? builder._text.ToUpper() : builder._text; _color = builder.Color; // text paint settings _fontSize = builder._fontSize; _textPaint = new Paint { Color = builder._textColor, AntiAlias = true, FakeBoldText = builder.IsBold }; _textPaint.SetStyle(Paint.Style.Fill); _textPaint.SetTypeface(builder.Font); _textPaint.TextAlign = Paint.Align.Center; _textPaint.StrokeWidth = builder.BorderThickness; // border paint settings _borderThickness = builder.BorderThickness; _bordercolor = builder._borderColor; _borderPaint = new Paint { Color = _bordercolor, AntiAlias = true }; _borderPaint.SetStyle(Paint.Style.Stroke); _borderPaint.StrokeWidth = _borderThickness; // drawable paint color var paint = Paint; paint.Color = _color; if (builder.Drawable != null) { _bitmap = ((BitmapDrawable)builder.Drawable).Bitmap; } } /// <summary> /// Interface IBuilder /// </summary> public interface IBuilder { /// <summary> /// Builds the specified text. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> TextDrawable Build(string text, Color color); /// <summary> /// Builds the specified drawable. /// </summary> /// <param name="drawable">The drawable.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> TextDrawable Build(Drawable drawable, Color color); } /// <summary> /// Interface IConfigBuilder /// </summary> public interface IConfigBuilder { /// <summary> /// Bolds this instance. /// </summary> /// <returns>IConfigBuilder.</returns> IConfigBuilder Bold(); /// <summary> /// Borders the color. /// </summary> /// <param name="color">The color.</param> /// <returns>IConfigBuilder.</returns> IConfigBuilder BorderColor(Color color); /// <summary> /// Ends the configuration. /// </summary> /// <returns>IShapeBuilder.</returns> IShapeBuilder EndConfig(); /// <summary> /// Fonts the size. /// </summary> /// <param name="size">The size.</param> /// <returns>IConfigBuilder.</returns> IConfigBuilder FontSize(int size); /// <summary> /// Heights the specified height. /// </summary> /// <param name="height">The height.</param> /// <returns>IConfigBuilder.</returns> IConfigBuilder Height(int height); /// <summary> /// Texts the color. /// </summary> /// <param name="color">The color.</param> /// <returns>IConfigBuilder.</returns> IConfigBuilder TextColor(Color color); /// <summary> /// To the upper case. /// </summary> /// <returns>IConfigBuilder.</returns> IConfigBuilder ToUpperCase(); /// <summary> /// Uses the font. /// </summary> /// <param name="font">The font.</param> /// <returns>IConfigBuilder.</returns> IConfigBuilder UseFont(Typeface font); /// <summary> /// Widthes the specified width. /// </summary> /// <param name="width">The width.</param> /// <returns>IConfigBuilder.</returns> IConfigBuilder Width(int width); /// <summary> /// Withes the border. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>IConfigBuilder.</returns> IConfigBuilder WithBorder(int thickness); /// <summary> /// Withes the color of the border. /// </summary> /// <param name="color">The color.</param> /// <returns>IConfigBuilder.</returns> IConfigBuilder WithBorderColor(Color color); } /// <summary> /// Interface IShapeBuilder /// </summary> public interface IShapeBuilder { /// <summary> /// Begins the configuration. /// </summary> /// <returns>IConfigBuilder.</returns> IConfigBuilder BeginConfig(); /// <summary> /// Builds the rect. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> TextDrawable BuildRect(string text, Color color); /// <summary> /// Builds the rect. /// </summary> /// <param name="drawable">The drawable.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> TextDrawable BuildRect(Drawable drawable, Color color); /// <summary> /// Builds the round. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> TextDrawable BuildRound(string text, Color color); /// <summary> /// Builds the round. /// </summary> /// <param name="drawable">The drawable.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> TextDrawable BuildRound(Drawable drawable, Color color); /// <summary> /// Builds the round rect. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <param name="radius">The radius.</param> /// <returns>TextDrawable.</returns> TextDrawable BuildRoundRect(string text, Color color, int radius); /// <summary> /// Builds the round rect. /// </summary> /// <param name="drawable">The drawable.</param> /// <param name="color">The color.</param> /// <param name="radius">The radius.</param> /// <returns>TextDrawable.</returns> TextDrawable BuildRoundRect(Drawable drawable, Color color, int radius); /// <summary> /// Rects this instance. /// </summary> /// <returns>IBuilder.</returns> IBuilder Rect(); /// <summary> /// Rounds this instance. /// </summary> /// <returns>IBuilder.</returns> IBuilder Round(); /// <summary> /// Rounds the rect. /// </summary> /// <param name="radius">The radius.</param> /// <returns>IBuilder.</returns> IBuilder RoundRect(int radius); } /// <summary> /// Return the intrinsic height of the underlying drawable object. /// </summary> /// <value>To be added.</value> /// <since version="Added in API level 1" /> /// <remarks><para tool="javadoc-to-mdoc">Return the intrinsic height of the underlying drawable object. Returns /// -1 if it has no intrinsic height, such as with a solid color. /// </para> /// <para tool="javadoc-to-mdoc"> /// <format type="text/html"> /// <a href="http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getIntrinsicHeight()" target="_blank">[Android Documentation]</a> /// </format> /// </para></remarks> public override int IntrinsicHeight => _width; /// <summary> /// Return the intrinsic width of the underlying drawable object. /// </summary> /// <value>To be added.</value> /// <since version="Added in API level 1" /> /// <remarks><para tool="javadoc-to-mdoc">Return the intrinsic width of the underlying drawable object. Returns /// -1 if it has no intrinsic width, such as with a solid color. /// </para> /// <para tool="javadoc-to-mdoc"> /// <format type="text/html"> /// <a href="http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getIntrinsicWidth()" target="_blank">[Android Documentation]</a> /// </format> /// </para></remarks> /// <summary> /// Return the intrinsic width of the underlying drawable object. /// </summary> /// <value>To be added.</value> /// <since version="Added in API level 1" /> /// <remarks><para tool="javadoc-to-mdoc">Return the intrinsic width of the underlying drawable object. Returns /// -1 if it has no intrinsic width, such as with a solid color. /// </para> /// <para tool="javadoc-to-mdoc"> /// <format type="text/html"> /// <a href="http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getIntrinsicWidth()" target="_blank">[Android Documentation]</a> /// </format> /// </para></remarks> public override int IntrinsicWidth => _height; /// <summary> /// Return the opacity/transparency of this Drawable. /// </summary> /// <value>To be added.</value> /// <since version="Added in API level 1" /> /// <remarks><para tool="javadoc-to-mdoc">Return the opacity/transparency of this Drawable. The returned value is /// one of the abstract format constants in /// <c><see cref="T:Android.Graphics.PixelFormat" /></c>: /// <c><see cref="F:Android.Graphics.Format.Unknown" /></c>, /// <c><see cref="F:Android.Graphics.Format.Translucent" /></c>, /// <c><see cref="F:Android.Graphics.Format.Transparent" /></c>, or /// <c><see cref="F:Android.Graphics.Format.Opaque" /></c>. /// </para> /// <para tool="javadoc-to-mdoc">Generally a Drawable should be as conservative as possible with the /// value it returns. For example, if it contains multiple child drawables /// and only shows one of them at a time, if only one of the children is /// TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be /// returned. You can use the method <c><see cref="M:Android.Graphics.Drawables.Drawable.ResolveOpacity(System.Int32, System.Int32)" /></c> to perform a /// standard reduction of two opacities to the appropriate single output. /// </para> /// <para tool="javadoc-to-mdoc">Note that the returned value does <i>not</i> take into account a /// custom alpha or color filter that has been applied by the client through /// the <c><see cref="M:Android.Graphics.Drawables.Drawable.SetAlpha(System.Int32)" /></c> or <c><see cref="M:Android.Graphics.Drawables.Drawable.SetColorFilter(Android.Graphics.ColorFilter)" /></c> methods.</para> /// <para tool="javadoc-to-mdoc"> /// <format type="text/html"> /// <a href="http://developer.android.com/reference/android/graphics/drawable/ShapeDrawable.html#getOpacity()" target="_blank">[Android Documentation]</a> /// </format> /// </para></remarks> /// <summary> /// Return the opacity/transparency of this Drawable. /// </summary> /// <value>To be added.</value> /// <since version="Added in API level 1" /> /// <remarks><para tool="javadoc-to-mdoc">Return the opacity/transparency of this Drawable. The returned value is /// one of the abstract format constants in /// <c><see cref="T:Android.Graphics.PixelFormat" /></c>: /// <c><see cref="F:Android.Graphics.Format.Unknown" /></c>, /// <c><see cref="F:Android.Graphics.Format.Translucent" /></c>, /// <c><see cref="F:Android.Graphics.Format.Transparent" /></c>, or /// <c><see cref="F:Android.Graphics.Format.Opaque" /></c>. /// </para> /// <para tool="javadoc-to-mdoc">Generally a Drawable should be as conservative as possible with the /// value it returns. For example, if it contains multiple child drawables /// and only shows one of them at a time, if only one of the children is /// TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be /// returned. You can use the method <c><see cref="M:Android.Graphics.Drawables.Drawable.ResolveOpacity(System.Int32, System.Int32)" /></c> to perform a /// standard reduction of two opacities to the appropriate single output. /// </para> /// <para tool="javadoc-to-mdoc">Note that the returned value does <i>not</i> take into account a /// custom alpha or color filter that has been applied by the client through /// the <c><see cref="M:Android.Graphics.Drawables.Drawable.SetAlpha(System.Int32)" /></c> or <c><see cref="M:Android.Graphics.Drawables.Drawable.SetColorFilter(Android.Graphics.ColorFilter)" /></c> methods.</para> /// <para tool="javadoc-to-mdoc"> /// <format type="text/html"> /// <a href="http://developer.android.com/reference/android/graphics/drawable/ShapeDrawable.html#getOpacity()" target="_blank">[Android Documentation]</a> /// </format> /// </para></remarks> public override int Opacity => (int)Format.Translucent; /// <summary> /// Gets the random color. /// </summary> /// <value>The random color.</value> public static Color RandomColor => GetRandomColor(); /// <summary> /// Gets the text drwable builder. /// </summary> /// <value>The text drwable builder.</value> public static IShapeBuilder TextDrwableBuilder => new Builder(); /// <summary> /// Sets the alpha. /// </summary> /// <param name="alpha">The alpha.</param> /// <summary> /// Sets the alpha. /// </summary> /// <param name="alpha">The alpha.</param> public override void SetAlpha(int alpha) { _textPaint.Alpha = alpha; } /// <summary> /// Sets the color filter. /// </summary> /// <param name="colorFilter">The color filter.</param> public override void SetColorFilter(ColorFilter colorFilter) { _textPaint.SetColorFilter(colorFilter); } /// <summary> /// Called when [draw]. /// </summary> /// <param name="shape">The shape.</param> /// <param name="canvas">The canvas.</param> /// <param name="paint">The paint.</param> protected override void OnDraw(Shape shape, Canvas canvas, Paint paint) { base.OnDraw(shape, canvas, paint); var r = Bounds; // draw border if (_borderThickness > 0) { DrawBorder(canvas); } var count = canvas.Save(); if (_bitmap == null) { canvas.Translate(r.Left, r.Top); } // draw text var width = _width < 0 ? r.Width() : _width; var height = _height < 0 ? r.Height() : _height; var fontSize = _fontSize < 0 ? Math.Min(width, height) / 2 : _fontSize; if (_bitmap == null) { _textPaint.TextSize = _fontSize; Rect textBounds = new Rect(); _textPaint.GetTextBounds(_text, 0, _text.Length, textBounds); canvas.DrawText(_text, width / 2, height / 2 - textBounds.ExactCenterY(), _textPaint); } else { canvas.DrawBitmap(_bitmap, (width - _bitmap.Width) / 2, (height - _bitmap.Height) / 2, null); } canvas.RestoreToCount(count); } /// <summary> /// Gets the random color. /// </summary> /// <returns>Color.</returns> private static Color GetRandomColor() { var hue = Rand.Next(255); var color = Color.HSVToColor( new[] { hue, 1.0f, 1.0f } ); return color; } /// <summary> /// Draws the border. /// </summary> /// <param name="canvas">The canvas.</param> private void DrawBorder(Canvas canvas) { var rect = new RectF(Bounds); rect.Inset(_borderThickness / 2, _borderThickness / 2); if (Shape is OvalShape) { canvas.DrawOval(rect, _borderPaint); } else if (Shape is RoundRectShape) { canvas.DrawRoundRect(rect, _radius, _radius, _borderPaint); } else { canvas.DrawRect(rect, _borderPaint); } } /// <summary> /// Class Builder. /// </summary> public class Builder : IConfigBuilder, IShapeBuilder, IBuilder { /// <summary> /// The _border color /// </summary> internal Color _borderColor; /// <summary> /// The _font size /// </summary> internal int _fontSize; /// <summary> /// The _height /// </summary> internal int _height; /// <summary> /// The _shape /// </summary> internal RectShape _shape; /// <summary> /// The _text /// </summary> internal string _text; /// <summary> /// The _text color /// </summary> internal Color _textColor; /// <summary> /// The _to upper case /// </summary> internal bool _toUpperCase; /// <summary> /// The _width /// </summary> internal int _width; /// <summary> /// The _border thickness /// </summary> internal int BorderThickness; /// <summary> /// The _color /// </summary> internal Color Color; /// <summary> /// The drawable /// </summary> internal Drawable Drawable; /// <summary> /// The _font /// </summary> internal Typeface Font; /// <summary> /// The _is bold /// </summary> internal bool IsBold; /// <summary> /// The _radius /// </summary> internal float Radius; /// <summary> /// Initializes a new instance of the <see cref="Builder" /> class. /// </summary> internal Builder() { _text = ""; Color = Color.Gray; _textColor = Color.White; _borderColor = Color.Transparent; BorderThickness = 0; _width = -1; _height = -1; _shape = new RectShape(); Font = Typeface.Create(Typeface.SansSerif, TypefaceStyle.Normal); _fontSize = -1; IsBold = false; _toUpperCase = false; } /// <summary> /// Begins the configuration. /// </summary> /// <returns>IConfigBuilder.</returns> public IConfigBuilder BeginConfig() { return this; } /// <summary> /// Bolds this instance. /// </summary> /// <returns>IConfigBuilder.</returns> public IConfigBuilder Bold() { IsBold = true; return this; } /// <summary> /// Borders the color. /// </summary> /// <param name="color">The color.</param> /// <returns>IConfigBuilder.</returns> public IConfigBuilder BorderColor(Color color) { _borderColor = color; return this; } /// <summary> /// Builds the specified text. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> public TextDrawable Build(string text, Color color) { Color = color; _text = text; return new TextDrawable(this); } /// <summary> /// Builds the specified drawable. /// </summary> /// <param name="drawable">The drawable.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> public TextDrawable Build(Drawable drawable, Color color) { Color = color; Drawable = drawable; return new TextDrawable(this); } /// <summary> /// Builds the rect. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> public TextDrawable BuildRect(string text, Color color) { Rect(); return Build(text, color); } /// <summary> /// Builds the rect. /// </summary> /// <param name="drawable">The drawable.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> public TextDrawable BuildRect(Drawable drawable, Color color) { Rect(); return Build(drawable, color); } /// <summary> /// Builds the round. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> public TextDrawable BuildRound(string text, Color color) { Round(); return Build(text, color); } /// <summary> /// Builds the round. /// </summary> /// <param name="drawable">The drawable.</param> /// <param name="color">The color.</param> /// <returns>TextDrawable.</returns> public TextDrawable BuildRound(Drawable drawable, Color color) { Round(); return Build(drawable, color); } /// <summary> /// Builds the round rect. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <param name="radius">The radius.</param> /// <returns>TextDrawable.</returns> public TextDrawable BuildRoundRect(string text, Color color, int radius) { RoundRect(radius); return Build(text, color); } /// <summary> /// Builds the round rect. /// </summary> /// <param name="drawable">The drawable.</param> /// <param name="color">The color.</param> /// <param name="radius">The radius.</param> /// <returns>TextDrawable.</returns> public TextDrawable BuildRoundRect(Drawable drawable, Color color, int radius) { RoundRect(radius); return Build(drawable, color); } /// <summary> /// Ends the configuration. /// </summary> /// <returns>IShapeBuilder.</returns> public IShapeBuilder EndConfig() { return this; } /// <summary> /// Fonts the size. /// </summary> /// <param name="size">The size.</param> /// <returns>IConfigBuilder.</returns> /// <exception cref="System.NotImplementedException"></exception> public IConfigBuilder FontSize(int size) { this._fontSize = size; return this; } /// <summary> /// Heights the specified height. /// </summary> /// <param name="height">The height.</param> /// <returns>IConfigBuilder.</returns> public IConfigBuilder Height(int height) { _height = height; return this; } /// <summary> /// Rects this instance. /// </summary> /// <returns>IBuilder.</returns> public IBuilder Rect() { _shape = new RectShape(); return this; } /// <summary> /// Rounds this instance. /// </summary> /// <returns>IBuilder.</returns> public IBuilder Round() { _shape = new OvalShape(); return this; } /// <summary> /// Rounds the rect. /// </summary> /// <param name="radius">The radius.</param> /// <returns>IBuilder.</returns> public IBuilder RoundRect(int radius) { Radius = radius; float[] radii = { radius, radius, radius, radius, radius, radius, radius, radius }; _shape = new RoundRectShape(radii, null, null); return this; } /// <summary> /// Texts the color. /// </summary> /// <param name="color">The color.</param> /// <returns>IConfigBuilder.</returns> public IConfigBuilder TextColor(Color color) { _textColor = color; return this; } /// <summary> /// To the upper case. /// </summary> /// <returns>IConfigBuilder.</returns> public IConfigBuilder ToUpperCase() { _toUpperCase = true; return this; } /// <summary> /// Uses the font. /// </summary> /// <param name="font">The font.</param> /// <returns>IConfigBuilder.</returns> public IConfigBuilder UseFont(Typeface font) { Font = font; return this; } /// <summary> /// Widthes the specified width. /// </summary> /// <param name="width">The width.</param> /// <returns>IConfigBuilder.</returns> public IConfigBuilder Width(int width) { _width = width; return this; } /// <summary> /// Withes the border. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>IConfigBuilder.</returns> public IConfigBuilder WithBorder(int thickness) { BorderThickness = thickness; return this; } /// <summary> /// Withes the color of the border. /// </summary> /// <param name="color">The color.</param> /// <returns>IConfigBuilder.</returns> public IConfigBuilder WithBorderColor(Color color) { this._borderColor = color; return this; } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// DeliveryReceiptResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Conversations.V1.Conversation.Message { public class DeliveryReceiptResource : Resource { public sealed class DeliveryStatusEnum : StringEnum { private DeliveryStatusEnum(string value) : base(value) {} public DeliveryStatusEnum() {} public static implicit operator DeliveryStatusEnum(string value) { return new DeliveryStatusEnum(value); } public static readonly DeliveryStatusEnum Read = new DeliveryStatusEnum("read"); public static readonly DeliveryStatusEnum Failed = new DeliveryStatusEnum("failed"); public static readonly DeliveryStatusEnum Delivered = new DeliveryStatusEnum("delivered"); public static readonly DeliveryStatusEnum Undelivered = new DeliveryStatusEnum("undelivered"); public static readonly DeliveryStatusEnum Sent = new DeliveryStatusEnum("sent"); } private static Request BuildFetchRequest(FetchDeliveryReceiptOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Conversations, "/v1/Conversations/" + options.PathConversationSid + "/Messages/" + options.PathMessageSid + "/Receipts/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch the delivery and read receipts of the conversation message /// </summary> /// <param name="options"> Fetch DeliveryReceipt parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of DeliveryReceipt </returns> public static DeliveryReceiptResource Fetch(FetchDeliveryReceiptOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch the delivery and read receipts of the conversation message /// </summary> /// <param name="options"> Fetch DeliveryReceipt parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of DeliveryReceipt </returns> public static async System.Threading.Tasks.Task<DeliveryReceiptResource> FetchAsync(FetchDeliveryReceiptOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch the delivery and read receipts of the conversation message /// </summary> /// <param name="pathConversationSid"> The unique ID of the Conversation for this delivery receipt. </param> /// <param name="pathMessageSid"> The SID of the message the delivery receipt belongs to. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of DeliveryReceipt </returns> public static DeliveryReceiptResource Fetch(string pathConversationSid, string pathMessageSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchDeliveryReceiptOptions(pathConversationSid, pathMessageSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch the delivery and read receipts of the conversation message /// </summary> /// <param name="pathConversationSid"> The unique ID of the Conversation for this delivery receipt. </param> /// <param name="pathMessageSid"> The SID of the message the delivery receipt belongs to. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of DeliveryReceipt </returns> public static async System.Threading.Tasks.Task<DeliveryReceiptResource> FetchAsync(string pathConversationSid, string pathMessageSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchDeliveryReceiptOptions(pathConversationSid, pathMessageSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadDeliveryReceiptOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Conversations, "/v1/Conversations/" + options.PathConversationSid + "/Messages/" + options.PathMessageSid + "/Receipts", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all delivery and read receipts of the conversation message /// </summary> /// <param name="options"> Read DeliveryReceipt parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of DeliveryReceipt </returns> public static ResourceSet<DeliveryReceiptResource> Read(ReadDeliveryReceiptOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<DeliveryReceiptResource>.FromJson("delivery_receipts", response.Content); return new ResourceSet<DeliveryReceiptResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all delivery and read receipts of the conversation message /// </summary> /// <param name="options"> Read DeliveryReceipt parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of DeliveryReceipt </returns> public static async System.Threading.Tasks.Task<ResourceSet<DeliveryReceiptResource>> ReadAsync(ReadDeliveryReceiptOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<DeliveryReceiptResource>.FromJson("delivery_receipts", response.Content); return new ResourceSet<DeliveryReceiptResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all delivery and read receipts of the conversation message /// </summary> /// <param name="pathConversationSid"> The unique ID of the Conversation for this delivery receipt. </param> /// <param name="pathMessageSid"> The SID of the message the delivery receipt belongs to. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of DeliveryReceipt </returns> public static ResourceSet<DeliveryReceiptResource> Read(string pathConversationSid, string pathMessageSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadDeliveryReceiptOptions(pathConversationSid, pathMessageSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all delivery and read receipts of the conversation message /// </summary> /// <param name="pathConversationSid"> The unique ID of the Conversation for this delivery receipt. </param> /// <param name="pathMessageSid"> The SID of the message the delivery receipt belongs to. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of DeliveryReceipt </returns> public static async System.Threading.Tasks.Task<ResourceSet<DeliveryReceiptResource>> ReadAsync(string pathConversationSid, string pathMessageSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadDeliveryReceiptOptions(pathConversationSid, pathMessageSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<DeliveryReceiptResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<DeliveryReceiptResource>.FromJson("delivery_receipts", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<DeliveryReceiptResource> NextPage(Page<DeliveryReceiptResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Conversations) ); var response = client.Request(request); return Page<DeliveryReceiptResource>.FromJson("delivery_receipts", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<DeliveryReceiptResource> PreviousPage(Page<DeliveryReceiptResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Conversations) ); var response = client.Request(request); return Page<DeliveryReceiptResource>.FromJson("delivery_receipts", response.Content); } /// <summary> /// Converts a JSON string into a DeliveryReceiptResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> DeliveryReceiptResource object represented by the provided JSON </returns> public static DeliveryReceiptResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<DeliveryReceiptResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique ID of the Account responsible for this participant. /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The unique ID of the Conversation for this message. /// </summary> [JsonProperty("conversation_sid")] public string ConversationSid { get; private set; } /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the message the delivery receipt belongs to /// </summary> [JsonProperty("message_sid")] public string MessageSid { get; private set; } /// <summary> /// A messaging channel-specific identifier for the message delivered to participant /// </summary> [JsonProperty("channel_message_sid")] public string ChannelMessageSid { get; private set; } /// <summary> /// The unique ID of the participant the delivery receipt belongs to. /// </summary> [JsonProperty("participant_sid")] public string ParticipantSid { get; private set; } /// <summary> /// The message delivery status /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public DeliveryReceiptResource.DeliveryStatusEnum Status { get; private set; } /// <summary> /// The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status /// </summary> [JsonProperty("error_code")] public int? ErrorCode { get; private set; } /// <summary> /// The date that this resource was created. /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date that this resource was last updated. /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// An absolute URL for this delivery receipt. /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private DeliveryReceiptResource() { } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Text; using Encog.Engine.Network.Activation; using Encog.MathUtil.Matrices; using Encog.Util; using Encog.Util.CSV; namespace Encog.Persist { /// <summary> /// This class is used internally to parse Encog files. A file section is part of /// a name-value pair file. /// </summary> /// public class EncogFileSection { /// <summary> /// Any large arrays that were read. /// </summary> private IList<double[]> _largeArrays = new List<double[]>(); /// <summary> /// The lines in this section/subsection. /// </summary> /// private readonly IList<String> _lines; /// <summary> /// The name of this section. /// </summary> /// private readonly String _sectionName; /// <summary> /// The name of this subsection. /// </summary> /// private readonly String _subSectionName; /// <summary> /// Construct the object. /// </summary> /// /// <param name="theSectionName">The section name.</param> /// <param name="theSubSectionName">The sub section name.</param> public EncogFileSection(String theSectionName, String theSubSectionName) { _lines = new List<String>(); _sectionName = theSectionName; _subSectionName = theSubSectionName; } /// <summary> /// Parse an activation function from a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The activation function.</returns> public static IActivationFunction ParseActivationFunction(string value) { IActivationFunction af; String[] cols = value.Split('|'); String afName = ReflectionUtil.AfPath + cols[0]; try { af = (IActivationFunction)ReflectionUtil.LoadObject(afName); } catch (Exception e) { throw new PersistError(e); } for (int i = 0; i < af.ParamNames.Length; i++) { af.Params[i] = CSVFormat.EgFormat.Parse(cols[i + 1]); } return af; } /// <value>The lines.</value> public IList<String> Lines { get { return _lines; } } /// <value>All lines separated by a delimiter.</value> public String LinesAsString { get { var result = new StringBuilder(); foreach (String line in _lines) { result.Append(line); result.Append("\n"); } return result.ToString(); } } /// <value>The section name.</value> public String SectionName { get { return _sectionName; } } /// <value>The section name.</value> public String SubSectionName { get { return _subSectionName; } } /// <summary> /// Parse an activation function from a string. /// </summary> /// /// <param name="paras">The params.</param> /// <param name="name">The name of the param to parse.</param> /// <returns>The parsed activation function.</returns> public static IActivationFunction ParseActivationFunction( IDictionary<String, String> paras, String name) { String v; try { v = paras[name]; if (v == null) { throw new PersistError("Missing property: " + name); } IActivationFunction af; String[] cols = v.Split('|'); String afName = ReflectionUtil.AfPath + cols[0]; try { af = (IActivationFunction) ReflectionUtil.LoadObject(afName); } catch (Exception e) { throw new PersistError(e); } for (int i = 0; i < af.ParamNames.Length; i++) { af.Params[i] = CSVFormat.EgFormat.Parse(cols[i + 1]); } return af; } catch (Exception ex) { throw new PersistError(ex); } } /// <summary> /// Parse a boolean from a name-value collection of params. /// </summary> /// /// <param name="paras">The name-value pairs.</param> /// <param name="name">The name to parse.</param> /// <returns>The parsed boolean value.</returns> public static bool ParseBoolean(IDictionary<String, String> paras, String name) { String v = null; try { v = paras[name]; if (v == null) { throw new PersistError("Missing property: " + name); } return v.Trim().ToLower()[0] == 't'; } catch (FormatException ) { throw new PersistError("Field: " + name + ", " + "invalid integer: " + v); } } /// <summary> /// Parse a double from a name-value collection of params. /// </summary> /// /// <param name="paras">The name-value pairs.</param> /// <param name="name">The name to parse.</param> /// <returns>The parsed double value.</returns> public static double ParseDouble(IDictionary<String, String> paras, String name) { String v = null; try { v = paras[name]; if (v == null) { throw new PersistError("Missing property: " + name); } return CSVFormat.EgFormat.Parse(v); } catch (FormatException ) { throw new PersistError("Field: " + name + ", " + "invalid integer: " + v); } } /// <summary> /// Parse a double array from a name-value collection of params. /// </summary> /// /// <param name="paras">The name-value pairs.</param> /// <param name="name">The name to parse.</param> /// <returns>The parsed double array value.</returns> public double[] ParseDoubleArray(IDictionary<String, String> paras, String name) { String v = null; try { if ( !paras.ContainsKey(name) ) { throw new PersistError("Missing property: " + name); } v = paras[name]; if (v.StartsWith("##")) { int i = int.Parse(v.Substring(2)); return _largeArrays[i]; } else { return NumberList.FromList(CSVFormat.EgFormat, v); } } catch (FormatException ) { throw new PersistError("Field: " + name + ", " + "invalid integer: " + v); } } /// <summary> /// Parse an int from a name-value collection of params. /// </summary> /// /// <param name="paras">The name-value pairs.</param> /// <param name="name">The name to parse.</param> /// <returns>The parsed int value.</returns> public static int ParseInt(IDictionary<String, String> paras, String name) { String v = null; try { v = paras[name]; if (v == null) { throw new PersistError("Missing property: " + name); } return Int32.Parse(v); } catch (FormatException) { throw new PersistError("Field: " + name + ", " + "invalid integer: " + v); } } /// <summary> /// Parse an int array from a name-value collection of params. /// </summary> /// /// <param name="paras">The name-value pairs.</param> /// <param name="name">The name to parse.</param> /// <returns>The parsed int array value.</returns> public static int[] ParseIntArray(IDictionary<String, String> paras, String name) { String v = null; try { v = paras[name]; if (v == null) { throw new PersistError("Missing property: " + name); } return NumberList.FromListInt(CSVFormat.EgFormat, v); } catch (FormatException ) { throw new PersistError("Field: " + name + ", " + "invalid integer: " + v); } } /// <summary> /// Parse a matrix from a name-value collection of params. /// </summary> /// /// <param name="paras">The name-value pairs.</param> /// <param name="name">The name to parse.</param> /// <returns>The parsed matrix value.</returns> public static Matrix ParseMatrix(IDictionary<String, String> paras, String name) { if (!paras.ContainsKey(name)) { throw new PersistError("Missing property: " + name); } String line = paras[name]; double[] d = NumberList.FromList(CSVFormat.EgFormat, line); var rows = (int) d[0]; var cols = (int) d[1]; var result = new Matrix(rows, cols); int index = 2; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { result[r, c] = d[index++]; } } return result; } /// <summary> /// Split a delimited string into columns. /// </summary> /// /// <param name="line">THe string to split.</param> /// <returns>The string split.</returns> public static IList<String> SplitColumns(String line) { IList<String> result = new List<String>(); string[] tok = line.Split(','); foreach (string t in tok) { String str = t.Trim(); if ((str.Length > 0) && (str[0] == '\"')) { str = str.Substring(1); if (str.EndsWith("\"")) { str = str.Substring(0, (str.Length - 1) - (0)); } } result.Add(str); } return result; } /// <returns>The params.</returns> public IDictionary<String, String> ParseParams() { IDictionary<String, String> result = new Dictionary<String, String>(); foreach (String line in _lines) { String line2 = line.Trim(); if (line2.Length > 0) { int idx = line2.IndexOf('='); if (idx == -1) { throw new EncogError("Invalid setup item: " + line); } String name = line2.Substring(0, (idx) - (0)).Trim(); String v = line2.Substring(idx + 1).Trim(); result[name] = v; } } return result; } /// <summary> /// Large arrays. /// </summary> public IList<double[]> LargeArrays { get { return _largeArrays; } set { _largeArrays = value; } } /// <inheritdoc/> public override sealed String ToString() { var result = new StringBuilder("["); result.Append(GetType().Name); result.Append(" sectionName="); result.Append(_sectionName); result.Append(", subSectionName="); result.Append(_subSectionName); result.Append("]"); return result.ToString(); } } }
using DataTypes; using MyCouch; using Newtonsoft.Json; using System; using System.Linq; using System.Threading.Tasks; using Shared; namespace Setup { public class DatabaseInitializer { private AppSettings _appSettings; public DatabaseInitializer() { _appSettings = SharedConfiguration.GetAppSettings(); } public async Task Run() { string docString; // Check for database existence var dbPath = _appSettings.CouchDbPath; var uri = new Uri(dbPath); var dbName = uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped); var dbRoot = uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped); Console.WriteLine("NOTE: Before running Photo Management Studio, CouchDB must be installed and"); Console.WriteLine(" configured to allow all clients to connect to allow replication to"); Console.WriteLine(" client installations. Please edit the local.ini file, probably located at"); Console.WriteLine(" C:\\Program Files(x86)\\Apache Software Foundation\\CouchDB\\etc\\couchdb"); Console.WriteLine(" and add the following line under the [httpd] section:"); Console.WriteLine(); Console.WriteLine(" bind_address = 0.0.0.0"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine($"Connecting to CouchDB database at {dbRoot}..."); using (var client = new MyCouchServerClient(dbRoot)) { // Creates the database, but only if it does not exist. Console.WriteLine($"Looking for database '{dbName}'..."); var db = await client.Databases.GetAsync(dbName); if (!string.IsNullOrWhiteSpace(db.Error) && db.Error.Equals("not_found")) { Console.WriteLine($"Database '{dbName}' not found, we'll create it now..."); await client.Databases.PutAsync(dbName); Console.WriteLine($"Database '{dbName}' created..."); } else { Console.WriteLine($"Database '{dbName}' exists, continuing..."); } } Console.WriteLine(); using (var store = new MyCouchStore(dbRoot, dbName)) { Console.WriteLine("Checking whether view for Server Detail exists..."); var serverViewExists = await store.ExistsAsync("_design/serverDetail"); if (!serverViewExists) { Console.WriteLine("Server Detail view not found, we'll create it now..."); docString = JsonConvert.SerializeObject(new { language = "javascript", views = new { get = new { map = "function(doc) { if (doc.$doctype == 'serverDetail') { emit(doc._id, doc); } }" } } }); await store.Client.Documents.PutAsync("_design/serverDetail", docString); Console.WriteLine("Server Detail view created..."); } else { Console.WriteLine("Server Detail view exists, continuing..."); } Console.WriteLine(); var dbServerDetailQuery = new Query("serverDetail", "get"); var dbServerDetailRows = await store.QueryAsync<ServerDetail>(dbServerDetailQuery); var dbServerDetail = dbServerDetailRows.Select(x => x.Value).FirstOrDefault(); if (dbServerDetail == null) { dbServerDetail = new ServerDetail { ServerDetailId = Guid.NewGuid().ToString(), ServerId = String.Empty, ServerName = String.Empty }; } var serverId = dbServerDetail.ServerId; var serverName = dbServerDetail.ServerName; while (true) { if (GetServerName(ref serverName, ref serverId)) { break; } } if (serverName.Equals(dbServerDetail.ServerName) && serverId.Equals(dbServerDetail.ServerId)) { Console.WriteLine("No change to Server Identification, continuing..."); } else { dbServerDetail.ServerId = serverId; dbServerDetail.ServerName = serverName; if (String.IsNullOrWhiteSpace(dbServerDetail.ServerDetailRev)) { // create new entry Console.WriteLine("Creating new Server Identification entry..."); dbServerDetail = await store.StoreAsync(dbServerDetail); Console.WriteLine("Server Identification entry created..."); } else { Console.WriteLine("Updating existing Server Identification entry..."); dbServerDetail = await store.StoreAsync(dbServerDetail); Console.WriteLine("Server Identification entry updated..."); } } // Set up Default Views Console.WriteLine(); serverViewExists = await store.ExistsAsync("_design/collections"); if (!serverViewExists) { Console.WriteLine("Creating Collections View..."); docString = JsonConvert.SerializeObject(new { language = "javascript", views = new { all = new { map = "function(doc) { if (doc.$doctype == 'collection') { emit(doc._id, doc); } }" } } }); await store.Client.Documents.PutAsync("_design/collections", docString); } serverViewExists = await store.ExistsAsync("_design/imports"); if (!serverViewExists) { Console.WriteLine("Creating Imports View..."); docString = JsonConvert.SerializeObject(new { language = "javascript", views = new { all = new { map = "function(doc) { if (doc.$doctype == 'import') { emit(doc._id, doc); } }" } } }); await store.Client.Documents.PutAsync("_design/imports", docString); } serverViewExists = await store.ExistsAsync("_design/media"); if (!serverViewExists) { Console.WriteLine("Creating Media View..."); docString = JsonConvert.SerializeObject(new { language = "javascript", views = new { all = new { map = "function(doc) { if (doc.$doctype == 'media') { emit(doc._id, doc); } }" } } }); await store.Client.Documents.PutAsync("_design/media", docString); } serverViewExists = await store.ExistsAsync("_design/tags"); if (!serverViewExists) { Console.WriteLine("Creating Tags View..."); docString = JsonConvert.SerializeObject(new { language = "javascript", views = new { parents = new { map = "function(doc) { if (doc.$doctype == 'tag' && doc.subType == 'parent') { emit(doc._id, doc); } }" }, buckets = new { map = "function(doc) { if (doc.$doctype == 'tag' && doc.subType == 'bucket') { emit(doc._id, doc); } }" }, tags = new { map = "function(doc) { if (doc.$doctype == 'tag' && doc.subType == 'tag') { emit(doc._id, doc); } }" }, } }); await store.Client.Documents.PutAsync("_design/tags", docString); } } } private bool GetServerName(ref string serverName, ref string serverId) { do { Console.Write("Enter a name for this server (e.g. My Photo Server): "); if (!string.IsNullOrWhiteSpace(serverName)) { Console.Write($" [current name: {serverName}] "); } var name = Console.ReadLine(); if (!string.IsNullOrWhiteSpace(name)) { serverName = name; } } while (string.IsNullOrWhiteSpace(serverName)); serverId = string.IsNullOrWhiteSpace(serverId) ? string.Join("-", serverName.Split(' ')).ToLowerInvariant() : serverId; Console.WriteLine(); Console.WriteLine("We'll use the following to identify the server. Note: Once the Server ID has been set it cannot be changed."); Console.WriteLine($"\tServer Name: {serverName}"); Console.WriteLine($"\tServer ID: {serverId}"); Console.Write("Is this correct? [Y/n] "); var response = Console.ReadLine(); if (response.Length > 0 && response.ToLower().ElementAt(0) == 'n') { return false; } return true; } } }
using System; namespace Server.Items { [FlipableAttribute( 0x1BD7, 0x1BDA )] public class BaseWoodBoard : Item, ICommodity { private CraftResource m_Resource; [CommandProperty( AccessLevel.GameMaster )] public CraftResource Resource { get { return m_Resource; } set { m_Resource = value; InvalidateProperties(); } } int ICommodity.DescriptionNumber { get { if ( m_Resource >= CraftResource.OakWood && m_Resource <= CraftResource.YewWood ) return 1075052 + ( (int)m_Resource - (int)CraftResource.OakWood ); switch ( m_Resource ) { case CraftResource.Bloodwood: return 1075055; case CraftResource.Frostwood: return 1075056; case CraftResource.Heartwood: return 1075062; //WHY Osi. Why? } return LabelNumber; } } bool ICommodity.IsDeedable { get { return true; } } public BaseWoodBoard(): this(1) { } public BaseWoodBoard( int amount ) : this( CraftResource.RegularWood, amount ) { } public BaseWoodBoard( CraftResource resource ) : this( resource, 1 ) { } public BaseWoodBoard(CraftResource resource, int amount) : base( 0x1BD7 ) { Stackable = true; Amount = amount; m_Resource = resource; Hue = CraftResources.GetHue( resource ); } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( !CraftResources.IsStandard( m_Resource ) ) { int num = CraftResources.GetLocalizationNumber( m_Resource ); if ( num > 0 ) list.Add( num ); else list.Add( CraftResources.GetName( m_Resource ) ); } } public BaseWoodBoard(Serial serial) : base(serial) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 3 ); writer.Write( (int)m_Resource ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 3: case 2: { m_Resource = (CraftResource)reader.ReadInt(); break; } } if ( (version == 0 && Weight == 0.1) || ( version <= 2 && Weight == 2 ) ) Weight = -1; if ( version <= 1 ) m_Resource = CraftResource.RegularWood; } } public class Board : BaseWoodBoard { [Constructable] public Board() : this(1) { } [Constructable] public Board(int amount) : base(CraftResource.RegularWood, amount) { } public Board(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class HeartwoodBoard : BaseWoodBoard { [Constructable] public HeartwoodBoard() : this( 1 ) { } [Constructable] public HeartwoodBoard( int amount ) : base( CraftResource.Heartwood, amount ) { } public HeartwoodBoard( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class BloodwoodBoard : BaseWoodBoard { [Constructable] public BloodwoodBoard() : this( 1 ) { } [Constructable] public BloodwoodBoard( int amount ) : base( CraftResource.Bloodwood, amount ) { } public BloodwoodBoard( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class FrostwoodBoard : BaseWoodBoard { [Constructable] public FrostwoodBoard() : this( 1 ) { } [Constructable] public FrostwoodBoard( int amount ) : base( CraftResource.Frostwood, amount ) { } public FrostwoodBoard( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class OakBoard : BaseWoodBoard { [Constructable] public OakBoard() : this( 1 ) { } [Constructable] public OakBoard( int amount ) : base( CraftResource.OakWood, amount ) { } public OakBoard( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class AshBoard : BaseWoodBoard { [Constructable] public AshBoard() : this( 1 ) { } [Constructable] public AshBoard( int amount ) : base( CraftResource.AshWood, amount ) { } public AshBoard( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class YewBoard : BaseWoodBoard { [Constructable] public YewBoard() : this( 1 ) { } [Constructable] public YewBoard( int amount ) : base( CraftResource.YewWood, amount ) { } public YewBoard( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
using System; using System.Diagnostics; namespace SharpFlame.Pathfinding { public class PathfinderNetwork { public int FindParentNodeCount; public PathfinderNode[] FindParentNodes = new PathfinderNode[0]; public LargeArrays NetworkLargeArrays = new LargeArrays(); public int NodeLayerCount; public PathfinderLayer[] NodeLayers = new PathfinderLayer[0]; public int GetNodeLayerCount { get { return NodeLayerCount; } } public PathfinderLayer get_GetNodeLayer(int Num) { return NodeLayers[Num]; } public void NodeLayer_Add(PathfinderLayer NewNodeLayer) { if ( NodeLayerCount > 0 ) { NodeLayers[NodeLayerCount - 1].ParentLayer = NewNodeLayer; } Array.Resize(ref NodeLayers, NodeLayerCount + 1); NodeLayers[NodeLayerCount] = NewNodeLayer; NodeLayers[NodeLayerCount].Network_LayerNum = NodeLayerCount; NodeLayerCount++; } public void FindParentNode_Add(PathfinderNode NewFindParentNode) { if ( NewFindParentNode.Network_FindParentNum >= 0 ) { return; } if ( FindParentNodes.GetUpperBound(0) < FindParentNodeCount ) { Array.Resize(ref FindParentNodes, (FindParentNodeCount + 1) * 2); } FindParentNodes[FindParentNodeCount] = NewFindParentNode; FindParentNodes[FindParentNodeCount].Network_FindParentNum = FindParentNodeCount; FindParentNodeCount++; } public void FindParentNode_Remove(int Num) { FindParentNodes[Num].Network_FindParentNum = -1; FindParentNodes[Num] = null; FindParentNodeCount--; if ( Num < FindParentNodeCount ) { FindParentNodes[Num] = FindParentNodes[FindParentNodeCount]; FindParentNodes[Num].Network_FindParentNum = Num; } if ( FindParentNodeCount * 3 < FindParentNodes.GetUpperBound(0) ) { Array.Resize(ref FindParentNodes, FindParentNodeCount * 2); } } public void Deallocate() { var A = 0; for ( A = 0; A <= NodeLayerCount - 1; A++ ) { NodeLayers[A].ForceDeallocate(); } NodeLayers = null; FindParentNodes = null; } public PathList[] GetPath(PathfinderNode[] StartNodes, PathfinderNode FinishNode, int Accuracy, int MinClearance) { var StartNodeCount = StartNodes.GetUpperBound(0) + 1; var Paths = new PathList[NodeLayerCount]; var LayerStartNodes = new PathfinderNode[NodeLayerCount, StartNodeCount]; var LayerFinishNodes = new PathfinderNode[NodeLayerCount]; var LayerNum = 0; var Destinations = new PathfinderNode[24]; var DestinationCount = 0; var FinishIsParent = default(bool); var CalcNodeCount = new int[24]; var FloodRouteArgs = new sFloodRouteArgs(); var FinalLayer = 0; var StartCanReach = new bool[StartNodeCount]; var tmpNodeA = default(PathfinderNode); var tmpNodeB = default(PathfinderNode); var CanReachCount = 0; var FirstLayer = 0; var BestPaths = new Path[24]; var BestValues = new float[24]; var PathNum = 0; var StopMultiPathing = default(bool); var Visit = NetworkLargeArrays.Nodes_Booleans; var NodeValues = NetworkLargeArrays.Nodes_ValuesA; var Nodes_Nodes = NetworkLargeArrays.Nodes_Nodes; var StartPath = NetworkLargeArrays.Nodes_Path; var A = 0; var B = 0; var C = 0; var D = 0; var E = 0; FinalLayer = StartNodes[0].Layer.Network_LayerNum; LayerFinishNodes[FinalLayer] = FinishNode; B = FinalLayer; do { if ( LayerFinishNodes[B].ParentNode == null ) { FirstLayer = B; break; } LayerFinishNodes[B + 1] = LayerFinishNodes[B].ParentNode; B++; } while ( true ); for ( A = 0; A <= StartNodeCount - 1; A++ ) { LayerStartNodes[FinalLayer, A] = StartNodes[A]; B = FinalLayer; do { if ( LayerStartNodes[B, A].ParentNode == null ) { if ( LayerStartNodes[B, A] == LayerFinishNodes[B] ) { StartCanReach[A] = true; CanReachCount++; } break; } LayerStartNodes[B + 1, A] = LayerStartNodes[B, A].ParentNode; B++; } while ( true ); } if ( CanReachCount == 0 ) { return null; } LayerNum = FirstLayer; Paths[LayerNum].Paths = new Path[0]; Paths[LayerNum].Paths[0] = new Path(); Paths[LayerNum].PathCount = 1; Paths[LayerNum].Paths[0].Nodes = new PathfinderNode[1]; Paths[LayerNum].Paths[0].Nodes[0] = LayerFinishNodes[LayerNum]; Paths[LayerNum].Paths[0].NodeCount = 1; var LastLayer = 0; do { LastLayer = LayerNum; LayerNum--; if ( LayerNum < FinalLayer ) { break; } if ( StopMultiPathing ) { if ( Accuracy < 0 ) { Debugger.Break(); } for ( PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++ ) { CalcNodeCount[PathNum] = Math.Min(Accuracy, Convert.ToInt32(Paths[LastLayer].Paths[PathNum].NodeCount - 1)); } Destinations[0] = Paths[LastLayer].Paths[0].Nodes[CalcNodeCount[0]]; DestinationCount = 1; FinishIsParent = true; } else { if ( Accuracy >= 0 ) { for ( PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++ ) { if ( Paths[LastLayer].Paths[PathNum].NodeCount > Accuracy ) { StopMultiPathing = true; break; } } } Destinations[0] = LayerFinishNodes[LayerNum]; if ( LayerNum == FinalLayer ) { DestinationCount = 1; } else { for ( A = 0; A <= Destinations[0].ConnectionCount - 1; A++ ) { Destinations[1 + A] = Destinations[0].Connections[A].GetOtherNode(Destinations[0]); } DestinationCount = 1 + Destinations[0].ConnectionCount; } for ( PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++ ) { CalcNodeCount[PathNum] = Paths[LastLayer].Paths[PathNum].NodeCount - 1; } FinishIsParent = false; } for ( PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++ ) { for ( A = 0; A <= CalcNodeCount[PathNum]; A++ ) { tmpNodeA = Paths[LastLayer].Paths[PathNum].Nodes[A]; for ( D = 0; D <= tmpNodeA.ConnectionCount - 1; D++ ) { tmpNodeB = tmpNodeA.Connections[D].GetOtherNode(tmpNodeA); for ( E = 0; E <= tmpNodeB.ConnectionCount - 1; E++ ) { C = tmpNodeB.Connections[E].GetOtherNode(tmpNodeB).Layer_NodeNum; Visit[C] = false; } } } } for ( PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++ ) { for ( A = 0; A <= CalcNodeCount[PathNum]; A++ ) { tmpNodeA = Paths[LastLayer].Paths[PathNum].Nodes[A]; C = tmpNodeA.Layer_NodeNum; Visit[C] = true; for ( E = 0; E <= tmpNodeA.NodeCount - 1; E++ ) { C = tmpNodeA.Nodes[E].Layer_NodeNum; NodeValues[C] = float.MaxValue; } for ( D = 0; D <= tmpNodeA.ConnectionCount - 1; D++ ) { tmpNodeB = tmpNodeA.Connections[D].GetOtherNode(tmpNodeA); C = tmpNodeB.Layer_NodeNum; Visit[C] = true; for ( E = 0; E <= tmpNodeB.NodeCount - 1; E++ ) { C = tmpNodeB.Nodes[E].Layer_NodeNum; NodeValues[C] = float.MaxValue; } } } } FloodRouteArgs = new sFloodRouteArgs(); FloodRouteArgs.CurrentPath = StartPath; FloodRouteArgs.FinishNodes = Destinations; FloodRouteArgs.FinishNodeCount = DestinationCount; FloodRouteArgs.FinishIsParent = FinishIsParent; FloodRouteArgs.Visit = Visit; FloodRouteArgs.NodeValues = NodeValues; FloodRouteArgs.SourceNodes = Nodes_Nodes; FloodRouteArgs.MinClearance = MinClearance; for ( A = 0; A <= DestinationCount - 1; A++ ) { BestPaths[A] = null; BestValues[A] = float.MaxValue; } for ( A = 0; A <= StartNodeCount - 1; A++ ) { if ( StartCanReach[A] ) { StartPath.NodeCount = 1; StartPath.Nodes[0] = LayerStartNodes[LayerNum, A]; StartPath.Value = 0.0F; FloodRouteArgs.BestPaths = new Path[DestinationCount]; FloodRoute(ref FloodRouteArgs); for ( PathNum = 0; PathNum <= DestinationCount - 1; PathNum++ ) { if ( FloodRouteArgs.BestPaths[PathNum] != null ) { if ( FloodRouteArgs.BestPaths[PathNum].Value < BestValues[PathNum] ) { BestValues[PathNum] = FloodRouteArgs.BestPaths[PathNum].Value; BestPaths[PathNum] = FloodRouteArgs.BestPaths[PathNum]; } } } } } Paths[LayerNum].Paths = new Path[DestinationCount]; Paths[LayerNum].PathCount = 0; for ( PathNum = 0; PathNum <= DestinationCount - 1; PathNum++ ) { if ( BestPaths[PathNum] != null ) { Paths[LayerNum].Paths[Paths[LayerNum].PathCount] = BestPaths[PathNum]; Paths[LayerNum].PathCount++; } } Array.Resize(ref Paths[LayerNum].Paths, Paths[LayerNum].PathCount); if ( Paths[LayerNum].PathCount == 0 ) { return null; } } while ( true ); return Paths; } public Path[] GetAllPaths(PathfinderNode[] StartNodes, PathfinderNode FinishNode, int MinClearance) { var StartNodeCount = StartNodes.GetUpperBound(0) + 1; var LayerStartNodes = new PathfinderNode[32, StartNodeCount]; var LayerFinishNodes = new PathfinderNode[32]; var LayerNum = 0; var FloodRouteDArgs = new sFloodRouteAllArgs(); var FinalLayer = 0; var StartCanReach = new bool[StartNodeCount]; var tmpNodeA = default(PathfinderNode); var CanReachCount = 0; var FirstLayer = 0; var SubPaths = new Path[32]; var Nodes_Nodes = NetworkLargeArrays.Nodes_Nodes; var Visit = NetworkLargeArrays.Nodes_Booleans; var NodeValues = NetworkLargeArrays.Nodes_ValuesA; var NodeValuesB = NetworkLargeArrays.Nodes_ValuesB; var A = 0; var B = 0; var C = 0; var D = 0; FinalLayer = StartNodes[0].Layer.Network_LayerNum; LayerFinishNodes[FinalLayer] = FinishNode; B = FinalLayer; do { if ( LayerFinishNodes[B].ParentNode == null ) { FirstLayer = B; break; } LayerFinishNodes[B + 1] = LayerFinishNodes[B].ParentNode; B++; } while ( true ); for ( A = 0; A <= StartNodeCount - 1; A++ ) { LayerStartNodes[FinalLayer, A] = StartNodes[A]; B = FinalLayer; do { if ( LayerStartNodes[B, A].ParentNode == null ) { if ( LayerStartNodes[B, A] == LayerFinishNodes[B] ) { StartCanReach[A] = true; CanReachCount++; } break; } LayerStartNodes[B + 1, A] = LayerStartNodes[B, A].ParentNode; B++; } while ( true ); } if ( CanReachCount == 0 ) { return null; } LayerNum = FirstLayer; SubPaths[LayerNum] = new Path(); SubPaths[LayerNum].Nodes = new[] {LayerFinishNodes[LayerNum]}; SubPaths[LayerNum].NodeCount = 1; var LastLayer = 0; do { LastLayer = LayerNum; LayerNum--; if ( LayerNum < FinalLayer ) { break; } for ( A = 0; A <= SubPaths[LastLayer].NodeCount - 1; A++ ) { tmpNodeA = SubPaths[LastLayer].Nodes[A]; for ( B = 0; B <= tmpNodeA.ConnectionCount - 1; B++ ) { C = tmpNodeA.Connections[B].GetOtherNode(tmpNodeA).Layer_NodeNum; Visit[C] = false; } } for ( A = 0; A <= SubPaths[LastLayer].NodeCount - 1; A++ ) { tmpNodeA = SubPaths[LastLayer].Nodes[A]; C = tmpNodeA.Layer_NodeNum; Visit[C] = true; for ( D = 0; D <= tmpNodeA.NodeCount - 1; D++ ) { C = tmpNodeA.Nodes[D].Layer_NodeNum; NodeValues[C] = float.MaxValue; NodeValuesB[C] = float.MaxValue; } } FloodRouteDArgs = new sFloodRouteAllArgs(); FloodRouteDArgs.FinishNode = LayerFinishNodes[LayerNum]; FloodRouteDArgs.Visit = Visit; FloodRouteDArgs.NodeValuesA = NodeValues; FloodRouteDArgs.SourceNodes = Nodes_Nodes; FloodRouteDArgs.NodeValuesB = NodeValuesB; FloodRouteDArgs.MinClearance = MinClearance; FloodRouteDArgs.BestTolerance = (float)(Math.Pow(1.1D, LayerNum)); FloodRouteDArgs.StartNodes = new PathfinderNode[StartNodeCount]; for ( A = 0; A <= StartNodeCount - 1; A++ ) { if ( StartCanReach[A] ) { FloodRouteDArgs.StartNodes[FloodRouteDArgs.StartNodeCount] = LayerStartNodes[LayerNum, A]; FloodRouteDArgs.StartNodeCount++; } } Array.Resize(ref FloodRouteDArgs.StartNodes, FloodRouteDArgs.StartNodeCount); FloodRouteAll(ref FloodRouteDArgs); SubPaths[LayerNum] = new Path(); SubPaths[LayerNum].Nodes = new PathfinderNode[FloodRouteDArgs.BestNodeCount]; for ( A = 0; A <= FloodRouteDArgs.BestNodeCount - 1; A++ ) { SubPaths[LayerNum].Nodes[A] = FloodRouteDArgs.SourceNodes[A]; } SubPaths[LayerNum].NodeCount = FloodRouteDArgs.BestNodeCount; if ( FloodRouteDArgs.BestNodeCount == 0 ) { Debugger.Break(); return SubPaths; } } while ( true ); return SubPaths; } public void FloodRoute(ref sFloodRouteArgs Args) { var CurrentNode = default(PathfinderNode); var ConnectedNode = default(PathfinderNode); var A = 0; var SourceNodeCount = 0; var SourceNodeNum = 0; var tmpConnection = default(PathfinderConnection); float ResultValue = 0; var BestPath = default(Path); var StartNode = default(PathfinderNode); var B = 0; float BestDist = 0; float Dist = 0; var BestNode = default(PathfinderNode); var C = 0; StartNode = Args.CurrentPath.Nodes[0]; Args.SourceNodes[0] = StartNode; SourceNodeCount = 1; Args.NodeValues[StartNode.Layer_NodeNum] = 0.0F; SourceNodeNum = 0; while ( SourceNodeNum < SourceNodeCount ) { CurrentNode = Args.SourceNodes[SourceNodeNum]; for ( A = 0; A <= CurrentNode.ConnectionCount - 1; A++ ) { tmpConnection = CurrentNode.Connections[A]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); if ( ConnectedNode.ParentNode != null ) { if ( Args.Visit[ConnectedNode.ParentNode.Layer_NodeNum] ) { if ( ConnectedNode.Clearance >= Args.MinClearance ) { ResultValue = Args.NodeValues[CurrentNode.Layer_NodeNum] + tmpConnection.Value; if ( ResultValue < Args.NodeValues[ConnectedNode.Layer_NodeNum] ) { Args.NodeValues[ConnectedNode.Layer_NodeNum] = ResultValue; Args.SourceNodes[SourceNodeCount] = ConnectedNode; SourceNodeCount++; } } } } } SourceNodeNum++; } for ( A = 0; A <= Args.FinishNodeCount - 1; A++ ) { if ( Args.FinishIsParent ) { BestNode = null; BestDist = float.MaxValue; for ( C = 0; C <= Args.FinishNodes[A].NodeCount - 1; C++ ) { CurrentNode = Args.FinishNodes[A].Nodes[C]; Dist = Args.NodeValues[CurrentNode.Layer_NodeNum]; if ( Dist < BestDist ) { BestDist = Dist; BestNode = CurrentNode; } } CurrentNode = BestNode; } else { CurrentNode = Args.FinishNodes[A]; } if ( CurrentNode == null ) { //no path return; } SourceNodeCount = 0; BestDist = Args.NodeValues[CurrentNode.Layer_NodeNum]; if ( BestDist == float.MaxValue ) { //no path return; } do { Args.SourceNodes[SourceNodeCount] = CurrentNode; SourceNodeCount++; if ( CurrentNode == StartNode ) { break; } BestNode = null; for ( B = 0; B <= CurrentNode.ConnectionCount - 1; B++ ) { tmpConnection = CurrentNode.Connections[B]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); if ( ConnectedNode.ParentNode != null ) { if ( Args.Visit[ConnectedNode.ParentNode.Layer_NodeNum] ) { Dist = Args.NodeValues[ConnectedNode.Layer_NodeNum]; if ( Dist < BestDist ) { BestDist = Dist; BestNode = ConnectedNode; } } } } if ( BestNode == null ) { Args.BestPaths[A] = null; return; } CurrentNode = BestNode; } while ( true ); BestPath = new Path(); Args.BestPaths[A] = BestPath; BestPath.Value = Args.NodeValues[Args.FinishNodes[A].Layer_NodeNum]; BestPath.NodeCount = SourceNodeCount; BestPath.Nodes = new PathfinderNode[BestPath.NodeCount]; for ( B = 0; B <= BestPath.NodeCount - 1; B++ ) { BestPath.Nodes[B] = Args.SourceNodes[SourceNodeCount - B - 1]; } } } public void FloodSpan(ref sFloodSpanArgs Args) { var CurrentNode = default(PathfinderNode); var ConnectedNode = default(PathfinderNode); var A = 0; var SourceNodeCount = 0; var SourceNodeNum = 0; var tmpConnection = default(PathfinderConnection); float ResultValue = 0; var BestPath = default(Path); var StartNode = default(PathfinderNode); var B = 0; float BestDist = 0; float Dist = 0; var BestNode = default(PathfinderNode); var C = 0; StartNode = Args.CurrentPath.Nodes[0]; Args.SourceNodes[0] = StartNode; SourceNodeCount = 1; Args.NodeValues[StartNode.Layer_NodeNum] = 0.0F; SourceNodeNum = 0; while ( SourceNodeNum < SourceNodeCount ) { CurrentNode = Args.SourceNodes[SourceNodeNum]; for ( A = 0; A <= CurrentNode.ConnectionCount - 1; A++ ) { tmpConnection = CurrentNode.Connections[A]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); if ( ConnectedNode.ParentNode == Args.SourceParentNode ) { ResultValue = Args.NodeValues[CurrentNode.Layer_NodeNum] + tmpConnection.Value; if ( ResultValue < Args.NodeValues[ConnectedNode.Layer_NodeNum] ) { Args.NodeValues[ConnectedNode.Layer_NodeNum] = ResultValue; Args.SourceNodes[SourceNodeCount] = ConnectedNode; SourceNodeCount++; } } } SourceNodeNum++; } for ( A = 0; A <= Args.FinishNodeCount - 1; A++ ) { if ( Args.FinishIsParent ) { BestNode = null; BestDist = float.MaxValue; for ( C = 0; C <= Args.FinishNodes[A].NodeCount - 1; C++ ) { CurrentNode = Args.FinishNodes[A].Nodes[C]; Dist = Args.NodeValues[CurrentNode.Layer_NodeNum]; if ( Dist < BestDist ) { BestDist = Dist; BestNode = CurrentNode; } } CurrentNode = BestNode; } else { CurrentNode = Args.FinishNodes[A]; } if ( CurrentNode == null ) { //no path return; } SourceNodeCount = 0; BestDist = Args.NodeValues[CurrentNode.Layer_NodeNum]; if ( BestDist == float.MaxValue ) { //no path return; } do { Args.SourceNodes[SourceNodeCount] = CurrentNode; SourceNodeCount++; if ( CurrentNode == StartNode ) { break; } BestNode = null; for ( B = 0; B <= CurrentNode.ConnectionCount - 1; B++ ) { tmpConnection = CurrentNode.Connections[B]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); if ( ConnectedNode.ParentNode == Args.SourceParentNode ) { Dist = Args.NodeValues[ConnectedNode.Layer_NodeNum]; if ( Dist < BestDist ) { BestDist = Dist; BestNode = ConnectedNode; } } } if ( BestNode == null ) { Args.BestPaths[A] = null; //no path return; } CurrentNode = BestNode; } while ( true ); BestPath = new Path(); Args.BestPaths[A] = BestPath; BestPath.Value = Args.NodeValues[Args.FinishNodes[A].Layer_NodeNum]; BestPath.NodeCount = SourceNodeCount; BestPath.Nodes = new PathfinderNode[BestPath.NodeCount]; for ( B = 0; B <= BestPath.NodeCount - 1; B++ ) { BestPath.Nodes[B] = Args.SourceNodes[SourceNodeCount - B - 1]; } } } public void FloodForValues(ref sFloodForValuesArgs Args) { var CurrentNode = default(PathfinderNode); var ConnectedNode = default(PathfinderNode); var A = 0; var SourceNodeCount = 0; var SourceNodeNum = 0; var tmpConnection = default(PathfinderConnection); float ResultValue = 0; var BestPath = default(Path); var StartNode = default(PathfinderNode); var B = 0; float BestDist = 0; float Dist = 0; var BestNode = default(PathfinderNode); var C = 0; StartNode = Args.CurrentPath.Nodes[0]; Args.SourceNodes[0] = StartNode; SourceNodeCount = 1; Args.NodeValues[StartNode.Layer_NodeNum] = 0.0F; SourceNodeNum = 0; while ( SourceNodeNum < SourceNodeCount ) { CurrentNode = Args.SourceNodes[SourceNodeNum]; for ( A = 0; A <= CurrentNode.ConnectionCount - 1; A++ ) { tmpConnection = CurrentNode.Connections[A]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); if ( ConnectedNode.ParentNode == Args.SourceParentNodeA || ConnectedNode.ParentNode == Args.SourceParentNodeB ) { ResultValue = Args.NodeValues[CurrentNode.Layer_NodeNum] + tmpConnection.Value; if ( ResultValue < Args.NodeValues[ConnectedNode.Layer_NodeNum] ) { Args.NodeValues[ConnectedNode.Layer_NodeNum] = ResultValue; Args.SourceNodes[SourceNodeCount] = ConnectedNode; SourceNodeCount++; } } } SourceNodeNum++; } for ( A = 0; A <= Args.FinishNodeCount - 1; A++ ) { if ( Args.FinishIsParent ) { BestNode = null; BestDist = float.MaxValue; for ( C = 0; C <= Args.FinishNodes[A].NodeCount - 1; C++ ) { CurrentNode = Args.FinishNodes[A].Nodes[C]; Dist = Args.NodeValues[CurrentNode.Layer_NodeNum]; if ( Dist < BestDist ) { BestDist = Dist; BestNode = CurrentNode; } } CurrentNode = BestNode; } else { CurrentNode = Args.FinishNodes[A]; } if ( CurrentNode == null ) { //no path return; } SourceNodeCount = 0; BestDist = Args.NodeValues[CurrentNode.Layer_NodeNum]; if ( BestDist == float.MaxValue ) { //no path return; } do { Args.SourceNodes[SourceNodeCount] = CurrentNode; SourceNodeCount++; if ( CurrentNode == StartNode ) { break; } BestNode = null; for ( B = 0; B <= CurrentNode.ConnectionCount - 1; B++ ) { tmpConnection = CurrentNode.Connections[B]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); if ( ConnectedNode.ParentNode == Args.SourceParentNodeA || ConnectedNode.ParentNode == Args.SourceParentNodeB ) { Dist = Args.NodeValues[ConnectedNode.Layer_NodeNum]; if ( Dist < BestDist ) { BestDist = Dist; BestNode = ConnectedNode; } } } if ( BestNode == null ) { Args.BestPaths[A] = null; //no path return; } CurrentNode = BestNode; } while ( true ); BestPath = new Path(); Args.BestPaths[A] = BestPath; BestPath.Value = Args.NodeValues[Args.FinishNodes[A].Layer_NodeNum]; BestPath.NodeCount = SourceNodeCount; BestPath.Nodes = new PathfinderNode[BestPath.NodeCount]; for ( B = 0; B <= BestPath.NodeCount - 1; B++ ) { BestPath.Nodes[B] = Args.SourceNodes[SourceNodeCount - B - 1]; } } } public void FloodRouteAll(ref sFloodRouteAllArgs Args) { var CurrentNode = default(PathfinderNode); var ConnectedNode = default(PathfinderNode); var SourceNodeCount = 0; var SourceNodeNum = 0; var tmpConnection = default(PathfinderConnection); float ResultValue = 0; float BestValue = 0; var A = 0; SourceNodeCount = Args.StartNodeCount; for ( A = 0; A <= SourceNodeCount - 1; A++ ) { Args.SourceNodes[A] = Args.StartNodes[A]; Args.NodeValuesA[Args.StartNodes[A].Layer_NodeNum] = 0.0F; } SourceNodeNum = 0; while ( SourceNodeNum < SourceNodeCount ) { CurrentNode = Args.SourceNodes[SourceNodeNum]; for ( A = 0; A <= CurrentNode.ConnectionCount - 1; A++ ) { tmpConnection = CurrentNode.Connections[A]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); if ( Args.Visit[ConnectedNode.ParentNode.Layer_NodeNum] ) { if ( ConnectedNode.Clearance >= Args.MinClearance ) { ResultValue = Args.NodeValuesA[CurrentNode.Layer_NodeNum] + tmpConnection.Value; if ( ResultValue < Args.NodeValuesA[ConnectedNode.Layer_NodeNum] ) { Args.NodeValuesA[ConnectedNode.Layer_NodeNum] = ResultValue; Args.SourceNodes[SourceNodeCount] = ConnectedNode; SourceNodeCount++; } } } } SourceNodeNum++; } SourceNodeCount = 0; BestValue = Args.NodeValuesA[Args.FinishNode.Layer_NodeNum]; if ( BestValue == float.MaxValue ) { Args.BestNodeCount = 0; return; } BestValue *= Args.BestTolerance; Args.SourceNodes[0] = Args.FinishNode; SourceNodeCount = 1; Args.NodeValuesB[Args.FinishNode.Layer_NodeNum] = 0.0F; SourceNodeNum = 0; while ( SourceNodeNum < SourceNodeCount ) { CurrentNode = Args.SourceNodes[SourceNodeNum]; for ( A = 0; A <= CurrentNode.ConnectionCount - 1; A++ ) { tmpConnection = CurrentNode.Connections[A]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); if ( Args.Visit[ConnectedNode.ParentNode.Layer_NodeNum] ) { ResultValue = Args.NodeValuesB[CurrentNode.Layer_NodeNum] + tmpConnection.Value; if ( ResultValue < Args.NodeValuesB[ConnectedNode.Layer_NodeNum] ) { Args.NodeValuesB[ConnectedNode.Layer_NodeNum] = ResultValue; if ( Args.NodeValuesA[ConnectedNode.Layer_NodeNum] + ResultValue <= BestValue + 500.0F ) { Args.SourceNodes[SourceNodeCount] = ConnectedNode; SourceNodeCount++; } } } } SourceNodeNum++; } Args.BestNodeCount = SourceNodeCount; } public void FindCalc() { PathfinderNode[] ShuffledNodes = null; var ShuffledNodeCount = 0; int[] Positions = null; var PositionCount = 0; var RandNum = 0; var A = 0; while ( FindParentNodeCount > 0 ) { Positions = new int[FindParentNodeCount]; ShuffledNodeCount = FindParentNodeCount; ShuffledNodes = new PathfinderNode[ShuffledNodeCount]; for ( A = 0; A <= FindParentNodeCount - 1; A++ ) { Positions[PositionCount] = PositionCount; PositionCount++; } for ( A = 0; A <= FindParentNodeCount - 1; A++ ) { RandNum = App.Random.Next() * PositionCount; ShuffledNodes[Positions[RandNum]] = FindParentNodes[A]; PositionCount--; if ( RandNum < PositionCount ) { Positions[RandNum] = Positions[PositionCount]; } } for ( A = 0; A <= ShuffledNodeCount - 1; A++ ) { if ( ShuffledNodes[A].Network_FindParentNum >= 0 ) { if ( ShuffledNodes[A].ParentNode == null ) { ShuffledNodes[A].FindParent(); } FindParentNode_Remove(ShuffledNodes[A].Network_FindParentNum); } } } //remove empty layers var LayerNum = NodeLayerCount - 1; do { if ( NodeLayers[LayerNum].NodeCount > 0 ) { break; } NodeLayers[LayerNum].Network_LayerNum = -1; if ( LayerNum == 0 ) { break; } NodeLayers[LayerNum - 1].ParentLayer = null; LayerNum--; } while ( true ); if ( LayerNum < NodeLayerCount - 1 ) { Array.Resize(ref NodeLayers, LayerNum + 1); NodeLayerCount = LayerNum + 1; } } public void LargeArraysResize() { NetworkLargeArrays.Resize(this); } //maps lowest values from the start node to all other nodes public void FloodProximity(ref sFloodProximityArgs Args) { var CurrentNode = default(PathfinderNode); var ConnectedNode = default(PathfinderNode); var A = 0; var SourceNodeCount = 0; var SourceNodeNum = 0; var tmpConnection = default(PathfinderConnection); float ResultValue = 0; var StartNode = default(PathfinderNode); StartNode = Args.StartNode; NetworkLargeArrays.Nodes_Nodes[0] = StartNode; SourceNodeCount = 1; Args.NodeValues[StartNode.Layer_NodeNum] = 0.0F; SourceNodeNum = 0; while ( SourceNodeNum < SourceNodeCount ) { CurrentNode = NetworkLargeArrays.Nodes_Nodes[SourceNodeNum]; for ( A = 0; A <= CurrentNode.ConnectionCount - 1; A++ ) { tmpConnection = CurrentNode.Connections[A]; ConnectedNode = tmpConnection.GetOtherNode(CurrentNode); ResultValue = Args.NodeValues[CurrentNode.Layer_NodeNum] + tmpConnection.Value; if ( ResultValue < Args.NodeValues[ConnectedNode.Layer_NodeNum] ) { Args.NodeValues[ConnectedNode.Layer_NodeNum] = ResultValue; NetworkLargeArrays.Nodes_Nodes[SourceNodeCount] = ConnectedNode; SourceNodeCount++; } } SourceNodeNum++; } } public void ClearChangedNodes() { var A = 0; for ( A = 0; A <= NodeLayerCount - 1; A++ ) { NodeLayers[A].ClearChangedNodes(); } } public bool NodeCanReachNode(PathfinderNode StartNode, PathfinderNode FinishNode) { var StartParent = StartNode; var FinishParent = FinishNode; do { if ( StartParent == FinishParent ) { return true; } StartParent = StartParent.ParentNode; if ( StartParent == null ) { return false; } FinishParent = FinishParent.ParentNode; if ( FinishParent == null ) { return false; } } while ( true ); } public struct PathList { public int PathCount; public Path[] Paths; } public struct sFloodForValuesArgs { public Path[] BestPaths; public Path CurrentPath; public bool FinishIsParent; public int FinishNodeCount; public PathfinderNode[] FinishNodes; public int MinClearance; public float[] NodeValues; public PathfinderNode[] SourceNodes; public PathfinderNode SourceParentNodeA; public PathfinderNode SourceParentNodeB; } public struct sFloodProximityArgs { public float[] NodeValues; public PathfinderNode StartNode; } public struct sFloodRouteAllArgs { public int BestNodeCount; public float BestTolerance; public PathfinderNode FinishNode; public int MinClearance; public float[] NodeValuesA; public float[] NodeValuesB; public PathfinderNode[] SourceNodes; public int StartNodeCount; public PathfinderNode[] StartNodes; public bool[] Visit; } public struct sFloodRouteArgs { public Path[] BestPaths; public Path CurrentPath; public bool FinishIsParent; public int FinishNodeCount; public PathfinderNode[] FinishNodes; public int MinClearance; public float[] NodeValues; public PathfinderNode[] SourceNodes; public bool[] Visit; } public struct sFloodSpanArgs { public Path[] BestPaths; public Path CurrentPath; public bool FinishIsParent; public int FinishNodeCount; public PathfinderNode[] FinishNodes; public int MinClearance; public float[] NodeValues; public PathfinderNode[] SourceNodes; public PathfinderNode SourceParentNode; } } }
using System; using System.Data; using System.Data.OleDb; using System.Collections; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.Framework.TableFrame.DS { public class sys_TableAndGroupDS { private const string THIS = "PCSComUtils.Framework.TableFrame.DS.DS.sys_TableAndGroupDS"; public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { sys_TableAndGroupVO objObject = (sys_TableAndGroupVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO " + sys_TableAndGroupTable.TABLE_NAME + " ( " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEID_FLD + "," + sys_TableAndGroupTable.TABLEORDER_FLD + ")" + "VALUES(?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableAndGroupTable.TABLEGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_TableAndGroupTable.TABLEGROUPID_FLD].Value = objObject.TableGroupID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableAndGroupTable.TABLEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_TableAndGroupTable.TABLEID_FLD].Value = objObject.TableID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableAndGroupTable.TABLEORDER_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_TableAndGroupTable.TABLEORDER_FLD].Value = objObject.TableOrder; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = string.Empty; strSql = "DELETE " + sys_TableAndGroupTable.TABLE_NAME + " WHERE " + "TableID" + "=" + pintID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void DeleteTableAndGroup(int pintTableID, int pintTableGroupID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = string.Empty; strSql = "DELETE " + sys_TableAndGroupTable.TABLE_NAME + " WHERE " + sys_TableAndGroupTable.TABLEID_FLD + "=" + pintTableID.ToString() + " AND " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "=" + pintTableGroupID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + sys_TableAndGroupTable.TABLEANDGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEID_FLD + "," + sys_TableAndGroupTable.TABLEORDER_FLD + " FROM " + sys_TableAndGroupTable.TABLE_NAME +" WHERE " + sys_TableAndGroupTable.TABLEANDGROUPID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); sys_TableAndGroupVO objObject = new sys_TableAndGroupVO(); while (odrPCS.Read()) { objObject.TableAndGroupID = int.Parse(odrPCS[sys_TableAndGroupTable.TABLEANDGROUPID_FLD].ToString()); objObject.TableGroupID = int.Parse(odrPCS[sys_TableAndGroupTable.TABLEGROUPID_FLD].ToString()); objObject.TableID = int.Parse(odrPCS[sys_TableAndGroupTable.TABLEID_FLD].ToString()); objObject.TableOrder = int.Parse(odrPCS[sys_TableAndGroupTable.TABLEORDER_FLD].ToString()); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public int CountTableInGroup(int pintTableID) { const string METHOD_NAME = THIS + ".CountTableInGroup()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT Count(*)" + " FROM " + sys_TableAndGroupTable.TABLE_NAME +" WHERE " + sys_TableAndGroupTable.TABLEID_FLD + "=" + pintTableID; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); object objResult = ocmdPCS.ExecuteScalar(); if (objResult != null) { return int.Parse(objResult.ToString()); } else { return 0; } } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public bool CheckIfTableExisted(int pintTableId,int pintTableGroupID) { const string METHOD_NAME = THIS + ".GetMaxTableOrder()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT count(*) " + " FROM " + sys_TableAndGroupTable.TABLE_NAME + " WHERE " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "=" + pintTableGroupID + " AND " + sys_TableAndGroupTable.TABLEID_FLD + "=" + pintTableId; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); int intTableCount = int.Parse(ocmdPCS.ExecuteScalar().ToString()); if (intTableCount == 0) { return false; }else { return true; } } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public int GetMaxTableOrder(int pintTableGroupID) { const string METHOD_NAME = THIS + ".GetMaxTableOrder()"; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT isnull(Max(" + sys_TableAndGroupTable.TABLEORDER_FLD + "),0) + 1 " + " FROM " + sys_TableAndGroupTable.TABLE_NAME +" WHERE " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "=" + pintTableGroupID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); return int.Parse(ocmdPCS.ExecuteScalar().ToString()); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; sys_TableAndGroupVO objObject = (sys_TableAndGroupVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "UPDATE sys_TableAndGroup SET " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "= ?" + "," + sys_TableAndGroupTable.TABLEID_FLD + "= ?" + "," + sys_TableAndGroupTable.TABLEORDER_FLD + "= ?" +" WHERE " + sys_TableAndGroupTable.TABLEANDGROUPID_FLD + "= ?"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableAndGroupTable.TABLEGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_TableAndGroupTable.TABLEGROUPID_FLD].Value = objObject.TableGroupID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableAndGroupTable.TABLEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_TableAndGroupTable.TABLEID_FLD].Value = objObject.TableID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableAndGroupTable.TABLEORDER_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_TableAndGroupTable.TABLEORDER_FLD].Value = objObject.TableOrder; ocmdPCS.Parameters.Add(new OleDbParameter(sys_TableAndGroupTable.TABLEANDGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_TableAndGroupTable.TABLEANDGROUPID_FLD].Value = objObject.TableAndGroupID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT " + sys_TableAndGroupTable.TABLEANDGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEID_FLD + "," + sys_TableAndGroupTable.TABLEORDER_FLD + " FROM " +sys_TableAndGroupTable.TABLE_NAME + " ORDER BY " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEORDER_FLD; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,sys_TableAndGroupTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + sys_TableAndGroupTable.TABLEANDGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEID_FLD + "," + sys_TableAndGroupTable.TABLEORDER_FLD; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,sys_TableAndGroupTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public int GetGroupIDByTableID(int pintTableID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; string strSql = "SELECT " + sys_TableAndGroupTable.TABLEGROUPID_FLD + " FROM " + sys_TableAndGroupTable.TABLE_NAME + " WHERE " + sys_TableAndGroupTable.TABLEID_FLD + "=" + pintTableID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); int mGroupID = int.Parse(ocmdPCS.ExecuteScalar().ToString()); return mGroupID; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME,ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public ArrayList GetObjectVOs(int pintTableGroupID) { ArrayList arrObjects = new ArrayList(); const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); string strSql = "SELECT " + sys_TableAndGroupTable.TABLEANDGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEID_FLD + "," + sys_TableAndGroupTable.TABLEORDER_FLD + " FROM " + sys_TableAndGroupTable.TABLE_NAME + " WHERE " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "=" + pintTableGroupID.ToString() + "ORDER BY " + sys_TableAndGroupTable.TABLEORDER_FLD; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); while (odrPCS.Read()) { sys_TableAndGroupVO objAndVO = new sys_TableAndGroupVO(); objAndVO.TableAndGroupID = int.Parse(odrPCS[sys_TableAndGroupTable.TABLEANDGROUPID_FLD].ToString()); objAndVO.TableGroupID = int.Parse(odrPCS[sys_TableAndGroupTable.TABLEGROUPID_FLD].ToString()); objAndVO.TableID = int.Parse(odrPCS[sys_TableAndGroupTable.TABLEID_FLD].ToString()); objAndVO.TableOrder = int.Parse(odrPCS[sys_TableAndGroupTable.TABLEORDER_FLD].ToString()); arrObjects.Add(objAndVO); } return arrObjects; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME,ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public int GetTablePositionInGroup(int pintGroupID,int pintTableId) { const string METHOD_NAME = THIS + ".GetTablePositionInGroup()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT isnull(" + sys_TableAndGroupTable.TABLEORDER_FLD + ",0) " + " FROM " + sys_TableAndGroupTable.TABLE_NAME +" WHERE " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "=" + pintGroupID +" And " + sys_TableAndGroupTable.TABLEID_FLD + "=" + pintTableId; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); return int.Parse(ocmdPCS.ExecuteScalar().ToString()); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void CopyTwoGroup(int pintFromGroup, int pintToGroup) { const string METHOD_NAME = THIS + ".CopyTwoGroup()"; string strSql = string.Empty; strSql= "INSERT INTO " + sys_TableAndGroupTable.TABLE_NAME + "(" + sys_TableAndGroupTable.TABLEGROUPID_FLD + "," + sys_TableAndGroupTable.TABLEID_FLD + "," + sys_TableAndGroupTable.TABLEORDER_FLD + ")" + " SELECT " + pintToGroup + "," + sys_TableAndGroupTable.TABLEID_FLD + "," + sys_TableAndGroupTable.TABLEORDER_FLD + " FROM " + sys_TableAndGroupTable.TABLE_NAME + " WHERE " + sys_TableAndGroupTable.TABLEGROUPID_FLD + "=" + pintFromGroup + "" ; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using System; using System.Collections.Generic; using NUnit.Framework; using OpenQA.Selenium.Environment; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium { [TestFixture] public class AlertsTest : DriverTestFixture { [Test] public void ShouldBeAbleToOverrideTheWindowAlertMethod() { driver.Url = CreateAlertPage("cheese"); ((IJavaScriptExecutor)driver).ExecuteScript( "window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }"); driver.FindElement(By.Id("alert")).Click(); } [Test] public void ShouldAllowUsersToAcceptAnAlertManually() { driver.Url = CreateAlertPage("cheese"); driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", driver.Title); } [Test] public void ShouldThrowArgumentNullExceptionWhenKeysNull() { driver.Url = CreateAlertPage("cheese"); driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); try { Assert.That(() => alert.SendKeys(null), Throws.ArgumentNullException); } finally { alert.Accept(); } } [Test] public void ShouldAllowUsersToAcceptAnAlertWithNoTextManually() { driver.Url = CreateAlertPage(""); driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", driver.Title); } [Test] [IgnoreBrowser(Browser.Chrome, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")] [IgnoreBrowser(Browser.Edge, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")] [IgnoreBrowser(Browser.IE, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")] [IgnoreBrowser(Browser.Firefox, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")] [IgnoreBrowser(Browser.Safari, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")] public void ShouldGetTextOfAlertOpenedInSetTimeout() { driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts") .WithScripts( "function slowAlert() { window.setTimeout(function(){ alert('Slow'); }, 200); }") .WithBody( "<a href='#' id='slow-alert' onclick='slowAlert();'>click me</a>")); driver.FindElement(By.Id("slow-alert")).Click(); // DO NOT WAIT OR SLEEP HERE. // This is a regression test for a bug where only the first switchTo call would throw, // and only if it happens before the alert actually loads. IAlert alert = driver.SwitchTo().Alert(); try { Assert.AreEqual("Slow", alert.Text); } finally { alert.Accept(); } } [Test] public void ShouldAllowUsersToDismissAnAlertManually() { driver.Url = CreateAlertPage("cheese"); driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Dismiss(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", driver.Title); } [Test] public void ShouldAllowAUserToAcceptAPrompt() { driver.Url = CreatePromptPage(null); driver.FindElement(By.Id("prompt")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Prompt", driver.Title); } [Test] public void ShouldAllowAUserToDismissAPrompt() { driver.Url = CreatePromptPage(null); driver.FindElement(By.Id("prompt")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Dismiss(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Prompt", driver.Title); } [Test] public void ShouldAllowAUserToSetTheValueOfAPrompt() { driver.Url = CreatePromptPage(null); driver.FindElement(By.Id("prompt")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.SendKeys("cheese"); alert.Accept(); string result = driver.FindElement(By.Id("text")).Text; Assert.AreEqual("cheese", result); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome does not throw when setting the text of an alert")] public void SettingTheValueOfAnAlertThrows() { driver.Url = CreateAlertPage("cheese"); driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); try { alert.SendKeys("cheese"); Assert.Fail("Expected exception"); } catch (ElementNotInteractableException) { } finally { alert.Accept(); } } [Test] public void ShouldAllowTheUserToGetTheTextOfAnAlert() { driver.Url = CreateAlertPage("cheese"); driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); string value = alert.Text; alert.Accept(); Assert.AreEqual("cheese", value); } [Test] public void ShouldAllowTheUserToGetTheTextOfAPrompt() { driver.Url = CreatePromptPage(null); driver.FindElement(By.Id("prompt")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); string value = alert.Text; alert.Accept(); Assert.AreEqual("Enter something", value); } [Test] public void AlertShouldNotAllowAdditionalCommandsIfDimissed() { driver.Url = CreateAlertPage("cheese"); driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Dismiss(); string text; Assert.That(() => text = alert.Text, Throws.InstanceOf<NoAlertPresentException>()); } [Test] public void ShouldAllowUsersToAcceptAnAlertInAFrame() { string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>")); driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts") .WithBody(String.Format("<iframe src='{0}' name='iframeWithAlert'></iframe>", iframe))); driver.SwitchTo().Frame("iframeWithAlert"); driver.FindElement(By.Id("alertInFrame")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", driver.Title); } [Test] public void ShouldAllowUsersToAcceptAnAlertInANestedFrame() { string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>")); string iframe2 = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody(string.Format("<iframe src='{0}' name='iframeWithAlert'></iframe>", iframe))); driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts") .WithBody(string.Format("<iframe src='{0}' name='iframeWithIframe'></iframe>", iframe2))); driver.SwitchTo().Frame("iframeWithIframe").SwitchTo().Frame("iframeWithAlert"); driver.FindElement(By.Id("alertInFrame")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Accept(); // If we can perform any action, we're good to go Assert.AreEqual("Testing Alerts", driver.Title); } [Test] public void SwitchingToMissingAlertThrows() { driver.Url = CreateAlertPage("cheese"); Assert.That(() => AlertToBePresent(), Throws.InstanceOf<NoAlertPresentException>()); } [Test] public void SwitchingToMissingAlertInAClosedWindowThrows() { string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()); driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody(String.Format( "<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", blank))); string mainWindow = driver.CurrentWindowHandle; try { driver.FindElement(By.Id("open-new-window")).Click(); WaitFor(WindowHandleCountToBe(2), "Window count was not 2"); WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'"); driver.Close(); WaitFor(WindowHandleCountToBe(1), "Window count was not 1"); try { AlertToBePresent().Accept(); Assert.Fail("Expected exception"); } catch (NoSuchWindowException) { // Expected } } finally { driver.SwitchTo().Window(mainWindow); WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'"); } } [Test] public void PromptShouldUseDefaultValueIfNoKeysSent() { driver.Url = CreatePromptPage("This is a default value"); driver.FindElement(By.Id("prompt")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Accept(); IWebElement element = driver.FindElement(By.Id("text")); WaitFor(ElementTextToEqual(element, "This is a default value"), "Element text was not 'This is a default value'"); Assert.AreEqual("This is a default value", element.Text); } [Test] public void PromptShouldHaveNullValueIfDismissed() { driver.Url = CreatePromptPage("This is a default value"); driver.FindElement(By.Id("prompt")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Dismiss(); IWebElement element = driver.FindElement(By.Id("text")); WaitFor(ElementTextToEqual(element, "null"), "Element text was not 'null'"); Assert.AreEqual("null", element.Text); } [Test] [IgnoreBrowser(Browser.Remote)] public void HandlesTwoAlertsFromOneInteraction() { driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithScripts( "function setInnerText(id, value) {", " document.getElementById(id).innerHTML = '<p>' + value + '</p>';", "}", "function displayTwoPrompts() {", " setInnerText('text1', prompt('First'));", " setInnerText('text2', prompt('Second'));", "}") .WithBody( "<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>", "<div id='text1'></div>", "<div id='text2'></div>")); driver.FindElement(By.Id("double-prompt")).Click(); IAlert alert1 = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert1.SendKeys("brie"); alert1.Accept(); IAlert alert2 = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert2.SendKeys("cheddar"); alert2.Accept(); IWebElement element1 = driver.FindElement(By.Id("text1")); WaitFor(ElementTextToEqual(element1, "brie"), "Element text was not 'brie'"); Assert.AreEqual("brie", element1.Text); IWebElement element2 = driver.FindElement(By.Id("text2")); WaitFor(ElementTextToEqual(element2, "cheddar"), "Element text was not 'cheddar'"); Assert.AreEqual("cheddar", element2.Text); } [Test] public void ShouldHandleAlertOnPageLoad() { string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithOnLoad("javascript:alert(\"onload\")") .WithBody("<p>Page with onload event handler</p>")); driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody(string.Format("<a id='open-page-with-onload-alert' href='{0}'>open new page</a>", pageWithOnLoad))); driver.FindElement(By.Id("open-page-with-onload-alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); string value = alert.Text; alert.Accept(); Assert.AreEqual("onload", value); IWebElement element = driver.FindElement(By.TagName("p")); WaitFor(ElementTextToEqual(element, "Page with onload event handler"), "Element text was not 'Page with onload event handler'"); } [Test] public void ShouldHandleAlertOnPageLoadUsingGet() { driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithOnLoad("javascript:alert(\"onload\")") .WithBody("<p>Page with onload event handler</p>")); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); string value = alert.Text; alert.Accept(); Assert.AreEqual("onload", value); WaitFor(ElementTextToEqual(driver.FindElement(By.TagName("p")), "Page with onload event handler"), "Could not find element with text 'Page with onload event handler'"); } [Test] [IgnoreBrowser(Browser.Chrome, "Test with onLoad alert hangs Chrome.")] [IgnoreBrowser(Browser.Safari, "Safari driver does not allow commands in any window when an alert is active")] public void ShouldNotHandleAlertInAnotherWindow() { string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithOnLoad("javascript:alert(\"onload\")") .WithBody("<p>Page with onload event handler</p>")); driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody(string.Format( "<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", pageWithOnLoad))); string mainWindow = driver.CurrentWindowHandle; string onloadWindow = null; try { driver.FindElement(By.Id("open-new-window")).Click(); List<String> allWindows = new List<string>(driver.WindowHandles); allWindows.Remove(mainWindow); Assert.AreEqual(1, allWindows.Count); onloadWindow = allWindows[0]; try { IWebElement el = driver.FindElement(By.Id("open-new-window")); WaitFor<IAlert>(AlertToBePresent, TimeSpan.FromSeconds(5), "No alert found"); Assert.Fail("Expected exception"); } catch (WebDriverException) { // An operation timed out exception is expected, // since we're using WaitFor<T>. } } finally { driver.SwitchTo().Window(onloadWindow); WaitFor<IAlert>(AlertToBePresent, "No alert found").Dismiss(); driver.Close(); driver.SwitchTo().Window(mainWindow); WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'"); } } [Test] [IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")] [IgnoreBrowser(Browser.Chrome, "Chrome does not trigger alerts on unload.")] [IgnoreBrowser(Browser.Edge, "Edge does not trigger alerts on unload.")] public void ShouldHandleAlertOnPageUnload() { string pageWithOnBeforeUnload = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithOnBeforeUnload("return \"onunload\";") .WithBody("<p>Page with onbeforeunload event handler</p>")); driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody(string.Format("<a id='open-page-with-onunload-alert' href='{0}'>open new page</a>", pageWithOnBeforeUnload))); IWebElement element = WaitFor<IWebElement>(ElementToBePresent(By.Id("open-page-with-onunload-alert")), "Could not find element with id 'open-page-with-onunload-alert'"); element.Click(); driver.Navigate().Back(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); string value = alert.Text; alert.Accept(); Assert.AreEqual("onunload", value); element = WaitFor<IWebElement>(ElementToBePresent(By.Id("open-page-with-onunload-alert")), "Could not find element with id 'open-page-with-onunload-alert'"); WaitFor(ElementTextToEqual(element, "open new page"), "Element text was not 'open new page'"); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome does not implicitly handle onBeforeUnload alert")] [IgnoreBrowser(Browser.Safari, "Safari driver does not implicitly (or otherwise) handle onBeforeUnload alerts")] //[IgnoreBrowser(Browser.Edge, "Edge driver does not implicitly (or otherwise) handle onBeforeUnload alerts")] public void ShouldImplicitlyHandleAlertOnPageBeforeUnload() { string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage().WithTitle("Success")); driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Page with onbeforeunload handler") .WithBody(String.Format( "<a id='link' href='{0}'>Click here to navigate to another page.</a>", blank))); SetSimpleOnBeforeUnload("onbeforeunload message"); driver.FindElement(By.Id("link")).Click(); WaitFor(() => driver.Title == "Success", "Title was not 'Success'"); } [Test] [IgnoreBrowser(Browser.IE, "Test as written does not trigger alert; also onbeforeunload alert on close will hang browser")] [IgnoreBrowser(Browser.Chrome, "Test as written does not trigger alert")] [IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")] [IgnoreBrowser(Browser.Edge, "Edge does not trigger alerts on unload.")] public void ShouldHandleAlertOnWindowClose() { string pageWithOnBeforeUnload = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithOnBeforeUnload("javascript:alert(\"onbeforeunload\")") .WithBody("<p>Page with onbeforeunload event handler</p>")); driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithBody(string.Format( "<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", pageWithOnBeforeUnload))); string mainWindow = driver.CurrentWindowHandle; try { driver.FindElement(By.Id("open-new-window")).Click(); WaitFor(WindowHandleCountToBe(2), "Window count was not 2"); WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'"); driver.Close(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); string value = alert.Text; alert.Accept(); Assert.AreEqual("onbeforeunload", value); } finally { driver.SwitchTo().Window(mainWindow); WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text equal to 'open new window'"); } } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome does not supply text in UnhandledAlertException")] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.Safari, "Safari driver does not do unhandled alerts")] public void IncludesAlertTextInUnhandledAlertException() { driver.Url = CreateAlertPage("cheese"); driver.FindElement(By.Id("alert")).Click(); WaitFor<IAlert>(AlertToBePresent, "No alert found"); try { string title = driver.Title; Assert.Fail("Expected UnhandledAlertException"); } catch (UnhandledAlertException e) { Assert.AreEqual("cheese", e.AlertText); } } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] [IgnoreBrowser(Browser.Opera)] public void CanQuitWhenAnAlertIsPresent() { driver.Url = CreateAlertPage("cheese"); driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); EnvironmentManager.Instance.CloseCurrentDriver(); } [Test] [IgnoreBrowser(Browser.Safari, "Safari driver cannot handle alert thrown via JavaScript")] public void ShouldHandleAlertOnFormSubmit() { driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts"). WithBody("<form id='theForm' action='javascript:alert(\"Tasty cheese\");'>", "<input id='unused' type='submit' value='Submit'>", "</form>")); IWebElement element = driver.FindElement(By.Id("theForm")); element.Submit(); IAlert alert = driver.SwitchTo().Alert(); string text = alert.Text; alert.Accept(); Assert.AreEqual("Tasty cheese", text); Assert.AreEqual("Testing Alerts", driver.Title); } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] [IgnoreBrowser(Browser.Safari, "onBeforeUnload dialogs hang Safari")] public void ShouldHandleAlertOnPageBeforeUnload() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html"); IWebElement element = driver.FindElement(By.Id("navigate")); element.Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Dismiss(); Assert.That(driver.Url, Does.Contain("pageWithOnBeforeUnloadMessage.html")); // Can't move forward or even quit the driver // until the alert is accepted. element.Click(); alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Accept(); WaitFor(() => { return driver.Url.Contains(alertsPage); }, "Browser URL does not contain " + alertsPage); Assert.That(driver.Url, Does.Contain(alertsPage)); } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] [IgnoreBrowser(Browser.Safari, "onBeforeUnload dialogs hang Safari")] public void ShouldHandleAlertOnPageBeforeUnloadAlertAtQuit() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html"); IWebElement element = driver.FindElement(By.Id("navigate")); element.Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); driver.Quit(); driver = null; } // Disabling test for all browsers. Authentication API is not supported by any driver yet. // [Test] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.Edge)] [IgnoreBrowser(Browser.Firefox)] [IgnoreBrowser(Browser.IE)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.Remote)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToHandleAuthenticationDialog() { driver.Url = authenticationPage; IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.SetAuthenticationCredentials("test", "test"); alert.Accept(); Assert.That(driver.FindElement(By.TagName("h1")).Text, Does.Contain("authorized")); } // Disabling test for all browsers. Authentication API is not supported by any driver yet. // [Test] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.Edge)] [IgnoreBrowser(Browser.Firefox)] [IgnoreBrowser(Browser.IE)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.Remote)] [IgnoreBrowser(Browser.Safari)] public void ShouldBeAbleToDismissAuthenticationDialog() { driver.Url = authenticationPage; IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); alert.Dismiss(); } // Disabling test for all browsers. Authentication API is not supported by any driver yet. // [Test] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.Edge)] [IgnoreBrowser(Browser.Firefox)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.Remote)] [IgnoreBrowser(Browser.Safari)] public void ShouldThrowAuthenticatingOnStandardAlert() { driver.Url = alertsPage; driver.FindElement(By.Id("alert")).Click(); IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found"); try { alert.SetAuthenticationCredentials("test", "test"); Assert.Fail("Should not be able to Authenticate"); } catch (UnhandledAlertException) { // this is an expected exception } // but the next call should be good. alert.Dismiss(); } private IAlert AlertToBePresent() { return driver.SwitchTo().Alert(); } private string CreateAlertPage(string alertText) { return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Alerts") .WithBody("<a href='#' id='alert' onclick='alert(\"" + alertText + "\");'>click me</a>")); } private string CreatePromptPage(string defaultText) { return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage() .WithTitle("Testing Prompt") .WithScripts( "function setInnerText(id, value) {", " document.getElementById(id).innerHTML = '<p>' + value + '</p>';", "}", defaultText == null ? "function displayPrompt() { setInnerText('text', prompt('Enter something')); }" : "function displayPrompt() { setInnerText('text', prompt('Enter something', '" + defaultText + "')); }") .WithBody( "<a href='#' id='prompt' onclick='displayPrompt();'>click me</a>", "<div id='text'>acceptor</div>")); } private void SetSimpleOnBeforeUnload(string returnText) { ((IJavaScriptExecutor)driver).ExecuteScript( "var returnText = arguments[0]; window.onbeforeunload = function() { return returnText; }", returnText); } private Func<IWebElement> ElementToBePresent(By locator) { return () => { IWebElement foundElement = null; try { foundElement = driver.FindElement(By.Id("open-page-with-onunload-alert")); } catch (NoSuchElementException) { } return foundElement; }; } private Func<bool> ElementTextToEqual(IWebElement element, string text) { return () => { return element.Text == text; }; } private Func<bool> WindowWithName(string name) { return () => { try { driver.SwitchTo().Window(name); return true; } catch (NoSuchWindowException) { } return false; }; } private Func<bool> WindowHandleCountToBe(int count) { return () => { return driver.WindowHandles.Count == count; }; } } }
// // System.IO.TextReader // // Authors: // Marcin Szczepanski (marcins@zipworld.com.au) // Miguel de Icaza (miguel@gnome.org) // Marek Safar (marek.safar@gmail.com) // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // Copyright 2011 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace Morph.IO { public abstract class TextReader /*: MarshalByRefObject, IDisposable */{ sealed class NullTextReader : TextReader { public override string ReadLine() { return null; } public override string ReadToEnd() { return String.Empty; } } public static readonly TextReader Null = new NullTextReader(); protected TextReader() { } public virtual void Close() { //Dispose(true); } public void Dispose() { //Dispose(true); } //protected virtual void Dispose(bool disposing) //{ // if (disposing) // { // // If we are explicitly disposed, we can avoid finalization. // GC.SuppressFinalize(this); // } // return; //} public virtual int Peek() { return -1; } public virtual int Read() { return -1; } public virtual int Read(/*[In, Out]*/ char[] buffer, int index, int count) { int c, i; for (i = 0; i < count; i++) { if ((c = Read()) == -1) return i; buffer[index + i] = (char)c; } return i; } public virtual int ReadBlock(/*[In, Out]*/ char[] buffer, int index, int count) { int total_read_count = 0; int current_read_count = 0; do { current_read_count = Read(buffer, index, count); index += current_read_count; total_read_count += current_read_count; count -= current_read_count; } while (current_read_count != 0 && count > 0); return total_read_count; } public virtual string ReadLine() { var result = new System.Text.StringBuilder(); int c; while ((c = Read()) != -1) { // check simple character line ending if (c == '\n') break; if (c == '\r') { if (Peek() == '\n') Read(); break; } result.Append((char)c); } if (c == -1 && result.Length == 0) return null; return result.ToString(); } public virtual string ReadToEnd() { var result = new System.Text.StringBuilder(); int c; while ((c = Read()) != -1) result.Append((char)c); return result.ToString(); } //public static TextReader Synchronized (TextReader reader) //{ // if (reader == null) // { // //throw new ArgumentNullException ("reader is null"); // } // if (reader is SynchronizedReader) // return reader; // //return new SynchronizedReader (reader); //} } // // Synchronized Reader implementation, used internally. // sealed class SynchronizedReader : TextReader { readonly TextReader reader; public SynchronizedReader(TextReader reader) { this.reader = reader; } public override void Close() { lock (this) { reader.Close(); } } public override int Peek() { lock (this) { return reader.Peek(); } } public override int ReadBlock(char[] buffer, int index, int count) { lock (this) { return reader.ReadBlock(buffer, index, count); } } public override string ReadLine() { lock (this) { return reader.ReadLine(); } } public override string ReadToEnd() { lock (this) { return reader.ReadToEnd(); } } public override int Read() { lock (this) { return reader.Read(); } } public override int Read(char[] buffer, int index, int count) { lock (this) { return reader.Read(buffer, index, count); } } } }
// *********************************************************************** // Copyright (c) 2012-2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if PARALLEL using System; using System.Collections.Generic; using System.Threading; namespace NUnit.Framework.Internal.Execution { /// <summary> /// The dispatcher needs to do different things at different, /// non-overlapped times. For example, non-parallel tests may /// not be run at the same time as parallel tests. We model /// this using the metaphor of a working shift. The WorkShift /// class associates one or more WorkItemQueues with one or /// more TestWorkers. /// /// Work in the queues is processed until all queues are empty /// and all workers are idle. Both tests are needed because a /// worker that is busy may end up adding more work to one of /// the queues. At that point, the shift is over and another /// shift may begin. This cycle continues until all the tests /// have been run. /// </summary> public class WorkShift { private static Logger log = InternalTrace.GetLogger("WorkShift"); private object _syncRoot = new object(); private int _busyCount = 0; /// <summary> /// Construct a WorkShift /// </summary> public WorkShift(string name) { Name = name; IsActive = false; Queues = new List<WorkItemQueue>(); Workers = new List<TestWorker>(); } #region Public Events and Properties /// <summary> /// Event that fires when the shift has ended /// </summary> public event EventHandler EndOfShift; /// <summary> /// The Name of this shift /// </summary> public string Name { get; } /// <summary> /// Gets a flag indicating whether the shift is currently active /// </summary> public bool IsActive { get; private set; } /// <summary> /// Gets a list of the queues associated with this shift. /// </summary> /// <remarks>Used for testing</remarks> public IList<WorkItemQueue> Queues { get; } /// <summary> /// Gets the list of workers associated with this shift. /// </summary> public IList<TestWorker> Workers { get; } /// <summary> /// Gets a bool indicating whether this shift has any work to do /// </summary> public bool HasWork { get { foreach (var q in Queues) if (!q.IsEmpty) return true; return false; } } #endregion #region Public Methods /// <summary> /// Add a WorkItemQueue to the shift, starting it if the /// shift is currently active. /// </summary> public void AddQueue(WorkItemQueue queue) { log.Debug("{0} shift adding queue {1}", Name, queue.Name); Queues.Add(queue); if (IsActive) queue.Start(); } /// <summary> /// Assign a worker to the shift. /// </summary> /// <param name="worker"></param> public void Assign(TestWorker worker) { log.Debug("{0} shift assigned worker {1}", Name, worker.Name); Workers.Add(worker); } bool _firstStart = true; /// <summary> /// Start or restart processing for the shift /// </summary> public void Start() { log.Info("{0} shift starting", Name); IsActive = true; if (_firstStart) StartWorkers(); foreach (var q in Queues) q.Start(); _firstStart = false; } private void StartWorkers() { foreach (var worker in Workers) { worker.Busy += (s, ea) => Interlocked.Increment(ref _busyCount); worker.Idle += (s, ea) => { // Quick check first using Interlocked.Decrement if (Interlocked.Decrement(ref _busyCount) == 0) lock (_syncRoot) { // Check busy count again under the lock. If there is no work // try to restore any saved queues and end the shift. if (_busyCount == 0 && !HasWork) { EndShift(); } } }; worker.Start(); } } /// <summary> /// End the shift, pausing all queues and raising /// the EndOfShift event. /// </summary> public void EndShift() { log.Info("{0} shift ending", Name); IsActive = false; // Pause all queues for this shift foreach (var q in Queues) q.Pause(); // Signal the dispatcher that shift ended EndOfShift(this, EventArgs.Empty); } /// <summary> /// Shut down the shift. /// </summary> public void ShutDown() { IsActive = false; foreach (var q in Queues) q.Stop(); } /// <summary> /// Cancel (abort or stop) the shift without completing all work /// </summary> /// <param name="force">true if the WorkShift should be aborted, false if it should allow its currently running tests to complete</param> public void Cancel(bool force) { if (force) IsActive = false; foreach (var w in Workers) w.Cancel(force); } #endregion } } #endif
// *********************************************************************** // Copyright (c) 2007-2012 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace NUnit.Framework.Internal { /// <summary> /// Helper methods for inspecting a type by reflection. /// /// Many of these methods take ICustomAttributeProvider as an /// argument to avoid duplication, even though certain attributes can /// only appear on specific types of members, like MethodInfo or Type. /// /// In the case where a type is being examined for the presence of /// an attribute, interface or named member, the Reflect methods /// operate with the full name of the member being sought. This /// removes the necessity of the caller having a reference to the /// assembly that defines the item being sought and allows the /// NUnit core to inspect assemblies that reference an older /// version of the NUnit framework. /// </summary> public static class Reflect { private static readonly BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; // A zero-length Type array - not provided by System.Type for all CLR versions we support. private static readonly Type[] EmptyTypes = new Type[0]; #region Get Methods of a type /// <summary> /// Examine a fixture type and return an array of methods having a /// particular attribute. The array is order with base methods first. /// </summary> /// <param name="fixtureType">The type to examine</param> /// <param name="attributeType">The attribute Type to look for</param> /// <param name="inherit">Specifies whether to search the fixture type inheritance chain</param> /// <returns>The array of methods found</returns> public static MethodInfo[] GetMethodsWithAttribute(Type fixtureType, Type attributeType, bool inherit) { List<MethodInfo> list = new List<MethodInfo>(); #if NETCF if (fixtureType.IsGenericTypeDefinition) { var genArgs = fixtureType.GetGenericArguments(); Type[] args = new Type[genArgs.Length]; for (int ix = 0; ix < genArgs.Length; ++ix) { args[ix] = typeof(object); } fixtureType = fixtureType.MakeGenericType(args); } #endif var flags = AllMembers | (inherit ? BindingFlags.FlattenHierarchy : BindingFlags.DeclaredOnly); foreach (MethodInfo method in fixtureType.GetMethods(flags)) { if (method.IsDefined(attributeType, inherit)) list.Add(method); } list.Sort(new BaseTypesFirstComparer()); return list.ToArray(); } private class BaseTypesFirstComparer : IComparer<MethodInfo> { public int Compare(MethodInfo m1, MethodInfo m2) { if (m1 == null || m2 == null) return 0; Type m1Type = m1.DeclaringType; Type m2Type = m2.DeclaringType; if ( m1Type == m2Type ) return 0; if ( m1Type.IsAssignableFrom(m2Type) ) return -1; return 1; } } /// <summary> /// Examine a fixture type and return true if it has a method with /// a particular attribute. /// </summary> /// <param name="fixtureType">The type to examine</param> /// <param name="attributeType">The attribute Type to look for</param> /// <returns>True if found, otherwise false</returns> public static bool HasMethodWithAttribute(Type fixtureType, Type attributeType) { #if NETCF if (fixtureType.ContainsGenericParameters) return false; #endif foreach (MethodInfo method in fixtureType.GetMethods(AllMembers | BindingFlags.FlattenHierarchy)) { if (method.IsDefined(attributeType, false)) return true; } return false; } #endregion #region Invoke Constructors /// <summary> /// Invoke the default constructor on a Type /// </summary> /// <param name="type">The Type to be constructed</param> /// <returns>An instance of the Type</returns> public static object Construct(Type type) { ConstructorInfo ctor = type.GetConstructor(EmptyTypes); if (ctor == null) throw new InvalidTestFixtureException(type.FullName + " does not have a default constructor"); return ctor.Invoke(null); } /// <summary> /// Invoke a constructor on a Type with arguments /// </summary> /// <param name="type">The Type to be constructed</param> /// <param name="arguments">Arguments to the constructor</param> /// <returns>An instance of the Type</returns> public static object Construct(Type type, object[] arguments) { if (arguments == null) return Construct(type); Type[] argTypes = GetTypeArray(arguments); ConstructorInfo ctor = type.GetConstructor(argTypes); if (ctor == null) throw new InvalidTestFixtureException(type.FullName + " does not have a suitable constructor"); return ctor.Invoke(arguments); } /// <summary> /// Returns an array of types from an array of objects. /// Used because the compact framework doesn't support /// Type.GetTypeArray() /// </summary> /// <param name="objects">An array of objects</param> /// <returns>An array of Types</returns> private static Type[] GetTypeArray(object[] objects) { Type[] types = new Type[objects.Length]; int index = 0; foreach (object o in objects) types[index++] = o.GetType(); return types; } #endregion #region Invoke Methods /// <summary> /// Invoke a parameterless method returning void on an object. /// </summary> /// <param name="method">A MethodInfo for the method to be invoked</param> /// <param name="fixture">The object on which to invoke the method</param> public static object InvokeMethod( MethodInfo method, object fixture ) { return InvokeMethod(method, fixture, null); } /// <summary> /// Invoke a method, converting any TargetInvocationException to an NUnitException. /// </summary> /// <param name="method">A MethodInfo for the method to be invoked</param> /// <param name="fixture">The object on which to invoke the method</param> /// <param name="args">The argument list for the method</param> /// <returns>The return value from the invoked method</returns> public static object InvokeMethod( MethodInfo method, object fixture, params object[] args ) { if(method != null) { try { return method.Invoke(fixture, args); } catch (Exception e) { #if !PORTABLE // No need to wrap or rethrow ThreadAbortException if (!(e is System.Threading.ThreadAbortException)) #endif { if (e is TargetInvocationException) throw new NUnitException("Rethrown", e.InnerException); else throw new NUnitException("Rethrown", e); } } } return null; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Events; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Events; namespace DynamoAutomation { /// <summary> /// Implements the Revit add-in interface IExternalApplication. /// </summary> [Transaction(TransactionMode.ReadOnly)] [Regeneration(RegenerationOption.Manual)] [Journaling(JournalingMode.NoCommandData)] public class Swallower : IExternalApplication { #region private properties private static bool journalModeIsPermissive; private static bool journalChecked; private static UIControlledApplication uiCtrlApp; private static EventHandler<DocumentOpeningEventArgs> openingHandler; private static EventHandler<DocumentClosingEventArgs> closingHandler; private static EventHandler<DialogBoxShowingEventArgs> dialogHandler; private static EventHandler<FailuresProcessingEventArgs> warningsHandler; private static int popupsNum; private static int warningsNum; private static string currDocName; private static string reportPath; #endregion /// <summary> /// Implements the external application which should be called when /// Revit starts before a file or default template is actually loaded. /// </summary> /// <param name="application">The controlled application.</param> /// <returns>Return the status of the external application.</returns> public Result OnStartup(UIControlledApplication application) { try { journalChecked = false; journalModeIsPermissive = false; uiCtrlApp = application; // This handler will be disconnected at the end of the opening trigger openingHandler = new EventHandler<DocumentOpeningEventArgs>(ActivateSwallowers); application.ControlledApplication.DocumentOpening += openingHandler; string jrnPath = application.ControlledApplication.RecordingJournalFilename; jrnPath.Replace(".txt.", ""); reportPath = jrnPath + "_ErrorReport.txt"; return Result.Succeeded; } catch (Exception ex) { //don't use a dialog to display these, we might block those! :) System.Windows.Forms.MessageBox.Show(ex.ToString(), "DynamoAutomation Error"); return Result.Failed; } } /// <summary> /// Implements the external application which should be called when Revit is about to exit. /// </summary> /// <param name="application">The controlled application.</param> /// <returns>Return the status of the external application.</returns> public Result OnShutdown(UIControlledApplication application) { try { uiCtrlApp.ControlledApplication.DocumentOpening -= openingHandler; if (journalModeIsPermissive) { application.DialogBoxShowing -= dialogHandler; application.ControlledApplication.FailuresProcessing -= warningsHandler; application.ControlledApplication.DocumentClosing -= closingHandler; } return Result.Succeeded; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString(), "DynamoAutomation Error"); return Result.Failed; } } /// <summary> /// Assigns event handlers for DialogBoxShowing and FailuresProcessing if we're in debug mode /// journal playback /// </summary> private void ActivateSwallowers(object o, DocumentOpeningEventArgs e) { currDocName = Path.GetFileNameWithoutExtension(e.PathName); warningsNum = 0; popupsNum = 0; // And we'll only want to add them if the journal is actually running in permissive mode if (!journalChecked && CheckJournalingMode() ) { dialogHandler = new EventHandler<DialogBoxShowingEventArgs>(DismissAllDialogs); warningsHandler = new EventHandler<FailuresProcessingEventArgs>(DismissAllWarnings); closingHandler = new EventHandler<DocumentClosingEventArgs >(PopulateReport); uiCtrlApp.DialogBoxShowing += dialogHandler; uiCtrlApp.ControlledApplication.FailuresProcessing += warningsHandler; uiCtrlApp.ControlledApplication.DocumentClosing += closingHandler; journalChecked = true; } } /// <summary> /// Checks if Revit is run in journal playback mode and permissive journaling is activated /// </summary> private bool CheckJournalingMode() { string recJournal = uiCtrlApp.ControlledApplication.RecordingJournalFilename; // https://msdn.microsoft.com/en-us/library/ms182334.aspx // We'll want to use StreamReader for speed, but need to be careful regarding // shared access, hence opening via FileStream */ Stream stream = null; try { stream = new FileStream(recJournal, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using (var reader = new StreamReader(stream, Encoding.Unicode) ) { stream = null; string line = null; while (!reader.EndOfStream) { line = reader.ReadLine(); if (line.Contains("Jrn.Directive \"DebugMode\"") ) { // Set this flag so we know we should remove event handlers OnShutdown journalModeIsPermissive = true; return true; } } return false; } } finally { if(stream != null) stream.Dispose(); } } private void PopulateReport(object o, DocumentClosingEventArgs e) { PopulateReport(); } private void PopulateReport() { string line; if (warningsNum != 0 || popupsNum != 0) { line = String.Format("Document '{0}' contained {1} warnings and {2} popups{3}", currDocName, warningsNum, popupsNum, Environment.NewLine); } else { line = String.Format("Document '{0}' contained NO warnings & popups{1}", currDocName, Environment.NewLine); } try { File.AppendAllText(reportPath, line); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString(), "DynamoAutomation Error"); } } /// <summary> /// Will dismiss all dialogs /// </summary> private void DismissAllDialogs(object o, DialogBoxShowingEventArgs e) { e.OverrideResult(1); popupsNum += 1; } /// <summary> /// Will dismiss all warnings /// </summary> private void DismissAllWarnings(object o, FailuresProcessingEventArgs e) { FailuresAccessor fa = e.GetFailuresAccessor(); IList<FailureMessageAccessor> failList = fa.GetFailureMessages(); // Inside event handler, get all warnings // warningsNum += failList.Count; foreach (FailureMessageAccessor failure in failList) { fa.DeleteWarning(failure); warningsNum += 1; } } } }
// 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.ServiceModel.Channels { using System; using System.ServiceModel.Description; using Microsoft.Xml; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.ServiceModel.Dispatcher; using System.Net.Security; using System.Text; public sealed class SymmetricSecurityBindingElement : SecurityBindingElement, IPolicyExportExtension { private MessageProtectionOrder _messageProtectionOrder; private SecurityTokenParameters _protectionTokenParameters; private bool _requireSignatureConfirmation; private SymmetricSecurityBindingElement(SymmetricSecurityBindingElement elementToBeCloned) : base(elementToBeCloned) { _messageProtectionOrder = elementToBeCloned._messageProtectionOrder; if (elementToBeCloned._protectionTokenParameters != null) _protectionTokenParameters = (SecurityTokenParameters)elementToBeCloned._protectionTokenParameters.Clone(); _requireSignatureConfirmation = elementToBeCloned._requireSignatureConfirmation; } public SymmetricSecurityBindingElement() : this((SecurityTokenParameters)null) { // empty } public SymmetricSecurityBindingElement(SecurityTokenParameters protectionTokenParameters) : base() { _messageProtectionOrder = SecurityBindingElement.defaultMessageProtectionOrder; _requireSignatureConfirmation = SecurityBindingElement.defaultRequireSignatureConfirmation; _protectionTokenParameters = protectionTokenParameters; } public bool RequireSignatureConfirmation { get { return _requireSignatureConfirmation; } set { _requireSignatureConfirmation = value; } } public MessageProtectionOrder MessageProtectionOrder { get { return _messageProtectionOrder; } set { if (!MessageProtectionOrderHelper.IsDefined(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); _messageProtectionOrder = value; } } public SecurityTokenParameters ProtectionTokenParameters { get { return _protectionTokenParameters; } set { _protectionTokenParameters = value; } } internal override ISecurityCapabilities GetIndividualISecurityCapabilities() { bool supportsServerAuthentication = false; bool supportsClientAuthentication; bool supportsClientWindowsIdentity; GetSupportingTokensCapabilities(out supportsClientAuthentication, out supportsClientWindowsIdentity); if (ProtectionTokenParameters != null) { supportsClientAuthentication = supportsClientAuthentication || ProtectionTokenParameters.SupportsClientAuthentication; supportsClientWindowsIdentity = supportsClientWindowsIdentity || ProtectionTokenParameters.SupportsClientWindowsIdentity; if (ProtectionTokenParameters.HasAsymmetricKey) { supportsServerAuthentication = ProtectionTokenParameters.SupportsClientAuthentication; } else { supportsServerAuthentication = ProtectionTokenParameters.SupportsServerAuthentication; } } return new SecurityCapabilities(supportsClientAuthentication, supportsServerAuthentication, supportsClientWindowsIdentity, ProtectionLevel.EncryptAndSign, ProtectionLevel.EncryptAndSign); } internal override bool SessionMode { get { SecureConversationSecurityTokenParameters secureConversationTokenParameters = this.ProtectionTokenParameters as SecureConversationSecurityTokenParameters; if (secureConversationTokenParameters != null) return secureConversationTokenParameters.RequireCancellation; else return false; } } internal override bool SupportsDuplex { get { return this.SessionMode; } } internal override bool SupportsRequestReply { get { return true; } } public override void SetKeyDerivation(bool requireDerivedKeys) { base.SetKeyDerivation(requireDerivedKeys); if (_protectionTokenParameters != null) _protectionTokenParameters.RequireDerivedKeys = requireDerivedKeys; } internal override bool IsSetKeyDerivation(bool requireDerivedKeys) { if (!base.IsSetKeyDerivation(requireDerivedKeys)) return false; if (_protectionTokenParameters != null && _protectionTokenParameters.RequireDerivedKeys != requireDerivedKeys) return false; return true; } protected override IChannelFactory<TChannel> BuildChannelFactoryCore<TChannel>(BindingContext context) { throw new NotImplementedException(); } public override T GetProperty<T>(BindingContext context) { if (context == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); if (typeof(T) == typeof(ChannelProtectionRequirements)) { AddressingVersion addressing = MessageVersion.Default.Addressing; #pragma warning disable 56506 MessageEncodingBindingElement encoding = context.Binding.Elements.Find<MessageEncodingBindingElement>(); if (encoding != null) { addressing = encoding.MessageVersion.Addressing; } ChannelProtectionRequirements myRequirements = base.GetProtectionRequirements(addressing, ProtectionLevel.EncryptAndSign); myRequirements.Add(context.GetInnerProperty<ChannelProtectionRequirements>() ?? new ChannelProtectionRequirements()); return (T)(object)myRequirements; } else { return base.GetProperty<T>(context); } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine(base.ToString()); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "MessageProtectionOrder: {0}", _messageProtectionOrder.ToString())); sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "RequireSignatureConfirmation: {0}", _requireSignatureConfirmation.ToString())); sb.Append("ProtectionTokenParameters: "); if (_protectionTokenParameters != null) sb.AppendLine(_protectionTokenParameters.ToString().Trim().Replace("\n", "\n ")); else sb.AppendLine("null"); return sb.ToString().Trim(); } public override BindingElement Clone() { return new SymmetricSecurityBindingElement(this); } void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context) { //SecurityBindingElement.ExportPolicy(exporter, context); throw new NotImplementedException(); } } }
// <copyright file="FileSystemSearchTests.cs" company="Heleonix - Hennadii Lutsyshyn"> // Copyright (c) 2016-present Heleonix - Hennadii Lutsyshyn. All rights reserved. // Licensed under the MIT license. See LICENSE file in the repository root for full license information. // </copyright> namespace Heleonix.Build.Tests.Tasks { using System.IO; using System.Text.RegularExpressions; using Heleonix.Build.Tasks; using Heleonix.Build.Tests.Common; using Heleonix.Testing.NUnit.Aaa; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NUnit.Framework; using static Heleonix.Testing.NUnit.Aaa.AaaSpec; /// <summary> /// Tests the <see cref="FileSystemSearch"/>. /// </summary> [ComponentTest(Type = typeof(FileSystemSearch))] public static class FileSystemSearchTests { /// <summary> /// Tests the <see cref="FileSystemSearch.ExecuteInternal"/>. /// </summary> [MemberTest(Name = nameof(FileSystemSearch.Execute))] public static void Execute() { FileSystemSearch task = null; var succeeded = false; ITaskItem startDir = null; string direction = null; string types = null; string pathRegExp = null; string pathRegExpOptions = null; string contentRegExp = null; string contentRegExpOptions = null; string rootDir = null; Act(() => { task = new FileSystemSearch { BuildEngine = new TestBuildEngine(), StartDir = startDir, Direction = direction, Types = types, PathRegExp = pathRegExp, PathRegExpOptions = pathRegExpOptions, ContentRegExp = contentRegExp, ContentRegExpOptions = contentRegExpOptions, }; succeeded = task.Execute(); }); When("directories exist", () => { Arrange(() => { rootDir = PathHelper.GetRandomFileInCurrentDir(); Directory.CreateDirectory(Path.Combine(rootDir, "1", "11", "111")); using (var f = File.CreateText(Path.Combine(rootDir, "1", "1a.txt"))) { f.Write("1a"); } using (var f = File.CreateText(Path.Combine(rootDir, "1", "1b.txt"))) { f.Write("1b"); } using (var f = File.CreateText(Path.Combine(rootDir, "1", "11", "111", "111aaa.txt"))) { f.Write("111aaa"); } using (var f = File.CreateText(Path.Combine(rootDir, "1", "11", "111", "111bbb.txt"))) { f.Write("111bbb"); } Directory.CreateDirectory(Path.Combine(rootDir, "2", "22", "222")); using (var f = File.CreateText(Path.Combine(rootDir, "2", "2a.txt"))) { f.Write("2a"); } using (var f = File.CreateText(Path.Combine(rootDir, "2", "2b.txt"))) { f.Write("2b"); } using (var f = File.CreateText(Path.Combine(rootDir, "2", "22", "222", "222aaa.txt"))) { f.Write("222aaa"); } using (var f = File.CreateText(Path.Combine(rootDir, "2", "22", "222", "222bbb.txt"))) { f.Write("222bbb"); } }); Teardown(() => { Directory.Delete(rootDir, true); }); And("start directory exist", () => { Arrange(() => { startDir = new TaskItem(rootDir); }); And("type of items to search is not specified", () => { And("search direction is not specified", () => { And("search options are not specified", () => { Should("find all directories and files", () => { Assert.That(succeeded, Is.True); Assert.That(task.FoundFiles, Has.Length.EqualTo(8)); Assert.That(task.FoundDirs, Has.Length.EqualTo(7)); Assert.That(task.FoundItems, Has.Length.EqualTo(15)); }); }); And("search options are specified", () => { Arrange(() => { pathRegExp = @"^.*aaa`.txt$"; pathRegExpOptions = RegexOptions.IgnoreCase.ToString(); contentRegExp = ".*111aaa.*"; contentRegExpOptions = RegexOptions.IgnoreCase.ToString(); }); Teardown(() => { pathRegExp = null; pathRegExpOptions = null; contentRegExp = null; contentRegExpOptions = null; }); Should("find the only 111aaa.txt file", () => { Assert.That(succeeded, Is.True); Assert.That(task.FoundFiles, Has.Length.EqualTo(1)); Assert.That(task.FoundFiles[0].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "1", "11", "111", "111aaa.txt"))); Assert.That(task.FoundDirs, Has.Length.EqualTo(0)); Assert.That(task.FoundItems, Has.Length.EqualTo(1)); }); }); }); And("search direction is Down", () => { Arrange(() => { direction = "Down"; }); Teardown(() => { direction = null; }); Should("find all directories and files", () => { Assert.That(succeeded, Is.True); Assert.That(task.FoundFiles, Has.Length.EqualTo(8)); Assert.That(task.FoundDirs, Has.Length.EqualTo(7)); Assert.That(task.FoundItems, Has.Length.EqualTo(15)); }); }); And("search direction is Up", () => { Arrange(() => { direction = "Up"; startDir = new TaskItem(Path.Combine(rootDir, "1", "11", "111")); }); Teardown(() => { direction = null; startDir = null; }); And("search options are specified", () => { Arrange(() => { pathRegExp = @"(^.*/111$)|(^.*/111[a-z]+`.txt$)"; }); Teardown(() => { pathRegExp = null; }); Should("find all directories and files", () => { Assert.That(succeeded, Is.True); Assert.That(task.FoundFiles, Has.Length.EqualTo(2)); Assert.That(task.FoundDirs, Has.Length.EqualTo(1)); Assert.That(task.FoundItems, Has.Length.EqualTo(3)); }); }); And("search options are not specified", () => { Arrange(() => { pathRegExp = null; }); Should("find all directories and files", () => { Assert.That(succeeded, Is.True); Assert.That( task.FoundFiles[0].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "1", "11", "111", "111aaa.txt"))); Assert.That( task.FoundFiles[1].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "1", "11", "111", "111bbb.txt"))); Assert.That( task.FoundFiles[2].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "1", "1a.txt"))); Assert.That( task.FoundFiles[3].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "1", "1b.txt"))); Assert.That( task.FoundDirs[0].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "1", "11", "111"))); Assert.That( task.FoundDirs[1].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "1", "11"))); Assert.That( task.FoundDirs[2].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "1"))); Assert.That( task.FoundDirs[3].ItemSpec, Is.EqualTo(Path.Combine(rootDir, "2"))); Assert.That(task.FoundItems, Has.Length.GreaterThan(8)); }); }); }); }); And("type of items to search is Files", () => { Arrange(() => { types = "Files"; }); Should("find all files", () => { Assert.That(succeeded, Is.True); Assert.That(task.FoundFiles, Has.Length.EqualTo(8)); Assert.That(task.FoundDirs, Has.Length.EqualTo(0)); Assert.That(task.FoundItems, Has.Length.EqualTo(8)); }); }); And("type of items to search is Directories", () => { Arrange(() => { types = "Directories"; }); Should("find all directories", () => { Assert.That(succeeded, Is.True); Assert.That(task.FoundFiles, Has.Length.EqualTo(0)); Assert.That(task.FoundDirs, Has.Length.EqualTo(7)); Assert.That(task.FoundItems, Has.Length.EqualTo(7)); }); }); And("type of items to search is All", () => { Arrange(() => { types = "All"; }); Should("find all directories and files", () => { Assert.That(succeeded, Is.True); Assert.That(task.FoundFiles, Has.Length.EqualTo(8)); Assert.That(task.FoundDirs, Has.Length.EqualTo(7)); Assert.That(task.FoundItems, Has.Length.EqualTo(15)); }); }); }); And("start directory does not exist", () => { Arrange(() => { startDir = new TaskItem(Path.Combine(rootDir, Path.GetRandomFileName())); }); Should("succeed fithout any found items", () => { Assert.That(succeeded, Is.True); Assert.That(task.FoundFiles, Has.Length.Zero); Assert.That(task.FoundDirs, Has.Length.Zero); Assert.That(task.FoundItems, Has.Length.Zero); }); }); }); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using _safe_project_name_.Areas.HelpPage.ModelDescriptions; using _safe_project_name_.Areas.HelpPage.Models; namespace _safe_project_name_.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// ZlibCodec.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-November-03 15:40:51> // // ------------------------------------------------------------------ // // This module defines a Codec for ZLIB compression and // decompression. This code extends code that was based the jzlib // implementation of zlib, but this code is completely novel. The codec // class is new, and encapsulates some behaviors that are new, and some // that were present in other classes in the jzlib code base. In // keeping with the license for jzlib, the copyright to the jzlib code // is included below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; using Interop=System.Runtime.InteropServices; namespace EpLibrary.cs { /// <summary> /// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951). /// </summary> /// /// <remarks> /// This class compresses and decompresses data according to the Deflate algorithm /// and optionally, the ZLIB format, as documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see /// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>. /// </remarks> [Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000D")] [Interop.ComVisible(true)] #if !NETCF [Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)] #endif sealed public class ZlibCodec { /// <summary> /// The buffer from which data is taken. /// </summary> public byte[] InputBuffer; /// <summary> /// An index into the InputBuffer array, indicating where to start reading. /// </summary> public int NextIn; /// <summary> /// The number of bytes available in the InputBuffer, starting at NextIn. /// </summary> /// <remarks> /// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesIn; /// <summary> /// Total number of bytes read so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesIn; /// <summary> /// Buffer to store output data. /// </summary> public byte[] OutputBuffer; /// <summary> /// An index into the OutputBuffer array, indicating where to start writing. /// </summary> public int NextOut; /// <summary> /// The number of bytes available in the OutputBuffer, starting at NextOut. /// </summary> /// <remarks> /// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesOut; /// <summary> /// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesOut; /// <summary> /// used for diagnostics, when something goes wrong! /// </summary> public System.String Message; internal DeflateManager dstate; internal InflateManager istate; internal uint _Adler32; /// <summary> /// The compression level to use in this codec. Useful only in compression mode. /// </summary> public CompressionLevel CompressLevel = CompressionLevel.Default; /// <summary> /// The number of Window Bits to use. /// </summary> /// <remarks> /// This gauges the size of the sliding window, and hence the /// compression effectiveness as well as memory consumption. It's best to just leave this /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies /// a 32k window. /// </remarks> public int WindowBits = ZlibConstants.WindowBitsDefault; /// <summary> /// The compression strategy to use. /// </summary> /// <remarks> /// This is only effective in compression. The theory offered by ZLIB is that different /// strategies could potentially produce significant differences in compression behavior /// for different data sets. Unfortunately I don't have any good recommendations for how /// to set it differently. When I tested changing the strategy I got minimally different /// compression performance. It's best to leave this property alone if you don't have a /// good feel for it. Or, you may want to produce a test harness that runs through the /// different strategy options and evaluates them on different file types. If you do that, /// let me know your results. /// </remarks> public CompressionStrategy Strategy = CompressionStrategy.Default; /// <summary> /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this. /// </summary> public int Adler32 { get { return (int)_Adler32; } } /// <summary> /// Create a ZlibCodec. /// </summary> /// <remarks> /// If you use this default constructor, you will later have to explicitly call /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress /// or decompress. /// </remarks> public ZlibCodec() { } /// <summary> /// Create a ZlibCodec that either compresses or decompresses. /// </summary> /// <param name="mode"> /// Indicates whether the codec should compress (deflate) or decompress (inflate). /// </param> public ZlibCodec(CompressionMode mode) { if (mode == CompressionMode.Compress) { int rc = InitializeDeflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate."); } else if (mode == CompressionMode.Decompress) { int rc = InitializeInflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate."); } else throw new ZlibException("Invalid ZlibStreamFlavor."); } /// <summary> /// Initialize the inflation state. /// </summary> /// <remarks> /// It is not necessary to call this before using the ZlibCodec to inflate data; /// It is implicitly called when you call the constructor. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate() { return InitializeInflate(this.WindowBits); } /// <summary> /// Initialize the inflation state with an explicit flag to /// govern the handling of RFC1950 header bytes. /// </summary> /// /// <remarks> /// By default, the ZLIB header defined in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If /// you want to read a zlib stream you should specify true for /// expectRfc1950Header. If you have a deflate stream, you will want to specify /// false. It is only necessary to invoke this initializer explicitly if you /// want to specify false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte /// pair when reading the stream of data to be inflated.</param> /// /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(bool expectRfc1950Header) { return InitializeInflate(this.WindowBits, expectRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for inflation, with the specified number of window bits. /// </summary> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeInflate(int windowBits) { this.WindowBits = windowBits; return InitializeInflate(windowBits, true); } /// <summary> /// Initialize the inflation state with an explicit flag to govern the handling of /// RFC1950 header bytes. /// </summary> /// /// <remarks> /// If you want to read a zlib stream you should specify true for /// expectRfc1950Header. In this case, the library will expect to find a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or /// GZIP stream, which does not have such a header, you will want to specify /// false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading /// the stream of data to be inflated.</param> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(int windowBits, bool expectRfc1950Header) { this.WindowBits = windowBits; if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); istate = new InflateManager(expectRfc1950Header); return istate.Initialize(this, windowBits); } /// <summary> /// Inflate the data in the InputBuffer, placing the result in the OutputBuffer. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and /// AvailableBytesOut before calling this method. /// </remarks> /// <example> /// <code> /// private void InflateBuffer() /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec decompressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length); /// MemoryStream ms = new MemoryStream(DecompressedBytes); /// /// int rc = decompressor.InitializeInflate(); /// /// decompressor.InputBuffer = CompressedBytes; /// decompressor.NextIn = 0; /// decompressor.AvailableBytesIn = CompressedBytes.Length; /// /// decompressor.OutputBuffer = buffer; /// /// // pass 1: inflate /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("inflating: " + decompressor.Message); /// /// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("inflating: " + decompressor.Message); /// /// if (buffer.Length - decompressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// decompressor.EndInflate(); /// } /// /// </code> /// </example> /// <param name="flush">The flush to use when inflating.</param> /// <returns>Z_OK if everything goes well.</returns> public int Inflate(FlushType flush) { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Inflate(flush); } /// <summary> /// Ends an inflation session. /// </summary> /// <remarks> /// Call this after successively calling Inflate(). This will cause all buffers to be flushed. /// After calling this you cannot call Inflate() without a intervening call to one of the /// InitializeInflate() overloads. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int EndInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); int ret = istate.End(); istate = null; return ret; } /// <summary> /// I don't know what this does! /// </summary> /// <returns>Z_OK if everything goes well.</returns> public int SyncInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Sync(); } /// <summary> /// Initialize the ZlibCodec for deflation operation. /// </summary> /// <remarks> /// The codec will use the MAX window bits and the default level of compression. /// </remarks> /// <example> /// <code> /// int bufferSize = 40000; /// byte[] CompressedBytes = new byte[bufferSize]; /// byte[] DecompressedBytes = new byte[bufferSize]; /// /// ZlibCodec compressor = new ZlibCodec(); /// /// compressor.InitializeDeflate(CompressionLevel.Default); /// /// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress); /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = compressor.InputBuffer.Length; /// /// compressor.OutputBuffer = CompressedBytes; /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = CompressedBytes.Length; /// /// while (compressor.TotalBytesIn != TextToCompress.Length &amp;&amp; compressor.TotalBytesOut &lt; bufferSize) /// { /// compressor.Deflate(FlushType.None); /// } /// /// while (true) /// { /// int rc= compressor.Deflate(FlushType.Finish); /// if (rc == ZlibConstants.Z_STREAM_END) break; /// } /// /// compressor.EndDeflate(); /// /// </code> /// </example> /// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns> public int InitializeDeflate() { return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified /// CompressionLevel. It will emit a ZLIB stream as it compresses. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level) { this.CompressLevel = level; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the explicit flag governing whether to emit an RFC1950 header byte pair. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified CompressionLevel. /// If you want to generate a zlib stream, you should specify true for /// wantRfc1950Header. In this case, the library will emit a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header) { this.CompressLevel = level; return _InternalInitializeDeflate(wantRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the specified number of window bits. /// </summary> /// <remarks> /// The codec will use the specified number of window bits and the specified CompressionLevel. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified /// CompressionLevel, the specified number of window bits, and the explicit flag /// governing whether to emit an RFC1950 header byte pair. /// </summary> /// /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(wantRfc1950Header); } private int _InternalInitializeDeflate(bool wantRfc1950Header) { if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate()."); dstate = new DeflateManager(); dstate.WantRfc1950HeaderBytes = wantRfc1950Header; return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy); } /// <summary> /// Deflate one batch of data. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer before calling this method. /// </remarks> /// <example> /// <code> /// private void DeflateBuffer(CompressionLevel level) /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec compressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length); /// MemoryStream ms = new MemoryStream(); /// /// int rc = compressor.InitializeDeflate(level); /// /// compressor.InputBuffer = UncompressedBytes; /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = UncompressedBytes.Length; /// /// compressor.OutputBuffer = buffer; /// /// // pass 1: deflate /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("deflating: " + compressor.Message); /// /// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("deflating: " + compressor.Message); /// /// if (buffer.Length - compressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// compressor.EndDeflate(); /// /// ms.Seek(0, SeekOrigin.Begin); /// CompressedBytes = new byte[compressor.TotalBytesOut]; /// ms.Read(CompressedBytes, 0, CompressedBytes.Length); /// } /// </code> /// </example> /// <param name="flush">whether to flush all data as you deflate. Generally you will want to /// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to /// flush everything. /// </param> /// <returns>Z_OK if all goes well.</returns> public int Deflate(FlushType flush) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.Deflate(flush); } /// <summary> /// End a deflation session. /// </summary> /// <remarks> /// Call this after making a series of one or more calls to Deflate(). All buffers are flushed. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public int EndDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this) //int ret = dstate.End(); dstate = null; return ZlibConstants.Z_OK; //ret; } /// <summary> /// Reset a codec for another deflation session. /// </summary> /// <remarks> /// Call this to reset the deflation state. For example if a thread is deflating /// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first /// block and before the next Deflate(None) of the second block. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public void ResetDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); dstate.Reset(); } /// <summary> /// Set the CompressionStrategy and CompressionLevel for a deflation session. /// </summary> /// <param name="level">the level of compression to use.</param> /// <param name="strategy">the strategy to use for compression.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.SetParams(level, strategy); } /// <summary> /// Set the dictionary to be used for either Inflation or Deflation. /// </summary> /// <param name="dictionary">The dictionary bytes to use.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDictionary(byte[] dictionary) { if (istate != null) return istate.SetDictionary(dictionary); if (dstate != null) return dstate.SetDictionary(dictionary); throw new ZlibException("No Inflate or Deflate state!"); } // Flush as much pending output as possible. All deflate() output goes // through this function so some applications may wish to modify it // to avoid allocating a large strm->next_out buffer and copying into it. // (See also read_buf()). internal void flush_pending() { int len = dstate.pendingCount; if (len > AvailableBytesOut) len = AvailableBytesOut; if (len == 0) return; if (dstate.pending.Length <= dstate.nextPending || OutputBuffer.Length <= NextOut || dstate.pending.Length < (dstate.nextPending + len) || OutputBuffer.Length < (NextOut + len)) { throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})", dstate.pending.Length, dstate.pendingCount)); } Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len); NextOut += len; dstate.nextPending += len; TotalBytesOut += len; AvailableBytesOut -= len; dstate.pendingCount -= len; if (dstate.pendingCount == 0) { dstate.nextPending = 0; } } // Read a new buffer from the current input stream, update the adler32 // and total number of bytes read. All deflate() input goes through // this function so some applications may wish to modify it to avoid // allocating a large strm->next_in buffer and copying from it. // (See also flush_pending()). internal int read_buf(byte[] buf, int start, int size) { int len = AvailableBytesIn; if (len > size) len = size; if (len == 0) return 0; AvailableBytesIn -= len; if (dstate.WantRfc1950HeaderBytes) { _Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len); } Array.Copy(InputBuffer, NextIn, buf, start, len); NextIn += len; TotalBytesIn += len; return len; } } }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGJustifyContentTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGJustifyContentTest { [Test] public void Test_justify_content_row_flex_start() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(20f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(92f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(82f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(72f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_row_flex_end() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.JustifyContent = YogaJustify.FlexEnd; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(72f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(82f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(92f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(20f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_row_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.JustifyContent = YogaJustify.Center; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(36f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(46f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(56f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(56f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(46f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(36f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_row_space_between() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.JustifyContent = YogaJustify.SpaceBetween; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(46f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(92f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(92f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(46f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_row_space_around() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.JustifyContent = YogaJustify.SpaceAround; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(12f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(46f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(80f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(80f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(102f, root_child0.LayoutHeight); Assert.AreEqual(46f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(102f, root_child1.LayoutHeight); Assert.AreEqual(12f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(102f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_column_flex_start() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_column_flex_end() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.FlexEnd; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(72f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(82f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(92f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(72f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(82f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(92f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_column_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(36f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(46f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(56f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(36f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(46f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(56f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_column_space_between() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.SpaceBetween; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(46f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(92f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(46f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(92f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_column_space_around() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.SpaceAround; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(12f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(46f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(80f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(12f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(46f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(80f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_row_min_width_and_margin() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.JustifyContent = YogaJustify.Center; root.MarginLeft = 100; root.MinWidth = 50; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 20; root_child0.Height = 20; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(100f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(50f, root.LayoutWidth); Assert.AreEqual(20f, root.LayoutHeight); Assert.AreEqual(15f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(100f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(50f, root.LayoutWidth); Assert.AreEqual(20f, root.LayoutHeight); Assert.AreEqual(15f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); } [Test] public void Test_justify_content_row_max_width_and_margin() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.JustifyContent = YogaJustify.Center; root.MarginLeft = 100; root.Width = 100; root.MaxWidth = 80; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 20; root_child0.Height = 20; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(100f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(80f, root.LayoutWidth); Assert.AreEqual(20f, root.LayoutHeight); Assert.AreEqual(30f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(100f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(80f, root.LayoutWidth); Assert.AreEqual(20f, root.LayoutHeight); Assert.AreEqual(30f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); } [Test] public void Test_justify_content_column_min_height_and_margin() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.MarginTop = 100; root.MinHeight = 50; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 20; root_child0.Height = 20; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(100f, root.LayoutY); Assert.AreEqual(20f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(15f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(100f, root.LayoutY); Assert.AreEqual(20f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(15f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); } [Test] public void Test_justify_content_colunn_max_height_and_margin() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.MarginTop = 100; root.Height = 100; root.MaxHeight = 80; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 20; root_child0.Height = 20; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(100f, root.LayoutY); Assert.AreEqual(20f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(100f, root.LayoutY); Assert.AreEqual(20f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); } [Test] public void Test_justify_content_column_space_evenly() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.SpaceEvenly; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(18f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(46f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(74f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(18f, root_child0.LayoutY); Assert.AreEqual(102f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(46f, root_child1.LayoutY); Assert.AreEqual(102f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(74f, root_child2.LayoutY); Assert.AreEqual(102f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_row_space_evenly() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.JustifyContent = YogaJustify.SpaceEvenly; root.Width = 102; root.Height = 102; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(26f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(51f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(0f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(77f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(0f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(102f, root.LayoutWidth); Assert.AreEqual(102f, root.LayoutHeight); Assert.AreEqual(77f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(51f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(0f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(26f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(0f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_justify_content_min_width_with_padding_child_width_greater_than_parent() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignContent = YogaAlign.Stretch; root.Width = 1000; root.Height = 1584; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.AlignContent = YogaAlign.Stretch; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexDirection = YogaFlexDirection.Row; root_child0_child0.JustifyContent = YogaJustify.Center; root_child0_child0.AlignContent = YogaAlign.Stretch; root_child0_child0.PaddingLeft = 100; root_child0_child0.PaddingRight = 100; root_child0_child0.MinWidth = 400; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.FlexDirection = YogaFlexDirection.Row; root_child0_child0_child0.AlignContent = YogaAlign.Stretch; root_child0_child0_child0.Width = 300; root_child0_child0_child0.Height = 100; root_child0_child0.Insert(0, root_child0_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(1000f, root.LayoutWidth); Assert.AreEqual(1584f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(1000f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(500f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(100f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(300f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(1000f, root.LayoutWidth); Assert.AreEqual(1584f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(1000f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(500f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(500f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(100f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(300f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0_child0.LayoutHeight); } [Test] public void Test_justify_content_min_width_with_padding_child_width_lower_than_parent() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignContent = YogaAlign.Stretch; root.Width = 1080; root.Height = 1584; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.AlignContent = YogaAlign.Stretch; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexDirection = YogaFlexDirection.Row; root_child0_child0.JustifyContent = YogaJustify.Center; root_child0_child0.AlignContent = YogaAlign.Stretch; root_child0_child0.PaddingLeft = 100; root_child0_child0.PaddingRight = 100; root_child0_child0.MinWidth = 400; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.FlexDirection = YogaFlexDirection.Row; root_child0_child0_child0.AlignContent = YogaAlign.Stretch; root_child0_child0_child0.Width = 199; root_child0_child0_child0.Height = 100; root_child0_child0.Insert(0, root_child0_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(1080f, root.LayoutWidth); Assert.AreEqual(1584f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(1080f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(400f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(101f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(199f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(1080f, root.LayoutWidth); Assert.AreEqual(1584f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(1080f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(680f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(400f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(101f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(199f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0_child0.LayoutHeight); } } }
// 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; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.NodejsTools.Jade { /// <summary> /// A collection of text ranges or objects that implement <seealso cref="ITextRange"/>. /// Ranges must not overlap. Can be sorted by range start positions. Can be searched /// in order to locate range that contains given position or range that starts /// at a given position. The search is a binary search. Collection implements /// <seealso cref="ITextRangeCollection"/> /// </summary> /// <typeparam name="T">A class or an interface that derives from <seealso cref="ITextRange"/></typeparam> [DebuggerDisplay("Count={Count}")] internal class TextRangeCollection<T> : IEnumerable<T>, ITextRangeCollection<T> where T : ITextRange { private static readonly IList<T> _emptyList = Array.Empty<T>(); private List<T> _items = new List<T>(); #region Construction public TextRangeCollection() { } public TextRangeCollection(IEnumerable<T> ranges) { Add(ranges); Sort(); } #endregion #region ITextRange public int Start => this.Count > 0 ? this[0].Start : 0; public int End => this.Count > 0 ? this[this.Count - 1].End : 0; public int Length => this.End - this.Start; public virtual bool Contains(int position) { return TextRange.Contains(this, position); } public void Shift(int offset) { foreach (var ct in this._items) { ct.Shift(offset); } } #endregion #region ITextRangeCollection /// <summary> /// Number of comments in the collection. /// </summary> public int Count => this._items.Count; /// <summary> /// Sorted list of comment tokens in the document. /// </summary> public IList<T> Items => this._items; /// <summary> /// Retrieves Nth item in the collection /// </summary> public T this[int index] { get { return this._items[index]; } } /// <summary> /// Adds item to collection. /// </summary> /// <param name="item">Item to add</param> public virtual void Add(T item) { this._items.Add(item); } /// <summary> /// Add a range of items to the collection /// </summary> /// <param name="items">Items to add</param> public void Add(IEnumerable<T> items) { this._items.AddRange(items); } /// <summary> /// Returns index of item that starts at the given position if exists, -1 otherwise. /// </summary> /// <param name="position">Position in a text buffer</param> /// <returns>Item index or -1 if not found</returns> public virtual int GetItemAtPosition(int position) { if (this.Count == 0) { return -1; } if (position < this[0].Start) { return -1; } if (position >= this[this.Count - 1].End) { return -1; } var min = 0; var max = this.Count - 1; while (min <= max) { var mid = min + (max - min) / 2; var item = this[mid]; if (item.Start == position) { return mid; } if (position < item.Start) { max = mid - 1; } else { min = mid + 1; } } return -1; } /// <summary> /// Returns index of items that contains given position if exists, -1 otherwise. /// </summary> /// <param name="position">Position in a text buffer</param> /// <returns>Item index or -1 if not found</returns> public virtual int GetItemContaining(int position) { if (this.Count == 0) { return -1; } if (position < this[0].Start) { return -1; } if (position > this[this.Count - 1].End) { return -1; } var min = 0; var max = this.Count - 1; while (min <= max) { var mid = min + (max - min) / 2; var item = this[mid]; if (item.Contains(position)) { return mid; } if (mid < this.Count - 1 && item.End <= position && position < this[mid + 1].Start) { return -1; } if (position < item.Start) { max = mid - 1; } else { min = mid + 1; } } return -1; } /// <summary> /// Retrieves first item that is after a given position /// </summary> /// <param name="position">Position in a text buffer</param> /// <returns>Item index or -1 if not found</returns> public virtual int GetFirstItemAfterPosition(int position) { if (this.Count == 0 || position > this[this.Count - 1].End) { return -1; } if (position < this[0].Start) { return 0; } var min = 0; var max = this.Count - 1; while (min <= max) { var mid = min + (max - min) / 2; var item = this[mid]; if (item.Contains(position)) { // Note that there may be multiple items with the same range. // To be sure we do pick the first one, walk back until we include // all elements containing passed position return GetFirstElementContainingPosition(mid, position); } if (mid > 0 && this[mid - 1].End <= position && item.Start >= position) { return mid; } if (position < item.Start) { max = mid - 1; } else { min = mid + 1; } } return -1; } private int GetFirstElementContainingPosition(int index, int position) { for (var i = index - 1; i >= 0; i--) { var item = this[i]; if (!item.Contains(position)) { index = i + 1; break; } else if (i == 0) { return 0; } } return index; } // assuming the item at index already contains the position private int GetLastElementContainingPosition(int index, int position) { for (var i = index; i < this.Count; i++) { var item = this[i]; if (!item.Contains(position)) { return i - 1; } } return this.Count - 1; } /// <summary> /// Retrieves first item that is after a given position /// </summary> /// <param name="position">Position in a text buffer</param> /// <returns>Item index or -1 if not found</returns> public virtual int GetLastItemBeforeOrAtPosition(int position) { if (this.Count == 0 || position < this[0].Start) { return -1; } if (position >= this[this.Count - 1].End) { return this.Count - 1; } var min = 0; var max = this.Count - 1; while (min <= max) { var mid = min + (max - min) / 2; var item = this[mid]; if (item.Contains(position)) { // Note that there may be multiple items with the same range. // To be sure we do pick the first one, walk back until we include // all elements containing passed position return GetLastElementContainingPosition(mid, position); } // position is in between two tokens if (mid > 0 && this[mid - 1].End <= position && item.Start >= position) { return mid - 1; } if (position < item.Start) { max = mid - 1; } else { min = mid + 1; } } return -1; } /// <summary> /// Retrieves first item that is before a given position, not intersecting or touching with position /// </summary> /// <param name="position">Position in a text buffer</param> /// <returns>Item index or -1 if not found</returns> public virtual int GetFirstItemBeforePosition(int position) { if (this.Count == 0 || position < this[0].End) { return -1; } var min = 0; var lastIndex = this.Count - 1; var max = this.Count - 1; if (position >= this[lastIndex].End) { return max; } while (min <= max) { var mid = min + (max - min) / 2; var item = this[mid]; if (item.Contains(position)) // guaranteed not to be negative by the first if in this method { return mid - 1; } if (mid < lastIndex && this[mid + 1].Start >= position && item.End <= position) { return mid; } if (position < item.Start) { max = mid - 1; } else { min = mid + 1; } } return -1; } /// <summary> /// Returns index of items that contains given position if exists, -1 otherwise. /// </summary> /// <param name="position">Position in a text buffer</param> /// <returns>Item index or -1 if not found</returns> public virtual IList<int> GetItemsContainingInclusiveEnd(int position) { IList<int> list = new List<int>(); if (this.Count > 0 && position >= this[0].Start && position <= this[this.Count - 1].End) { var min = 0; var max = this.Count - 1; while (min <= max) { var mid = min + (max - min) / 2; var item = this[mid]; if (item.Contains(position) || item.End == position) { list = GetItemsContainingInclusiveEndLinearFromAPoint(mid, position); break; } if (mid < this.Count - 1 && item.End <= position && position < this[mid + 1].Start) { break; } if (position < item.Start) { max = mid - 1; } else { min = mid + 1; } } } return list; } private IList<int> GetItemsContainingInclusiveEndLinearFromAPoint(int startingPoint, int position) { Debug.Assert(this.Count > 0 && startingPoint < this.Count, "Starting point not in token list"); var list = new List<int>(); for (var i = startingPoint; i >= 0; i--) { var item = this[i]; if (item.Contains(position) || item.End == position) { list.Insert(0, i); } else { break; } } if (startingPoint + 1 < this.Count) { for (var i = startingPoint + 1; i < this.Count; i++) { var item = this[i]; if (item.Contains(position) || item.End == position) { list.Add(i); } else { break; } } } return list; } #region ICompositeTextRange /// <summary> /// Shifts all tokens at of below given position by the specified offset. /// </summary> public virtual void ShiftStartingFrom(int position, int offset) { var min = 0; var max = this.Count - 1; if (this.Count == 0) { return; } if (position <= this[0].Start) { // all children are below the shifting point Shift(offset); } else { while (min <= max) { var mid = min + (max - min) / 2; if (this[mid].Contains(position)) { // Found: item contains start position if (this[mid] is ICompositeTextRange composite) { composite.ShiftStartingFrom(position, offset); } else { if (this[mid] is IExpandableTextRange expandable) { expandable.Expand(0, offset); } } // Now shift all remaining siblings that are below this one for (var i = mid + 1; i < this.Count; i++) { this[i].Shift(offset); } return; } else if (mid < this.Count - 1 && this[mid].End <= position && position <= this[mid + 1].Start) { // Between this item and the next sibling. Shift siblings for (var i = mid + 1; i < this.Count; i++) { this[i].Shift(offset); } return; } // Position does not belong to this item and is not between item end and next item start if (position < this[mid].Start) { // Item is after the given position. There may be better items // before this one so limit search to the range ending in this item. max = mid - 1; } else { // Proceed forward min = mid + 1; } } } } #endregion /// <summary> /// Finds out items that overlap a text range /// </summary> /// <param name="range">Text range</param> /// <returns>List of items that overlap the range</returns> public virtual IList<T> ItemsInRange(ITextRange range) { var list = _emptyList; var first = GetItemContaining(range.Start); if (first < 0) { first = GetFirstItemAfterPosition(range.Start); } if (first >= 0) { for (var i = first; i < this.Count; i++) { if (this._items[i].Start >= range.End) { break; } if (TextRange.Intersect(this._items[i], range)) { if (list == _emptyList) { list = new List<T>(); } list.Add(this._items[i]); } } } return list; } /// <summary> /// Removes items that overlap given text range /// </summary> /// <param name="range">Range to remove items in</param> /// <returns>Collection of removed items</returns> public ICollection<T> RemoveInRange(ITextRange range) { return RemoveInRange(range, false); } /// <summary> /// Removes items that overlap given text range /// </summary> /// <param name="range">Range to remove items in</param> /// <param name="inclusiveEnds">True if range end is inclusive</param> /// <returns>Collection of removed items</returns> public virtual ICollection<T> RemoveInRange(ITextRange range, bool inclusiveEnds) { var removed = _emptyList; var first = GetFirstItemAfterPosition(range.Start); if (first < 0 || (!inclusiveEnds && this[first].Start >= range.End) || (inclusiveEnds && this[first].Start > range.End)) { return removed; } var lastCandidate = GetLastItemBeforeOrAtPosition(range.End); var last = -1; if (lastCandidate < first) { lastCandidate = first; } if (!inclusiveEnds && first >= 0) { for (var i = lastCandidate; i >= first; i--) { var item = this._items[i]; if (item.Start < range.End) { last = i; break; } } } else { last = lastCandidate; } if (first >= 0 && last >= 0) { if (removed == _emptyList) { removed = new List<T>(); } for (var i = first; i <= last; i++) { removed.Add(this._items[i]); } this._items.RemoveRange(first, last - first + 1); } return removed; } /// <summary> /// Reflects multiple changes in text to the collection /// Items are expanded and/or shifted according to the changes /// passed. If change affects more than one range then affected items are removed /// </summary> /// <param name="changes">Collection of changes. Must be non-overlapping and sorted by position.</param> /// <param name="startInclusive">True if insertion at range start falls inside the range rather than outside.</param> /// <returns>Collection or removed blocks</returns> public ICollection<T> ReflectTextChange(IEnumerable<TextChangeEventArgs> changes, bool startInclusive = false) { var list = new List<T>(); foreach (var change in changes) { var removed = ReflectTextChange(change.Start, change.OldLength, change.NewLength, startInclusive); list.AddRange(removed); } return list; } /// <summary> /// Reflects changes in text to the collection. Items are expanded and/or /// shifted according to the change. If change affects more than one /// range then affected items are removed. /// </summary> /// <param name="start">Starting position of the change.</param> /// <param name="oldLength">Length of the changed fragment before the change.</param> /// <param name="newLength">Length of text fragment after the change.</param> /// <returns>Collection or removed blocks</returns> public ICollection<T> ReflectTextChange(int start, int oldLength, int newLength) { return ReflectTextChange(start, oldLength, newLength, false); } /// <summary> /// Reflects changes in text to the collection. Items are expanded and/or /// shifted according to the change. If change affects more than one /// range then affected items are removed. /// </summary> /// <param name="start">Starting position of the change.</param> /// <param name="oldLength">Length of the changed fragment before the change.</param> /// <param name="newLength">Length of text fragment after the change.</param> /// <param name="startInclusive">True if insertion at range start falls inside the range rather than outside.</param> /// <returns>Collection or removed blocks</returns> public virtual ICollection<T> ReflectTextChange(int start, int oldLength, int newLength, bool startInclusive) { var indexStart = GetItemContaining(start); var indexEnd = GetItemContaining(start + oldLength); ICollection<T> removed = _emptyList; // Make sure that end of the deleted range is not simply touching start // of an existing range since deleting span that is touching an existing // range does not invalidate the existing range: |__r1__|deleted|__r2__| if (indexEnd > indexStart && indexStart >= 0) { if (this[indexEnd].Start == start + oldLength) { indexEnd--; } } if (indexStart != indexEnd || (indexStart < 0 && indexEnd < 0)) { removed = RemoveInRange(new TextRange(start, oldLength)); } if (this.Count > 0) { var offset = newLength - oldLength; if (removed != _emptyList && removed.Count > 0) { indexStart = GetItemContaining(start); } if (indexStart >= 0) { // If range length is 0 it still contains the position. // Don't try and shrink zero length ranges and instead // shift them. var range = this[indexStart]; if (range.Length == 0 && offset < 0) { range.Shift(offset); } else if (!startInclusive && oldLength == 0 && start == range.Start) { // range.Contains(start) is true but we don't want to expand // the range if change is actually an insert right before // the existing range like in {some text inserted}|__r1__| range.Shift(offset); } else { // In Razor ranges may have end-inclusive set which // may cause us to try and shrink zero-length ranges. if (range.Length > 0 || offset > 0) { // In the case when range is end-inclusive as in Razor, // and change is right at the end of the range, we may end up // trying to shrink range that is really must be deleted. // If offset is bigger than the range length, delete it instead. if ((range is IExpandableTextRange) && (range.Length + offset >= 0)) { var expandable = range as IExpandableTextRange; expandable.Expand(0, offset); } else if (range is ICompositeTextRange) { var composite = range as ICompositeTextRange; composite.ShiftStartingFrom(start, offset); } else { RemoveAt(indexStart); indexStart--; if (removed == _emptyList) { removed = new List<T>(); } removed.Add(range); } } } for (var i = indexStart + 1; i < this.Count; i++) { this[i].Shift(offset); } } else { ShiftStartingFrom(start, offset); } } return removed; } public bool IsEqual(IEnumerable<T> other) { var otherCount = 0; foreach (var item in other) { otherCount++; } if (this.Count != otherCount) { return false; } var i = 0; foreach (var item in other) { if (this[i].Start != item.Start) { return false; } if (this[i].Length != item.Length) { return false; } i++; } return true; } public virtual void RemoveAt(int index) { this.Items.RemoveAt(index); } public virtual void RemoveRange(int startIndex, int count) { this._items.RemoveRange(startIndex, count); } public virtual void Clear() { this._items.Clear(); } public virtual void ReplaceAt(int index, T newItem) { this._items[index] = newItem; } /// <summary> /// Sorts comment collection by token start positions. /// </summary> public void Sort() { this._items.Sort(new RangeItemComparer()); } #endregion /// <summary> /// Returns collection of items in an array /// </summary> public T[] ToArray() { return this._items.ToArray(); } /// <summary> /// Returns collection of items in a list /// </summary> public IList<T> ToList() { var list = new List<T>(); list.AddRange(this._items); return list; } /// <summary> /// Compares two collections and calculates 'changed' range. In case this collection /// or comparand are empty, uses lowerBound and upperBound values as range /// delimiters. Typically lowerBound is 0 and upperBound is lentgh of the file. /// </summary> /// <param name="otherCollection">Collection to compare to</param> public virtual ITextRange RangeDifference(IEnumerable<ITextRange> otherCollection, int lowerBound, int upperBound) { if (otherCollection == null) { return TextRange.FromBounds(lowerBound, upperBound); } var other = new TextRangeCollection<ITextRange>(otherCollection); if (this.Count == 0 && other.Count == 0) { return TextRange.EmptyRange; } if (this.Count == 0) { return TextRange.FromBounds(lowerBound, upperBound); } if (other.Count == 0) { return TextRange.FromBounds(lowerBound, upperBound); } var minCount = Math.Min(this.Count, other.Count); var start = 0; var end = 0; int i, j; for (i = 0; i < minCount; i++) { start = Math.Min(this[i].Start, other[i].Start); if (this[i].Start != other[i].Start || this[i].Length != other[i].Length) { break; } } if (i == minCount) { if (this.Count == other.Count) { return TextRange.EmptyRange; } if (this.Count > other.Count) { return TextRange.FromBounds(Math.Min(upperBound, other[minCount - 1].Start), upperBound); } else { return TextRange.FromBounds(Math.Min(this[minCount - 1].Start, upperBound), upperBound); } } for (i = this.Count - 1, j = other.Count - 1; i >= 0 && j >= 0; i--, j--) { end = Math.Max(this[i].End, other[j].End); if (this[i].Start != other[j].Start || this[i].Length != other[j].Length) { break; } } if (start < end) { return TextRange.FromBounds(start, end); } return TextRange.FromBounds(lowerBound, upperBound); } /// <summary> /// Merges another collection into existing one. Only adds elements /// that are not present in this collection. Both collections must /// be sorted by position for the method to work properly. /// </summary> /// <param name="other"></param> public void Merge(TextRangeCollection<T> other) { var i = 0; var j = 0; var count = this.Count; while (true) { if (i > count - 1) { // Add elements remaining in the other collection for (; j < other.Count; j++) { this.Add(other[j]); } break; } if (j > other.Count - 1) { break; } if (this[i].Start < other[j].Start) { i++; } else if (other[j].Start < this[i].Start) { this.Add(other[j++]); } else { // Element is already in the collection j++; } } this.Sort(); } private class RangeItemComparer : IComparer<T> { #region IComparer<T> Members public int Compare(T x, T y) { return x.Start - y.Start; } #endregion } #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return this._items.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return this._items.GetEnumerator(); } #endregion } }
// Copyright (C) 2014 dot42 // // Original filename: EnumInfo.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Diagnostics; using System.Threading; using Dot42.Collections.Specialized; using Java.Util; using Java.Util.Concurrent; namespace Dot42.Internal { /// <summary> /// Base class for enum implementations /// </summary> [Include(TypeCondition = typeof(System.Enum))] internal abstract class EnumInfo { internal const string EnumInfoFieldName = "info$"; internal const string EnumDefaultFieldName = "default$"; private static readonly ConcurrentHashMap<Type, EnumInfo> enumInfo = new ConcurrentHashMap<Type, EnumInfo>(); private Enum defaultValue; public readonly Type Underlying; private class ValuesByUnderlying { public IntIntMap IntMap; public LongIntMap LongMap; public Enum[] CreatedEnums; } private ValuesByUnderlying valuesByUnderlying; private readonly ArrayList<Enum> values = new ArrayList<Enum>(); private readonly HashMap<string, Enum> valuesByName = new HashMap<string, Enum>(); private HashMap<string, Enum> valuesByUpperCase; public EnumInfo(Type underlying) { Underlying = underlying; } /// <summary> /// Create a new instance with given underlying value /// </summary> [Include(TypeCondition = typeof(System.Enum))] protected virtual Enum Create(int value) { return null; } /// <summary> /// Create a new instance with given underlying value /// </summary> [Include(TypeCondition = typeof(System.Enum))] protected virtual Enum Create(long value) { return null; } [Include(TypeCondition = typeof (System.Enum))] public Enum DefaultValue() { if (defaultValue == null) { defaultValue = Underlying == typeof(long) ? GetValue(0L) : GetValue(0); } return defaultValue; } [Include(TypeCondition = typeof (System.Enum))] public Array Values() { var array = Java.Lang.Reflect.Array.NewInstance(DefaultValue().GetType(), values.Count); return values.ToArray((object[])array); } /// <summary> /// Gets a value with the given underlying value. /// </summary> [Include(TypeCondition = typeof(System.Enum))] public Enum GetValue(int value) { if (value == 0 && defaultValue != null) { return defaultValue; } if (Underlying == typeof(long)) return GetValue((long)value); if (valuesByUnderlying == null) { var lookup = InitializeIntLookup(); Interlocked.CompareExchange(ref valuesByUnderlying, lookup, null); } // to keep this scalable, we use a lock-free implementation while (true) { var vals = valuesByUnderlying; int idx = vals.IntMap.Get(value); if (idx != IntIntMap.NoValue) { if (idx >= 0) return values[idx]; return vals.CreatedEnums[-idx - 1]; } // insert a new value into a new instance var newEnum = Create(value); if (!AddNewIntEnum(vals, value, newEnum)) continue; return newEnum; } } /// <summary> /// Gets a value with the given underlying value. /// </summary> [Include(TypeCondition = typeof(System.Enum))] public Enum GetValue(long value) { if (value == 0 && defaultValue != null) { return defaultValue; } if(Underlying != typeof(long)) return GetValue((int)value); // we set up our own data structure, to make sure // there is no boxing on this possibly heavy used path. // even better might be a long-based hashmap instead of // the binary search. if (valuesByUnderlying == null) { var lookup = InitializeLongLookup(); Interlocked.CompareExchange(ref valuesByUnderlying, lookup, null); } // to keep this scalable, we use a lock-free implementation while (true) { var vals = valuesByUnderlying; int idx = vals.LongMap.Get(value); if (idx != IntIntMap.NoValue) { if (idx >= 0) return values[idx]; return vals.CreatedEnums[-idx - 1]; } // insert a new value into a new instance var newEnum = Create(value); if (!AddNewLongEnum(vals, value, newEnum)) continue; return newEnum; } } /// <summary> /// Gets a value with the given underlying value. /// </summary> [Include(TypeCondition = typeof(System.Enum))] public Enum Parse(string value, bool ignoreCase, bool throwIfNotFound) { HashMap<string, Enum> hashMap; if (ignoreCase) { if (valuesByUpperCase == null) InitializeValuesByUpperCaseName(); value = value.ToUpperInvariant(); hashMap = valuesByUpperCase; Debug.Assert(hashMap != null); } else { hashMap = valuesByName; } var ret = hashMap.Get(value); if(ret == null && throwIfNotFound) throw new ArgumentException(); return ret; } private void InitializeValuesByUpperCaseName() { lock (valuesByName) { valuesByUpperCase = new HashMap<string, Enum>(); foreach (var entry in valuesByName.EntrySet().AsEnumerable()) { valuesByUpperCase.Put(entry.Key.ToUpperInvariant(), entry.Value); } } } /// <summary> /// Add a given instance. This is only called from the static initializer of each enum. /// (and might better be protected and called from the constructor of an enum info) /// </summary> [Include(TypeCondition = typeof(System.Enum))] public void Add(int value, string name, Enum instance) { values.Add(instance); valuesByName.Put(name, instance); } /// <summary> /// Add a given instance. This is only called from the static initializer of each enum. /// (and might better be protected and called from the constructor of an enum info) /// </summary> [Include(TypeCondition = typeof(System.Enum))] public void Add(long value, string name, Enum instance) { values.Add(instance); valuesByName.Put(name, instance); } [Include(TypeCondition = typeof(System.Enum))] public static EnumInfo GetEnumInfo(Type enumType) { var info = enumInfo.Get(enumType); if (info == null) { var infoField = enumType.JavaGetDeclaredField(EnumInfoFieldName); info = (EnumInfo) infoField.Get(null); enumInfo.Put(enumType, info); } return info; } private ValuesByUnderlying InitializeIntLookup() { var vals = new IntIntMap(values.Count + 1, 0.55f); for (int i = 0; i < values.Count; ++i) { var value = values[i].IntValue(); if (vals.Get(value) == IntIntMap.NoValue) vals.Put(value, i); } return new ValuesByUnderlying {IntMap = vals}; } private bool AddNewIntEnum(ValuesByUnderlying vals, int enumValue, Enum newEnum) { // create new data structure var lookup = InitializeIntLookup(); var map = lookup.IntMap; var prevEnums = vals.CreatedEnums; int prevLen; if (prevEnums == null) { prevLen = 0; lookup.CreatedEnums = new[] {newEnum}; } else { prevLen = prevEnums.Length; lookup.CreatedEnums = Arrays.CopyOf(prevEnums, prevLen + 1); lookup.CreatedEnums[prevLen] = newEnum; for (int i = 0; i < prevLen; ++i) { map.Put(prevEnums[i].IntValue(), -i - 1); } } map.Put(enumValue, -prevLen - 1); // only update if no one else was faster. return Interlocked.CompareExchange(ref valuesByUnderlying, lookup, vals) == vals; } private ValuesByUnderlying InitializeLongLookup() { var vals = new LongIntMap(values.Count + 1, 0.55f); for (int i = 0; i < values.Count; ++i) { var value = values[i].LongValue(); if (vals.Get(value) == LongIntMap.NoValue) vals.Put(value, i); } return new ValuesByUnderlying { LongMap = vals }; } private bool AddNewLongEnum(ValuesByUnderlying vals, long enumValue, Enum newEnum) { // create new data structure var lookup = InitializeLongLookup(); var map = lookup.LongMap; var prevEnums = vals.CreatedEnums; int prevLen; if (prevEnums == null) { prevLen = 0; lookup.CreatedEnums = new[] { newEnum }; } else { prevLen = prevEnums.Length; lookup.CreatedEnums = Arrays.CopyOf(prevEnums, prevLen + 1); lookup.CreatedEnums[prevLen] = newEnum; for (int i = 0; i < prevLen; ++i) { map.Put(prevEnums[i].LongValue(), -i - 1); } } map.Put(enumValue, -prevLen - 1); // only update if no one else was faster. return Interlocked.CompareExchange(ref valuesByUnderlying, lookup, vals) == vals; } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.IO; using Xunit; using NLog.Common; using NLog.Config; using NLog.Targets; using System.Threading.Tasks; public class LogManagerTests : NLogTestBase { [Fact] public void GetLoggerTest() { ILogger loggerA = LogManager.GetLogger("A"); ILogger loggerA2 = LogManager.GetLogger("A"); ILogger loggerB = LogManager.GetLogger("B"); Assert.Same(loggerA, loggerA2); Assert.NotSame(loggerA, loggerB); Assert.Equal("A", loggerA.Name); Assert.Equal("B", loggerB.Name); } [Fact] public void GarbageCollectionTest() { string uniqueLoggerName = Guid.NewGuid().ToString(); ILogger loggerA1 = LogManager.GetLogger(uniqueLoggerName); GC.Collect(); ILogger loggerA2 = LogManager.GetLogger(uniqueLoggerName); Assert.Same(loggerA1, loggerA2); } static WeakReference GetWeakReferenceToTemporaryLogger() { string uniqueLoggerName = Guid.NewGuid().ToString(); return new WeakReference(LogManager.GetLogger(uniqueLoggerName)); } [Fact] public void GarbageCollection2Test() { WeakReference wr = GetWeakReferenceToTemporaryLogger(); // nobody's holding a reference to this Logger anymore, so GC.Collect(2) should free it GC.Collect(); Assert.False(wr.IsAlive); } [Fact] public void NullLoggerTest() { ILogger l = LogManager.CreateNullLogger(); Assert.Equal(String.Empty, l.Name); } [Fact] public void ThrowExceptionsTest() { FileTarget ft = new FileTarget(); ft.FileName = ""; // invalid file name SimpleConfigurator.ConfigureForTargetLogging(ft); LogManager.ThrowExceptions = false; LogManager.GetLogger("A").Info("a"); LogManager.ThrowExceptions = true; try { LogManager.GetLogger("A").Info("a"); Assert.True(false, "Should not be reached."); } catch { Assert.True(true); } LogManager.ThrowExceptions = false; } [Fact(Skip="Side effects to other unit tests.")] public void GlobalThresholdTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog globalThreshold='Info'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Assert.Equal(LogLevel.Info, LogManager.GlobalThreshold); // nothing gets logged because of globalThreshold LogManager.GetLogger("A").Debug("xxx"); AssertDebugLastMessage("debug", ""); // lower the threshold LogManager.GlobalThreshold = LogLevel.Trace; LogManager.GetLogger("A").Debug("yyy"); AssertDebugLastMessage("debug", "yyy"); // raise the threshold LogManager.GlobalThreshold = LogLevel.Info; // this should be yyy, meaning that the target is in place // only rules have been modified. LogManager.GetLogger("A").Debug("zzz"); AssertDebugLastMessage("debug", "yyy"); LogManager.Shutdown(); LogManager.Configuration = null; } [Fact] public void DisableLoggingTest_UsingStatement() { const string LoggerConfig = @" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='DisableLoggingTest_UsingStatement_A' levels='Trace' writeTo='debug' /> <logger name='DisableLoggingTest_UsingStatement_B' levels='Error' writeTo='debug' /> </rules> </nlog>"; // Disable/Enable logging should affect ALL the loggers. ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_UsingStatement_A"); ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_UsingStatement_B"); LogManager.Configuration = CreateConfigurationFromString(LoggerConfig); // The starting state for logging is enable. Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); loggerA.Trace("---"); AssertDebugLastMessage("debug", "---"); using (LogManager.DisableLogging()) { Assert.False(LogManager.IsLoggingEnabled()); // The last of LastMessage outside using statement should be returned. loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "---"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "---"); } Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); LogManager.Shutdown(); LogManager.Configuration = null; } [Fact] public void DisableLoggingTest_WithoutUsingStatement() { const string LoggerConfig = @" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='DisableLoggingTest_WithoutUsingStatement_A' levels='Trace' writeTo='debug' /> <logger name='DisableLoggingTest_WithoutUsingStatement_B' levels='Error' writeTo='debug' /> </rules> </nlog>"; // Disable/Enable logging should affect ALL the loggers. ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_A"); ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_B"); LogManager.Configuration = CreateConfigurationFromString(LoggerConfig); // The starting state for logging is enable. Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); loggerA.Trace("---"); AssertDebugLastMessage("debug", "---"); LogManager.DisableLogging(); Assert.False(LogManager.IsLoggingEnabled()); // The last value of LastMessage before DisableLogging() should be returned. loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "---"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "---"); LogManager.EnableLogging(); Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); LogManager.Shutdown(); LogManager.Configuration = null; } private int _reloadCounter = 0; private void WaitForConfigReload(int counter) { while (_reloadCounter < counter) { System.Threading.Thread.Sleep(100); } } private void OnConfigReloaded(object sender, LoggingConfigurationReloadedEventArgs e) { Console.WriteLine("OnConfigReloaded success={0}", e.Succeeded); _reloadCounter++; } [Fact] public void AutoReloadTest() { #if NETSTANDARD if (IsTravis()) { Console.WriteLine("[SKIP] LogManagerTests.AutoReloadTest because we are running in Travis"); return; } #endif using (new InternalLoggerScope()) { string fileName = Path.GetTempFileName(); try { _reloadCounter = 0; LogManager.ConfigurationReloaded += OnConfigReloaded; using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } LogManager.Configuration = new XmlLoggingConfiguration(fileName); AssertDebugCounter("debug", 0); ILogger logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); InternalLogger.Info("Rewriting test file..."); // now write the file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } InternalLogger.Info("Rewritten."); WaitForConfigReload(1); logger.Debug("aaa"); AssertDebugLastMessage("debug", "xxx aaa"); // write the file again, this time make an error using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(2); logger.Debug("bbb"); AssertDebugLastMessage("debug", "xxx bbb"); // write the corrected file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='zzz ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(3); logger.Debug("ccc"); AssertDebugLastMessage("debug", "zzz ccc"); } finally { LogManager.ConfigurationReloaded -= OnConfigReloaded; if (File.Exists(fileName)) File.Delete(fileName); } } } [Fact] public void GivenCurrentClass_WhenGetCurrentClassLogger_ThenLoggerShouldBeCurrentClass() { var logger = LogManager.GetCurrentClassLogger(); Assert.Equal(this.GetType().FullName, logger.Name); } private static class ImAStaticClass { [UsedImplicitly] public static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger(); static ImAStaticClass() { } public static void DummyToInvokeInitializers() { } } [Fact] public void GetCurrentClassLogger_static_class() { ImAStaticClass.DummyToInvokeInitializers(); Assert.Equal(typeof(ImAStaticClass).FullName, ImAStaticClass.Logger.Name); } private abstract class ImAAbstractClass { public Logger Logger { get; private set; } public Logger LoggerType { get; private set; } public string BaseName { get { return typeof(ImAAbstractClass).FullName; } } /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> protected ImAAbstractClass() { Logger = NLog.LogManager.GetCurrentClassLogger(); LoggerType = NLog.LogManager.GetCurrentClassLogger(typeof(Logger)); } protected ImAAbstractClass(string param1, Func<string> param2) { Logger = NLog.LogManager.GetCurrentClassLogger(); LoggerType = NLog.LogManager.GetCurrentClassLogger(typeof(Logger)); } } private class InheritedFromAbstractClass : ImAAbstractClass { public Logger LoggerInherited = NLog.LogManager.GetCurrentClassLogger(); public Logger LoggerTypeInherited = NLog.LogManager.GetCurrentClassLogger(typeof(Logger)); public string InheritedName { get { return GetType().FullName; } } public InheritedFromAbstractClass() : base() { } public InheritedFromAbstractClass(string param1, Func<string> param2) : base(param1, param2) { } } /// <summary> /// Creating instance in a abstract ctor should not be a problem /// </summary> [Fact] public void GetCurrentClassLogger_abstract_class() { var instance = new InheritedFromAbstractClass(); Assert.Equal(instance.BaseName, instance.Logger.Name); Assert.Equal(instance.BaseName, instance.LoggerType.Name); Assert.Equal(instance.InheritedName, instance.LoggerInherited.Name); Assert.Equal(instance.InheritedName, instance.LoggerTypeInherited.Name); } /// <summary> /// Creating instance in a abstract ctor should not be a problem /// </summary> [Fact] public void GetCurrentClassLogger_abstract_class_with_parameter() { var instance = new InheritedFromAbstractClass("Hello", null); Assert.Equal(instance.BaseName, instance.Logger.Name); Assert.Equal(instance.BaseName, instance.LoggerType.Name); } /// <summary> /// I'm a class which isn't inhereting from Logger /// </summary> private class ImNotALogger { } /// <summary> /// ImNotALogger inherits not from Logger , but should not throw an exception /// </summary> [Fact] public void GetLogger_wrong_loggertype_should_continue() { var instance = LogManager.GetLogger("a", typeof(ImNotALogger)); Assert.NotNull(instance); } /// <summary> /// ImNotALogger inherits not from Logger , but should not throw an exception /// </summary> [Fact] public void GetLogger_wrong_loggertype_should_continue_even_if_class_is_static() { var instance = LogManager.GetLogger("a", typeof(ImAStaticClass)); Assert.NotNull(instance); } [Fact] public void GivenLazyClass_WhenGetCurrentClassLogger_ThenLoggerNameShouldBeCurrentClass() { var logger = new Lazy<ILogger>(LogManager.GetCurrentClassLogger); Assert.Equal(this.GetType().FullName, logger.Value.Name); } [Fact] public void ThreadSafe_Shutdown() { LogManager.Configuration = new LoggingConfiguration(); LogManager.ThrowExceptions = true; LogManager.Configuration.AddTarget("memory", new NLog.Targets.Wrappers.BufferingTargetWrapper(new MemoryQueueTarget(500), 5, 1)); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, LogManager.Configuration.FindTargetByName("memory"))); LogManager.Configuration.AddTarget("memory2", new NLog.Targets.Wrappers.BufferingTargetWrapper(new MemoryQueueTarget(500), 5, 1)); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, LogManager.Configuration.FindTargetByName("memory2"))); var stopFlag = false; var exceptionThrown = false; Task.Run(() => { try { var logger = LogManager.GetLogger("Hello"); while (!stopFlag) { logger.Debug("Hello World"); System.Threading.Thread.Sleep(1); } } catch { exceptionThrown = true; } }); Task.Run(() => { try { var logger = LogManager.GetLogger("Hello"); while (!stopFlag) { logger.Debug("Hello World"); System.Threading.Thread.Sleep(1); } } catch { exceptionThrown = true; } }); System.Threading.Thread.Sleep(20); LogManager.Shutdown(); // Shutdown active LoggingConfiguration System.Threading.Thread.Sleep(20); stopFlag = true; System.Threading.Thread.Sleep(20); Assert.False(exceptionThrown); } /// <summary> /// Note: THe problem can be reproduced when: debugging the unittest + "break when exception is thrown" checked in visual studio. /// /// https://github.com/NLog/NLog/issues/500 /// </summary> [Fact] public void ThreadSafe_getCurrentClassLogger_test() { MemoryQueueTarget mTarget = new MemoryQueueTarget(1000); MemoryQueueTarget mTarget2 = new MemoryQueueTarget(1000); var task1 = Task.Run(() => { //need for init LogManager.Configuration = new LoggingConfiguration(); LogManager.ThrowExceptions = true; LogManager.Configuration.AddTarget("memory", mTarget); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, mTarget)); System.Threading.Thread.Sleep(1); LogManager.ReconfigExistingLoggers(); System.Threading.Thread.Sleep(1); mTarget.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}"; }); var task2 = task1.ContinueWith((t) => { LogManager.Configuration.AddTarget("memory2", mTarget2); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, mTarget2)); System.Threading.Thread.Sleep(1); LogManager.ReconfigExistingLoggers(); System.Threading.Thread.Sleep(1); mTarget2.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}"; }); System.Threading.Thread.Sleep(1); Parallel.For(0, 8, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, (e) => { bool task1Complete = false, task2Complete = false; for (int i = 0; i < 100; ++i) { if (i > 25 && !task1Complete) { task1.Wait(5000); task1Complete = true; } if (i > 75 && !task2Complete) { task2.Wait(5000); task2Complete = true; } // Multiple threads initializing new loggers while configuration is changing var loggerA = LogManager.GetLogger(e + "A" + i); loggerA.Info("Hi there {0}", e); var loggerB = LogManager.GetLogger(e + "B" + i); loggerB.Info("Hi there {0}", e); var loggerC = LogManager.GetLogger(e + "C" + i); loggerC.Info("Hi there {0}", e); var loggerD = LogManager.GetLogger(e + "D" + i); loggerD.Info("Hi there {0}", e); }; }); Assert.NotEqual(0, mTarget.Logs.Count + mTarget2.Logs.Count); } /// <summary> /// target for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> [Target("Memory")] public sealed class MemoryQueueTarget : TargetWithLayout { private int maxSize; public MemoryQueueTarget() : this(1) { } public MemoryQueueTarget(string name) { this.Name = name; } public MemoryQueueTarget(int size) { this.maxSize = size; } protected override void InitializeTarget() { base.InitializeTarget(); this.Logs = new Queue<string>(maxSize); } protected override void CloseTarget() { base.CloseTarget(); this.Logs = null; } internal Queue<string> Logs { get; private set; } protected override void Write(LogEventInfo logEvent) { if (this.Logs == null) throw new ObjectDisposedException("MemoryQueueTarget"); string msg = this.Layout.Render(logEvent); if (msg.Length > 100) msg = msg.Substring(0, 100) + "..."; this.Logs.Enqueue(msg); while (this.Logs.Count > maxSize) { Logs.Dequeue(); } } } } }
using System; using System.Linq.Expressions; using FluentAssertions; using MongoDB.Bson; using MongoDB.Messaging.Storage; using Xunit; namespace MongoDB.Messaging.Tests.Storage { public class QueueRepositoryTest { [Fact] public async void SaveFind() { var repo = GetRepository(); var message = new Message(); message.Name = "SaveFind"; message.Id.Should().BeNullOrEmpty(); var m = await repo.Save(message); m.Should().Be(message); message.Id.Should().NotBeNullOrEmpty(); string key = message.Id; var one = await repo.Find(key); one.Id.Should().Be(key); } [Fact] public async void FindOne() { var repo = GetRepository(); var message = new Message(); message.Name = "FindOne"; await repo.Save(message); Expression<Func<Message, bool>> criteria = (m) => m.State == MessageState.None && m.Result == MessageResult.None; var one = await repo.FindOne(criteria); one.Should().NotBeNull(); } [Fact] public async void FindAll() { var repo = GetRepository(); var message = new Message(); message.Name = "FindAll"; await repo.Save(message); Expression<Func<Message, bool>> criteria = (m) => m.State == MessageState.None && m.Result == MessageResult.None; var list = await repo.FindAll(criteria); list.Should().NotBeNullOrEmpty(); } [Fact] public async void SaveDelete() { var repo = GetRepository(); var message = new Message(); message.Name = "SaveDelete"; message.Id.Should().BeNullOrEmpty(); var m = await repo.Save(message); m.Should().Be(message); message.Id.Should().NotBeNullOrEmpty(); string key = message.Id; long count = await repo.Delete(key); count.Should().BeGreaterThan(0); } [Fact] public async void DeleteOne() { var repo = GetRepository(); var message = new Message(); message.Name = "DeleteOne"; await repo.Save(message); Expression<Func<Message, bool>> criteria = (m) => m.State == MessageState.None && m.Result == MessageResult.None; long count = await repo.DeleteOne(criteria); count.Should().BeGreaterThan(0); } [Fact] public async void DeleteAll() { var repo = GetRepository(); var message = new Message(); message.Name = "DeleteAll"; await repo.Save(message); Expression<Func<Message, bool>> criteria = (m) => m.State == MessageState.None && m.Result == MessageResult.None; long count = await repo.DeleteAll(criteria); count.Should().BeGreaterThan(0); } [Fact] public async void Count() { var repo = GetRepository(); var message = new Message(); message.Name = "Count"; await repo.Save(message); Expression<Func<Message, bool>> criteria = (m) => m.State == MessageState.None && m.Result == MessageResult.None; long count = await repo.Count(criteria); count.Should().BeGreaterThan(0); } [Fact] public async void SaveWithNoId() { var repo = GetRepository(); var message = new Message(); message.Name = "SaveWithNoId"; message.Id.Should().BeNullOrEmpty(); var m = await repo.Save(message); m.Should().Be(message); message.Id.Should().NotBeNullOrEmpty(); } [Fact] public async void SaveWithNewId() { var repo = GetRepository(); var message = new Message(); message.Id = ObjectId.GenerateNewId().ToString(); message.Name = "SaveWithNewId"; var m = await repo.Save(message); m.Should().Be(message); message.Id.Should().NotBeNullOrEmpty(); } [Fact] public async void SaveWithNewIdThenUpdate() { var repo = GetRepository(); var message = new Message(); message.Name = "SaveWithNewIdThenUpdate"; message.Id.Should().BeNullOrEmpty(); // create var m = await repo.Save(message); m.Should().Be(message); message.Id.Should().NotBeNullOrEmpty(); message.Description = "updated message"; // update await repo.Save(message); } [Fact] public async void EnqueueDequeue() { var repo = GetRepository(); var message = new Message(); message.Name = "EnqueueDequeue"; var m = await repo.Enqueue(message); m.Should().Be(message); message.Id.Should().NotBeNullOrEmpty(); message.State.Should().Be(MessageState.Queued); string key = message.Id; var dequeued = await repo.Dequeue(); dequeued.Should().NotBeNull(); dequeued.Id.Should().Be(key); dequeued.State.Should().Be(MessageState.Processing); dequeued.StartTime.Should().BeAfter(DateTime.MinValue); dequeued.Status.Should().NotBeNullOrEmpty(); await repo.UpdateStatus(key, "Loading Test Data ..."); await repo.MarkComplete(key, MessageResult.Successful, "Test Complete"); var completed = await repo.Find(key); completed.State.Should().Be(MessageState.Complete); completed.Result.Should().Be(MessageResult.Successful); completed.EndTime.Should().BeAfter(DateTime.MinValue); completed.Status.Should().NotBeNullOrEmpty(); } private static QueueRepository GetRepository() { var database = MongoConnection.GetDatabase("Messaging"); var collection = database.GetCollection<Message>("test-queue"); var repo = new QueueRepository(collection); return repo; } } }
using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IDefaultApi { #region Synchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>string</returns> string AddDeed (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> ApiResponse<string> AddDeedWithHttpInfo (DeedApplication body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class DefaultApi : IDefaultApi { /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class. /// </summary> /// <returns></returns> public DefaultApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public DefaultApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>string</returns> public string AddDeed (DeedApplication body) { ApiResponse<string> localVarResponse = AddDeedWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> public ApiResponse< string > AddDeedWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DefaultApi->AddDeed"); var localVarPath = "/deed/"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling AddDeed: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling AddDeed: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body) { ApiResponse<string> localVarResponse = await AddDeedAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided.\n The reponse will return a URL that can retrieve the created deed. \n &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling AddDeed"); var localVarPath = "/deed/"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling AddDeed: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling AddDeed: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } } }
// 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 1.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for CustomDomainsOperations. /// </summary> public static partial class CustomDomainsOperationsExtensions { /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static IPage<CustomDomain> ListByEndpoint(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName) { return operations.ListByEndpointAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult(); } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CustomDomain>> ListByEndpointAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEndpointWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets an exisitng custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain Get(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.GetAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Gets an exisitng custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> GetAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> public static CustomDomain Create(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName) { return operations.CreateAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName).GetAwaiter().GetResult(); } /// <summary> /// Creates a new custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> CreateAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain Delete(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.DeleteAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> DeleteAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Disable https delivery of the custom domain. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain DisableCustomHttps(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.DisableCustomHttpsAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Disable https delivery of the custom domain. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> DisableCustomHttpsAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DisableCustomHttpsWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Enable https delivery of the custom domain. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain EnableCustomHttps(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.EnableCustomHttpsAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Enable https delivery of the custom domain. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> EnableCustomHttpsAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.EnableCustomHttpsWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> public static CustomDomain BeginCreate(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName) { return operations.BeginCreateAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName).GetAwaiter().GetResult(); } /// <summary> /// Creates a new custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> BeginCreateAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> public static CustomDomain BeginDelete(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName) { return operations.BeginDeleteAsync(resourceGroupName, profileName, endpointName, customDomainName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing custom domain within an endpoint. /// </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='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='customDomainName'> /// Name of the custom domain within an endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CustomDomain> BeginDeleteAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<CustomDomain> ListByEndpointNext(this ICustomDomainsOperations operations, string nextPageLink) { return operations.ListByEndpointNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists all of the existing custom domains within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CustomDomain>> ListByEndpointNextAsync(this ICustomDomainsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEndpointNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using MusicStoreB2C; using MusicStoreB2C.Models; using MusicStoreB2C.ViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Dynamic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace MusicStoreB2C.Controllers { [Authorize] public class ManageController : Controller { private readonly ILogger<ManageController> _logger; public ManageController(MusicStoreContext dbContext, ILogger<ManageController> logger // ,UserManager<ApplicationUser> userManager, // SignInManager<ApplicationUser> signInManager ) { DbContext = dbContext; _logger = logger; // UserManager = userManager; // SignInManager = signInManager; } public UserManager<ApplicationUser> UserManager { get; } public SignInManager<ApplicationUser> SignInManager { get; } public MusicStoreContext DbContext { get; } // // GET: /Manage/Index public async Task<ActionResult> Index([FromServices] MusicStoreContext dbContext, ManageMessageId? message = null) { ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); var orderHistory = OrderHistory.GetOrderHistory(dbContext, user); dynamic userProps = await Startup.adB2C.GetUserProperties(user).Result; string mobile = userProps.mobile; var model = new IndexViewModel { HasPassword = false, // await UserManager.HasPasswordAsync(user), HasOrders = await orderHistory.HasOrdersAsync(), PhoneNumber = mobile, // await UserManager.GetPhoneNumberAsync(user), TwoFactor = false, // await UserManager.GetTwoFactorEnabledAsync(user), Logins = null, // await UserManager.GetLoginsAsync(user), BrowserRemembered = false, //= await SignInManager.IsTwoFactorClientRememberedAsync(user) ThumbnailPhoto = await Startup.adB2C.GetUserThumbnail(user), UserProps = userProps }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(string loginProvider, string providerKey) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = new IdentityResult(); // await UserManager.RemoveLoginAsync(user, loginProvider, providerKey); if (result.Succeeded) { // await SignInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction("ManageLogins", new { Message = message }); } // // GET: /Account/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Account/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); // Generate the token and send it var code = ""; // await UserManager.GenerateChangePhoneNumberTokenAsync(user, model.Number); await MessageServices.SendSmsAsync(model.Number, "Your security code is: " + code); return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { // await UserManager.SetTwoFactorEnabledAsync(user, true); // TODO: flow remember me somehow? // await SignInManager.SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { // await UserManager.SetTwoFactorEnabledAsync(user, false); // await SignInManager.SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", "Manage"); } // // GET: /Account/VerifyPhoneNumber public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { // This code allows you exercise the flow without actually sending codes // For production use please register a SMS provider in IdentityConfig and generate a code here. #if DEMO ViewBag.Code = ""; // await UserManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); #endif await Task.Delay(1); return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Account/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = new IdentityResult(); // await UserManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { // await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "Failed to verify phone"); return View(model); } // // GET: /Account/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = new IdentityResult(); //await UserManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { // await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword public IActionResult ChangePassword() { return View(); } // // POST: /Account/Manage [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = new IdentityResult(); //await UserManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { // await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction("Index", new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = new IdentityResult(); //await UserManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { // await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction("Index", new { Message = ManageMessageId.Error }); } // // POST: /Manage/RememberBrowser [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RememberBrowser() { var user = await GetCurrentUserAsync(); if (user != null) { // await SignInManager.RememberTwoFactorClientAsync(user); // await SignInManager.SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", "Manage"); } // // POST: /Manage/ForgetBrowser [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgetBrowser() { await SignInManager.ForgetTwoFactorClientAsync(); return RedirectToAction("Index", "Manage"); } // // GET: /Account/Manage public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewBag.StatusMessage = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } // var userLogins = await UserManager.GetLoginsAsync(user); // var otherLogins = SignInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); ViewBag.ShowRemoveButton = false; // user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { // CurrentLogins = userLogins, // OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public ActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, UserManager.GetUserId(User)); return new ChallengeResult(provider, properties); } // // GET: /Manage/LinkLoginCallback public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var loginInfo = (ExternalLoginInfo)null; // await SignInManager.GetExternalLoginInfoAsync(await UserManager.GetUserIdAsync(user)); if (loginInfo == null) { return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } var result = (IdentityResult)null; // await UserManager.AddLoginAsync(user, loginInfo); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; return RedirectToAction("ManageLogins", new { Message = message }); } // // GET: /Account/ViewOrders public async Task<ActionResult> ViewOrders() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var orderHistory = OrderHistory.GetOrderHistory(DbContext, user); var viewModel = new ViewOrdersViewModel { Orders = await orderHistory.GetOrders(), OrderTotal = await orderHistory.GetOrdersTotal(), }; return View(viewModel); } // // GET: /Account/ViewOrderDetails public async Task<ActionResult> ViewOrderDetails(int id) { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var orderHistory = OrderHistory.GetOrderHistory(DbContext, user); var viewModel = new ViewOrderDetailsViewModel { OrderId = id, OrderDetails = await orderHistory.GetOrderDetails(id), OrderTotal = await orderHistory.GetOrderTotal(id), }; return View(viewModel); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private Task<ClaimsPrincipal> GetCurrentUserAsync() { // return UserManager.GetUserAsync(HttpContext.User); return Task.FromResult(User); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.ServiceModel; using System.Threading; using System.Windows.Threading; using DevExpress.Utils; using DevExpress.Mvvm.Native; #if !DXCORE3 namespace DevExpress.Mvvm.UI.Native { public interface IJumpAction { string CommandId { get; } string ApplicationPath { get; } string Arguments { get; } string WorkingDirectory { get; } void SetStartInfo(string applicationPath, string arguments); void Execute(); } public interface IJumpActionsManager { void BeginUpdate(); void EndUpdate(); void RegisterAction(IJumpAction jumpAction, string commandLineArgumentPrefix, Func<string> launcherPath); } public class JumpActionsManager : JumpActionsManagerBase, IJumpActionsManager { static object factoryLock = new object(); static Func<JumpActionsManager> factory = () => new JumpActionsManager(); public static Func<JumpActionsManager> Factory { get { return factory; } set { lock(factoryLock) { GuardHelper.ArgumentNotNull(value, "value"); factory = value; } } } static JumpActionsManager current; public static JumpActionsManager Current { get { lock(factoryLock) { if(current == null) { current = Factory(); if(current == null) throw new InvalidOperationException(); } return current; } } } protected class RegisteredJumpAction { WeakReference taskReference; public RegisteredJumpAction(IJumpAction jumpAction) { Id = jumpAction.CommandId; taskReference = new WeakReference(jumpAction); Dispatcher = Dispatcher.CurrentDispatcher; } public string Id { get; private set; } public Dispatcher Dispatcher { get; private set; } public IJumpAction GetJumpAction() { return taskReference == null ? null : (IJumpAction)taskReference.Target; } } [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] class ApplicationInstance : IApplicationInstance { readonly JumpActionsManager manager; public ApplicationInstance(JumpActionsManager manager) { this.manager = manager; } void IApplicationInstance.Execute(string command) { manager.ExecuteCore(command); } } readonly Dictionary<string, RegisteredJumpAction> jumpActions = new Dictionary<string, RegisteredJumpAction>(); GuidData applicationInstanceId; ServiceHost applicationInstanceHost; Tuple<IntPtr, IntPtr> isAliveFlagFile; volatile bool registered = false; ICurrentProcess currentProcess; volatile bool updating = false; public JumpActionsManager(ICurrentProcess currentProcess = null, int millisecondsTimeout = DefaultMillisecondsTimeout) : base(millisecondsTimeout) { this.currentProcess = currentProcess ?? new CurrentProcess(); } protected override void Dispose(bool disposing) { try { if(disposing) Monitor.Enter(jumpActions); try { Mutex mainMutex = WaitMainMutex(!disposing); try { UnregisterInstance(!disposing); } finally { mainMutex.ReleaseMutex(); } } finally { if(disposing) Monitor.Exit(jumpActions); } } catch(TimeoutException) { if(disposing) throw; } finally { base.Dispose(disposing); } } public void BeginUpdate() { if(updating) throw new InvalidOperationException(); Monitor.Enter(jumpActions); try { Mutex mainMutex = WaitMainMutex(false); try { ClearActions(); } catch { mainMutex.ReleaseMutex(); throw; } } catch { Monitor.Exit(jumpActions); throw; } updating = true; } public void EndUpdate() { if(!updating) throw new InvalidOperationException(); try { Mutex mainMutex = GetMainMutex(false); mainMutex.ReleaseMutex(); } finally { updating = false; Monitor.Exit(jumpActions); } } [SecuritySafeCritical] public void RegisterAction(IJumpAction jumpAction, string commandLineArgumentPrefix, Func<string> launcherPath) { GuardHelper.ArgumentNotNull(jumpAction, "jumpAction"); if(!updating) throw new InvalidOperationException(); RegisterInstance(); RegisteredJumpAction registeredjumpAction = PrepareJumpActionToRegister(jumpAction, commandLineArgumentPrefix, launcherPath); AddAction(registeredjumpAction); if(ShouldExecute(jumpAction.CommandId, commandLineArgumentPrefix)) ExecuteCore(jumpAction.CommandId); } protected virtual RegisteredJumpAction PrepareJumpActionToRegister(IJumpAction jumpAction, string commandLineArgumentPrefix, Func<string> launcherPath) { RegisteredJumpAction registeredJumpAction = new RegisteredJumpAction(jumpAction); string exePath = jumpAction.ApplicationPath; string applicationArguments = jumpAction.Arguments ?? string.Empty; if(string.IsNullOrEmpty(exePath)) exePath = currentProcess.ExecutablePath; if(string.Equals(exePath, currentProcess.ExecutablePath, StringComparison.OrdinalIgnoreCase)) { string actionArg = commandLineArgumentPrefix + Uri.EscapeDataString(registeredJumpAction.Id); applicationArguments = string.IsNullOrEmpty(applicationArguments) ? actionArg : applicationArguments + actionArg; } string launcherArguments = string.Join(" ", currentProcess.ApplicationId, Uri.EscapeDataString(registeredJumpAction.Id), Uri.EscapeDataString(exePath), string.Format("\"{0}\"", Uri.EscapeDataString(applicationArguments)) ); if(!string.IsNullOrEmpty(jumpAction.WorkingDirectory)) launcherArguments = string.Join(" ", launcherArguments, Uri.EscapeDataString(jumpAction.WorkingDirectory)); jumpAction.SetStartInfo(launcherPath(), launcherArguments); return registeredJumpAction; } protected override string ApplicationId { get { return currentProcess.ApplicationId; } } #if DEBUG protected override object CurrentProcessTag { get { return currentProcess; } } #endif bool ShouldExecute(string command, string commandLineArgumentPrefix) { string arg = commandLineArgumentPrefix + Uri.EscapeDataString(command); return currentProcess.CommandLineArgs.Skip(1).Where(a => string.Equals(a, arg)).Any(); } void ExecuteCore(string command) { RegisteredJumpAction registeredJumpAction; if(!jumpActions.TryGetValue(command, out registeredJumpAction)) return; IJumpAction jumpAction = registeredJumpAction.GetJumpAction(); if(jumpAction == null) jumpActions.Remove(command); else registeredJumpAction.Dispatcher.BeginInvoke((Action)jumpAction.Execute); } void AddAction(RegisteredJumpAction jumpAction) { jumpActions[jumpAction.Id] = jumpAction; } void ClearActions() { jumpActions.Clear(); } void RegisterInstance() { if(registered) return; GuidData[] registeredApplicationInstances = GetApplicationInstances(true); CreateInstance(); GuidData[] newApplicationInstances = new GuidData[registeredApplicationInstances.Length + 1]; newApplicationInstances[0] = applicationInstanceId; Array.Copy(registeredApplicationInstances, 0, newApplicationInstances, 1, registeredApplicationInstances.Length); UpdateInstancesFile(newApplicationInstances); registered = true; } [SecuritySafeCritical] void CreateInstance() { applicationInstanceId = new GuidData(Guid.NewGuid()); applicationInstanceHost = new ServiceHost(new ApplicationInstance(this), new Uri(GetServiceUri(applicationInstanceId))); applicationInstanceHost.AddServiceEndpoint(typeof(IApplicationInstance), new NetNamedPipeBinding(), EndPointName); applicationInstanceHost.Open(new TimeSpan(0, 0, 0, 0, MillisecondsTimeout)); bool alreadyExists; isAliveFlagFile = CreateFileMappingAndMapView(1, GetIsAliveFlagFileName(applicationInstanceId), out alreadyExists); } [SecuritySafeCritical] void DeleteInstance() { UnmapViewAndCloseFileMapping(isAliveFlagFile); isAliveFlagFile = null; applicationInstanceHost.Close(new TimeSpan(0, 0, 0, 0, MillisecondsTimeout)); applicationInstanceHost = null; applicationInstanceId = new GuidData(Guid.Empty); } void UnregisterInstance(bool safe) { if(!registered) return; GuidData[] registeredApplicationInstances = GetApplicationInstances(true); GuidData[] newApplicationInstances = new GuidData[registeredApplicationInstances.Length - 1]; int i = 0; foreach(GuidData instance in registeredApplicationInstances) { if(instance.AsGuid == applicationInstanceId.AsGuid) continue; newApplicationInstances[i] = instance; ++i; } UpdateInstancesFile(newApplicationInstances); registered = false; if(!safe && applicationInstanceHost != null) DeleteInstance(); } } } #endif
using System; using NUnit.Framework; using System.Collections.ObjectModel; namespace OpenQA.Selenium { [TestFixture] public class ExecutingAsyncJavascriptTest : DriverTestFixture { private IJavaScriptExecutor executor; private TimeSpan originalTimeout = TimeSpan.MinValue; [SetUp] public void SetUpEnvironment() { if (driver is IJavaScriptExecutor) { executor = (IJavaScriptExecutor)driver; } try { originalTimeout = driver.Manage().Timeouts().AsynchronousJavaScript; } catch (NotImplementedException) { // For driver implementations that do not support getting timeouts, // just set a default 30-second timeout. originalTimeout = TimeSpan.FromSeconds(30); } driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(1); } [TearDown] public void TearDownEnvironment() { driver.Manage().Timeouts().AsynchronousJavaScript = originalTimeout; } [Test] public void ShouldNotTimeoutIfCallbackInvokedImmediately() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1](123);"); Assert.That(result, Is.InstanceOf<long>()); Assert.That((long)result, Is.EqualTo(123)); } [Test] public void ShouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NeitherNullNorUndefined() { driver.Url = ajaxyPage; Assert.That((long)executor.ExecuteAsyncScript("arguments[arguments.length - 1](123);"), Is.EqualTo(123)); driver.Url = ajaxyPage; Assert.That(executor.ExecuteAsyncScript("arguments[arguments.length - 1]('abc');").ToString(), Is.EqualTo("abc")); driver.Url = ajaxyPage; Assert.That((bool)executor.ExecuteAsyncScript("arguments[arguments.length - 1](false);"), Is.False); driver.Url = ajaxyPage; Assert.That((bool)executor.ExecuteAsyncScript("arguments[arguments.length - 1](true);"), Is.True); } [Test] public void ShouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NullAndUndefined() { driver.Url = ajaxyPage; Assert.That(executor.ExecuteAsyncScript("arguments[arguments.length - 1](null);"), Is.Null); Assert.That(executor.ExecuteAsyncScript("arguments[arguments.length - 1]();"), Is.Null); } [Test] public void ShouldBeAbleToReturnAnArrayLiteralFromAnAsyncScript() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1]([]);"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<ReadOnlyCollection<object>>()); Assert.That((ReadOnlyCollection<object>)result, Has.Count.EqualTo(0)); } [Test] public void ShouldBeAbleToReturnAnArrayObjectFromAnAsyncScript() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1](new Array());"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<ReadOnlyCollection<object>>()); Assert.That((ReadOnlyCollection<object>)result, Has.Count.EqualTo(0)); } [Test] public void ShouldBeAbleToReturnArraysOfPrimitivesFromAsyncScripts() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1]([null, 123, 'abc', true, false]);"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<ReadOnlyCollection<object>>()); ReadOnlyCollection<object> resultList = result as ReadOnlyCollection<object>; Assert.That(resultList.Count, Is.EqualTo(5)); Assert.That(resultList[0], Is.Null); Assert.That((long)resultList[1], Is.EqualTo(123)); Assert.That(resultList[2].ToString(), Is.EqualTo("abc")); Assert.That((bool)resultList[3], Is.True); Assert.That((bool)resultList[4], Is.False); } [Test] public void ShouldBeAbleToReturnWebElementsFromAsyncScripts() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1](document.body);"); Assert.That(result, Is.InstanceOf<IWebElement>()); Assert.That(((IWebElement)result).TagName.ToLower(), Is.EqualTo("body")); } [Test] public void ShouldBeAbleToReturnArraysOfWebElementsFromAsyncScripts() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1]([document.body, document.body]);"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<ReadOnlyCollection<IWebElement>>()); ReadOnlyCollection<IWebElement> resultsList = (ReadOnlyCollection<IWebElement>)result; Assert.That(resultsList, Has.Count.EqualTo(2)); Assert.That(resultsList[0], Is.InstanceOf<IWebElement>()); Assert.That(resultsList[1], Is.InstanceOf<IWebElement>()); Assert.That(((IWebElement)resultsList[0]).TagName.ToLower(), Is.EqualTo("body")); Assert.That(((IWebElement)resultsList[0]), Is.EqualTo((IWebElement)resultsList[1])); } [Test] public void ShouldTimeoutIfScriptDoesNotInvokeCallback() { driver.Url = ajaxyPage; Assert.That(() => executor.ExecuteAsyncScript("return 1 + 2;"), Throws.InstanceOf<WebDriverTimeoutException>()); } [Test] public void ShouldTimeoutIfScriptDoesNotInvokeCallbackWithAZeroTimeout() { driver.Url = ajaxyPage; Assert.That(() => executor.ExecuteAsyncScript("window.setTimeout(function() {}, 0);"), Throws.InstanceOf<WebDriverTimeoutException>()); } [Test] public void ShouldNotTimeoutIfScriptCallsbackInsideAZeroTimeout() { driver.Url = ajaxyPage; executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(function() { callback(123); }, 0)"); } [Test] public void ShouldTimeoutIfScriptDoesNotInvokeCallbackWithLongTimeout() { driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromMilliseconds(500); driver.Url = ajaxyPage; Assert.That(() => executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(callback, 1500);"), Throws.InstanceOf<WebDriverTimeoutException>()); } [Test] public void ShouldDetectPageLoadsWhileWaitingOnAnAsyncScriptAndReturnAnError() { driver.Url = ajaxyPage; Assert.That(() => executor.ExecuteAsyncScript("window.location = '" + dynamicPage + "';"), Throws.InstanceOf<WebDriverException>()); } [Test] public void ShouldCatchErrorsWhenExecutingInitialScript() { driver.Url = ajaxyPage; Assert.That(() => executor.ExecuteAsyncScript("throw Error('you should catch this!');"), Throws.InstanceOf<WebDriverException>()); } [Test] public void ShouldNotTimeoutWithMultipleCallsTheFirstOneBeingSynchronous() { driver.Url = ajaxyPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromMilliseconds(1000); Assert.That((bool)executor.ExecuteAsyncScript("arguments[arguments.length - 1](true);"), Is.True); Assert.That((bool)executor.ExecuteAsyncScript("var cb = arguments[arguments.length - 1]; window.setTimeout(function(){cb(true);}, 9);"), Is.True); } [Test] [IgnoreBrowser(Browser.Chrome, ".NET language bindings do not properly parse JavaScript stack trace")] [IgnoreBrowser(Browser.Firefox, ".NET language bindings do not properly parse JavaScript stack trace")] [IgnoreBrowser(Browser.IE, ".NET language bindings do not properly parse JavaScript stack trace")] [IgnoreBrowser(Browser.Edge, ".NET language bindings do not properly parse JavaScript stack trace")] [IgnoreBrowser(Browser.Safari, ".NET language bindings do not properly parse JavaScript stack trace")] public void ShouldCatchErrorsWithMessageAndStacktraceWhenExecutingInitialScript() { driver.Url = ajaxyPage; string js = "function functionB() { throw Error('errormessage'); };" + "function functionA() { functionB(); };" + "functionA();"; Exception ex = Assert.Catch(() => executor.ExecuteAsyncScript(js)); Assert.That(ex, Is.InstanceOf<WebDriverException>()); Assert.That(ex.Message.Contains("errormessage")); Assert.That(ex.StackTrace.Contains("functionB")); } [Test] public void ShouldBeAbleToExecuteAsynchronousScripts() { // Reset the timeout to the 30-second default instead of zero. driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(30); driver.Url = ajaxyPage; IWebElement typer = driver.FindElement(By.Name("typer")); typer.SendKeys("bob"); Assert.AreEqual("bob", typer.GetAttribute("value")); driver.FindElement(By.Id("red")).Click(); driver.FindElement(By.Name("submit")).Click(); Assert.AreEqual(1, GetNumberOfDivElements(), "There should only be 1 DIV at this point, which is used for the butter message"); driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(10); string text = (string)executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.registerListener(arguments[arguments.length - 1]);"); Assert.AreEqual("bob", text); Assert.AreEqual("", typer.GetAttribute("value")); Assert.AreEqual(2, GetNumberOfDivElements(), "There should be 1 DIV (for the butter message) + 1 DIV (for the new label)"); } [Test] public void ShouldBeAbleToPassMultipleArgumentsToAsyncScripts() { driver.Url = ajaxyPage; long result = (long)executor.ExecuteAsyncScript("arguments[arguments.length - 1](arguments[0] + arguments[1]);", 1, 2); Assert.AreEqual(3, result); } [Test] public void ShouldBeAbleToMakeXMLHttpRequestsAndWaitForTheResponse() { string script = "var url = arguments[0];" + "var callback = arguments[arguments.length - 1];" + // Adapted from http://www.quirksmode.org/js/xmlhttp.html "var XMLHttpFactories = [" + " function () {return new XMLHttpRequest()}," + " function () {return new ActiveXObject('Msxml2.XMLHTTP')}," + " function () {return new ActiveXObject('Msxml3.XMLHTTP')}," + " function () {return new ActiveXObject('Microsoft.XMLHTTP')}" + "];" + "var xhr = false;" + "while (!xhr && XMLHttpFactories.length) {" + " try {" + " xhr = XMLHttpFactories.shift().call();" + " } catch (e) {}" + "}" + "if (!xhr) throw Error('unable to create XHR object');" + "xhr.open('GET', url, true);" + "xhr.onreadystatechange = function() {" + " if (xhr.readyState == 4) callback(xhr.responseText);" + "};" + "xhr.send();"; driver.Url = ajaxyPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(3); string response = (string)executor.ExecuteAsyncScript(script, sleepingPage + "?time=2"); Assert.AreEqual("<html><head><title>Done</title></head><body>Slept for 2s</body></html>", response.Trim()); } [Test] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not alerts thrown during async JavaScript; driver hangs until alert dismissed")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] public void ThrowsIfScriptTriggersAlert() { driver.Url = simpleTestPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); ((IJavaScriptExecutor)driver).ExecuteAsyncScript( "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('Look! An alert!'); }, 50);"); Assert.That(() => driver.Title, Throws.InstanceOf<UnhandledAlertException>()); string title = driver.Title; } [Test] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not alerts thrown during async JavaScript; driver hangs until alert dismissed")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] public void ThrowsIfAlertHappensDuringScript() { driver.Url = slowLoadingAlertPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); ((IJavaScriptExecutor)driver).ExecuteAsyncScript("setTimeout(arguments[0], 1000);"); Assert.That(() => driver.Title, Throws.InstanceOf<UnhandledAlertException>()); // Shouldn't throw string title = driver.Title; } [Test] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not alerts thrown during async JavaScript; driver hangs until alert dismissed")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] public void ThrowsIfScriptTriggersAlertWhichTimesOut() { driver.Url = simpleTestPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); ((IJavaScriptExecutor)driver) .ExecuteAsyncScript("setTimeout(function() { window.alert('Look! An alert!'); }, 50);"); Assert.That(() => driver.Title, Throws.InstanceOf<UnhandledAlertException>()); // Shouldn't throw string title = driver.Title; } [Test] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not alerts thrown during async JavaScript; driver hangs until alert dismissed")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] public void ThrowsIfAlertHappensDuringScriptWhichTimesOut() { driver.Url = slowLoadingAlertPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); ((IJavaScriptExecutor)driver).ExecuteAsyncScript(""); Assert.That(() => driver.Title, Throws.InstanceOf<UnhandledAlertException>()); // Shouldn't throw string title = driver.Title; } [Test] [IgnoreBrowser(Browser.Chrome, "Driver chooses not to return text from unhandled alert")] [IgnoreBrowser(Browser.Edge, "Driver chooses not to return text from unhandled alert")] [IgnoreBrowser(Browser.Firefox, "Driver chooses not to return text from unhandled alert")] [IgnoreBrowser(Browser.Safari, "Does not alerts thrown during async JavaScript; driver hangs until alert dismissed")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] public void IncludesAlertTextInUnhandledAlertException() { driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); string alertText = "Look! An alert!"; ((IJavaScriptExecutor)driver).ExecuteAsyncScript( "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('" + alertText + "'); }, 50);"); Assert.That(() => driver.Title, Throws.InstanceOf<UnhandledAlertException>().With.Property("AlertText").EqualTo(alertText)); } private long GetNumberOfDivElements() { IJavaScriptExecutor jsExecutor = driver as IJavaScriptExecutor; // Selenium does not support "findElements" yet, so we have to do this through a script. return (long)jsExecutor.ExecuteScript("return document.getElementsByTagName('div').length;"); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Diagnostics.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Squiggles { public class ErrorSquiggleProducerTests : AbstractSquiggleProducerTests { [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void ErrorTagGeneratedForError() { var spans = GetErrorSpans("class C {"); Assert.Equal(1, spans.Count()); var firstSpan = spans.First(); Assert.Equal(PredefinedErrorTypeNames.SyntaxError, firstSpan.Tag.ErrorType); } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void ErrorTagGeneratedForWarning() { var spans = GetErrorSpans("class C { long x = 5l; }"); Assert.Equal(1, spans.Count()); Assert.Equal(PredefinedErrorTypeNames.Warning, spans.First().Tag.ErrorType); } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void ErrorTagGeneratedForWarningAsError() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <CompilationOptions ReportDiagnostic = ""Error"" /> <Document FilePath = ""Test.cs"" > class Program { void Test() { int a = 5; } } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var spans = GetErrorSpans(workspace); Assert.Equal(1, spans.Count()); Assert.Equal(PredefinedErrorTypeNames.SyntaxError, spans.First().Tag.ErrorType); } } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void SuggestionTagsForUnnecessaryCode() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath = ""Test.cs"" > // System is used - rest are unused. using System.Collections; using System; using System.Diagnostics; using System.Collections.Generic; class Program { void Test() { Int32 x = 2; // Int32 can be simplified. x += 1; } } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var analyzerMap = ImmutableDictionary.CreateBuilder<string, ImmutableArray<DiagnosticAnalyzer>>(); analyzerMap.Add(LanguageNames.CSharp, ImmutableArray.Create<DiagnosticAnalyzer>( new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer())); var spans = GetErrorSpans(workspace, analyzerMap.ToImmutable()) .OrderBy(s => s.Span.Span.Start).ToImmutableArray(); Assert.Equal(3, spans.Length); var first = spans[0]; var second = spans[1]; var third = spans[2]; Assert.Equal(PredefinedErrorTypeNames.Suggestion, first.Tag.ErrorType); Assert.Equal(CSharpFeaturesResources.RemoveUnnecessaryUsingsDiagnosticTitle, first.Tag.ToolTipContent); Assert.Equal(40, first.Span.Start); Assert.Equal(25, first.Span.Length); Assert.Equal(PredefinedErrorTypeNames.Suggestion, second.Tag.ErrorType); Assert.Equal(CSharpFeaturesResources.RemoveUnnecessaryUsingsDiagnosticTitle, second.Tag.ToolTipContent); Assert.Equal(82, second.Span.Start); Assert.Equal(60, second.Span.Length); Assert.Equal(PredefinedErrorTypeNames.Suggestion, third.Tag.ErrorType); Assert.Equal(WorkspacesResources.NameCanBeSimplified, third.Tag.ToolTipContent); Assert.Equal(196, third.Span.Start); Assert.Equal(5, third.Span.Length); } } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void ErrorDoesNotCrashPastEOF() { var spans = GetErrorSpans("class C { int x ="); Assert.Equal(3, spans.Count()); } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void SemanticErrorReported() { var spans = GetErrorSpans("class C : Bar { }"); Assert.Equal(1, spans.Count()); var firstSpan = spans.First(); Assert.Equal(PredefinedErrorTypeNames.SyntaxError, firstSpan.Tag.ErrorType); Assert.Contains("Bar", (string)firstSpan.Tag.ToolTipContent, StringComparison.Ordinal); } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void BuildErrorZeroLengthSpan() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath = ""Test.cs"" > class Test { } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var document = workspace.Documents.First(); var updateArgs = new DiagnosticsUpdatedArgs( new object(), workspace, workspace.CurrentSolution, document.Project.Id, document.Id, ImmutableArray.Create( CreateDiagnosticData(workspace, document, new TextSpan(0, 0)), CreateDiagnosticData(workspace, document, new TextSpan(0, 1)))); var spans = GetErrorsFromUpdateSource(workspace, document, updateArgs); Assert.Equal(1, spans.Count()); var first = spans.First(); Assert.Equal(1, first.Span.Span.Length); } } [Fact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public void LiveErrorZeroLengthSpan() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath = ""Test.cs"" > class Test { } </Document> </Project> </Workspace>"; using (var workspace = TestWorkspaceFactory.CreateWorkspace(workspaceXml)) { var document = workspace.Documents.First(); var updateArgs = new DiagnosticsUpdatedArgs( new LiveId(), workspace, workspace.CurrentSolution, document.Project.Id, document.Id, ImmutableArray.Create( CreateDiagnosticData(workspace, document, new TextSpan(0, 0)), CreateDiagnosticData(workspace, document, new TextSpan(0, 1)))); var spans = GetErrorsFromUpdateSource(workspace, document, updateArgs); Assert.Equal(2, spans.Count()); var first = spans.First(); var second = spans.Last(); Assert.Equal(1, first.Span.Span.Length); Assert.Equal(1, second.Span.Span.Length); } } private class LiveId : ISupportLiveUpdate { public LiveId() { } } private static IEnumerable<ITagSpan<IErrorTag>> GetErrorSpans(params string[] content) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(content)) { return GetErrorSpans(workspace); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using System; using System.Diagnostics; using System.Security.Principal; using Xunit; namespace System.ServiceProcess.Tests { internal sealed class ServiceProvider { public readonly string TestMachineName; public readonly TimeSpan ControlTimeout; public readonly string TestServiceName; public readonly string TestServiceDisplayName; public readonly string DependentTestServiceNamePrefix; public readonly string DependentTestServiceDisplayNamePrefix; public readonly string TestServiceRegistryKey; public ServiceProvider() { TestMachineName = "."; ControlTimeout = TimeSpan.FromSeconds(120); TestServiceName = Guid.NewGuid().ToString(); TestServiceDisplayName = "Test Service " + TestServiceName; DependentTestServiceNamePrefix = TestServiceName + ".Dependent"; DependentTestServiceDisplayNamePrefix = TestServiceDisplayName + ".Dependent"; TestServiceRegistryKey = @"HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\" + TestServiceName; // Create the service CreateTestServices(); } private void CreateTestServices() { // Create the test service and its dependent services. Then, start the test service. // All control tests assume that the test service is running when they are executed. // So all tests should make sure to restart the service if they stop, pause, or shut // it down. RunServiceExecutable("create"); } public void DeleteTestServices() { RunServiceExecutable("delete"); RegistryKey users = Registry.Users; if (users.OpenSubKey(".DEFAULT\\dotnetTests") != null) users.DeleteSubKeyTree(".DEFAULT\\dotnetTests"); } private void RunServiceExecutable(string action) { const string serviceExecutable = "System.ServiceProcess.ServiceController.TestNativeService.exe"; var process = new Process(); process.StartInfo.FileName = serviceExecutable; process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\" {2}", TestServiceName, TestServiceDisplayName, action); process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { throw new Exception("error: " + serviceExecutable + " failed with exit code " + process.ExitCode.ToString()); } } } [OuterLoop(/* Modifies machine state */)] public class ServiceControllerTests : IDisposable { private const int ExpectedDependentServiceCount = 3; private static readonly Lazy<bool> s_runningWithElevatedPrivileges = new Lazy<bool>( () => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)); private readonly ServiceProvider _testService; public ServiceControllerTests() { _testService = new ServiceProvider(); } private static bool RunningWithElevatedPrivileges { get { return s_runningWithElevatedPrivileges.Value; } } private void AssertExpectedProperties(ServiceController testServiceController) { var comparer = PlatformDetection.IsFullFramework ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; // Full framework upper cases the name Assert.Equal(_testService.TestServiceName, testServiceController.ServiceName, comparer); Assert.Equal(_testService.TestServiceDisplayName, testServiceController.DisplayName); Assert.Equal(_testService.TestMachineName, testServiceController.MachineName); Assert.Equal(ServiceType.Win32OwnProcess, testServiceController.ServiceType); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void ConstructWithServiceName() { var controller = new ServiceController(_testService.TestServiceName); AssertExpectedProperties(controller); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void ConstructWithServiceName_ToUpper() { var controller = new ServiceController(_testService.TestServiceName.ToUpperInvariant()); AssertExpectedProperties(controller); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void ConstructWithDisplayName() { var controller = new ServiceController(_testService.TestServiceDisplayName); AssertExpectedProperties(controller); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void ConstructWithMachineName() { var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName); AssertExpectedProperties(controller); Assert.Throws<ArgumentException>(() => { var c = new ServiceController(_testService.TestServiceName, ""); }); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void ControlCapabilities() { var controller = new ServiceController(_testService.TestServiceName); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.True(controller.CanStop); Assert.True(controller.CanPauseAndContinue); Assert.False(controller.CanShutdown); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void StartWithArguments() { var controller = new ServiceController(_testService.TestServiceName); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Stopped, controller.Status); var args = new[] { "a", "b", "c", "d", "e" }; controller.Start(args); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); // The test service writes the arguments that it was started with to the _testService.TestServiceRegistryKey. // Read this key to verify that the arguments were properly passed to the service. string argsString = Registry.GetValue(_testService.TestServiceRegistryKey, "ServiceArguments", null) as string; Assert.Equal(string.Join(",", args), argsString); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void Start_NullArg_ThrowsArgumentNullException() { var controller = new ServiceController(_testService.TestServiceName); Assert.Throws<ArgumentNullException>(() => controller.Start(new string[] { null } )); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void StopAndStart() { var controller = new ServiceController(_testService.TestServiceName); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); for (int i = 0; i < 2; i++) { controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Stopped, controller.Status); controller.Start(); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); } } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void PauseAndContinue() { var controller = new ServiceController(_testService.TestServiceName); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); for (int i = 0; i < 2; i++) { controller.Pause(); controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Paused, controller.Status); controller.Continue(); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); } } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void GetServices_FindSelf() { bool foundTestService = false; foreach (var service in ServiceController.GetServices()) { if (service.ServiceName == _testService.TestServiceName) { foundTestService = true; AssertExpectedProperties(service); } } Assert.True(foundTestService, "Test service was not enumerated with all services"); } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void Dependencies() { // The test service creates a number of dependent services, each of which is depended on // by all the services created after it. var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ExpectedDependentServiceCount, controller.DependentServices.Length); for (int i = 0; i < controller.DependentServices.Length; i++) { var dependent = AssertHasDependent(controller, _testService.DependentTestServiceNamePrefix + i, _testService.DependentTestServiceDisplayNamePrefix + i); Assert.Equal(ServiceType.Win32OwnProcess, dependent.ServiceType); // Assert that this dependent service is depended on by all the test services created after it Assert.Equal(ExpectedDependentServiceCount - i - 1, dependent.DependentServices.Length); for (int j = i + 1; j < ExpectedDependentServiceCount; j++) { AssertHasDependent(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j); } // Assert that the dependent service depends on the main test service AssertDependsOn(dependent, _testService.TestServiceName, _testService.TestServiceDisplayName); // Assert that this dependent service depends on all the test services created before it Assert.Equal(i + 1, dependent.ServicesDependedOn.Length); for (int j = i - 1; j >= 0; j--) { AssertDependsOn(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j); } } } [ConditionalFact(nameof(RunningWithElevatedPrivileges))] public void ServicesStartMode() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ServiceStartMode.Manual, controller.StartType); // Check for the startType of the dependent services. for (int i = 0; i < controller.DependentServices.Length; i++) { Assert.Equal(ServiceStartMode.Disabled, controller.DependentServices[i].StartType); } } public void Dispose() { _testService.DeleteTestServices(); } private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName) { var dependent = FindService(controller.DependentServices, serviceName, displayName); Assert.NotNull(dependent); return dependent; } private static ServiceController AssertDependsOn(ServiceController controller, string serviceName, string displayName) { var dependency = FindService(controller.ServicesDependedOn, serviceName, displayName); Assert.NotNull(dependency); return dependency; } private static ServiceController FindService(ServiceController[] services, string serviceName, string displayName) { foreach (ServiceController service in services) { if (service.ServiceName == serviceName && service.DisplayName == displayName) { return service; } } return null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Xml; namespace WHOperation { public partial class vendorLabelMaster : Form { String cConnStr = "Persist Security Info=False;User ID=appuser;pwd=application;Initial Catalog=dbWHOperation;Data Source=142.2.70.81;pooling=true"; List<byte[]> lLabelImage; public vendorLabelMaster() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged); this.pictureBox1.MouseHover += new EventHandler(this.pictureBox1_MouseOverHandle); this.pictureBox1.MouseLeave += new EventHandler(this.pictureBox1_MouseLeaveHandle); base.OnLoad(e); } private void pictureBox1_MouseOverHandle(object sender, EventArgs e) { pictureBox1.Height = 300; pictureBox1.Width = 250; Point x = new Point(); x.X = groupBox2.Location.X; x.Y = groupBox2.Location.Y; pictureBox1.Location = x; } private void pictureBox1_MouseLeaveHandle(object sender, EventArgs e) { pictureBox1.Height = 115; pictureBox1.Width = 150; Point x = new Point(); x.X = 107; x.Y = 129; pictureBox1.Location = x; } private void dataGridView1_SelectionChanged(object sender, EventArgs e) { setFieldData(); procSelRowData(); tfvendor.ReadOnly = true; tftemplateid.ReadOnly = true; lhMode.Text = ""; bhSave.Enabled = false; lhMode.Text = ""; } void setFieldData() { cbdataname.Items.Clear(); cbdataname.Items.Add("DATECODE"); cbdataname.Items.Add("MFGRPART"); cbdataname.Items.Add("MFGDATE"); cbdataname.Items.Add("EXPIREDATE"); cbdataname.Items.Add("RECQTY"); cbdataname.Items.Add("LOTNUMBER"); cbdataname.Items.Add("DNPARTNUMBER"); } private void bhAdd_Click(object sender, EventArgs e) { bhSave.Enabled = true; lhMode.Text = "A"; tfvendor.ReadOnly = false; tftemplateid.ReadOnly = false; dataGridView2.Rows.Clear(); } private void bhEdit_Click(object sender, EventArgs e) { bhSave.Enabled = true; lhMode.Text = "E"; tfvendor.ReadOnly = true; tftemplateid.ReadOnly = true; } private void bhDelete_Click(object sender, EventArgs e) { String cVendor, cTemplateID,cQuery; DataGridViewRow cRow; DialogResult cRet; cRow = dataGridView1.CurrentRow; if (cRow == null) return; cVendor = cRow.Cells[0].Value.ToString(); cTemplateID = cRow.Cells[1].Value.ToString(); cRet = MessageBox.Show("Are you sure to delete?", "Warning", MessageBoxButtons.YesNo); if (cRet == DialogResult.No) return; using (SqlConnection conn1 = new SqlConnection(cConnStr)) { conn1.Open(); cQuery = "delete from PIMLVendorTemplate where vendorid='" + cVendor + "' and TemplateID='" + cTemplateID + "'"; SqlCommand myComm = new SqlCommand(cQuery, conn1); myComm.ExecuteNonQuery(); loadVendorData(); } } private void bhSave_Click(object sender, EventArgs e) { if (saveHeader() == 0) { bhSave.Enabled = false; tfvendor.ReadOnly = true; tftemplateid.ReadOnly = true; } } string valHeader() { String cRet,cQuery; int cCo; SqlDataReader myReader; SqlCommand cmdIns; cRet = "0"; cCo = 0; using (SqlConnection conn1 = new SqlConnection(cConnStr)) { conn1.Open(); cQuery = "select count(*) from PIMLVendorTemplate where vendorID='"+tfvendor.Text+"' and templateID='"+tftemplateid.Text+"'"; cmdIns = new SqlCommand(cQuery,conn1); myReader = cmdIns.ExecuteReader(); while (myReader.Read()) { cCo = myReader.GetInt32(0); } if (cCo > 0) { cRet = "1"; } } return cRet; } int saveHeader() { byte[] cImage; String cDefault,cQuery; SqlParameter _guidParam; SqlCommand cmdIns; if (lhMode.Text == "A") { if (valHeader() != "0") { MessageBox.Show("Data validation failed"); return 1; } } if (tffilename.Text.Length > 0) cImage = File.ReadAllBytes(@tffilename.Text); else cImage = File.ReadAllBytes(Application.StartupPath + @"\images\NotAvailable.png"); if (cbdefault.Checked == true) cDefault = "Y"; else cDefault = "N"; using (SqlConnection conn1 = new SqlConnection(cConnStr)) { conn1.Open(); if (lhMode.Text == "E") { cQuery = "update PIMLVendorTemplate set isDefault='" + cDefault + "' where VendorID='" + tfvendor.Text + "' and TemplateID='" + tftemplateid.Text + "' "; cmdIns = new SqlCommand(cQuery, conn1); } else { cQuery = "insert into PIMLVendorTemplate (VendorID,TemplateID,isDefault,templateImage) values('" + tfvendor.Text + "','" + tftemplateid.Text + "','" + cDefault + "',@fileD) "; _guidParam = new SqlParameter("@fileD", System.Data.SqlDbType.Binary); _guidParam.Value = cImage; cmdIns = new SqlCommand(cQuery, conn1); cmdIns.Parameters.Add(_guidParam); } cmdIns.ExecuteNonQuery(); if (lhMode.Text == "E"){ if (tffilename.Text.Length > 0) { cQuery = "update PIMLVendorTemplate set templateImage=@fileD where VendorID='" + tfvendor.Text + "' and TemplateID='" + tftemplateid.Text + "' "; cmdIns = new SqlCommand(cQuery, conn1); _guidParam = new SqlParameter("@fileD", System.Data.SqlDbType.Binary); _guidParam.Value = cImage; cmdIns.Parameters.Add(_guidParam); cmdIns.ExecuteNonQuery(); pictureBox1.Image = getImage(cImage); } } } tffilename.Text = ""; loadVendorData(); return 0; } void procSelRowData() { byte[] cImage; int cR; DataGridViewRow cRow; StringBuilder cXMLData = new StringBuilder(); if (dataGridView1.RowCount == 0) { dataGridView2.Rows.Clear(); return; } cR = dataGridView1.CurrentRow.Index; cRow = dataGridView1.CurrentRow; cImage = lLabelImage[cR]; if (cImage.Length > 0) { } else { cImage = File.ReadAllBytes(Application.StartupPath + @"\images\notavailable.png"); } pictureBox1.Image = getImage(cImage); tfvendor.Text = cRow.Cells[0].Value.ToString(); tftemplateid.Text = cRow.Cells[1].Value.ToString(); cXMLData.Append(cRow.Cells[3].Value.ToString()); if (cRow.Cells[2].Value.ToString().Trim().ToUpper() == "Y") cbdefault.Checked = true; else cbdefault.Checked = false; //processXML(cXMLData); //old version if (cXMLData.Length > 0) processXMLv01(cXMLData); // new version else dataGridView2.Rows.Clear(); } private void bhgetimagefile_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); tffilename.Text = openFileDialog1.FileName; } void processXMLv01(StringBuilder cXMLData) { XmlDocument xmlDoc = new XmlDocument(); String cLabelType,c2DSeperator; xmlDoc.LoadXml(cXMLData.ToString()); String[] cRec = new String[4]; XmlNodeList xmlDevices = xmlDoc.SelectNodes("/Header/Field"); dataGridView2.Rows.Clear(); foreach (XmlNode device in xmlDevices) { cRec = new String[4]; cRec[0] = device.SelectNodes("Name").Item(0).InnerXml; cRec[1] = device.SelectNodes("Prefix").Item(0).InnerXml; cRec[2] = device.SelectNodes("Seperator").Item(0).InnerXml; cRec[3] = device.SelectNodes("Index").Item(0).InnerXml; dataGridView2.Rows.Add(cRec); if (cbdataname.Items.IndexOf(cRec[0].ToUpper()) >= 0) { cbdataname.Items.RemoveAt(cbdataname.Items.IndexOf(cRec[0].ToUpper())); } } cLabelType = "Single"; c2DSeperator = ""; try { xmlDevices = xmlDoc.SelectNodes("/Header/type"); cLabelType = xmlDevices.Item(0).InnerXml; xmlDevices = xmlDoc.SelectNodes("/Header/twodseperator"); c2DSeperator = xmlDevices.Item(0).InnerXml; } catch (Exception ex) { } tflabeltype.Text = cLabelType; tf2dseperator.Text = c2DSeperator; } void processXML(StringBuilder cXMLData) { DataRow cR; String[] cRec = new String[4]; DataSet dsAuthors = new DataSet("Template"); byte[] byteArray = Encoding.ASCII.GetBytes(cXMLData.ToString()); MemoryStream stream = new MemoryStream(byteArray); StreamReader xx1 = new StreamReader(stream); dataGridView2.Rows.Clear(); try { dsAuthors.ReadXml(xx1); } catch (Exception) { return; } finally { } int i = 0; if (dsAuthors.Tables.IndexOf("Field") < 0) return; while (i <= dsAuthors.Tables["Field"].Rows.Count - 1) { cRec = new String[4]; cR = dsAuthors.Tables["Field"].Rows[i]; cRec[0] = cR.ItemArray[0].ToString(); cRec[1] = cR.ItemArray[1].ToString(); cRec[2] = cR.ItemArray[2].ToString(); cRec[3] = cR.ItemArray[3].ToString(); dataGridView2.Rows.Add(cRec); if (cbdataname.Items.IndexOf(cRec[0].ToUpper()) >= 0) { cbdataname.Items.RemoveAt(cbdataname.Items.IndexOf(cRec[0].ToUpper())); } i += 1; } if (dsAuthors.Tables.IndexOf("Header") >= 0) tflabeltype.Text = dsAuthors.Tables["Header"].Rows[0].ItemArray[1].ToString(); else tflabeltype.Text = "Single"; } void loadVendorData() { String cQuery; String[] cRec = new String[4]; SqlDataReader myReader; byte[] cImage; dataGridView1.Rows.Clear(); lLabelImage = new List<byte[]>(); try { if (tfsearchvendor.Text.Length > 0){ cQuery = "select VendorID,TemplateID,isDefault,xmlVendorData,templateImage from PIMLVendorTemplate where vendorid like '"+tfsearchvendor.Text +"%' Order by VendorID,TemplateID "; //cQuery = "select VendorID,TemplateID,isDefault,xmlVendorData from PIMLVendorTemplate where vendorid like '" + tfsearchvendor.Text + "%' Order by VendorID,TemplateID "; }else{ cQuery = "select VendorID,TemplateID,isDefault,xmlVendorData,templateImage from PIMLVendorTemplate Order by VendorID,TemplateID "; //cQuery = "select VendorID,TemplateID,isDefault,xmlVendorData from PIMLVendorTemplate Order by VendorID,TemplateID "; } using (SqlConnection conn = new SqlConnection(cConnStr)) { conn.Open(); SqlCommand cmd = new SqlCommand(cQuery, conn); myReader = cmd.ExecuteReader(); while (myReader.Read()) { cRec[0] = myReader.GetValue(0).ToString(); cRec[1] = myReader.GetValue(1).ToString(); cRec[2] = myReader.GetValue(2).ToString(); cRec[3] = myReader.GetValue(3).ToString(); cImage = new byte[0]; //lLabelImage.Add(cImage); //lLabelImage.Add((byte[])myReader[4]); if (myReader[4] is DBNull) { cImage = new byte[0]; lLabelImage.Add(cImage); } else { lLabelImage.Add((byte[])myReader[4]); } dataGridView1.Rows.Add(cRec); } myReader.Close(); procSelRowData(); } } catch (Exception) { } finally { } } Image getImage(byte[] cByte) { MemoryStream ms = new MemoryStream(cByte); Image returnImage = Image.FromStream(ms); return returnImage; } private void button1_Click(object sender, EventArgs e) { loadVendorData(); } private void bdDelete_Click(object sender, EventArgs e) { String cField; int cR; DataGridViewRow cRow; cRow = dataGridView2.CurrentRow; if (dataGridView2.RowCount ==0) return; cField = cRow.Cells[0].Value.ToString(); cR = dataGridView2.CurrentRow.Index; dataGridView2.Rows.RemoveAt(cR); cbdataname.Items.Add(cField); } private void bdSave_Click(object sender, EventArgs e) { String cField,cPrefix,cSeperator,cIndex; Double cTemp; if (cbdataname.SelectedItem == null) return; cField = cbdataname.SelectedItem.ToString(); cPrefix = tfprefix.Text; cSeperator= tfseperator.Text; cIndex = tfindex.Text; if (cSeperator == " ") cSeperator = "SPACE"; if (cSeperator.Length > 0) { if (cIndex.Length == 0) { cIndex = "1"; } else { if (!Double.TryParse(cIndex, out cTemp)) { cIndex = "1"; } } } cbdataname.Items.RemoveAt(cbdataname.Items.IndexOf(cbdataname.SelectedItem)); dataGridView2.Rows.Add(cField,cPrefix,cSeperator,cIndex); tfprefix.Text = ""; tfseperator.Text = ""; tfindex.Text = ""; } private void bdsavexml_Click(object sender, EventArgs e) { String cXMLData,cPrefix,cFieldName,cQuery,cIndex,cSeperator; DataGridViewRow cRow; SqlCommand cmdIns; int i; if (lhMode.Text == "A" || dataGridView1.RowCount == 0) { MessageBox.Show("Save Header and Add Data Labels"); return; } if (tflabeltype.SelectedIndex < 0) { tflabeltype.SelectedIndex = 0; } cXMLData = "<Header>"; i = 0; while (i <= dataGridView2.Rows.Count - 1) { cRow = dataGridView2.Rows[i]; cFieldName = cRow.Cells[0].Value.ToString(); cPrefix = cRow.Cells[1].Value.ToString(); cSeperator = cRow.Cells[2].Value.ToString(); cIndex = cRow.Cells[3].Value.ToString(); cPrefix = cPrefix.Replace("<", "&lt;"); cPrefix = cPrefix.Replace(">", "&gt;"); //cFieldName = cFieldName.Substring(3, cFieldName.Length - 3); cXMLData += "<Field>"; cXMLData += "<Name>" + cFieldName + "</Name>"; cXMLData += "<Prefix>" + cPrefix + "</Prefix>"; cXMLData += "<Seperator>" + cSeperator + "</Seperator>"; cXMLData += "<Index>" + cIndex + "</Index>"; cXMLData += "</Field>"; i += 1; } cXMLData += "<type>" + tflabeltype.SelectedItem.ToString() + "</type>"; cXMLData += "<twodseperator>" + @tf2dseperator.Text + "</twodseperator>"; cXMLData += "</Header>"; cRow = dataGridView1.CurrentRow; cRow.Cells[3].Value = cXMLData; cQuery = "update PIMLVendorTemplate set xmlVendorData='"+cXMLData+"' where vendorid='"+tfvendor.Text+"' and templateID='"+tftemplateid.Text+"'"; using (SqlConnection conn1 = new SqlConnection(cConnStr)) { conn1.Open(); cmdIns = new SqlCommand(cQuery, conn1); cmdIns.ExecuteNonQuery(); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Ssl { using System.Linq; using Apache.Ignite.Core.Ssl; using Apache.Ignite.Core.Common; using NUnit.Framework; /// <summary> /// SSL configuration tests. /// </summary> [Category(TestUtils.CategoryIntensive)] public class SslConfigurationTest { /** Test Password. */ private const string Password = "123456"; /** Key Store file. */ private const string KeyStoreFilePath = @"Config/KeyStore/server.jks"; /** Trust Store file. */ private const string TrustStoreFilePath = @"Config/KeyStore/trust.jks"; /// <summary> /// Test teardown. /// </summary> [TearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Returns SSL Context factory for tests. /// </summary> private static SslContextFactory GetSslContextFactory() { return new SslContextFactory(KeyStoreFilePath, Password, TrustStoreFilePath, Password); } /// <summary> /// Tests Node Start with SslContextFactory /// </summary> [Test] public void TestStart([Values(null, TrustStoreFilePath)] string trustStoreFilePath) { var factory = GetSslContextFactory(); factory.TrustStoreFilePath = trustStoreFilePath; var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SslContextFactory = factory }; var grid = Ignition.Start(cfg); Assert.IsNotNull(grid); Assert.AreEqual(1, grid.GetCluster().GetNodes().Count); var cfgFactory = grid.GetConfiguration().SslContextFactory; Assert.True(cfgFactory is SslContextFactory); var sslContextFactory = (SslContextFactory)cfgFactory; Assert.AreEqual(Password, sslContextFactory.KeyStorePassword); Assert.AreEqual(Password, sslContextFactory.TrustStorePassword); Assert.AreEqual(KeyStoreFilePath, sslContextFactory.KeyStoreFilePath); Assert.AreEqual(trustStoreFilePath, sslContextFactory.TrustStoreFilePath); } /// <summary> /// Tests IgniteException when SSL configuration /// </summary> [Test] public void TestConfigurationExceptions() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SslContextFactory = new SslContextFactory(@"WrongPath/server.jks", Password, TrustStoreFilePath, Password) }; var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.True(ex.Message.StartsWith(@"Failed to initialize key store (key store file was not found): " + @"[path=WrongPath/server.jks")); cfg.SslContextFactory = new SslContextFactory(KeyStoreFilePath, Password, @"WrongPath/trust.jks", Password); ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.True(ex.Message.StartsWith(@"Failed to initialize key store (key store file was not found): " + @"[path=WrongPath/trust.jks")); cfg.SslContextFactory = new SslContextFactory(KeyStoreFilePath, "654321", TrustStoreFilePath, Password); ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.AreEqual(@"Failed to initialize key store (I/O error occurred): Config/KeyStore/server.jks", ex.Message); cfg.SslContextFactory = new SslContextFactory(KeyStoreFilePath, Password, TrustStoreFilePath, "654321"); ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.AreEqual(@"Failed to initialize key store (I/O error occurred): Config/KeyStore/trust.jks", ex.Message); } /// <summary> /// Tests Node Start with SslContextFactory from Spring xml. /// </summary> [Test] public void TestStartWithConfigPath() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = @"Config/ssl.xml", }; var grid = Ignition.Start(cfg); Assert.IsNotNull(grid); Assert.AreEqual(1, grid.GetCluster().GetNodes().Count); var factory = grid.GetConfiguration().SslContextFactory; Assert.True(factory is SslContextFactory); var sslContextFactory = (SslContextFactory)factory; Assert.AreEqual(Password, sslContextFactory.KeyStorePassword); Assert.AreEqual(Password, sslContextFactory.TrustStorePassword); Assert.AreEqual(KeyStoreFilePath, sslContextFactory.KeyStoreFilePath); Assert.AreEqual(TrustStoreFilePath, sslContextFactory.TrustStoreFilePath); } /// <summary> /// Simple test with 2 SSL nodes. /// </summary> [Test] public void TestTwoServers() { var cfg1 = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = @"Config/ssl.xml" }; var cfg2 = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "grid2")) { SslContextFactory = GetSslContextFactory() }; var grid1 = Ignition.Start(cfg1); Assert.AreEqual("grid1", grid1.Name); Assert.AreSame(grid1, Ignition.GetIgnite()); Assert.AreSame(grid1, Ignition.GetAll().Single()); var grid2 = Ignition.Start(cfg2); Assert.AreEqual("grid2", grid2.Name); Assert.Throws<IgniteException>(() => Ignition.GetIgnite()); Assert.AreSame(grid1, Ignition.GetIgnite("grid1")); Assert.AreSame(grid1, Ignition.TryGetIgnite("grid1")); Assert.AreSame(grid2, Ignition.GetIgnite("grid2")); Assert.AreSame(grid2, Ignition.TryGetIgnite("grid2")); Assert.AreEqual(new[] {grid1, grid2}, Ignition.GetAll().OrderBy(x => x.Name).ToArray()); Assert.AreEqual(2, grid1.GetCluster().GetNodes().Count); Assert.AreEqual(2, grid2.GetCluster().GetNodes().Count); } /// <summary> /// Simple test with 1 SSL node and 1 no-SSL node. /// </summary> [Test] public void TestSslConfigurationMismatch() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "grid1")); var sslCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "grid2")) { SslContextFactory = GetSslContextFactory() }; Ignition.Start(cfg); var ex = Assert.Throws<IgniteException>(() => Ignition.Start(sslCfg)); Assert.True(ex.Message.StartsWith(@"Unable to establish secure connection. " + @"Was remote cluster configured with SSL?")); Ignition.StopAll(true); Ignition.Start(sslCfg); ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.True(ex.Message.StartsWith(@"Unable to establish secure connection. " + @"Was remote cluster configured with SSL?")); } /// <summary> /// Tests the client-server mode. /// </summary> [Test] public void TestClientServer() { var factory = GetSslContextFactory(); var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "grid1")) { SslContextFactory = factory }; var clientCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "grid2")) { SslContextFactory = factory, ClientMode = true }; using (var serv = Ignition.Start(servCfg)) // start server-mode ignite first { Assert.IsFalse(serv.GetCluster().GetLocalNode().IsClient); using (var grid = Ignition.Start(clientCfg)) { Assert.IsTrue(grid.GetCluster().GetLocalNode().IsClient); Assert.AreEqual(2, grid.GetCluster().GetNodes().Count); Assert.AreEqual(2, serv.GetCluster().GetNodes().Count); Assert.AreEqual(1, grid.GetCluster().ForServers().GetNodes().Count); Assert.AreEqual(1, serv.GetCluster().ForServers().GetNodes().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 Microsoft.Win32; using System.Diagnostics; using System.Security.Principal; using Xunit; namespace System.ServiceProcess.Tests { internal sealed class ServiceProvider { public readonly string TestMachineName; public readonly TimeSpan ControlTimeout; public readonly string TestServiceName; public readonly string TestServiceDisplayName; public readonly string DependentTestServiceNamePrefix; public readonly string DependentTestServiceDisplayNamePrefix; public readonly string TestServiceRegistryKey; public ServiceProvider() { TestMachineName = "."; ControlTimeout = TimeSpan.FromSeconds(3); TestServiceName = Guid.NewGuid().ToString(); TestServiceDisplayName = "Test Service " + TestServiceName; DependentTestServiceNamePrefix = TestServiceName + ".Dependent"; DependentTestServiceDisplayNamePrefix = TestServiceDisplayName + ".Dependent"; TestServiceRegistryKey = @"HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\" + TestServiceName; // Create the service CreateTestServices(); } private void CreateTestServices() { // Create the test service and its dependent services. Then, start the test service. // All control tests assume that the test service is running when they are executed. // So all tests should make sure to restart the service if they stop, pause, or shut // it down. RunServiceExecutable("create"); } public void DeleteTestServices() { RunServiceExecutable("delete"); RegistryKey users = Registry.Users; if (users.OpenSubKey(".DEFAULT\\dotnetTests") != null) users.DeleteSubKeyTree(".DEFAULT\\dotnetTests"); } private void RunServiceExecutable(string action) { const string serviceExecutable = "System.ServiceProcess.ServiceController.TestNativeService.exe"; var process = new Process(); process.StartInfo.FileName = serviceExecutable; process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\" {2}", TestServiceName, TestServiceDisplayName, action); process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { throw new Exception("error: " + serviceExecutable + " failed with exit code " + process.ExitCode.ToString()); } } } public class ServiceControllerTests : IDisposable { private const int ExpectedDependentServiceCount = 3; ServiceProvider _testService; public ServiceControllerTests() { _testService = new ServiceProvider(); } private static bool RunningWithElevatedPrivileges { get { return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } } [ConditionalFact("RunningWithElevatedPrivileges")] public void ConstructWithServiceName() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(_testService.TestServiceName, controller.ServiceName); Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName); Assert.Equal(_testService.TestMachineName, controller.MachineName); Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType); } [ConditionalFact("RunningWithElevatedPrivileges")] public void ConstructWithDisplayName() { var controller = new ServiceController(_testService.TestServiceDisplayName); Assert.Equal(_testService.TestServiceName, controller.ServiceName); Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName); Assert.Equal(_testService.TestMachineName, controller.MachineName); Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType); } [ConditionalFact("RunningWithElevatedPrivileges")] public void ConstructWithMachineName() { var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName); Assert.Equal(_testService.TestServiceName, controller.ServiceName); Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName); Assert.Equal(_testService.TestMachineName, controller.MachineName); Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType); Assert.Throws<ArgumentException>(() => { var c = new ServiceController(_testService.TestServiceName, ""); }); } [ConditionalFact("RunningWithElevatedPrivileges")] public void ControlCapabilities() { var controller = new ServiceController(_testService.TestServiceName); Assert.True(controller.CanStop); Assert.True(controller.CanPauseAndContinue); Assert.False(controller.CanShutdown); } [ConditionalFact("RunningWithElevatedPrivileges")] public void StartWithArguments() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ServiceControllerStatus.Running, controller.Status); controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Stopped, controller.Status); var args = new[] { "a", "b", "c", "d", "e" }; controller.Start(args); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); // The test service writes the arguments that it was started with to the _testService.TestServiceRegistryKey. // Read this key to verify that the arguments were properly passed to the service. string argsString = Registry.GetValue(_testService.TestServiceRegistryKey, "ServiceArguments", null) as string; Assert.Equal(string.Join(",", args), argsString); } [ConditionalFact("RunningWithElevatedPrivileges")] public void StopAndStart() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ServiceControllerStatus.Running, controller.Status); for (int i = 0; i < 2; i++) { controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Stopped, controller.Status); controller.Start(); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); } } [ConditionalFact("RunningWithElevatedPrivileges")] public void PauseAndContinue() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ServiceControllerStatus.Running, controller.Status); for (int i = 0; i < 2; i++) { controller.Pause(); controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Paused, controller.Status); controller.Continue(); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); } } [ConditionalFact("RunningWithElevatedPrivileges")] public void WaitForStatusTimeout() { var controller = new ServiceController(_testService.TestServiceName); Assert.Throws<System.ServiceProcess.TimeoutException>(() => controller.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.Zero)); } [ConditionalFact("RunningWithElevatedPrivileges")] public void GetServices() { bool foundTestService = false; foreach (var service in ServiceController.GetServices()) { if (service.ServiceName == _testService.TestServiceName) { foundTestService = true; } } Assert.True(foundTestService, "Test service was not enumerated with all services"); } [ConditionalFact("RunningWithElevatedPrivileges")] public void GetDevices() { var devices = ServiceController.GetDevices(); Assert.True(devices.Length != 0); const ServiceType SERVICE_TYPE_DRIVER = ServiceType.FileSystemDriver | ServiceType.KernelDriver | ServiceType.RecognizerDriver; Assert.All(devices, device => Assert.NotEqual(0, (int)(device.ServiceType & SERVICE_TYPE_DRIVER))); } [ConditionalFact("RunningWithElevatedPrivileges")] public void Dependencies() { // The test service creates a number of dependent services, each of which is depended on // by all the services created after it. var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ExpectedDependentServiceCount, controller.DependentServices.Length); for (int i = 0; i < controller.DependentServices.Length; i++) { var dependent = AssertHasDependent(controller, _testService.DependentTestServiceNamePrefix + i, _testService.DependentTestServiceDisplayNamePrefix + i); Assert.Equal(ServiceType.Win32OwnProcess, dependent.ServiceType); // Assert that this dependent service is depended on by all the test services created after it Assert.Equal(ExpectedDependentServiceCount - i - 1, dependent.DependentServices.Length); for (int j = i + 1; j < ExpectedDependentServiceCount; j++) { AssertHasDependent(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j); } // Assert that the dependent service depends on the main test service AssertDependsOn(dependent, _testService.TestServiceName, _testService.TestServiceDisplayName); // Assert that this dependent service depends on all the test services created before it Assert.Equal(i + 1, dependent.ServicesDependedOn.Length); for (int j = i - 1; j >= 0; j--) { AssertDependsOn(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j); } } } [ConditionalFact("RunningWithElevatedPrivileges")] public void ServicesStartMode() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ServiceStartMode.Manual, controller.StartType); // Check for the startType of the dependent services. for (int i = 0; i < controller.DependentServices.Length; i++) { Assert.Equal(ServiceStartMode.Disabled, controller.DependentServices[i].StartType); } } public void Dispose() { _testService.DeleteTestServices(); } private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName) { var dependent = FindService(controller.DependentServices, serviceName, displayName); Assert.NotNull(dependent); return dependent; } private static ServiceController AssertDependsOn(ServiceController controller, string serviceName, string displayName) { var dependency = FindService(controller.ServicesDependedOn, serviceName, displayName); Assert.NotNull(dependency); return dependency; } private static ServiceController FindService(ServiceController[] services, string serviceName, string displayName) { foreach (ServiceController service in services) { if (service.ServiceName == serviceName && service.DisplayName == displayName) { return service; } } return null; } } }
// // ModuleDefinition.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using SR = System.Reflection; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Cecil.PE; using Mono.Collections.Generic; namespace Mono.Cecil { public enum ReadingMode { Immediate = 1, Deferred = 2, } public sealed class ReaderParameters { ReadingMode reading_mode; IAssemblyResolver assembly_resolver; Stream symbol_stream; ISymbolReaderProvider symbol_reader_provider; bool read_symbols; public ReadingMode ReadingMode { get { return reading_mode; } set { reading_mode = value; } } public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } set { assembly_resolver = value; } } public Stream SymbolStream { get { return symbol_stream; } set { symbol_stream = value; } } public ISymbolReaderProvider SymbolReaderProvider { get { return symbol_reader_provider; } set { symbol_reader_provider = value; } } public bool ReadSymbols { get { return read_symbols; } set { read_symbols = value; } } public ReaderParameters () : this (ReadingMode.Deferred) { } public ReaderParameters (ReadingMode readingMode) { this.reading_mode = readingMode; } } #if !READ_ONLY public sealed class ModuleParameters { ModuleKind kind; TargetRuntime runtime; TargetArchitecture architecture; IAssemblyResolver assembly_resolver; public ModuleKind Kind { get { return kind; } set { kind = value; } } public TargetRuntime Runtime { get { return runtime; } set { runtime = value; } } public TargetArchitecture Architecture { get { return architecture; } set { architecture = value; } } public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } set { assembly_resolver = value; } } public ModuleParameters () { this.kind = ModuleKind.Dll; this.runtime = GetCurrentRuntime (); this.architecture = TargetArchitecture.I386; } static TargetRuntime GetCurrentRuntime () { #if !CF return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime (); #else var corlib_version = typeof (object).Assembly.GetName ().Version; switch (corlib_version.Major) { case 1: return corlib_version.Minor == 0 ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case 2: return TargetRuntime.Net_2_0; case 4: return TargetRuntime.Net_4_0; default: throw new NotSupportedException (); } #endif } } public sealed class WriterParameters { Stream symbol_stream; ISymbolWriterProvider symbol_writer_provider; bool write_symbols; #if !SILVERLIGHT && !CF SR.StrongNameKeyPair key_pair; #endif public Stream SymbolStream { get { return symbol_stream; } set { symbol_stream = value; } } public ISymbolWriterProvider SymbolWriterProvider { get { return symbol_writer_provider; } set { symbol_writer_provider = value; } } public bool WriteSymbols { get { return write_symbols; } set { write_symbols = value; } } #if !SILVERLIGHT && !CF public SR.StrongNameKeyPair StrongNameKeyPair { get { return key_pair; } set { key_pair = value; } } #endif } #endif public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider { internal Image Image; internal MetadataSystem MetadataSystem; internal ReadingMode ReadingMode; internal ISymbolReaderProvider SymbolReaderProvider; internal ISymbolReader SymbolReader; internal IAssemblyResolver assembly_resolver; internal TypeSystem type_system; readonly MetadataReader reader; readonly string fq_name; internal ModuleKind kind; TargetRuntime runtime; TargetArchitecture architecture; ModuleAttributes attributes; Guid mvid; internal AssemblyDefinition assembly; MethodDefinition entry_point; #if !READ_ONLY MetadataImporter importer; #endif Collection<CustomAttribute> custom_attributes; Collection<AssemblyNameReference> references; Collection<ModuleReference> modules; Collection<Resource> resources; Collection<ExportedType> exported_types; TypeDefinitionCollection types; public bool IsMain { get { return kind != ModuleKind.NetModule; } } public ModuleKind Kind { get { return kind; } set { kind = value; } } public TargetRuntime Runtime { get { return runtime; } set { runtime = value; } } public TargetArchitecture Architecture { get { return architecture; } set { architecture = value; } } public ModuleAttributes Attributes { get { return attributes; } set { attributes = value; } } public string FullyQualifiedName { get { return fq_name; } } public Guid Mvid { get { return mvid; } set { mvid = value; } } internal bool HasImage { get { return Image != null; } } public bool HasSymbols { get { return SymbolReader != null; } } public override MetadataScopeType MetadataScopeType { get { return MetadataScopeType.ModuleDefinition; } } public AssemblyDefinition Assembly { get { return assembly; } } #if !READ_ONLY internal MetadataImporter MetadataImporter { get { return importer ?? (importer = new MetadataImporter (this)); } } #endif public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } } public TypeSystem TypeSystem { get { return type_system ?? (type_system = TypeSystem.CreateTypeSystem (this)); } } public bool HasAssemblyReferences { get { if (references != null) return references.Count > 0; return HasImage && Image.HasTable (Table.AssemblyRef); } } public Collection<AssemblyNameReference> AssemblyReferences { get { if (references != null) return references; if (HasImage) return references = Read (this, (_, reader) => reader.ReadAssemblyReferences ()); return references = new Collection<AssemblyNameReference> (); } } public bool HasModuleReferences { get { if (modules != null) return modules.Count > 0; return HasImage && Image.HasTable (Table.ModuleRef); } } public Collection<ModuleReference> ModuleReferences { get { if (modules != null) return modules; if (HasImage) return modules = Read (this, (_, reader) => reader.ReadModuleReferences ()); return modules = new Collection<ModuleReference> (); } } public bool HasResources { get { if (resources != null) return resources.Count > 0; if (HasImage) return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ()); return false; } } public Collection<Resource> Resources { get { if (resources != null) return resources; if (HasImage) return resources = Read (this, (_, reader) => reader.ReadResources ()); return resources = new Collection<Resource> (); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (this); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (this)); } } public bool HasTypes { get { if (types != null) return types.Count > 0; return HasImage && Image.HasTable (Table.TypeDef); } } public Collection<TypeDefinition> Types { get { if (types != null) return types; if (HasImage) return types = Read (this, (_, reader) => reader.ReadTypes ()); return types = new TypeDefinitionCollection (this); } } public bool HasExportedTypes { get { if (exported_types != null) return exported_types.Count > 0; return HasImage && Image.HasTable (Table.ExportedType); } } public Collection<ExportedType> ExportedTypes { get { if (exported_types != null) return exported_types; if (HasImage) return exported_types = Read (this, (_, reader) => reader.ReadExportedTypes ()); return exported_types = new Collection<ExportedType> (); } } public MethodDefinition EntryPoint { get { if (entry_point != null) return entry_point; if (HasImage) return entry_point = Read (this, (_, reader) => reader.ReadEntryPoint ()); return entry_point = null; } set { entry_point = value; } } internal ModuleDefinition () { this.MetadataSystem = new MetadataSystem (); this.token = new MetadataToken (TokenType.Module, 1); this.assembly_resolver = GlobalAssemblyResolver.Instance; } internal ModuleDefinition (Image image) : this () { this.Image = image; this.kind = image.Kind; this.runtime = image.Runtime; this.architecture = image.Architecture; this.attributes = image.Attributes; this.fq_name = image.FileName; this.reader = new MetadataReader (this); } public bool HasTypeReference (string fullName) { return HasTypeReference (string.Empty, fullName); } public bool HasTypeReference (string scope, string fullName) { CheckFullName (fullName); if (!HasImage) return false; return GetTypeReference (scope, fullName) != null; } public bool TryGetTypeReference (string fullName, out TypeReference type) { return TryGetTypeReference (string.Empty, fullName, out type); } public bool TryGetTypeReference (string scope, string fullName, out TypeReference type) { CheckFullName (fullName); if (!HasImage) { type = null; return false; } return (type = GetTypeReference (scope, fullName)) != null; } TypeReference GetTypeReference (string scope, string fullname) { return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2)); } public IEnumerable<TypeReference> GetTypeReferences () { if (!HasImage) return Empty<TypeReference>.Array; return Read (this, (_, reader) => reader.GetTypeReferences ()); } public IEnumerable<MemberReference> GetMemberReferences () { if (!HasImage) return Empty<MemberReference>.Array; return Read (this, (_, reader) => reader.GetMemberReferences ()); } public TypeDefinition GetType (string fullName) { CheckFullName (fullName); var position = fullName.IndexOf ('/'); if (position > 0) return GetNestedType (fullName); return ((TypeDefinitionCollection) this.Types).GetType (fullName); } public TypeDefinition GetType (string @namespace, string name) { Mixin.CheckName (name); return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name); } static void CheckFullName (string fullName) { if (fullName == null) throw new ArgumentNullException ("fullName"); if (fullName.Length == 0) throw new ArgumentException (); } TypeDefinition GetNestedType (string fullname) { var names = fullname.Split ('/'); var type = GetType (names [0]); if (type == null) return null; for (int i = 1; i < names.Length; i++) { var nested_type = type.GetNestedType (names [i]); if (nested_type == null) return null; type = nested_type; } return type; } internal FieldDefinition Resolve (FieldReference field) { return MetadataResolver.Resolve (AssemblyResolver, field); } internal MethodDefinition Resolve (MethodReference method) { return MetadataResolver.Resolve (AssemblyResolver, method); } internal TypeDefinition Resolve (TypeReference type) { return MetadataResolver.Resolve (AssemblyResolver, type); } #if !READ_ONLY static void CheckType (object type) { if (type == null) throw new ArgumentNullException ("type"); } static void CheckField (object field) { if (field == null) throw new ArgumentNullException ("field"); } static void CheckMethod (object method) { if (method == null) throw new ArgumentNullException ("method"); } static void CheckContext (IGenericParameterProvider context, ModuleDefinition module) { if (context == null) return; if (context.Module != module) throw new ArgumentException (); } #if !CF public TypeReference Import (Type type) { CheckType (type); return MetadataImporter.ImportType (type, null, ImportGenericKind.Definition); } public TypeReference Import (Type type, TypeReference context) { return Import (type, (IGenericParameterProvider) context); } public TypeReference Import (Type type, MethodReference context) { return Import (type, (IGenericParameterProvider) context); } TypeReference Import (Type type, IGenericParameterProvider context) { CheckType (type); CheckContext (context, this); return MetadataImporter.ImportType ( type, (IGenericContext) context, context != null ? ImportGenericKind.Open : ImportGenericKind.Definition); } public FieldReference Import (SR.FieldInfo field) { CheckField (field); return MetadataImporter.ImportField (field, null); } public FieldReference Import (SR.FieldInfo field, TypeReference context) { return Import (field, (IGenericParameterProvider) context); } public FieldReference Import (SR.FieldInfo field, MethodReference context) { return Import (field, (IGenericParameterProvider) context); } FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context) { CheckField (field); CheckContext (context, this); return MetadataImporter.ImportField (field, (IGenericContext) context); } public MethodReference Import (SR.MethodBase method) { CheckMethod (method); return MetadataImporter.ImportMethod (method, null, ImportGenericKind.Definition); } public MethodReference Import (SR.MethodBase method, TypeReference context) { return Import (method, (IGenericParameterProvider) context); } public MethodReference Import (SR.MethodBase method, MethodReference context) { return Import (method, (IGenericParameterProvider) context); } MethodReference Import (SR.MethodBase method, IGenericParameterProvider context) { CheckMethod (method); CheckContext (context, this); return MetadataImporter.ImportMethod (method, (IGenericContext) context, context != null ? ImportGenericKind.Open : ImportGenericKind.Definition); } #endif public TypeReference Import (TypeReference type) { CheckType (type); if (type.Module == this) return type; return MetadataImporter.ImportType (type, null); } public TypeReference Import (TypeReference type, TypeReference context) { return Import (type, (IGenericParameterProvider) context); } public TypeReference Import (TypeReference type, MethodReference context) { return Import (type, (IGenericParameterProvider) context); } TypeReference Import (TypeReference type, IGenericParameterProvider context) { CheckType (type); if (type.Module == this) return type; CheckContext (context, this); return MetadataImporter.ImportType (type, (IGenericContext) context); } public FieldReference Import (FieldReference field) { CheckField (field); if (field.Module == this) return field; return MetadataImporter.ImportField (field, null); } public FieldReference Import (FieldReference field, TypeReference context) { return Import (field, (IGenericParameterProvider) context); } public FieldReference Import (FieldReference field, MethodReference context) { return Import (field, (IGenericParameterProvider) context); } FieldReference Import (FieldReference field, IGenericParameterProvider context) { CheckField (field); if (field.Module == this) return field; CheckContext (context, this); return MetadataImporter.ImportField (field, (IGenericContext) context); } public MethodReference Import (MethodReference method) { CheckMethod (method); if (method.Module == this) return method; return MetadataImporter.ImportMethod (method, null); } public MethodReference Import (MethodReference method, TypeReference context) { return Import (method, (IGenericParameterProvider) context); } public MethodReference Import (MethodReference method, MethodReference context) { return Import (method, (IGenericParameterProvider) context); } MethodReference Import (MethodReference method, IGenericParameterProvider context) { CheckMethod (method); if (method.Module == this) return method; CheckContext (context, this); return MetadataImporter.ImportMethod (method, (IGenericContext) context); } #endif public IMetadataTokenProvider LookupToken (int token) { return LookupToken (new MetadataToken ((uint) token)); } public IMetadataTokenProvider LookupToken (MetadataToken token) { return Read (token, (t, reader) => reader.LookupToken (t)); } internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read) { var position = reader.position; var context = reader.context; var ret = read (item, reader); reader.position = position; reader.context = context; return ret; } void ProcessDebugHeader () { if (Image == null || Image.Debug.IsZero) return; byte [] header; var directory = Image.GetDebugHeader (out header); if (!SymbolReader.ProcessDebugHeader (directory, header)) throw new InvalidOperationException (); } #if !READ_ONLY public static ModuleDefinition CreateModule (string name, ModuleKind kind) { return CreateModule (name, new ModuleParameters { Kind = kind }); } public static ModuleDefinition CreateModule (string name, ModuleParameters parameters) { Mixin.CheckName (name); Mixin.CheckParameters (parameters); var module = new ModuleDefinition { Name = name, kind = parameters.Kind, runtime = parameters.Runtime, architecture = parameters.Architecture, mvid = Guid.NewGuid (), Attributes = ModuleAttributes.ILOnly, }; if (parameters.AssemblyResolver != null) module.assembly_resolver = parameters.AssemblyResolver; if (parameters.Kind != ModuleKind.NetModule) { var assembly = new AssemblyDefinition (); module.assembly = assembly; module.assembly.Name = new AssemblyNameDefinition (name, new Version (0, 0)); assembly.main_module = module; } module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic)); return module; } #endif public void ReadSymbols () { if (string.IsNullOrEmpty (fq_name)) throw new InvalidOperationException (); var provider = SymbolProvider.GetPlatformReaderProvider (); SymbolReader = provider.GetSymbolReader (this, fq_name); ProcessDebugHeader (); } public void ReadSymbols (ISymbolReader reader) { if (reader == null) throw new ArgumentNullException ("reader"); SymbolReader = reader; ProcessDebugHeader (); } public static ModuleDefinition ReadModule (string fileName) { return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred)); } public static ModuleDefinition ReadModule (Stream stream) { return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred)); } public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters) { using (var stream = GetFileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { return ReadModule (stream, parameters); } } static void CheckStream (object stream) { if (stream == null) throw new ArgumentNullException ("stream"); } public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters) { CheckStream (stream); if (!stream.CanRead || !stream.CanSeek) throw new ArgumentException (); Mixin.CheckParameters (parameters); return ModuleReader.CreateModuleFrom ( ImageReader.ReadImageFrom (stream), parameters); } static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (fileName.Length == 0) throw new ArgumentException (); return new FileStream (fileName, mode, access, share); } #if !READ_ONLY public void Write (string fileName) { Write (fileName, new WriterParameters ()); } public void Write (Stream stream) { Write (stream, new WriterParameters ()); } public void Write (string fileName, WriterParameters parameters) { using (var stream = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { Write (stream, parameters); } } public void Write (Stream stream, WriterParameters parameters) { CheckStream (stream); if (!stream.CanWrite || !stream.CanSeek) throw new ArgumentException (); Mixin.CheckParameters (parameters); ModuleWriter.WriteModuleTo (this, stream, parameters); } #endif } static partial class Mixin { public static void CheckParameters (object parameters) { if (parameters == null) throw new ArgumentNullException ("parameters"); } public static bool HasImage (this ModuleDefinition self) { return self != null && self.HasImage; } public static string GetFullyQualifiedName (this Stream self) { #if !SILVERLIGHT var file_stream = self as FileStream; if (file_stream == null) return string.Empty; return Path.GetFullPath (file_stream.Name); #else return string.Empty; #endif } public static TargetRuntime ParseRuntime (this string self) { switch (self [1]) { case '1': return self [3] == '0' ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case '2': return TargetRuntime.Net_2_0; case '4': default: return TargetRuntime.Net_4_0; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Reflection; using Avalonia.Collections; using Avalonia.Controls; using Avalonia.Controls.Metadata; using Avalonia.Markup.Xaml.MarkupExtensions; using Avalonia.Styling; using Avalonia.VisualTree; namespace Avalonia.Diagnostics.ViewModels { internal class ControlDetailsViewModel : ViewModelBase, IDisposable { private readonly IVisual _control; private IDictionary<object, List<PropertyViewModel>>? _propertyIndex; private PropertyViewModel? _selectedProperty; private DataGridCollectionView? _propertiesView; private bool _snapshotStyles; private bool _showInactiveStyles; private string? _styleStatus; private object? _selectedEntity; private readonly Stack<(string Name,object Entry)> _selectedEntitiesStack = new(); private string? _selectedEntityName; private string? _selectedEntityType; public ControlDetailsViewModel(TreePageViewModel treePage, IVisual control) { _control = control; TreePage = treePage; Layout = new ControlLayoutViewModel(control); NavigateToProperty(control, (control as IControl)?.Name ?? control.ToString()); AppliedStyles = new ObservableCollection<StyleViewModel>(); PseudoClasses = new ObservableCollection<PseudoClassViewModel>(); if (control is StyledElement styledElement) { styledElement.Classes.CollectionChanged += OnClassesChanged; var pseudoClassAttributes = styledElement.GetType().GetCustomAttributes<PseudoClassesAttribute>(true); foreach (var classAttribute in pseudoClassAttributes) { foreach (var className in classAttribute.PseudoClasses) { PseudoClasses.Add(new PseudoClassViewModel(className, styledElement)); } } var styleDiagnostics = styledElement.GetStyleDiagnostics(); foreach (var appliedStyle in styleDiagnostics.AppliedStyles) { var styleSource = appliedStyle.Source; var setters = new List<SetterViewModel>(); if (styleSource is Style style) { foreach (var setter in style.Setters) { if (setter is Setter regularSetter && regularSetter.Property != null) { var setterValue = regularSetter.Value; var resourceInfo = GetResourceInfo(setterValue); SetterViewModel setterVm; if (resourceInfo.HasValue) { var resourceKey = resourceInfo.Value.resourceKey; var resourceValue = styledElement.FindResource(resourceKey); setterVm = new ResourceSetterViewModel(regularSetter.Property, resourceKey, resourceValue, resourceInfo.Value.isDynamic); } else { setterVm = new SetterViewModel(regularSetter.Property, setterValue); } setters.Add(setterVm); } } AppliedStyles.Add(new StyleViewModel(appliedStyle, style.Selector?.ToString() ?? "No selector", setters)); } } UpdateStyles(); } } private (object resourceKey, bool isDynamic)? GetResourceInfo(object? value) { if (value is StaticResourceExtension staticResource) { return (staticResource.ResourceKey, false); } else if (value is DynamicResourceExtension dynamicResource && dynamicResource.ResourceKey != null) { return (dynamicResource.ResourceKey, true); } return null; } public TreePageViewModel TreePage { get; } public DataGridCollectionView? PropertiesView { get => _propertiesView; private set => RaiseAndSetIfChanged(ref _propertiesView, value); } public ObservableCollection<StyleViewModel> AppliedStyles { get; } public ObservableCollection<PseudoClassViewModel> PseudoClasses { get; } public object? SelectedEntity { get => _selectedEntity; set { RaiseAndSetIfChanged(ref _selectedEntity, value); } } public string? SelectedEntityName { get => _selectedEntityName; set { RaiseAndSetIfChanged(ref _selectedEntityName, value); } } public string? SelectedEntityType { get => _selectedEntityType; set { RaiseAndSetIfChanged(ref _selectedEntityType, value); } } public PropertyViewModel? SelectedProperty { get => _selectedProperty; set => RaiseAndSetIfChanged(ref _selectedProperty, value); } public bool SnapshotStyles { get => _snapshotStyles; set => RaiseAndSetIfChanged(ref _snapshotStyles, value); } public bool ShowInactiveStyles { get => _showInactiveStyles; set => RaiseAndSetIfChanged(ref _showInactiveStyles, value); } public string? StyleStatus { get => _styleStatus; set => RaiseAndSetIfChanged(ref _styleStatus, value); } public ControlLayoutViewModel Layout { get; } protected override void OnPropertyChanged(PropertyChangedEventArgs e) { base.OnPropertyChanged(e); if (e.PropertyName == nameof(SnapshotStyles)) { if (!SnapshotStyles) { UpdateStyles(); } } } public void UpdateStyleFilters() { foreach (var style in AppliedStyles) { var hasVisibleSetter = false; foreach (var setter in style.Setters) { setter.IsVisible = TreePage.SettersFilter.Filter(setter.Name); hasVisibleSetter |= setter.IsVisible; } style.IsVisible = hasVisibleSetter; } } public void Dispose() { if (_control is INotifyPropertyChanged inpc) { inpc.PropertyChanged -= ControlPropertyChanged; } if (_control is AvaloniaObject ao) { ao.PropertyChanged -= ControlPropertyChanged; } if (_control is StyledElement se) { se.Classes.CollectionChanged -= OnClassesChanged; } } private IEnumerable<PropertyViewModel> GetAvaloniaProperties(object o) { if (o is AvaloniaObject ao) { return AvaloniaPropertyRegistry.Instance.GetRegistered(ao) .Union(AvaloniaPropertyRegistry.Instance.GetRegisteredAttached(ao.GetType())) .Select(x => new AvaloniaPropertyViewModel(ao, x)); } else { return Enumerable.Empty<AvaloniaPropertyViewModel>(); } } private IEnumerable<PropertyViewModel> GetClrProperties(object o) { foreach (var p in GetClrProperties(o, o.GetType())) { yield return p; } foreach (var i in o.GetType().GetInterfaces()) { foreach (var p in GetClrProperties(o, i)) { yield return p; } } } private IEnumerable<PropertyViewModel> GetClrProperties(object o, Type t) { return t.GetProperties() .Where(x => x.GetIndexParameters().Length == 0) .Select(x => new ClrPropertyViewModel(o, x)); } private void ControlPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) { if (_propertyIndex is { } && _propertyIndex.TryGetValue(e.Property, out var properties)) { foreach (var property in properties) { property.Update(); } } Layout.ControlPropertyChanged(sender, e); } private void ControlPropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName != null && _propertyIndex is { } && _propertyIndex.TryGetValue(e.PropertyName, out var properties)) { foreach (var property in properties) { property.Update(); } } if (!SnapshotStyles) { UpdateStyles(); } } private void OnClassesChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (!SnapshotStyles) { UpdateStyles(); } } private void UpdateStyles() { int activeCount = 0; foreach (var style in AppliedStyles) { style.Update(); if (style.IsActive) { activeCount++; } } var propertyBuckets = new Dictionary<AvaloniaProperty, List<SetterViewModel>>(); foreach (var style in AppliedStyles) { if (!style.IsActive) { continue; } foreach (var setter in style.Setters) { if (propertyBuckets.TryGetValue(setter.Property, out var setters)) { foreach (var otherSetter in setters) { otherSetter.IsActive = false; } setter.IsActive = true; setters.Add(setter); } else { setter.IsActive = true; setters = new List<SetterViewModel> { setter }; propertyBuckets.Add(setter.Property, setters); } } } foreach (var pseudoClass in PseudoClasses) { pseudoClass.Update(); } StyleStatus = $"Styles ({activeCount}/{AppliedStyles.Count} active)"; } private bool FilterProperty(object arg) { return !(arg is PropertyViewModel property) || TreePage.PropertiesFilter.Filter(property.Name); } private class PropertyComparer : IComparer<PropertyViewModel> { public static PropertyComparer Instance { get; } = new PropertyComparer(); public int Compare(PropertyViewModel? x, PropertyViewModel? y) { var groupX = GroupIndex(x?.Group); var groupY = GroupIndex(y?.Group); if (groupX != groupY) { return groupX - groupY; } else { return string.CompareOrdinal(x?.Name, y?.Name); } } private int GroupIndex(string? group) { switch (group) { case "Properties": return 0; case "Attached Properties": return 1; case "CLR Properties": return 2; default: return 3; } } } public void ApplySelectedProperty() { var selectedProperty = SelectedProperty; var selectedEntity = SelectedEntity; var selectedEntityName = SelectedEntityName; if (selectedEntity == null || selectedProperty == null) return; object? property; if (selectedProperty.Key is AvaloniaProperty avaloniaProperty) { property = (_selectedEntity as IControl)?.GetValue(avaloniaProperty); } else { property = selectedEntity.GetType().GetProperties() .FirstOrDefault(pi => pi.Name == selectedProperty.Name && pi.DeclaringType == selectedProperty.DeclaringType && pi.PropertyType.Name == selectedProperty.Type) ?.GetValue(selectedEntity); } if (property == null) return; _selectedEntitiesStack.Push((Name:selectedEntityName!,Entry:selectedEntity)); NavigateToProperty(property, selectedProperty.Name); } public void ApplyParentProperty() { if (_selectedEntitiesStack.Any()) { var property = _selectedEntitiesStack.Pop(); NavigateToProperty(property.Entry, property.Name); } } protected void NavigateToProperty(object o, string entityName) { var oldSelectedEntity = SelectedEntity; if (oldSelectedEntity is IAvaloniaObject ao1) { ao1.PropertyChanged -= ControlPropertyChanged; } else if (oldSelectedEntity is INotifyPropertyChanged inpc1) { inpc1.PropertyChanged -= ControlPropertyChanged; } SelectedEntity = o; SelectedEntityName = entityName; SelectedEntityType = o.ToString(); var properties = GetAvaloniaProperties(o) .Concat(GetClrProperties(o)) .OrderBy(x => x, PropertyComparer.Instance) .ThenBy(x => x.Name) .ToList(); _propertyIndex = properties.GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.ToList()); var view = new DataGridCollectionView(properties); view.GroupDescriptions.Add(new DataGridPathGroupDescription(nameof(AvaloniaPropertyViewModel.Group))); view.Filter = FilterProperty; PropertiesView = view; if (o is IAvaloniaObject ao2) { ao2.PropertyChanged += ControlPropertyChanged; } else if (o is INotifyPropertyChanged inpc2) { inpc2.PropertyChanged += ControlPropertyChanged; } } } }
using Lens.Translations; using NUnit.Framework; namespace Lens.Test.Features { [TestFixture] internal class FunctionalTest : TestBase { [Test] public void CreateFunctionObjectFromName() { var src = @" var fx = double::IsInfinity fx (1.0 / 0)"; Test(src, true, true); } [Test] public void Closure1() { var src = @" var a = 0 var b = 2 var fx = x:int -> a = b * x fx 3 a"; Test(src, 6); } [Test] public void Closure2() { var src = @" var result = 0 var x1 = 1 var fx1 = a:int -> x1 = x1 + 1 var x2 = 1 var fx2 = b:int -> x2 = x2 + 1 result = x1 + x2 + b fx2 a fx1 10 result"; Test(src, 14); } [Test] public void ClosureError1() { var src = @" fun doStuff:Func<int, int> (x:ref int) -> (y:int -> x + y) "; TestError(src, CompilerMessages.ClosureRef); } [Test] public void RefValueError1() { var src = @" fun inc (x:ref int) -> x = x + 1 let value = 1 inc (ref value) "; TestError(src, CompilerMessages.ConstantByRef); } [Test] public void RefValueError2() { var src = @" fun inc (x:ref int) -> x = x + 1 var value = 1 inc value "; TestError(src, CompilerMessages.ReferenceArgExpected); } [Test] public void RefValueError3() { var src = @" fun doStuff (x:int) -> print x var value = 1 doStuff (ref value) "; TestError(src, CompilerMessages.ReferenceArgUnexpected); } [Test] public void FunctionComposition1() { var src = @" let add = (a:int b:int) -> a + b let square = x:int -> x ** 2 as int let inc = x:int -> x + 1 let asi = add :> square :> inc asi 1 2 "; Test(src, 10); } [Test] public void FunctionComposition2() { var src = @" let invConcat = (x:string y:string) -> y + x let invParse = invConcat :> int::Parse invParse ""37"" ""13"" "; Test(src, 1337); } [Test] public void FunctionComposition3() { var src = @" fun invConcat:string (x:string y:string) -> y + x let invParse = invConcat :> int::Parse invParse ""37"" ""13"" "; Test(src, 1337); } [Test] public void FunctionCompositionError1() { var src = @" let fx1 = (x:string) -> x let fx2 = (x:int) -> x fx1 :> fx2 "; TestError(src, CompilerMessages.DelegatesNotCombinable); } [Test] public void Wildcards1() { var src = @" let fx1 = string::Format <_, object[]> as object let fx2 = string::Join <string, _, _, _> as object let fx3 = int::Parse <_> as object new [fx1; fx2; fx3] |> Where x -> x <> null |> Count () "; Test(src, 3); } [Test] public void WildcardsError1() { var src = @"int::Parse <_, _>"; TestError(src, CompilerMessages.TypeMethodAmbiguous); } [Test] public void WildcardsError2() { var src = @"int::Parse <string, string>"; TestError(src, CompilerMessages.TypeMethodNotFound); } [Test] public void PartialApplication1() { var src = @" fun add:int (x:int y:int) -> x + y let add2 = add 2 _ let add3 = add _ 3 (add2 1) + (add3 4) "; Test(src, 10); } [Test] public void PartialApplication2() { var src = @" let prepend = string::Concat ""test:"" _ prepend ""hello"" "; Test(src, "test:hello"); } [Test] public void PartialApplication3() { var src = @" fun add:int (x:int y:int z:int) -> x + y + z let fx1 = add 1 _ _ let fx2 = fx1 2 _ fx2 3 "; Test(src, 6); } [Test] public void PartialApplicationError1() { var src = @" fun add:int (x:int y:int) -> x + y add _ "; TestError(src, CompilerMessages.FunctionNotFound); } [Test] public void PartialApplicationError2() { var src = @" fun add:int (x:int y:int) -> x + y add _ _ _ "; TestError(src, CompilerMessages.FunctionNotFound); } [Test] public void ConstructorApplication1() { var src = @" let repeater = new string (""a""[0]) _ new [repeater 2; repeater 3] "; Test(src, new[] {"aa", "aaa"}); } [Test] public void ConstructorApplication2() { var src = @" record Data Value : int Coeff : int let dataFx = new Data _ 2 new [dataFx 1; dataFx 2; dataFx 3] |> Sum x:Data -> x.Value * x.Coeff "; Test(src, 12); } [Test] public void ConstructorApplicationError1() { var src = @" record Data Value : int Coeff : int new Data _"; TestError(src, CompilerMessages.TypeConstructorNotFound); } [Test] public void ConstructorApplicationError2() { var src = @" record Data Value : int Coeff : int new Data _ _ _"; TestError(src, CompilerMessages.TypeConstructorNotFound); } [Test] public void FunctionUnneededArgs() { var src = @" fun sum:int (a:int b:int) -> a + b fun sum:int (a:int b:int _:int) -> a + b fun sum:int (a:int b:int _:int _:int) -> a + b new [ sum 1 2 sum 1 2 3 sum 1 2 3 4 ] "; Test(src, new[] {3, 3, 3}); } [Test] public void LambdaUnneededArgs() { var src = @" var x : Func<int, int, int> var y : Func<int, int, int> x = (_ _) -> 1 y = (_ b) -> b + 1 new [x 1 2; y 1 2] "; Test(src, new[] {1, 3}); } [Test] public void OverloadPartialApplicationError() { var src = "println _"; TestError(src, CompilerMessages.FunctionInvocationAmbiguous); } } }
#define AWSSDK_UNITY // // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Text; using Amazon.Runtime.Internal.Auth; using Amazon.Util; using System.Globalization; namespace Amazon.Runtime { /// <summary> /// This class is the base class of all the configurations settings to connect /// to a service. /// </summary> public abstract partial class ClientConfig { // Represents infinite timeout. http://msdn.microsoft.com/en-us/library/system.threading.timeout.infinite.aspx internal static readonly TimeSpan InfiniteTimeout = TimeSpan.FromMilliseconds(-1); // Represents max timeout. public static readonly TimeSpan MaxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); #if !BCL && !AWSSDK_UNITY private RegionEndpoint regionEndpoint = null; #else private RegionEndpoint regionEndpoint = GetDefaultRegionEndpoint(); #endif private bool useHttp = false; private string serviceURL = null; private string authRegion = null; private string authServiceName = null; private string userAgent = Amazon.Util.AWSSDKUtils.SDKUserAgent; private string signatureVersion = "2"; private SigningAlgorithm signatureMethod = SigningAlgorithm.HmacSHA256; private int maxErrorRetry = 4; private bool readEntireResponse = false; private bool logResponse = false; private int bufferSize = AWSSDKUtils.DefaultBufferSize; private long progressUpdateInterval = AWSSDKUtils.DefaultProgressUpdateInterval; private bool resignRetries = false; private ICredentials proxyCredentials; private bool logMetrics = AWSConfigs.LoggingConfig.LogMetrics; private bool disableLogging = false; private TimeSpan? timeout = null; private bool allowAutoRedirect = true; /// <summary> /// Gets Service Version /// </summary> public abstract string ServiceVersion { get; } /// <summary> /// Gets and sets of the signatureMethod property. /// </summary> public SigningAlgorithm SignatureMethod { get { return this.signatureMethod; } set { this.signatureMethod = value; } } /// <summary> /// Gets and sets of the SignatureVersion property. /// </summary> public string SignatureVersion { get { return this.signatureVersion; } set { this.signatureVersion = value; } } /// <summary> /// Gets and sets of the UserAgent property. /// </summary> public string UserAgent { get { return this.userAgent; } set { this.userAgent = value; } } /// <summary> /// Gets and sets the RegionEndpoint property. The region constant to use that /// determines the endpoint to use. If this is not set /// then the client will fallback to the value of ServiceURL. /// </summary> public RegionEndpoint RegionEndpoint { get { return regionEndpoint; } set { this.serviceURL = null; this.regionEndpoint = value; if (this.regionEndpoint != null) { var endpoint = this.regionEndpoint.GetEndpointForService(RegionEndpointServiceName); if (endpoint != null && endpoint.SignatureVersionOverride != null) this.SignatureVersion = endpoint.SignatureVersionOverride; } } } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public abstract string RegionEndpointServiceName { get; } /// <summary> /// Gets and sets of the ServiceURL property. /// This is an optional property; change it /// only if you want to try a different service /// endpoint. /// </summary> public string ServiceURL { get { return this.serviceURL; } set { this.regionEndpoint = null; this.serviceURL = value; } } /// <summary> /// Gets and sets the UseHttp. /// If this property is set to true, the client attempts /// to use HTTP protocol, if the target endpoint supports it. /// By default, this property is set to false. /// </summary> public bool UseHttp { get { return this.useHttp; } set { this.useHttp = value; } } public string DetermineServiceURL() { string url; if (this.ServiceURL != null) { url = this.ServiceURL; } else { url = GetUrl(this.RegionEndpoint, this.RegionEndpointServiceName, this.UseHttp); } return url; } internal static string GetUrl(RegionEndpoint regionEndpoint, string regionEndpointServiceName, bool useHttp) { var endpoint = regionEndpoint.GetEndpointForService(regionEndpointServiceName); string url = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", useHttp ? "http://" : "https://", endpoint.Hostname)).AbsoluteUri; return url; } /// <summary> /// Gets and sets the AuthenticationRegion property. /// Used in AWS4 request signing, this is an optional property; /// change it only if the region cannot be determined from the /// service endpoint. /// </summary> public string AuthenticationRegion { get { return this.authRegion; } set { this.authRegion = value; } } /// <summary> /// Gets and sets the AuthenticationServiceName property. /// Used in AWS4 request signing, this is the short-form /// name of the service being called. /// </summary> public string AuthenticationServiceName { get { return this.authServiceName; } set { this.authServiceName = value; } } /// <summary> /// Gets and sets of the MaxErrorRetry property. /// </summary> public int MaxErrorRetry { get { return this.maxErrorRetry; } set { this.maxErrorRetry = value; } } /// <summary> /// Gets and sets the LogResponse. /// If this property is set to true, the service response /// is read in its entirety and logged. /// </summary> public bool LogResponse { get { return this.logResponse; } set { this.logResponse = value; } } /// <summary> /// Gets and sets the ReadEntireResponse. /// If this property is set to true, the service response /// is read in its entirety before being processed. /// </summary> public bool ReadEntireResponse { get { return this.readEntireResponse; } set { this.readEntireResponse = value; } } /// <summary> /// Gets and Sets the BufferSize property. /// The BufferSize controls the buffer used to read in from input streams and write /// out to the request. /// </summary> public int BufferSize { get { return this.bufferSize; } set { this.bufferSize = value; } } /// <summary> /// <para> /// Gets or sets the interval at which progress update events are raised /// for upload operations. By default, the progress update events are /// raised at every 100KB of data transferred. /// </para> /// <para> /// If the value of this property is set less than ClientConfig.BufferSize, /// progress updates events will be raised at the interval specified by ClientConfig.BufferSize. /// </para> /// </summary> public long ProgressUpdateInterval { get { return progressUpdateInterval; } set { progressUpdateInterval = value; } } /// <summary> /// Flag on whether to resign requests on retry or not. /// </summary> public bool ResignRetries { get { return this.resignRetries; } set { this.resignRetries = value; } } /// <summary> /// This flag controls if .NET HTTP infrastructure should follow redirection /// responses (e.g. HTTP 307 - temporary redirect). /// </summary> protected internal bool AllowAutoRedirect { get { return this.allowAutoRedirect; } set { this.allowAutoRedirect = value; } } /// <summary> /// Flag on whether to log metrics for service calls. /// /// This can be set in the application's configs, as below: /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSLogMetrics" value"true"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// </summary> public bool LogMetrics { get { return this.logMetrics; } set { this.logMetrics = value; } } /// <summary> /// Flag on whether to completely disable logging for this client or not. /// </summary> internal bool DisableLogging { get { return this.disableLogging; } set { this.disableLogging = value; } } /// <summary> /// Credentials to use with a proxy. /// </summary> public ICredentials ProxyCredentials { get { if(this.proxyCredentials == null && (!string.IsNullOrEmpty(AWSConfigs.ProxyConfig.Username) || !string.IsNullOrEmpty(AWSConfigs.ProxyConfig.Password))) { return new NetworkCredential(AWSConfigs.ProxyConfig.Username, AWSConfigs.ProxyConfig.Password ?? string.Empty); } return this.proxyCredentials; } set { this.proxyCredentials = value; } } #region Constructor public ClientConfig() { Initialize(); } #endregion protected virtual void Initialize() { } /// <summary> /// Overrides the default request timeout value. /// </summary> /// <remarks> /// <para> /// If the value is set, the value is assigned to the Timeout property of the HTTPWebRequest/HttpClient object used /// to send requests. /// </para> /// <para> /// Please specify a timeout value only if the operation will not complete within the default intervals /// specified for an HttpWebRequest/HttpClient. /// </para> /// </remarks> /// <exception cref="System.ArgumentNullException">The timeout specified is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">The timeout specified is less than or equal to zero and is not Infinite.</exception> /// <seealso cref="P:System.Net.HttpWebRequest.Timeout"/> /// <seealso cref="P:System.Net.Http.HttpClient.Timeout"/> public TimeSpan? Timeout { get { return this.timeout; } set { ValidateTimeout(value); this.timeout = value; } } /// <summary> /// Enable or disable the Nagle algorithm on the underlying http /// client. /// /// This method is not intended to be called by consumers of the AWS SDK for .NET /// </summary> /// <param name="useNagle"></param> public void SetUseNagleIfAvailable(bool useNagle) { #if BCL this.UseNagleAlgorithm = useNagle; #endif } /// <summary> /// Performs validation on this config object. /// Throws exception if any of the required values are missing/invalid. /// </summary> public virtual void Validate() { if (RegionEndpoint == null && string.IsNullOrEmpty(this.ServiceURL)) throw new AmazonClientException("No RegionEndpoint or ServiceURL configured"); } public static void ValidateTimeout(TimeSpan? timeout) { if (!timeout.HasValue) { throw new ArgumentNullException("timeout"); } if (timeout != InfiniteTimeout && (timeout <= TimeSpan.Zero || timeout > MaxTimeout)) { throw new ArgumentOutOfRangeException("timeout"); } } /// <summary> /// Returns the request timeout value if its value is set, /// else returns client timeout value. /// </summary> public static TimeSpan? GetTimeoutValue(TimeSpan? clientTimeout, TimeSpan? requestTimeout) { return requestTimeout.HasValue ? requestTimeout : (clientTimeout.HasValue ? clientTimeout : null); } } }
namespace java.security { [global::MonoJavaBridge.JavaClass(typeof(global::java.security.Signature_))] public abstract partial class Signature : java.security.SignatureSpi { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Signature(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.security.Signature.staticClass, "toString", "()Ljava/lang/String;", ref global::java.security.Signature._m0) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public override global::java.lang.Object clone() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.Signature.staticClass, "clone", "()Ljava/lang/Object;", ref global::java.security.Signature._m1) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m2; public static global::java.security.Signature getInstance(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.security.Signature._m2.native == global::System.IntPtr.Zero) global::java.security.Signature._m2 = @__env.GetStaticMethodIDNoThrow(global::java.security.Signature.staticClass, "getInstance", "(Ljava/lang/String;Ljava/lang/String;)Ljava/security/Signature;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.security.Signature.staticClass, global::java.security.Signature._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.security.Signature; } private static global::MonoJavaBridge.MethodId _m3; public static global::java.security.Signature getInstance(java.lang.String arg0, java.security.Provider arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.security.Signature._m3.native == global::System.IntPtr.Zero) global::java.security.Signature._m3 = @__env.GetStaticMethodIDNoThrow(global::java.security.Signature.staticClass, "getInstance", "(Ljava/lang/String;Ljava/security/Provider;)Ljava/security/Signature;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.security.Signature.staticClass, global::java.security.Signature._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.security.Signature; } private static global::MonoJavaBridge.MethodId _m4; public static global::java.security.Signature getInstance(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.security.Signature._m4.native == global::System.IntPtr.Zero) global::java.security.Signature._m4 = @__env.GetStaticMethodIDNoThrow(global::java.security.Signature.staticClass, "getInstance", "(Ljava/lang/String;)Ljava/security/Signature;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.security.Signature.staticClass, global::java.security.Signature._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.security.Signature; } private static global::MonoJavaBridge.MethodId _m5; public virtual bool verify(byte[] arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.security.Signature.staticClass, "verify", "([B)Z", ref global::java.security.Signature._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; public virtual bool verify(byte[] arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.security.Signature.staticClass, "verify", "([BII)Z", ref global::java.security.Signature._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m7; public virtual void update(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "update", "([BII)V", ref global::java.security.Signature._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m8; public virtual void update(java.nio.ByteBuffer arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "update", "(Ljava/nio/ByteBuffer;)V", ref global::java.security.Signature._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public virtual void update(byte arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "update", "(B)V", ref global::java.security.Signature._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m10; public virtual void update(byte[] arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "update", "([B)V", ref global::java.security.Signature._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m11; public virtual global::java.lang.String getAlgorithm() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.security.Signature.staticClass, "getAlgorithm", "()Ljava/lang/String;", ref global::java.security.Signature._m11) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m12; public virtual global::java.security.Provider getProvider() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.Signature.staticClass, "getProvider", "()Ljava/security/Provider;", ref global::java.security.Signature._m12) as java.security.Provider; } private static global::MonoJavaBridge.MethodId _m13; public virtual global::java.security.AlgorithmParameters getParameters() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.Signature.staticClass, "getParameters", "()Ljava/security/AlgorithmParameters;", ref global::java.security.Signature._m13) as java.security.AlgorithmParameters; } private static global::MonoJavaBridge.MethodId _m14; public virtual int sign(byte[] arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.security.Signature.staticClass, "sign", "([BII)I", ref global::java.security.Signature._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m15; public virtual byte[] sign() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::java.security.Signature.staticClass, "sign", "()[B", ref global::java.security.Signature._m15) as byte[]; } private static global::MonoJavaBridge.MethodId _m16; public virtual void initVerify(java.security.PublicKey arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "initVerify", "(Ljava/security/PublicKey;)V", ref global::java.security.Signature._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public virtual void initVerify(java.security.cert.Certificate arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "initVerify", "(Ljava/security/cert/Certificate;)V", ref global::java.security.Signature._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m18; public virtual void initSign(java.security.PrivateKey arg0, java.security.SecureRandom arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "initSign", "(Ljava/security/PrivateKey;Ljava/security/SecureRandom;)V", ref global::java.security.Signature._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m19; public virtual void initSign(java.security.PrivateKey arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "initSign", "(Ljava/security/PrivateKey;)V", ref global::java.security.Signature._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public virtual void setParameter(java.lang.String arg0, java.lang.Object arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "setParameter", "(Ljava/lang/String;Ljava/lang/Object;)V", ref global::java.security.Signature._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m21; public virtual void setParameter(java.security.spec.AlgorithmParameterSpec arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature.staticClass, "setParameter", "(Ljava/security/spec/AlgorithmParameterSpec;)V", ref global::java.security.Signature._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public virtual global::java.lang.Object getParameter(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.Signature.staticClass, "getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", ref global::java.security.Signature._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m23; protected Signature(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.security.Signature._m23.native == global::System.IntPtr.Zero) global::java.security.Signature._m23 = @__env.GetMethodIDNoThrow(global::java.security.Signature.staticClass, "<init>", "(Ljava/lang/String;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.security.Signature.staticClass, global::java.security.Signature._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static Signature() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.security.Signature.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/Signature")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.security.Signature))] internal sealed partial class Signature_ : java.security.Signature { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal Signature_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; protected override void engineInitVerify(java.security.PublicKey arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature_.staticClass, "engineInitVerify", "(Ljava/security/PublicKey;)V", ref global::java.security.Signature_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; protected override void engineInitSign(java.security.PrivateKey arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature_.staticClass, "engineInitSign", "(Ljava/security/PrivateKey;)V", ref global::java.security.Signature_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; protected override byte[] engineSign() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::java.security.Signature_.staticClass, "engineSign", "()[B", ref global::java.security.Signature_._m2) as byte[]; } private static global::MonoJavaBridge.MethodId _m3; protected override bool engineVerify(byte[] arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.security.Signature_.staticClass, "engineVerify", "([B)Z", ref global::java.security.Signature_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; protected override void engineUpdate(byte arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature_.staticClass, "engineUpdate", "(B)V", ref global::java.security.Signature_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; protected override void engineUpdate(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature_.staticClass, "engineUpdate", "([BII)V", ref global::java.security.Signature_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m6; protected override void engineSetParameter(java.lang.String arg0, java.lang.Object arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.Signature_.staticClass, "engineSetParameter", "(Ljava/lang/String;Ljava/lang/Object;)V", ref global::java.security.Signature_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m7; protected override global::java.lang.Object engineGetParameter(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.Signature_.staticClass, "engineGetParameter", "(Ljava/lang/String;)Ljava/lang/Object;", ref global::java.security.Signature_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } static Signature_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.security.Signature_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/Signature")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using GroundJobs.MVC.Models; namespace GroundJobs.MVC.Migrations { [ContextType(typeof(ApplicationDbContext))] partial class CreateIdentitySchema { public override string Id { get { return "00000000000000_CreateIdentitySchema"; } } public override string ProductVersion { get { return "7.0.0-beta5"; } } public override void BuildTargetModel(ModelBuilder builder) { builder .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 1); b.Property<string>("Name") .Annotation("OriginalValueIndex", 2); b.Property<string>("NormalizedName") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ProviderKey") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 1); b.Property<string>("ProviderDisplayName") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId") .Annotation("OriginalValueIndex", 0); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 1); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("GroundJobs.MVC.Models.ApplicationUser", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<int>("AccessFailedCount") .Annotation("OriginalValueIndex", 1); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 2); b.Property<string>("Email") .Annotation("OriginalValueIndex", 3); b.Property<bool>("EmailConfirmed") .Annotation("OriginalValueIndex", 4); b.Property<bool>("LockoutEnabled") .Annotation("OriginalValueIndex", 5); b.Property<DateTimeOffset?>("LockoutEnd") .Annotation("OriginalValueIndex", 6); b.Property<string>("NormalizedEmail") .Annotation("OriginalValueIndex", 7); b.Property<string>("NormalizedUserName") .Annotation("OriginalValueIndex", 8); b.Property<string>("PasswordHash") .Annotation("OriginalValueIndex", 9); b.Property<string>("PhoneNumber") .Annotation("OriginalValueIndex", 10); b.Property<bool>("PhoneNumberConfirmed") .Annotation("OriginalValueIndex", 11); b.Property<string>("SecurityStamp") .Annotation("OriginalValueIndex", 12); b.Property<bool>("TwoFactorEnabled") .Annotation("OriginalValueIndex", 13); b.Property<string>("UserName") .Annotation("OriginalValueIndex", 14); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("GroundJobs.MVC.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("GroundJobs.MVC.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("GroundJobs.MVC.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using Microsoft.BizTalk.BaseFunctoids; using System.Text.RegularExpressions; namespace BizTalk.MapperExtensions.Functoid.Wizard { public class WzPageParametersConn : Microsoft.BizTalk.Wizard.WizardInteriorPage, WizardControlInterface { #region Global Variables private const string ParamsRegEx = @"^[0-9]+$"; public event AddWizardResultEvent _AddWizardResultEvent; public event AddFunctoidParameterEvent _AddFunctoidParameterEvent; private bool _IsLoaded = false; #endregion #region Form Components private System.ComponentModel.IContainer components = null; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtFunctoidParameter; private System.Windows.Forms.Button cmdFunctoidParameterDel; private System.Windows.Forms.Button cmdFunctoidParameterAdd; private System.Windows.Forms.ListBox lstFunctoidParameters; private System.Windows.Forms.ComboBox cmbParameterDataType; private System.Windows.Forms.ErrorProvider errorProvider; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtMinParams; private System.Windows.Forms.TextBox txtMaxParams; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ComboBox cmbInputConnType; private System.Windows.Forms.ComboBox cmbOutputConnType; private System.Windows.Forms.ComboBox cmbReturnDataType; private System.Windows.Forms.Button cmdMoveUp; private System.Windows.Forms.Button cmdMoveDown; private TextBox txtFunctoidFunctionName; private Label label8; private System.Windows.Forms.GroupBox grpParams; #endregion public WzPageParametersConn() { // This call is required by the Windows Form Designer. InitializeComponent(); this.AutoScaleDimensions = new SizeF(6F, 13F); this.AutoScaleMode = AutoScaleMode.Font; // TODO: Add any initialization after the InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } public bool NextButtonEnabled { get { return true; } } public bool NeedSummary { get { return false; } } protected void AddWizardResult(string strName, object Value) { PropertyPairEvent PropertyPair = new PropertyPairEvent(strName, Value); OnAddWizardResult(PropertyPair); } /// <summary> /// The protected OnRaiseProperty method raises the event by invoking /// the delegates. The sender is always this, the current instance /// of the class. /// </summary> /// <param name="e"></param> protected virtual void OnAddWizardResult(PropertyPairEvent e) { if (e != null) { // Invokes the delegates. _AddWizardResultEvent(this,e); } } protected void AddFunctoidParameter(string strName,string strValue) { PropertyPairEvent PropertyPair = new PropertyPairEvent(strName,strValue); OnAddFunctoidParameter(PropertyPair); } protected void RemoveFunctoidParameter(string strName) { PropertyPairEvent PropertyPair = new PropertyPairEvent(strName,null,true); OnAddFunctoidParameter(PropertyPair); } // The protected OnAddFunctoidParameter method raises the event by invoking // the delegates. The sender is always this, the current instance // of the class. protected virtual void OnAddFunctoidParameter(PropertyPairEvent e) { if (e != null) { // Invokes the delegates. _AddFunctoidParameterEvent(this,e); } } private void WzPageParametersConn_Leave(object sender, System.EventArgs e) { try { // Save functoid parameters int ParamCount = lstFunctoidParameters.Items.Count; for(int i=0; i < ParamCount; i++) { string strVal = lstFunctoidParameters.Items[i].ToString(); string strPropName = strVal.Substring(0,strVal.IndexOf("(") - 1); string strPropType = strVal.Replace(strPropName + " (",""); strPropType = strPropType.Replace(")",""); // I remove every parameter so that they stay in the list order RemoveFunctoidParameter(strPropName); AddFunctoidParameter(strPropName,strPropType); } // Save other wizard results AddWizardResult(WizardValues.FunctoidInputConnType, cmbInputConnType.Text); AddWizardResult(WizardValues.FunctoidOutputConnType, cmbOutputConnType.Text); AddWizardResult(WizardValues.FunctoidReturnType, cmbReturnDataType.Text); AddWizardResult(WizardValues.FunctoidMinParams, txtMinParams.Text); AddWizardResult(WizardValues.FunctoidMaxParams, txtMaxParams.Text); AddWizardResult(WizardValues.FunctoidFunctionName, txtFunctoidFunctionName.Text); } catch(Exception err) { MessageBox.Show(err.Message); Trace.WriteLine(err.Message + Environment.NewLine + err.StackTrace); } } private void WzPageParametersConn_Load(object sender, System.EventArgs e) { string[] strDataTypes = {"System.Boolean", "System.Byte", "System.Char", "System.DateTime", "System.Decimal", "System.Double", "System.Int16", "System.Int32", "System.Int64", "System.Object", "System.Sbyte", "System.Single", "System.String", "System.UInt16", "System.UInt32", "System.UInt64", }; string[] strConnectionTypes = Enum.GetNames(typeof(ConnectionType)); try { if (_IsLoaded) return; foreach(string strDataType in strDataTypes) { cmbParameterDataType.Items.Add(strDataType); cmbReturnDataType.Items.Add(strDataType); } cmbParameterDataType.Text = "System.String"; cmbReturnDataType.Text = "System.String"; foreach(string strConnectionType in strConnectionTypes) { cmbInputConnType.Items.Add(strConnectionType); cmbOutputConnType.Items.Add(strConnectionType); } cmbInputConnType.Text = "AllExceptRecord"; cmbOutputConnType.Text = "AllExceptRecord"; _IsLoaded = true; } catch(Exception err) { MessageBox.Show(err.Message); Trace.WriteLine(err.Message + Environment.NewLine + err.StackTrace); } } private bool VarNameAlreadyExists(string strValue) { foreach(object o in lstFunctoidParameters.Items) { string strObjVal = o.ToString(); strObjVal = strObjVal.Remove(strObjVal.IndexOf(" ("),strObjVal.Length - strObjVal.IndexOf(" (")); if (strObjVal == strValue) return true; } return false; } /// <summary> /// Resets all of the errorproviders when anything succeeds /// </summary> private void ResetAllErrProviders() { foreach(Control ctl in this.Controls) { if (errorProvider.GetError(ctl) != "") errorProvider.SetError(ctl, ""); } } private void cmdFunctoidParameterAdd_Click(object sender, System.EventArgs e) { try { ResetAllErrProviders(); if (!Regex.IsMatch(txtFunctoidParameter.Text,@"^[_a-zA-Z][_a-zA-Z0-9]*$")) { errorProvider.SetError(txtFunctoidParameter, "Please enter a valid name for the new parameter"); return; } if (VarNameAlreadyExists(txtFunctoidParameter.Text)) { errorProvider.SetError(txtFunctoidParameter, "Please enter a unique name. Two parameters cannot have the same name"); return; } lstFunctoidParameters.Items.Add(txtFunctoidParameter.Text + " (" + cmbParameterDataType.Text + ")"); txtFunctoidParameter.Clear(); cmbParameterDataType.Text = "System.String"; ProcessMinMaxParams(); txtFunctoidParameter.Focus(); } catch(Exception err) { MessageBox.Show(err.Message); Trace.WriteLine(err.Message + Environment.NewLine + err.StackTrace); } } private void cmdFunctoidParameterDel_Click(object sender, System.EventArgs e) { try { ResetAllErrProviders(); if (lstFunctoidParameters.SelectedItem == null) { errorProvider.SetError(cmdFunctoidParameterDel, "Please select a value in the parameter list"); return; } int selectedPos = lstFunctoidParameters.SelectedIndex; Object objItem = lstFunctoidParameters.SelectedItem; string strVal = objItem.ToString(); string strPropName = strVal.Substring(0,strVal.IndexOf("(") - 1); RemoveFunctoidParameter(strPropName); lstFunctoidParameters.Items.Remove(lstFunctoidParameters.SelectedItem); ProcessMinMaxParams(); // Selects the next item in the list if (lstFunctoidParameters.Items.Count > 0) { if (lstFunctoidParameters.Items.Count <= selectedPos) selectedPos = lstFunctoidParameters.Items.Count - 1; lstFunctoidParameters.SelectedIndex = selectedPos; } } catch(Exception err) { MessageBox.Show(err.Message); Trace.WriteLine(err.Message + Environment.NewLine + err.StackTrace); } } private void ProcessMinMaxParams() { txtMinParams.Text = lstFunctoidParameters.Items.Count.ToString(); txtMaxParams.Text = lstFunctoidParameters.Items.Count.ToString(); Params_Validating(grpParams,new System.ComponentModel.CancelEventArgs(false)); } private void Element_Changed(object sender, System.EventArgs e) { EnableNext(GetAllStates()); } private bool GetAllStates() { return (Regex.IsMatch(txtMinParams.Text, ParamsRegEx) && Regex.IsMatch(txtMaxParams.Text, ParamsRegEx) && Convert.ToInt32(txtMaxParams.Text) >= Convert.ToInt32(txtMinParams.Text)); } private void Params_Validating(object sender, System.ComponentModel.CancelEventArgs e) { // Validate Min. Params if (!Regex.IsMatch(txtMinParams.Text,ParamsRegEx)) errorProvider.SetError(txtMinParams, "Min parameters must be a number and can't be empty"); else errorProvider.SetError(txtMinParams,""); // Validate Max. Params if (!Regex.IsMatch(txtMaxParams.Text,ParamsRegEx)) errorProvider.SetError(txtMaxParams, "Max parameters must be a number and can't be empty"); else errorProvider.SetError(txtMaxParams,""); // Validate Min. Params <= Max. Params if (errorProvider.GetError(txtMinParams) == "" && errorProvider.GetError(txtMaxParams) == "") { if (Convert.ToInt32(txtMinParams.Text) > Convert.ToInt32(txtMaxParams.Text)) errorProvider.SetError(grpParams, "Max parameters can't be lower than Min parameters"); else errorProvider.SetError(grpParams,""); } else errorProvider.SetError(grpParams,""); // Enable Next if everything's OK EnableNext(GetAllStates()); } private void cmdMoveUp_Click(object sender, System.EventArgs e) { ResetAllErrProviders(); if (lstFunctoidParameters.SelectedItem == null) { errorProvider.SetError(lstFunctoidParameters, "Please select a value in the parameter list"); return; } if (lstFunctoidParameters.SelectedIndex > 0) { int selectedPos = lstFunctoidParameters.SelectedIndex; string auxParameter = (string)lstFunctoidParameters.Items[selectedPos-1]; lstFunctoidParameters.Items[selectedPos-1] = lstFunctoidParameters.Items[selectedPos]; lstFunctoidParameters.Items[selectedPos] = auxParameter; lstFunctoidParameters.SelectedIndex = selectedPos-1; } } private void cmdMoveDown_Click(object sender, System.EventArgs e) { ResetAllErrProviders(); if (lstFunctoidParameters.SelectedItem == null) { errorProvider.SetError(lstFunctoidParameters, "Please select a value in the parameter list"); return; } if (lstFunctoidParameters.SelectedIndex < lstFunctoidParameters.Items.Count-1) { int selectedPos = lstFunctoidParameters.SelectedIndex; string auxParameter = (string)lstFunctoidParameters.Items[selectedPos+1]; lstFunctoidParameters.Items[selectedPos+1] = lstFunctoidParameters.Items[selectedPos]; lstFunctoidParameters.Items[selectedPos] = auxParameter; lstFunctoidParameters.SelectedIndex = selectedPos+1; } } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WzPageParametersConn)); this.txtFunctoidParameter = new System.Windows.Forms.TextBox(); this.cmdFunctoidParameterDel = new System.Windows.Forms.Button(); this.cmdFunctoidParameterAdd = new System.Windows.Forms.Button(); this.cmbParameterDataType = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.lstFunctoidParameters = new System.Windows.Forms.ListBox(); this.label1 = new System.Windows.Forms.Label(); this.errorProvider = new System.Windows.Forms.ErrorProvider(this.components); this.txtMinParams = new System.Windows.Forms.TextBox(); this.txtMaxParams = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.cmbInputConnType = new System.Windows.Forms.ComboBox(); this.cmbOutputConnType = new System.Windows.Forms.ComboBox(); this.cmbReturnDataType = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.grpParams = new System.Windows.Forms.GroupBox(); this.cmdMoveUp = new System.Windows.Forms.Button(); this.cmdMoveDown = new System.Windows.Forms.Button(); this.txtFunctoidFunctionName = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.panelHeader.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit(); this.groupBox1.SuspendLayout(); this.grpParams.SuspendLayout(); this.SuspendLayout(); // // panelHeader // resources.ApplyResources(this.panelHeader, "panelHeader"); // // labelTitle // resources.ApplyResources(this.labelTitle, "labelTitle"); // // labelSubTitle // resources.ApplyResources(this.labelSubTitle, "labelSubTitle"); // // txtFunctoidParameter // resources.ApplyResources(this.txtFunctoidParameter, "txtFunctoidParameter"); this.txtFunctoidParameter.Name = "txtFunctoidParameter"; // // cmdFunctoidParameterDel // resources.ApplyResources(this.cmdFunctoidParameterDel, "cmdFunctoidParameterDel"); this.cmdFunctoidParameterDel.Name = "cmdFunctoidParameterDel"; this.cmdFunctoidParameterDel.Click += new System.EventHandler(this.cmdFunctoidParameterDel_Click); // // cmdFunctoidParameterAdd // resources.ApplyResources(this.cmdFunctoidParameterAdd, "cmdFunctoidParameterAdd"); this.cmdFunctoidParameterAdd.Name = "cmdFunctoidParameterAdd"; this.cmdFunctoidParameterAdd.Click += new System.EventHandler(this.cmdFunctoidParameterAdd_Click); // // cmbParameterDataType // this.cmbParameterDataType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbParameterDataType, "cmbParameterDataType"); this.cmbParameterDataType.Name = "cmbParameterDataType"; this.cmbParameterDataType.Sorted = true; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // lstFunctoidParameters // resources.ApplyResources(this.lstFunctoidParameters, "lstFunctoidParameters"); this.lstFunctoidParameters.Name = "lstFunctoidParameters"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // errorProvider // this.errorProvider.ContainerControl = this; resources.ApplyResources(this.errorProvider, "errorProvider"); // // txtMinParams // resources.ApplyResources(this.txtMinParams, "txtMinParams"); this.txtMinParams.Name = "txtMinParams"; this.txtMinParams.TextChanged += new System.EventHandler(this.Element_Changed); this.txtMinParams.Validating += new System.ComponentModel.CancelEventHandler(this.Params_Validating); // // txtMaxParams // resources.ApplyResources(this.txtMaxParams, "txtMaxParams"); this.txtMaxParams.Name = "txtMaxParams"; this.txtMaxParams.TextChanged += new System.EventHandler(this.Element_Changed); this.txtMaxParams.Validating += new System.ComponentModel.CancelEventHandler(this.Params_Validating); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // cmbInputConnType // this.cmbInputConnType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbInputConnType, "cmbInputConnType"); this.cmbInputConnType.Name = "cmbInputConnType"; this.cmbInputConnType.Sorted = true; this.cmbInputConnType.Leave += new System.EventHandler(this.WzPageParametersConn_Leave); // // cmbOutputConnType // this.cmbOutputConnType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbOutputConnType, "cmbOutputConnType"); this.cmbOutputConnType.Name = "cmbOutputConnType"; this.cmbOutputConnType.Sorted = true; // // cmbReturnDataType // this.cmbReturnDataType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbReturnDataType, "cmbReturnDataType"); this.cmbReturnDataType.Name = "cmbReturnDataType"; this.cmbReturnDataType.Sorted = true; // // groupBox1 // this.groupBox1.Controls.Add(this.cmbInputConnType); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.cmbOutputConnType); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.cmbReturnDataType); this.groupBox1.Controls.Add(this.label6); resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // grpParams // this.grpParams.Controls.Add(this.txtMinParams); this.grpParams.Controls.Add(this.txtMaxParams); this.grpParams.Controls.Add(this.label3); this.grpParams.Controls.Add(this.label4); resources.ApplyResources(this.grpParams, "grpParams"); this.grpParams.Name = "grpParams"; this.grpParams.TabStop = false; // // cmdMoveUp // resources.ApplyResources(this.cmdMoveUp, "cmdMoveUp"); this.cmdMoveUp.Name = "cmdMoveUp"; this.cmdMoveUp.Click += new System.EventHandler(this.cmdMoveUp_Click); // // cmdMoveDown // resources.ApplyResources(this.cmdMoveDown, "cmdMoveDown"); this.cmdMoveDown.Name = "cmdMoveDown"; this.cmdMoveDown.Click += new System.EventHandler(this.cmdMoveDown_Click); // // txtFunctoidFunctionName // resources.ApplyResources(this.txtFunctoidFunctionName, "txtFunctoidFunctionName"); this.txtFunctoidFunctionName.Name = "txtFunctoidFunctionName"; // // label8 // resources.ApplyResources(this.label8, "label8"); this.label8.Name = "label8"; // // WzPageParametersConn // this.Controls.Add(this.txtFunctoidFunctionName); this.Controls.Add(this.label8); this.Controls.Add(this.cmdMoveDown); this.Controls.Add(this.cmdMoveUp); this.Controls.Add(this.grpParams); this.Controls.Add(this.groupBox1); this.Controls.Add(this.txtFunctoidParameter); this.Controls.Add(this.cmdFunctoidParameterDel); this.Controls.Add(this.cmdFunctoidParameterAdd); this.Controls.Add(this.cmbParameterDataType); this.Controls.Add(this.label2); this.Controls.Add(this.lstFunctoidParameters); this.Controls.Add(this.label1); this.Name = "WzPageParametersConn"; resources.ApplyResources(this, "$this"); this.SubTitle = "Specify Functoid Parameters && Connection Types"; this.Title = "Functoid Parameters && Connection Types"; this.Load += new System.EventHandler(this.WzPageParametersConn_Load); this.Leave += new System.EventHandler(this.WzPageParametersConn_Leave); this.Controls.SetChildIndex(this.panelHeader, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.lstFunctoidParameters, 0); this.Controls.SetChildIndex(this.label2, 0); this.Controls.SetChildIndex(this.cmbParameterDataType, 0); this.Controls.SetChildIndex(this.cmdFunctoidParameterAdd, 0); this.Controls.SetChildIndex(this.cmdFunctoidParameterDel, 0); this.Controls.SetChildIndex(this.txtFunctoidParameter, 0); this.Controls.SetChildIndex(this.groupBox1, 0); this.Controls.SetChildIndex(this.grpParams, 0); this.Controls.SetChildIndex(this.cmdMoveUp, 0); this.Controls.SetChildIndex(this.cmdMoveDown, 0); this.Controls.SetChildIndex(this.label8, 0); this.Controls.SetChildIndex(this.txtFunctoidFunctionName, 0); this.panelHeader.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit(); this.groupBox1.ResumeLayout(false); this.grpParams.ResumeLayout(false); this.grpParams.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; #pragma warning disable 3021 namespace OpenTK { /// <summary>Represents a 2D vector using two single-precision floating-point numbers.</summary> /// <remarks> /// The Vector2 structure is suitable for interoperation with unmanaged code requiring two consecutive floats. /// </remarks> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector2 : IEquatable<Vector2> { #region Fields /// <summary> /// The X component of the Vector2. /// </summary> public float X; /// <summary> /// The Y component of the Vector2. /// </summary> public float Y; #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2(float value) { X = value; Y = value; } /// <summary> /// Constructs a new Vector2. /// </summary> /// <param name="x">The x coordinate of the net Vector2.</param> /// <param name="y">The y coordinate of the net Vector2.</param> public Vector2(float x, float y) { X = x; Y = y; } /// <summary> /// Constructs a new Vector2 from the given Vector2. /// </summary> /// <param name="v">The Vector2 to copy components from.</param> [Obsolete] public Vector2(Vector2 v) { X = v.X; Y = v.Y; } /// <summary> /// Constructs a new Vector2 from the given Vector3. /// </summary> /// <param name="v">The Vector3 to copy components from. Z is discarded.</param> [Obsolete] public Vector2(Vector3 v) { X = v.X; Y = v.Y; } /// <summary> /// Constructs a new Vector2 from the given Vector4. /// </summary> /// <param name="v">The Vector4 to copy components from. Z and W are discarded.</param> [Obsolete] public Vector2(Vector4 v) { X = v.X; Y = v.Y; } #endregion #region Public Members #region Instance #region public void Add() /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Add() method instead.")] public void Add(Vector2 right) { this.X += right.X; this.Y += right.Y; } /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Add() method instead.")] public void Add(ref Vector2 right) { this.X += right.X; this.Y += right.Y; } #endregion public void Add() #region public void Sub() /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Subtract() method instead.")] public void Sub(Vector2 right) { this.X -= right.X; this.Y -= right.Y; } /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Subtract() method instead.")] public void Sub(ref Vector2 right) { this.X -= right.X; this.Y -= right.Y; } #endregion public void Sub() #region public void Mult() /// <summary>Multiply this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Multiply() method instead.")] public void Mult(float f) { this.X *= f; this.Y *= f; } #endregion public void Mult() #region public void Div() /// <summary>Divide this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Divide() method instead.")] public void Div(float f) { float mult = 1.0f / f; this.X *= mult; this.Y *= mult; } #endregion public void Div() #region public float Length /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <see cref="LengthFast"/> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt(X * X + Y * Y); } } #endregion #region public float LengthFast /// <summary> /// Gets an approximation of the vector length (magnitude). /// </summary> /// <remarks> /// This property uses an approximation of the square root function to calculate vector magnitude, with /// an upper error bound of 0.001. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthSquared"/> public float LengthFast { get { return 1.0f / MathHelper.InverseSqrtFast(X * X + Y * Y); } } #endregion #region public float LengthSquared /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthFast"/> public float LengthSquared { get { return X * X + Y * Y; } } #endregion #region public Vector2 PerpendicularRight /// <summary> /// Gets the perpendicular vector on the right side of this vector. /// </summary> public Vector2 PerpendicularRight { get { return new Vector2(Y, -X); } } #endregion #region public Vector2 PerpendicularLeft /// <summary> /// Gets the perpendicular vector on the left side of this vector. /// </summary> public Vector2 PerpendicularLeft { get { return new Vector2(-Y, X); } } #endregion #region public void Normalize() /// <summary> /// Scales the Vector2 to unit length. /// </summary> public void Normalize() { float scale = 1.0f / this.Length; X *= scale; Y *= scale; } #endregion #region public void NormalizeFast() /// <summary> /// Scales the Vector2 to approximately unit length. /// </summary> public void NormalizeFast() { float scale = MathHelper.InverseSqrtFast(X * X + Y * Y); X *= scale; Y *= scale; } #endregion #region public void Scale() /// <summary> /// Scales the current Vector2 by the given amounts. /// </summary> /// <param name="sx">The scale of the X component.</param> /// <param name="sy">The scale of the Y component.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(float sx, float sy) { this.X = X * sx; this.Y = Y * sy; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(Vector2 scale) { this.X *= scale.X; this.Y *= scale.Y; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [CLSCompliant(false)] [Obsolete("Use static Multiply() method instead.")] public void Scale(ref Vector2 scale) { this.X *= scale.X; this.Y *= scale.Y; } #endregion public void Scale() #endregion #region Static #region Fields /// <summary> /// Defines a unit-length Vector2 that points towards the X-axis. /// </summary> public static readonly Vector2 UnitX = new Vector2(1, 0); /// <summary> /// Defines a unit-length Vector2 that points towards the Y-axis. /// </summary> public static readonly Vector2 UnitY = new Vector2(0, 1); /// <summary> /// Defines a zero-length Vector2. /// </summary> public static readonly Vector2 Zero = new Vector2(0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector2 One = new Vector2(1, 1); /// <summary> /// Defines the size of the Vector2 struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector2()); #endregion #region Obsolete #region Sub /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> [Obsolete("Use static Subtract() method instead.")] public static Vector2 Sub(Vector2 a, Vector2 b) { a.X -= b.X; a.Y -= b.Y; return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> [Obsolete("Use static Subtract() method instead.")] public static void Sub(ref Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X - b.X; result.Y = a.Y - b.Y; } #endregion #region Mult /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <returns>Result of the multiplication</returns> [Obsolete("Use static Multiply() method instead.")] public static Vector2 Mult(Vector2 a, float f) { a.X *= f; a.Y *= f; return a; } /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <param name="result">Result of the multiplication</param> [Obsolete("Use static Multiply() method instead.")] public static void Mult(ref Vector2 a, float f, out Vector2 result) { result.X = a.X * f; result.Y = a.Y * f; } #endregion #region Div /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <returns>Result of the division</returns> [Obsolete("Use static Divide() method instead.")] public static Vector2 Div(Vector2 a, float f) { float mult = 1.0f / f; a.X *= mult; a.Y *= mult; return a; } /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <param name="result">Result of the division</param> [Obsolete("Use static Divide() method instead.")] public static void Div(ref Vector2 a, float f, out Vector2 result) { float mult = 1.0f / f; result.X = a.X * mult; result.Y = a.Y * mult; } #endregion #endregion #region Add /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector2 Add(Vector2 a, Vector2 b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector2 a, ref Vector2 b, out Vector2 result) { result = new Vector2(a.X + b.X, a.Y + b.Y); } #endregion #region Subtract /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector2 Subtract(Vector2 a, Vector2 b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector2 a, ref Vector2 b, out Vector2 result) { result = new Vector2(a.X - b.X, a.Y - b.Y); } #endregion #region Multiply /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2 Multiply(Vector2 vector, float scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2 vector, float scale, out Vector2 result) { result = new Vector2(vector.X * scale, vector.Y * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2 Multiply(Vector2 vector, Vector2 scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2 vector, ref Vector2 scale, out Vector2 result) { result = new Vector2(vector.X * scale.X, vector.Y * scale.Y); } #endregion #region Divide /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2 Divide(Vector2 vector, float scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2 vector, float scale, out Vector2 result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2 Divide(Vector2 vector, Vector2 scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2 vector, ref Vector2 scale, out Vector2 result) { result = new Vector2(vector.X / scale.X, vector.Y / scale.Y); } #endregion #region ComponentMin /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector2 ComponentMin(Vector2 a, Vector2 b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void ComponentMin(ref Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; } #endregion #region ComponentMax /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector2 ComponentMax(Vector2 a, Vector2 b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void ComponentMax(ref Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; } #endregion #region Min /// <summary> /// Returns the Vector3 with the minimum magnitude /// </summary> /// <param name="left">Left operand</param> /// <param name="right">Right operand</param> /// <returns>The minimum Vector3</returns> public static Vector2 Min(Vector2 left, Vector2 right) { return left.LengthSquared < right.LengthSquared ? left : right; } #endregion #region Max /// <summary> /// Returns the Vector3 with the minimum magnitude /// </summary> /// <param name="left">Left operand</param> /// <param name="right">Right operand</param> /// <returns>The minimum Vector3</returns> public static Vector2 Max(Vector2 left, Vector2 right) { return left.LengthSquared >= right.LengthSquared ? left : right; } #endregion #region Clamp /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector2 Clamp(Vector2 vec, Vector2 min, Vector2 max) { vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector2 vec, ref Vector2 min, ref Vector2 max, out Vector2 result) { result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; } #endregion #region Normalize /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector2 Normalize(Vector2 vec) { float scale = 1.0f / vec.Length; vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector2 vec, out Vector2 result) { float scale = 1.0f / vec.Length; result.X = vec.X * scale; result.Y = vec.Y * scale; } #endregion #region NormalizeFast /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector2 NormalizeFast(Vector2 vec) { float scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y); vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void NormalizeFast(ref Vector2 vec, out Vector2 result) { float scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y); result.X = vec.X * scale; result.Y = vec.Y * scale; } #endregion #region Dot /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static float Dot(Vector2 left, Vector2 right) { return left.X * right.X + left.Y * right.Y; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector2 left, ref Vector2 right, out float result) { result = left.X * right.X + left.Y * right.Y; } #endregion #region Lerp /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector2 Lerp(Vector2 a, Vector2 b, float blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector2 a, ref Vector2 b, float blend, out Vector2 result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; } #endregion #region Barycentric /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector2 BaryCentric(Vector2 a, Vector2 b, Vector2 c, float u, float v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector2 a, ref Vector2 b, ref Vector2 c, float u, float v, out Vector2 result) { result = a; // copy Vector2 temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } #endregion #region Transform /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector2 Transform(Vector2 vec, Quaternion quat) { Vector2 result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector2 vec, ref Quaternion quat, out Vector2 result) { Quaternion v = new Quaternion(vec.X, vec.Y, 0, 0), i, t; Quaternion.Invert(ref quat, out i); Quaternion.Multiply(ref quat, ref v, out t); Quaternion.Multiply(ref t, ref i, out v); result = new Vector2(v.X, v.Y); } #endregion #endregion #region Operators /// <summary> /// Adds the specified instances. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>Result of addition.</returns> public static Vector2 operator +(Vector2 left, Vector2 right) { left.X += right.X; left.Y += right.Y; return left; } /// <summary> /// Subtracts the specified instances. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>Result of subtraction.</returns> public static Vector2 operator -(Vector2 left, Vector2 right) { left.X -= right.X; left.Y -= right.Y; return left; } /// <summary> /// Negates the specified instance. /// </summary> /// <param name="vec">Operand.</param> /// <returns>Result of negation.</returns> public static Vector2 operator -(Vector2 vec) { vec.X = -vec.X; vec.Y = -vec.Y; return vec; } /// <summary> /// Multiplies the specified instance by a scalar. /// </summary> /// <param name="vec">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(Vector2 vec, float scale) { vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Multiplies the specified instance by a scalar. /// </summary> /// <param name="scale">Left operand.</param> /// <param name="vec">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(float scale, Vector2 vec) { vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Divides the specified instance by a scalar. /// </summary> /// <param name="vec">Left operand</param> /// <param name="scale">Right operand</param> /// <returns>Result of the division.</returns> public static Vector2 operator /(Vector2 vec, float scale) { float mult = 1.0f / scale; vec.X *= mult; vec.Y *= mult; return vec; } /// <summary> /// Compares the specified instances for equality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>True if both instances are equal; false otherwise.</returns> public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); } /// <summary> /// Compares the specified instances for inequality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>True if both instances are not equal; false otherwise.</returns> public static bool operator !=(Vector2 left, Vector2 right) { return !left.Equals(right); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Vector2. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0}, {1})", X, Y); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector2)) return false; return this.Equals((Vector2)obj); } #endregion #endregion #endregion #region IEquatable<Vector2> Members /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector2 other) { return X == other.X && Y == other.Y; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using docdbwebservice.Areas.HelpPage.ModelDescriptions; using docdbwebservice.Areas.HelpPage.Models; namespace docdbwebservice.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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. // #define StressTest // set to raise the amount of time spent in concurrency tests that stress the collections using System; using System.Collections.Generic; using System.Collections.Tests; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public abstract class ProducerConsumerCollectionTests : IEnumerable_Generic_Tests<int> { protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>(); protected override int CreateT(int seed) => new Random(seed).Next(); protected override EnumerableOrder Order => EnumerableOrder.Unspecified; protected override IEnumerable<int> GenericIEnumerableFactory(int count) => CreateProducerConsumerCollection(count); protected IProducerConsumerCollection<int> CreateProducerConsumerCollection() => CreateProducerConsumerCollection<int>(); protected IProducerConsumerCollection<int> CreateProducerConsumerCollection(int count) => CreateProducerConsumerCollection(Enumerable.Range(0, count)); protected abstract IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>(); protected abstract IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection); protected abstract bool IsEmpty(IProducerConsumerCollection<int> pcc); protected abstract bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result); protected virtual IProducerConsumerCollection<int> CreateOracle() => CreateOracle(Enumerable.Empty<int>()); protected abstract IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection); protected static TaskFactory ThreadFactory { get; } = new TaskFactory( CancellationToken.None, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default); private const double ConcurrencyTestSeconds = #if StressTest 8.0; #else 1.0; #endif [Fact] public void Ctor_InvalidArgs_Throws() { AssertExtensions.Throws<ArgumentNullException>("collection", () => CreateProducerConsumerCollection(null)); } [Fact] public void Ctor_NoArg_ItemsAndCountMatch() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Equal(0, c.Count); Assert.True(IsEmpty(c)); Assert.Equal(Enumerable.Empty<int>(), c); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1000)] public void Ctor_Collection_ItemsAndCountMatch(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, count)); IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(1, count)); Assert.Equal(oracle.Count == 0, IsEmpty(c)); Assert.Equal(oracle.Count, c.Count); Assert.Equal<int>(oracle, c); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(3)] [InlineData(1000)] public void Ctor_InitializeFromCollection_ContainsExpectedItems(int numItems) { var expected = new HashSet<int>(Enumerable.Range(0, numItems)); IProducerConsumerCollection<int> pcc = CreateProducerConsumerCollection(expected); Assert.Equal(expected.Count, pcc.Count); int item; var actual = new HashSet<int>(); for (int i = 0; i < expected.Count; i++) { Assert.Equal(expected.Count - i, pcc.Count); Assert.True(pcc.TryTake(out item)); actual.Add(item); } Assert.False(pcc.TryTake(out item)); Assert.Equal(0, item); AssertSetsEqual(expected, actual); } [Fact] public void Add_TakeFromAnotherThread_ExpectedItemsTaken() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(IsEmpty(c)); Assert.Equal(0, c.Count); const int NumItems = 100000; Task producer = Task.Run(() => Parallel.For(1, NumItems + 1, i => Assert.True(c.TryAdd(i)))); var hs = new HashSet<int>(); while (hs.Count < NumItems) { int item; if (c.TryTake(out item)) hs.Add(item); } producer.GetAwaiter().GetResult(); Assert.True(IsEmpty(c)); Assert.Equal(0, c.Count); AssertSetsEqual(new HashSet<int>(Enumerable.Range(1, NumItems)), hs); } [Fact] public void AddSome_ThenInterleaveAddsAndTakes_MatchesOracle() { IProducerConsumerCollection<int> c = CreateOracle(); IProducerConsumerCollection<int> oracle = CreateProducerConsumerCollection(); Action take = () => { int item1; Assert.True(c.TryTake(out item1)); int item2; Assert.True(oracle.TryTake(out item2)); Assert.Equal(item1, item2); Assert.Equal(c.Count, oracle.Count); Assert.Equal<int>(c, oracle); }; for (int i = 0; i < 100; i++) { Assert.True(oracle.TryAdd(i)); Assert.True(c.TryAdd(i)); Assert.Equal(c.Count, oracle.Count); Assert.Equal<int>(c, oracle); // Start taking some after we've added some if (i > 50) { take(); } } // Take the rest while (c.Count > 0) { take(); } } [Fact] public void AddTake_RandomChangesMatchOracle() { const int Iters = 1000; var r = new Random(42); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < Iters; i++) { if (r.NextDouble() < .5) { Assert.Equal(oracle.TryAdd(i), c.TryAdd(i)); } else { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); } } Assert.Equal(oracle.Count, c.Count); } [Theory] [InlineData(100, 1, 100, true)] [InlineData(100, 4, 10, false)] [InlineData(1000, 11, 100, true)] [InlineData(100000, 2, 50000, true)] public void Initialize_ThenTakeOrPeekInParallel_ItemsObtainedAsExpected(int numStartingItems, int threadsCount, int itemsPerThread, bool take) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, numStartingItems)); int successes = 0; using (var b = new Barrier(threadsCount)) { WaitAllOrAnyFailed(Enumerable.Range(0, threadsCount).Select(threadNum => ThreadFactory.StartNew(() => { b.SignalAndWait(); for (int j = 0; j < itemsPerThread; j++) { int data; if (take ? c.TryTake(out data) : TryPeek(c, out data)) { Interlocked.Increment(ref successes); Assert.NotEqual(0, data); // shouldn't be default(T) } } })).ToArray()); } Assert.Equal( take ? numStartingItems : threadsCount * itemsPerThread, successes); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1000)] public void ToArray_AddAllItemsThenEnumerate_ItemsAndCountMatch(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < count; i++) { Assert.Equal(oracle.TryAdd(i + count), c.TryAdd(i + count)); } Assert.Equal(oracle.ToArray(), c.ToArray()); if (count > 0) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal(oracle.ToArray(), c.ToArray()); } } [Theory] [InlineData(1, 10)] [InlineData(2, 10)] [InlineData(10, 10)] [InlineData(100, 10)] public void ToArray_AddAndTakeItemsIntermixedWithEnumeration_ItemsAndCountMatch(int initialCount, int iters) { IEnumerable<int> initialItems = Enumerable.Range(1, initialCount); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); for (int i = 0; i < iters; i++) { Assert.Equal<int>(oracle, c); Assert.Equal(oracle.TryAdd(initialCount + i), c.TryAdd(initialCount + i)); Assert.Equal<int>(oracle, c); int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal<int>(oracle, c); } } [Fact] public void AddFromMultipleThreads_ItemsRemainAfterThreadsGoAway() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); for (int i = 0; i < 1000; i += 100) { // Create a thread that adds items to the collection ThreadFactory.StartNew(() => { for (int j = i; j < i + 100; j++) { Assert.True(c.TryAdd(j)); } }).GetAwaiter().GetResult(); // Allow threads to be collected GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } AssertSetsEqual(new HashSet<int>(Enumerable.Range(0, 1000)), new HashSet<int>(c)); } [Fact] public void AddManyItems_ThenTakeOnSameThread_ItemsOutputInExpectedOrder() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 100000)); IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(0, 100000)); for (int i = 99999; i >= 0; --i) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); } } [Fact] public void TryPeek_SucceedsOnEmptyCollectionThatWasOnceNonEmpty() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); int item; for (int i = 0; i < 2; i++) { Assert.False(TryPeek(c, out item)); Assert.Equal(0, item); } Assert.True(c.TryAdd(42)); for (int i = 0; i < 2; i++) { Assert.True(TryPeek(c, out item)); Assert.Equal(42, item); } Assert.True(c.TryTake(out item)); Assert.Equal(42, item); Assert.False(TryPeek(c, out item)); Assert.Equal(0, item); Assert.False(c.TryTake(out item)); Assert.Equal(0, item); } [Fact] public void AddTakeWithAtLeastOneElementInCollection_IsEmpty_AlwaysFalse() { int items = 1000; IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(c.TryAdd(0)); // make sure it's never empty var cts = new CancellationTokenSource(); // Consumer repeatedly calls IsEmpty until it's told to stop Task consumer = Task.Run(() => { while (!cts.IsCancellationRequested) Assert.False(IsEmpty(c)); }); // Producer adds/takes a bunch of items, then tells the consumer to stop Task producer = Task.Run(() => { int ignored; for (int i = 1; i <= items; i++) { Assert.True(c.TryAdd(i)); Assert.True(c.TryTake(out ignored)); } cts.Cancel(); }); Task.WaitAll(producer, consumer); } [Fact] public void CopyTo_Empty_NothingCopied() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); c.CopyTo(new int[0], 0); c.CopyTo(new int[10], 10); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_SzArray_ZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); int[] actual = new int[size]; c.CopyTo(actual, 0); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); int[] expected = new int[size]; oracle.CopyTo(expected, 0); Assert.Equal(expected, actual); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_SzArray_NonZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); int[] actual = new int[size + 2]; c.CopyTo(actual, 1); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); int[] expected = new int[size + 2]; oracle.CopyTo(expected, 1); Assert.Equal(expected, actual); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_ArrayZeroLowerBound_ZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); ICollection c = CreateProducerConsumerCollection(initialItems); Array actual = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 }); c.CopyTo(actual, 0); ICollection oracle = CreateOracle(initialItems); Array expected = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 }); oracle.CopyTo(expected, 0); Assert.Equal(expected.Cast<int>(), actual.Cast<int>()); } [Fact] public void CopyTo_ArrayNonZeroLowerBound_ExpectedElementsCopied() { int[] initialItems = Enumerable.Range(1, 10).ToArray(); const int LowerBound = 1; ICollection c = CreateProducerConsumerCollection(initialItems); Array actual = Array.CreateInstance(typeof(int), new int[] { initialItems.Length }, new int[] { LowerBound }); c.CopyTo(actual, LowerBound); ICollection oracle = CreateOracle(initialItems); int[] expected = new int[initialItems.Length]; oracle.CopyTo(expected, 0); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual.GetValue(i + LowerBound)); } } [Fact] public void CopyTo_InvalidArgs_Throws() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 10)); int[] dest = new int[10]; AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1)); Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length)); Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length - 2)); Assert.Throws<ArgumentException>(() => c.CopyTo(new int[7, 7], 0)); } [Fact] public void ICollectionCopyTo_InvalidArgs_Throws() { ICollection c = CreateProducerConsumerCollection(Enumerable.Range(0, 10)); Array dest = new int[10]; AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1)); Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length)); Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length - 2)); } [Theory] [InlineData(100, 1, 10)] [InlineData(4, 100000, 10)] public void BlockingCollection_WrappingCollection_ExpectedElementsTransferred(int numThreadsPerConsumerProducer, int numItemsPerThread, int producerSpin) { var bc = new BlockingCollection<int>(CreateProducerConsumerCollection()); long dummy = 0; Task[] producers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() => { for (int i = 1; i <= numItemsPerThread; i++) { for (int j = 0; j < producerSpin; j++) dummy *= j; // spin a little bc.Add(i); } })).ToArray(); Task[] consumers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() => { for (int i = 0; i < numItemsPerThread; i++) { const int TimeoutMs = 100000; int item; Assert.True(bc.TryTake(out item, TimeoutMs), $"Couldn't get {i}th item after {TimeoutMs}ms"); Assert.NotEqual(0, item); } })).ToArray(); WaitAllOrAnyFailed(producers); WaitAllOrAnyFailed(consumers); } [Fact] public void GetEnumerator_NonGeneric() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IEnumerable e = c; Assert.False(e.GetEnumerator().MoveNext()); Assert.True(c.TryAdd(42)); Assert.True(c.TryAdd(84)); var hs = new HashSet<int>(e.Cast<int>()); Assert.Equal(2, hs.Count); Assert.Contains(42, hs); Assert.Contains(84, hs); } [Fact] public void GetEnumerator_EnumerationsAreSnapshots() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c); using (IEnumerator<int> e1 = c.GetEnumerator()) { Assert.True(c.TryAdd(1)); using (IEnumerator<int> e2 = c.GetEnumerator()) { Assert.True(c.TryAdd(2)); using (IEnumerator<int> e3 = c.GetEnumerator()) { int item; Assert.True(c.TryTake(out item)); using (IEnumerator<int> e4 = c.GetEnumerator()) { Assert.False(e1.MoveNext()); Assert.True(e2.MoveNext()); Assert.False(e2.MoveNext()); Assert.True(e3.MoveNext()); Assert.True(e3.MoveNext()); Assert.False(e3.MoveNext()); Assert.True(e4.MoveNext()); Assert.False(e4.MoveNext()); } } } } } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(1, false)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(100, false)] public async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); using (var e = c.GetEnumerator()) { Assert.False(e.MoveNext()); } // Add, and validate enumeration after each item added for (int i = 1; i <= numItems; i++) { Assert.True(c.TryAdd(i)); Assert.Equal(i, c.Count); Assert.Equal(i, c.Distinct().Count()); } // Take, and validate enumerate after each item removed. Action consume = () => { for (int i = 1; i <= numItems; i++) { int item; Assert.True(c.TryTake(out item)); Assert.Equal(numItems - i, c.Count); Assert.Equal(numItems - i, c.Distinct().Count()); } }; if (consumeFromSameThread) { consume(); } else { await ThreadFactory.StartNew(consume); } } [Fact] public void TryAdd_TryTake_ToArray() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(c.TryAdd(42)); Assert.Equal(new[] { 42 }, c.ToArray()); Assert.True(c.TryAdd(84)); Assert.Equal(new[] { 42, 84 }, c.ToArray().OrderBy(i => i)); int item; Assert.True(c.TryTake(out item)); int remainingItem = item == 42 ? 84 : 42; Assert.Equal(new[] { remainingItem }, c.ToArray()); Assert.True(c.TryTake(out item)); Assert.Equal(remainingItem, item); Assert.Empty(c.ToArray()); } [Fact] public void ICollection_IsSynchronized_SyncRoot() { ICollection c = CreateProducerConsumerCollection(); Assert.False(c.IsSynchronized); Assert.Throws<NotSupportedException>(() => c.SyncRoot); } [Fact] public void ToArray_ParallelInvocations_Succeed() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c.ToArray()); const int NumItems = 10000; Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i))); Assert.Equal(NumItems, c.Count); Parallel.For(0, 10, i => { var hs = new HashSet<int>(c.ToArray()); Assert.Equal(NumItems, hs.Count); }); } [Fact] public void ToArray_AddTakeSameThread_ExpectedResultsAfterAddsAndTakes() { const int Items = 20; IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < Items; i++) { Assert.True(c.TryAdd(i)); Assert.True(oracle.TryAdd(i)); Assert.Equal(oracle.ToArray(), c.ToArray()); } for (int i = Items - 1; i >= 0; i--) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal(oracle.ToArray(), c.ToArray()); } } [Fact] public void GetEnumerator_ParallelInvocations_Succeed() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c.ToArray()); const int NumItems = 10000; Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i))); Assert.Equal(NumItems, c.Count); Parallel.For(0, 10, i => { var hs = new HashSet<int>(c); Assert.Equal(NumItems, hs.Count); }); } [Theory] [InlineData(1, ConcurrencyTestSeconds / 2)] [InlineData(4, ConcurrencyTestSeconds / 2)] public void ManyConcurrentAddsTakes_EnsureTrackedCountsMatchResultingCollection(int threadsPerProc, double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); DateTime end = default(DateTime); using (var b = new Barrier(Environment.ProcessorCount * threadsPerProc, _ => end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds))) { Task<int>[] tasks = Enumerable.Range(0, b.ParticipantCount).Select(_ => ThreadFactory.StartNew(() => { b.SignalAndWait(); int count = 0; var rand = new Random(); while (DateTime.UtcNow < end) { if (rand.NextDouble() < .5) { Assert.True(c.TryAdd(rand.Next())); count++; } else { int item; if (c.TryTake(out item)) count--; } } return count; })).ToArray(); Task.WaitAll(tasks); Assert.Equal(tasks.Sum(t => t.Result), c.Count); } } [Theory] [InlineData(3000000)] [OuterLoop] public void ManyConcurrentAddsTakes_CollectionRemainsConsistent(int operations) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); // Thread that adds Task<HashSet<int>> adds = ThreadFactory.StartNew(() => { for (int i = int.MinValue; i < (int.MinValue + operations); i++) { Assert.True(c.TryAdd(i)); } return new HashSet<int>(Enumerable.Range(int.MinValue, operations)); }); // Thread that adds and takes Task<KeyValuePair<HashSet<int>, HashSet<int>>> addsAndTakes = ThreadFactory.StartNew(() => { var added = new HashSet<int>(); var taken = new HashSet<int>(); // avoid 0 as default(T), to detect accidentally reading a default value for (int i = 1; i < (1 + operations); i++) { Assert.True(c.TryAdd(i)); added.Add(i); int item; if (c.TryTake(out item)) { Assert.NotEqual(0, item); taken.Add(item); } } return new KeyValuePair<HashSet<int>, HashSet<int>>(added, taken); }); // Thread that just takes Task<HashSet<int>> takes = ThreadFactory.StartNew(() => { var taken = new HashSet<int>(); for (int i = 1; i < (1 + operations); i++) { int item; if (c.TryTake(out item)) { Assert.NotEqual(0, item); taken.Add(item); } } return taken; }); // Wait for them all to finish WaitAllOrAnyFailed(adds, addsAndTakes, takes); // Combine everything they added and remove everything they took var total = new HashSet<int>(adds.Result); total.UnionWith(addsAndTakes.Result.Key); total.ExceptWith(addsAndTakes.Result.Value); total.ExceptWith(takes.Result); // What's left should match what's in the collection Assert.Equal(total.OrderBy(i => i), c.OrderBy(i => i)); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsTaking(double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task<long> addsTakes = ThreadFactory.StartNew(() => { long total = 0; while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); total++; } int item; if (TryPeek(c, out item)) { Assert.InRange(item, 1, MaxCount); } for (int i = 1; i <= MaxCount; i++) { if (c.TryTake(out item)) { total--; Assert.InRange(item, 1, MaxCount); } } } return total; }); Task<long> takesFromOtherThread = ThreadFactory.StartNew(() => { long total = 0; int item; while (DateTime.UtcNow < end) { if (c.TryTake(out item)) { total++; Assert.InRange(item, 1, MaxCount); } } return total; }); WaitAllOrAnyFailed(addsTakes, takesFromOtherThread); long remaining = addsTakes.Result - takesFromOtherThread.Result; Assert.InRange(remaining, 0, long.MaxValue); Assert.Equal(remaining, c.Count); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsPeeking(double seconds) { IProducerConsumerCollection<LargeStruct> c = CreateProducerConsumerCollection<LargeStruct>(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task<long> addsTakes = ThreadFactory.StartNew(() => { long total = 0; while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(new LargeStruct(i))); total++; } LargeStruct item; Assert.True(TryPeek(c, out item)); Assert.InRange(item.Value, 1, MaxCount); for (int i = 1; i <= MaxCount; i++) { if (c.TryTake(out item)) { total--; Assert.InRange(item.Value, 1, MaxCount); } } } return total; }); Task peeksFromOtherThread = ThreadFactory.StartNew(() => { LargeStruct item; while (DateTime.UtcNow < end) { if (TryPeek(c, out item)) { Assert.InRange(item.Value, 1, MaxCount); } } }); WaitAllOrAnyFailed(addsTakes, peeksFromOtherThread); Assert.Equal(0, addsTakes.Result); Assert.Equal(0, c.Count); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakes_ForceContentionWithToArray(double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task addsTakes = ThreadFactory.StartNew(() => { while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); } for (int i = 1; i <= MaxCount; i++) { int item; Assert.True(c.TryTake(out item)); Assert.InRange(item, 1, MaxCount); } } }); while (DateTime.UtcNow < end) { int[] arr = c.ToArray(); Assert.InRange(arr.Length, 0, MaxCount); Assert.DoesNotContain(0, arr); // make sure we didn't get default(T) } addsTakes.GetAwaiter().GetResult(); Assert.Equal(0, c.Count); } [Theory] [InlineData(0, ConcurrencyTestSeconds / 2)] [InlineData(1, ConcurrencyTestSeconds / 2)] public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount)); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task addsTakes = ThreadFactory.StartNew(() => { while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); } for (int i = 1; i <= MaxCount; i++) { int item; Assert.True(c.TryTake(out item)); Assert.InRange(item, 1, MaxCount); } } }); while (DateTime.UtcNow < end) { int[] arr = c.Select(i => i).ToArray(); Assert.InRange(arr.Length, initialCount, MaxCount + initialCount); Assert.DoesNotContain(0, arr); // make sure we didn't get default(T) } addsTakes.GetAwaiter().GetResult(); Assert.Equal(initialCount, c.Count); } [Theory] [InlineData(0)] [InlineData(10)] public void DebuggerAttributes_Success(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(count); DebuggerAttributes.ValidateDebuggerDisplayReferences(c); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c); } [Fact] public void DebuggerTypeProxy_Ctor_NullArgument_Throws() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Type proxyType = DebuggerAttributes.GetProxyType(c); var tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, new object[] { null })); Assert.IsType<ArgumentNullException>(tie.InnerException); } protected static void AssertSetsEqual<T>(HashSet<T> expected, HashSet<T> actual) { Assert.Equal(expected.Count, actual.Count); Assert.Subset(expected, actual); Assert.Subset(actual, expected); } protected static void WaitAllOrAnyFailed(params Task[] tasks) { if (tasks.Length == 0) { return; } int remaining = tasks.Length; var mres = new ManualResetEventSlim(); foreach (Task task in tasks) { task.ContinueWith(t => { if (Interlocked.Decrement(ref remaining) == 0 || t.IsFaulted) { mres.Set(); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } mres.Wait(); // Either all tasks are completed or at least one failed foreach (Task t in tasks) { if (t.IsFaulted) { t.GetAwaiter().GetResult(); // propagate for the first one that failed } } } private struct LargeStruct // used to help validate that values aren't torn while being read { private readonly long _a, _b, _c, _d, _e, _f, _g, _h; public LargeStruct(long value) { _a = _b = _c = _d = _e = _f = _g = _h = value; } public long Value { get { if (_a != _b || _a != _c || _a != _d || _a != _e || _a != _f || _a != _g || _a != _h) { throw new Exception($"Inconsistent {nameof(LargeStruct)}: {_a} {_b} {_c} {_d} {_e} {_f} {_g} {_h}"); } return _a; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Data; using Volte.Utils; namespace Volte.Data.Json { [Serializable] public class JSONTable { const string ZFILE_NAME = "JSONTable"; private readonly StringBuilder _Fields = new StringBuilder(); public JSONTable() { _Columns = new Columns(); _Variable = new JSONObject(); _Pointer = -1; } internal void Read(Lexer _Lexer) { _Columns = new Columns(); _Variable = new JSONObject(); if (!_Lexer.MatchChar('{')) { throw new ArgumentException("Invalid element", "element"); } _Lexer.NextToken(); if (!_Lexer.MatchChar('}')) { for (;;) { string name = _Lexer.ParseName(); if (name == "schema") { _Columns.Read(_Lexer); } else if (name == "vars") { _Variable.Read(_Lexer); } else if (name == "data") { _Lexer.SkipWhiteSpace(); if (_Lexer.Current == '[') { _Lexer.NextToken(); _Lexer.SkipWhiteSpace(); if (_Lexer.Current != ']') { for (;;) { Row row1 = new Row(_Columns.Count); row1.Read(_Lexer); _rows.Add(row1); _Lexer.SkipWhiteSpace(); if (_Lexer.Current == ',') { _Lexer.NextToken(); } else { break; } } } if (_Lexer.Current == ']') { _Lexer.NextToken(); } } } if (_Lexer.Current == ',') { _Lexer.NextToken(); } else { break; } } } } internal void Write(StringBuilder writer) { writer.AppendLine("{"); if (_Variable == null) { _Variable = new JSONObject(); } int _absolutePage = 0; int _PageSize = 0; int _RecordCount = this.RecordCount; if (_Variable.ContainsKey("absolutePage")){ _absolutePage = _Variable.GetInteger("absolutePage"); } if (_Variable.ContainsKey("pageSize")){ _PageSize = _Variable.GetInteger("pageSize"); } if (_Columns != null) { _Columns.Write(writer); writer.AppendLine(","); } if (this._rows != null) { writer.AppendLine("\"data\":"); writer.AppendLine("["); if (!_StructureOnly) { int _rec = 0; int _loc = 0; if (this.Paging){ int _TotalPages = 1; if (_PageSize <= 0) { _PageSize = _RecordCount; } else { _TotalPages = _RecordCount / _PageSize; if (_RecordCount > (_RecordCount / _PageSize) * _PageSize) { _TotalPages = _TotalPages + 1; } if (_absolutePage<=0){ _absolutePage=1; } if (_absolutePage>_TotalPages){ _absolutePage=_TotalPages; } if (_absolutePage > 1) { _loc = (_absolutePage - 1) * _PageSize; } } }else{ _PageSize = _RecordCount; } while ((_loc+_rec)<_RecordCount && _rec < _PageSize) { if (_rec > 0) { writer.AppendLine(","); } Row _row = _rows[_loc+_rec]; _row.Flatten = _Flatten; _row.Write(writer , _Columns); _rec++; } } _StructureOnly = false; writer.AppendLine("]"); } _Variable.SetValue("recordCount" , _RecordCount); writer.AppendLine(","); writer.AppendLine("\"vars\":"); _Variable.Write(writer); if (this._summary != null) { writer.AppendLine(","); writer.AppendLine("\"summary\":"); _summary.Write(writer); writer.AppendLine(""); } if (_merge.Count>0){ writer.AppendLine(","); writer.AppendLine("\"mergeCells\":"); _merge.Write(writer); writer.AppendLine(""); } if (_cells.Count>0){ writer.AppendLine(","); writer.AppendLine("\"cell\":"); _cells.Write(writer); writer.AppendLine(""); } writer.AppendLine("}"); } public void Parser(string _string) { this.Read(new Lexer(_string)); } public string ToString(bool xx = false) { _StructureOnly = xx; _s.Length = 0; this.Write(_s); return _s.ToString(); } public override string ToString() { _s.Length = 0; this.Write(_s); return _s.ToString(); } public string IndexString() { _s.Length = 0; return _s.ToString(); } public void AddNew() { _Draft = true; _Pointer = 0; _Row = new Row(_Columns.Count); _Readed = true; } public void Revert() { if (_Draft) { _Row = new Row(_Columns.Count); _Draft = false; _Readed = false; } } public void Update() { if (_Draft) { _rows.Add(_Row); } else { _rows[_Pointer] = _Row; } _Draft = false; } public void Open() { _Pointer = 0; if (_Pointer < _rows.Count) { _Row = _rows[_Pointer]; } else { _rows = null; } _Readed = true; } public void Close() { _rows = null; _Readed = false; _Draft = false; _Row = null; _Columns = new Columns(); _Variable = new JSONObject(); _Pointer = -1; } public object GetAttribute(int ndx , string att) { if (!_Readed) { _Readed = true; _Row = _rows[_Pointer]; } if (att.ToLower()=="scode"){ return _Row[ndx].sCode; }else{ return null; } } public object GetAttribute(string name , string att) { int _Ordinal = _Columns.Ordinal(name); if (_Ordinal == -1) { throw new ArgumentException("Invalid column name" , name+" Ordinal = "+_Ordinal.ToString()); } return GetAttribute(_Ordinal , att); } public void SetAttribute(int ndx , string att , object oValue) { if (!_Readed) { _Readed = true; _Row = _rows[_Pointer]; } Cell _Cell = _Row[ndx]; if (att.ToLower()=="scode"){ _Cell.sCode = oValue.ToString(); } _Row[ndx] = _Cell; } public void SetAttribute(string name , string att , string oValue) { int _Ordinal = _Columns.Ordinal(name); if (_Ordinal == -1) { throw new ArgumentException("Invalid column name" , "["+name+"] Ordinal = "+_Ordinal.ToString()); } SetAttribute(_Ordinal,att,oValue); } public object this[string name] { get { int _Ordinal = _Columns.Ordinal(name); if (_Ordinal == -1) { throw new ArgumentException("Invalid column name" , name+" Ordinal = "+_Ordinal.ToString()); } if (!_Readed) { _Readed = true; _Row = _rows[_Pointer]; } return _Row[_Ordinal].Value; } set { if (!object.Equals(value, null)) { int _Ordinal = _Columns.Ordinal(name); if (_Ordinal == -1) { throw new ArgumentException("Invalid column name" , "["+name+"] Ordinal = "+_Ordinal.ToString()); } Cell _Cell = _Row[_Ordinal]; _Cell.Value = value; _Row[_Ordinal] = _Cell; } } } public object this[int i] { get { if (!_Readed) { _Readed = true; _Row = _rows[_Pointer]; } return _Row[i].Value; } set { if (i < 0 || i >= _Columns.Count) { throw new ArgumentException("Invalid column index + _Columns=" + _Columns.Count, i.ToString()); } Cell _Cell = _Row[i]; _Cell.Value = value; _Row[i] = _Cell; } } public bool GetBoolean(string Name) { return this.GetBoolean(_Columns.Ordinal(Name)); } public bool GetBoolean(int Index) { object cValue = this[Index]; if (cValue==null || string.IsNullOrEmpty(cValue.ToString())) { return false; }else if (cValue is bool) { return (bool) cValue; } else if (cValue.Equals("Y") || cValue.Equals("y")) { return true; } else if (cValue.Equals("N") || cValue.Equals("n")) { return false; } else { return Util.ToBoolean(cValue); } } public decimal GetDecimal(int Index) { object cValue = this[Index]; if (cValue==null || string.IsNullOrEmpty(cValue.ToString())) { return 0; } return Util.ToDecimal(cValue); } public decimal GetDecimal(string Name) { return this.GetDecimal(_Columns.Ordinal(Name)); } public int GetInt32(int i) { return GetInteger(i); } public int GetInteger(int i) { return Util.ToInt32(this[i]); } public int GetInteger(string Name) { return Util.ToInt32(this[Name]); } public string GetString(int i) { return GetValue(i); } public object GetValue(int row , string name) { int i = _Columns.Ordinal(name); Row _tRow = _rows[row]; return _tRow[i].Value; } public object GetValue(int row , int i) { Row _tRow = _rows[row]; return _tRow[i].Value; } public string GetFormula(string name) { int i = _Columns.Ordinal(name); return GetFormula(i); } public string GetFormula(int i) { if (!_Readed) { _Readed = true; _Row = _rows[_Pointer]; } return _Row[i].sFormula; } public void SetFormula(string name , string sFormula) { SetFormula(_Columns.Ordinal(name) , sFormula); } public void SetFormula(int i , string sFormula) { if (i < 0 || i >= _Columns.Count) { throw new ArgumentException("Invalid column index + _Columns=" + _Columns.Count, i.ToString()); } Cell _Cell = _Row[i]; _Cell.sFormula = sFormula; _Row[i] = _Cell; } public string GetValue(int i) { object _obj = this[i]; if (_obj == null) { return ""; } else { return _obj.ToString(); } } public string GetValue(string Name) { object _obj = this[Name]; if (_obj == null) { return ""; } else { return _obj.ToString(); } } public DateTime GetDateTime(string Name) { int _Ordinal = _Columns.Ordinal(Name); return GetDateTime(_Ordinal); } public DateTime? GetDateTime2(string Name) { int _Ordinal = _Columns.Ordinal(Name); return GetDateTime(_Ordinal); } public DateTime GetDateTime(int i) { return Util.ToDateTime(this[i]); } public DateTime? GetDateTime2(int i) { return Util.ToDateTime(this[i]); } public void SetValue(string Name, object value) { this[Name] = value; } public void SetValue(int ndx, object value) { this[ndx] = value; } public void MoveFirst() { _Pointer = 0; _Readed = false; } public void MoveLast() { _Pointer = _rows.Count - 1; _Readed = false; } public void Locate(int cPoint) { _Pointer = cPoint; _Readed = false; if (_Pointer < _rows.Count) { _Row = _rows[_Pointer]; _Readed = true; _Draft = false; } } public void MovePrev() { _Pointer--; _Readed = false; } public void MoveNext() { _Pointer++; _Readed = false; } public void Declare(string name, string caption, string type, int width = 12, int scale = 2) { Column _Column = new Column(); _Column.Name = name; _Column.Hash = name.Replace("." , "_"); _Column.Caption = caption; _Column.DataType = type; _Column.Scale = scale; _Column.Width = width; _Columns.Add(_Column); } public void Declare(AttributeMapping _DataField) { Column _Column = new Column(); _Column.ColumnName = _DataField.ColumnName; _Column.Name = _DataField.Name; _Column.Hash = _DataField.Name.Replace(".", "_"); _Column.Caption = _DataField.Caption; _Column.Description = _DataField.Description; _Column.Scale = _DataField.Scale; _Column.Index = _DataField.Index; _Column.Width = _DataField.Width; _Column.Format = _DataField.Format; _Column.Status = _DataField.Status; _Column.EnableMode = _DataField.EnableMode; _Column.Reference = _DataField.Reference; _Column.TypeChar = _DataField.TypeChar; _Column.Compulsory = _DataField.Compulsory; _Column.Hidden = _DataField.Hidden; _Column.DataType = _DataField.DataType; _Column.DataBand = _DataField.DataBand; _Column.AlignName = _DataField.AlignName; _Column.Options = _DataField.Options; _Column.Props = _DataField.Props.Clone(); _Columns.Add(_Column); } public void DeclareStart() { _Columns = new Columns(); } public int Ordinal(string name) { return _Columns.Ordinal(name); } public bool ContainsKey(string name) { return _Columns.ContainsKey(name); } public string GetType(string name) { return _Columns.GetType(name); } public void DeclareFinal() { } public void Sort(string Name) { RowComparer _RowComparer = new RowComparer(_Columns, Name); _rows.Sort(_RowComparer.Compare); } public void Merge(int row , int col , int rowspan = 1 , int colspan = 1) { JSONObject v = new JSONObject(); v.SetLong("row" , row); v.SetLong("col" , col); v.SetLong("rowspan" , rowspan); v.SetLong("colspan" , colspan); _merge.Add(v); } public void Cell(int row , int col , JSONObject cell) { cell.SetLong("row" , row); cell.SetLong("col" , col); _cells.Add(cell); } public JSONObject Reference { get { if (!_Readed) { _Readed = true; _Row = _rows[_Pointer]; } if (_Row.Reference==null){ _Row.Reference = new JSONObject(); } return _Row.Reference; } set { _Row.Reference = value; } } public int RecordCount { get { if (_rows == null) { return -1; } else { return _rows.Count; } } } // Properties public bool EOF { get { if (_rows == null) { return true; } return _Pointer >= _rows.Count; } } public bool BOF { get { return _Pointer < 0; } } public JSONObject Variable { get { return _Variable; } } public List<Column> Fields { get { return _Columns.Fields; } } public List<Row> Rows { get { return _rows; } } public JSONArray Summary { get { return _summary; } } public JSONArray MergeCells { get { return _merge; } } public bool Paging { get { return _Paging; } set { _Paging = value; } } public Flatten Flatten { get { return _Flatten; } set { _Flatten = value; } } private Row _Row; private Columns _Columns; private readonly StringBuilder _s = new StringBuilder(); private JSONObject _Variable = new JSONObject(); private JSONArray _summary = new JSONArray(); private List<Row> _rows = new List<Row>(); private JSONArray _merge = new JSONArray(); private JSONArray _cells = new JSONArray(); private bool _Draft = false; private Flatten _Flatten = Flatten.Complex; private bool _Readed = false; private bool _StructureOnly = false; private bool _Paging = false; private int _Pointer = -1; } [Serializable] public enum Flatten { Complex, NameValue, Value } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; #if !(NET35 || NET20 || SILVERLIGHT) using System.Dynamic; #endif using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; using System.Security; namespace Newtonsoft.Json.Serialization { internal class JsonSerializerInternalWriter : JsonSerializerInternalBase { private JsonSerializerProxy _internalSerializer; private List<object> _serializeStack; private List<object> SerializeStack { get { if (_serializeStack == null) _serializeStack = new List<object>(); return _serializeStack; } } public JsonSerializerInternalWriter(JsonSerializer serializer) : base(serializer) { } public void Serialize(JsonWriter jsonWriter, object value) { if (jsonWriter == null) throw new ArgumentNullException("jsonWriter"); SerializeValue(jsonWriter, value, GetContractSafe(value), null, null); } private JsonSerializerProxy GetInternalSerializer() { if (_internalSerializer == null) _internalSerializer = new JsonSerializerProxy(this); return _internalSerializer; } private JsonContract GetContractSafe(object value) { if (value == null) return null; return Serializer.ContractResolver.ResolveContract(value.GetType()); } private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract) { JsonConverter converter = (member != null) ? member.Converter : null; if (value == null) { writer.WriteNull(); return; } if ((converter != null || ((converter = valueContract.Converter) != null) || ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null) || ((converter = valueContract.InternalConverter) != null)) && converter.CanWrite) { SerializeConvertable(writer, converter, value, valueContract); } else if (valueContract is JsonPrimitiveContract) { writer.WriteValue(value); } else if (valueContract is JsonStringContract) { SerializeString(writer, value, (JsonStringContract) valueContract); } else if (valueContract is JsonObjectContract) { SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract); } else if (valueContract is JsonDictionaryContract) { JsonDictionaryContract dictionaryContract = (JsonDictionaryContract) valueContract; SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionValueContract); } else if (valueContract is JsonArrayContract) { JsonArrayContract arrayContract = (JsonArrayContract) valueContract; SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, collectionValueContract); } else if (valueContract is JsonLinqContract) { ((JToken)value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null); } #if !SILVERLIGHT && !PocketPC else if (valueContract is JsonISerializableContract) { SerializeISerializable(writer, (ISerializable) value, (JsonISerializableContract) valueContract); } #endif #if !(NET35 || NET20 || SILVERLIGHT) else if (valueContract is JsonDynamicContract) { SerializeDynamic(writer, (IDynamicMetaObjectProvider) value, (JsonDynamicContract) valueContract); } #endif } private bool ShouldWriteReference(object value, JsonProperty property, JsonContract contract) { if (value == null) return false; if (contract is JsonPrimitiveContract) return false; bool? isReference = null; // value could be coming from a dictionary or array and not have a property if (property != null) isReference = property.IsReference; if (isReference == null) isReference = contract.IsReference; if (isReference == null) { if (contract is JsonArrayContract) isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays); else isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects); } if (!isReference.Value) return false; return Serializer.ReferenceResolver.IsReferenced(value); } private void WriteMemberInfoProperty(JsonWriter writer, object memberValue, JsonProperty property, JsonContract contract) { string propertyName = property.PropertyName; object defaultValue = property.DefaultValue; if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore && memberValue == null) return; if (property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling) == DefaultValueHandling.Ignore && Equals(memberValue, defaultValue)) return; if (ShouldWriteReference(memberValue, property, contract)) { writer.WritePropertyName(propertyName); WriteReference(writer, memberValue); return; } if (!CheckForCircularReference(memberValue, property.ReferenceLoopHandling, contract)) return; if (memberValue == null && property.Required == Required.Always) throw new JsonSerializationException("Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); writer.WritePropertyName(propertyName); SerializeValue(writer, memberValue, contract, property, null); } private bool CheckForCircularReference(object value, ReferenceLoopHandling? referenceLoopHandling, JsonContract contract) { if (value == null || contract is JsonPrimitiveContract) return true; if (SerializeStack.IndexOf(value) != -1) { switch (referenceLoopHandling.GetValueOrDefault(Serializer.ReferenceLoopHandling)) { case ReferenceLoopHandling.Error: throw new JsonSerializationException("Self referencing loop"); case ReferenceLoopHandling.Ignore: return false; case ReferenceLoopHandling.Serialize: return true; default: throw new InvalidOperationException("Unexpected ReferenceLoopHandling value: '{0}'".FormatWith(CultureInfo.InvariantCulture, Serializer.ReferenceLoopHandling)); } } return true; } private void WriteReference(JsonWriter writer, object value) { writer.WriteStartObject(); writer.WritePropertyName(JsonTypeReflector.RefPropertyName); writer.WriteValue(Serializer.ReferenceResolver.GetReference(value)); writer.WriteEndObject(); } internal static bool TryConvertToString(object value, Type type, out string s) { #if !PocketPC TypeConverter converter = ConvertUtils.GetConverter(type); // use the objectType's TypeConverter if it has one and can convert to a string if (converter != null #if !SILVERLIGHT && !(converter is ComponentConverter) #endif && converter.GetType() != typeof(TypeConverter)) { if (converter.CanConvertTo(typeof(string))) { #if !SILVERLIGHT s = converter.ConvertToInvariantString(value); #else s = converter.ConvertToString(value); #endif return true; } } #endif #if SILVERLIGHT || PocketPC if (value is Guid || value is Uri || value is TimeSpan) { s = value.ToString(); return true; } #endif if (value is Type) { s = ((Type)value).AssemblyQualifiedName; return true; } s = null; return false; } private void SerializeString(JsonWriter writer, object value, JsonStringContract contract) { contract.InvokeOnSerializing(value, Serializer.Context); string s; TryConvertToString(value, contract.UnderlyingType, out s); writer.WriteValue(s); contract.InvokeOnSerialized(value, Serializer.Context); } private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract) { contract.InvokeOnSerializing(value, Serializer.Context); SerializeStack.Add(value); writer.WriteStartObject(); bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects); if (isReference) { writer.WritePropertyName(JsonTypeReflector.IdPropertyName); writer.WriteValue(Serializer.ReferenceResolver.GetReference(value)); } if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract)) { WriteTypeProperty(writer, contract.UnderlyingType); } int initialDepth = writer.Top; foreach (JsonProperty property in contract.Properties) { try { if (!property.Ignored && property.Readable && ShouldSerialize(property, value)) { object memberValue = property.ValueProvider.GetValue(value); JsonContract memberContract = GetContractSafe(memberValue); WriteMemberInfoProperty(writer, memberValue, property, memberContract); } } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, ex)) HandleError(writer, initialDepth); else throw; } } writer.WriteEndObject(); SerializeStack.RemoveAt(SerializeStack.Count - 1); contract.InvokeOnSerialized(value, Serializer.Context); } private void WriteTypeProperty(JsonWriter writer, Type type) { writer.WritePropertyName(JsonTypeReflector.TypePropertyName); writer.WriteValue(ReflectionUtils.GetTypeName(type, Serializer.TypeNameAssemblyFormat)); } private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag) { return ((value & flag) == flag); } private bool HasFlag(TypeNameHandling value, TypeNameHandling flag) { return ((value & flag) == flag); } private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract) { if (ShouldWriteReference(value, null, contract)) { WriteReference(writer, value); } else { if (!CheckForCircularReference(value, null, contract)) return; SerializeStack.Add(value); converter.WriteJson(writer, value, GetInternalSerializer()); SerializeStack.RemoveAt(SerializeStack.Count - 1); } } private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract) { contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context); SerializeStack.Add(values.UnderlyingCollection); bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays); bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract); if (isReference || includeTypeDetails) { writer.WriteStartObject(); if (isReference) { writer.WritePropertyName(JsonTypeReflector.IdPropertyName); writer.WriteValue(Serializer.ReferenceResolver.GetReference(values.UnderlyingCollection)); } if (includeTypeDetails) { WriteTypeProperty(writer, values.UnderlyingCollection.GetType()); } writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName); } JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object)); writer.WriteStartArray(); int initialDepth = writer.Top; int index = 0; // note that an error in the IEnumerable won't be caught foreach (object value in values) { try { JsonContract valueContract = GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract)) { WriteReference(writer, value); } else { if (CheckForCircularReference(value, null, contract)) { SerializeValue(writer, value, valueContract, null, childValuesContract); } } } catch (Exception ex) { if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex)) HandleError(writer, initialDepth); else throw; } finally { index++; } } writer.WriteEndArray(); if (isReference || includeTypeDetails) { writer.WriteEndObject(); } SerializeStack.RemoveAt(SerializeStack.Count - 1); contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context); } #if !SILVERLIGHT && !PocketPC #if !NET20 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")] [SecuritySafeCritical] #endif private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract) { contract.InvokeOnSerializing(value, Serializer.Context); SerializeStack.Add(value); writer.WriteStartObject(); SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter()); value.GetObjectData(serializationInfo, Serializer.Context); foreach (SerializationEntry serializationEntry in serializationInfo) { writer.WritePropertyName(serializationEntry.Name); SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null); } writer.WriteEndObject(); SerializeStack.RemoveAt(SerializeStack.Count - 1); contract.InvokeOnSerialized(value, Serializer.Context); } #endif #if !(NET35 || NET20 || SILVERLIGHT) private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract) { contract.InvokeOnSerializing(value, Serializer.Context); SerializeStack.Add(value); writer.WriteStartObject(); foreach (string memberName in value.GetDynamicMemberNames()) { object memberValue; if (DynamicUtils.TryGetMember(value, memberName, out memberValue)) { writer.WritePropertyName(memberName); SerializeValue(writer, memberValue, GetContractSafe(memberValue), null, null); } } writer.WriteEndObject(); SerializeStack.RemoveAt(SerializeStack.Count - 1); contract.InvokeOnSerialized(value, Serializer.Context); } #endif private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContract collectionValueContract) { if (HasFlag(((member != null) ? member.TypeNameHandling : null) ?? Serializer.TypeNameHandling, typeNameHandlingFlag)) return true; if (member != null) { if ((member.TypeNameHandling ?? Serializer.TypeNameHandling) == TypeNameHandling.Auto && contract.UnderlyingType != member.PropertyType) return true; } else if (collectionValueContract != null) { if (Serializer.TypeNameHandling == TypeNameHandling.Auto && contract.UnderlyingType != collectionValueContract.UnderlyingType) return true; } return false; } private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract) { contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context); SerializeStack.Add(values.UnderlyingDictionary); writer.WriteStartObject(); bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects); if (isReference) { writer.WritePropertyName(JsonTypeReflector.IdPropertyName); writer.WriteValue(Serializer.ReferenceResolver.GetReference(values.UnderlyingDictionary)); } if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract)) { WriteTypeProperty(writer, values.UnderlyingDictionary.GetType()); } JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); int initialDepth = writer.Top; // Mono Unity 3.0 fix IDictionary d = values; foreach (DictionaryEntry entry in d) { string propertyName = GetPropertyName(entry); try { object value = entry.Value; JsonContract valueContract = GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract)) { writer.WritePropertyName(propertyName); WriteReference(writer, value); } else { if (!CheckForCircularReference(value, null, contract)) continue; writer.WritePropertyName(propertyName); SerializeValue(writer, value, valueContract, null, childValuesContract); } } catch (Exception ex) { if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex)) HandleError(writer, initialDepth); else throw; } } writer.WriteEndObject(); SerializeStack.RemoveAt(SerializeStack.Count - 1); contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context); } private string GetPropertyName(DictionaryEntry entry) { string propertyName; if (entry.Key is IConvertible) return Convert.ToString(entry.Key, CultureInfo.InvariantCulture); else if (TryConvertToString(entry.Key, entry.Key.GetType(), out propertyName)) return propertyName; else return entry.Key.ToString(); } private void HandleError(JsonWriter writer, int initialDepth) { ClearErrorContext(); while (writer.Top > initialDepth) { writer.WriteEnd(); } } private bool ShouldSerialize(JsonProperty property, object target) { if (property.ShouldSerialize == null) return true; return property.ShouldSerialize(target); } } }
/* * 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.Text; using ParquetSharp.Example.Data; using ParquetSharp.Example.Data.Simple; using ParquetSharp.External; using ParquetSharp.Hadoop; using ParquetSharp.Hadoop.Example; using ParquetSharp.Hadoop.Metadata; using ParquetSharp.IO.Api; using ParquetSharp.Schema; using Xunit; namespace ParquetHadoopTests.Hadoop { public class TestInputOutputFormatWithPadding { public const string FILE_CONTENT = "" + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ," + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ," + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static MessageType PARQUET_TYPE = Types.buildMessage() .required(BINARY).@as(UTF8).named("uuid") .required(BINARY).@as(UTF8).named("char") .named("FormatTestObject"); private static readonly Charset UTF_8 = Charset.forName("UTF-8"); /** * ParquetInputFormat that will not split the input file (easier validation) */ private class NoSplits : ParquetInputFormat { protected override bool isSplitable(JobContext context, Path filename) { return false; } } public class Writer : Mapper<LongWritable, Text, Void, Group> { public static readonly SimpleGroupFactory GROUP_FACTORY = new SimpleGroupFactory(PARQUET_TYPE); protected override void map(LongWritable key, Text value, Context context) { // writes each character of the line with a UUID string line = value.ToString(); for (int i = 0; i < line.length(); i += 1) { Group group = GROUP_FACTORY.newGroup(); group.add(0, Binary.fromString(UUID.randomUUID().ToString())); group.add(1, Binary.fromString(line.substring(i, i + 1))); context.write(null, group); } } } public class Reader : Mapper<Void, Group, LongWritable, Text> { protected override void map(Void key, Group value, Context context) { context.write(null, new Text(value.getString("char", 0))); } } // @Rule public TemporaryFolder temp = new TemporaryFolder(); [Fact] public void testBasicBehaviorWithPadding() { ParquetFileWriter.BLOCK_FS_SCHEMES.add("file"); File inputFile = temp.newFile(); FileOutputStream @out = new FileOutputStream(inputFile); @out.write(FILE_CONTENT.getBytes("UTF-8")); @out.close(); File tempFolder = temp.newFolder(); tempFolder.delete(); Path tempPath = new Path(tempFolder.toURI()); File outputFolder = temp.newFile(); outputFolder.delete(); Configuration conf = new Configuration(); // May test against multiple hadoop versions conf.set("dfs.block.size", "1024"); conf.set("dfs.blocksize", "1024"); conf.set("dfs.blockSize", "1024"); conf.set("fs.local.block.size", "1024"); // don't use a cached FS with a different block size conf.set("fs.file.impl.disable.cache", "true"); // disable summary metadata, it isn't needed conf.set("parquet.enable.summary-metadata", "false"); conf.set("parquet.example.schema", PARQUET_TYPE.ToString()); { Job writeJob = new Job(conf, "write"); writeJob.setInputFormatClass(typeof(TextInputFormat)); TextInputFormat.addInputPath(writeJob, new Path(inputFile.ToString())); writeJob.setOutputFormatClass(typeof(ParquetOutputFormat)); writeJob.setMapperClass(typeof(Writer)); writeJob.setNumReduceTasks(0); // write directly to Parquet without reduce ParquetOutputFormat.setWriteSupportClass(writeJob, typeof(GroupWriteSupport)); ParquetOutputFormat.setBlockSize(writeJob, 1024); ParquetOutputFormat.setPageSize(writeJob, 512); ParquetOutputFormat.setDictionaryPageSize(writeJob, 512); ParquetOutputFormat.setEnableDictionary(writeJob, true); ParquetOutputFormat.setMaxPaddingSize(writeJob, 1023); // always pad ParquetOutputFormat.setOutputPath(writeJob, tempPath); waitForJob(writeJob); } // make sure padding was added File parquetFile = getDataFile(tempFolder); ParquetMetadata footer = ParquetFileReader.readFooter(conf, new Path(parquetFile.ToString()), ParquetMetadataConverter.NO_FILTER); foreach (BlockMetaData block in footer.getBlocks()) { Assert.True("Block should start at a multiple of the block size", block.getStartingPos() % 1024 == 0); } { Job readJob = new Job(conf, "read"); readJob.setInputFormatClass(typeof(NoSplits)); ParquetInputFormat.setReadSupportClass(readJob, typeof(GroupReadSupport)); TextInputFormat.addInputPath(readJob, tempPath); readJob.setOutputFormatClass(typeof(TextOutputFormat)); readJob.setMapperClass(typeof(Reader)); readJob.setNumReduceTasks(0); // write directly to text without reduce TextOutputFormat.setOutputPath(readJob, new Path(outputFolder.ToString())); waitForJob(readJob); } File dataFile = getDataFile(outputFolder); Assert.NotNull("Should find a data file", dataFile); StringBuilder contentBuilder = new StringBuilder(); foreach (string line in Files.readAllLines(dataFile, UTF_8)) { contentBuilder.Append(line); } string reconstructed = contentBuilder.ToString(); Assert.Equal("Should match written file content", FILE_CONTENT, reconstructed); ParquetFileWriter.BLOCK_FS_SCHEMES.remove("file"); } private void waitForJob(Job job) { job.submit(); while (!job.isComplete()) { sleep(100); } if (!job.isSuccessful()) { throw new RuntimeException("job failed " + job.getJobName()); } } private File getDataFile(File location) { File[] files = location.listFiles(); File dataFile = null; if (files != null) { foreach (File file in files) { if (file.getName().startsWith("part-")) { dataFile = file; break; } } } return dataFile; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Text { using System.Runtime.Serialization; using System.Text; using System; using System.Diagnostics.Contracts; // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public abstract class Encoder { internal EncoderFallback m_fallback = null; [NonSerialized] internal EncoderFallbackBuffer m_fallbackBuffer = null; internal void SerializeEncoder(SerializationInfo info) { info.AddValue("m_fallback", this.m_fallback); } protected Encoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } [System.Runtime.InteropServices.ComVisible(false)] public EncoderFallback Fallback { get { return m_fallback; } set { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0) throw new ArgumentException( Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), "value"); m_fallback = value; m_fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. [System.Runtime.InteropServices.ComVisible(false)] public EncoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { if (m_fallback != null) m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); else m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return m_fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer != null; } } // Reset the Encoder // // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset(). // // Virtual implimentation has to call GetBytes with flush and a big enough buffer to clear a 0 char string // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big. [System.Runtime.InteropServices.ComVisible(false)] public virtual void Reset() { char[] charTemp = {}; byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)]; GetBytes(charTemp, 0, 0, byteTemp, 0, true); if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Returns the number of bytes the next call to GetBytes will // produce if presented with the given range of characters and the given // value of the flush parameter. The returned value takes into // account the state in which the encoder was left following the last call // to GetBytes. The state of the encoder is not affected by a call // to this method. // public abstract int GetByteCount(char[] chars, int index, int count, bool flush); // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so avoid this method if you might be calling external encodings. [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); char[] arrChar = new char[count]; int index; for (index = 0; index < count; index++) arrChar[index] = chars[index]; return GetByteCount(arrChar, 0, count, flush); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. The method encodes charCount characters from // chars starting at index charIndex, storing the resulting // bytes in bytes starting at index byteIndex. The encoding // takes into account the state in which the encoder was left following the // last call to this method. The flush parameter indicates whether // the encoder should flush any shift-states and partial characters at the // end of the conversion. To ensure correct termination of a sequence of // blocks of encoded bytes, the last call to GetBytes should specify // a value of true for the flush parameter. // // An exception occurs if the byte array is not large enough to hold the // complete encoding of the characters. The GetByteCount method can // be used to determine the exact number of bytes that will be produced for // a given range of characters. Alternatively, the GetMaxByteCount // method of the Encoding that produced this encoder can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implimentation of an // external GetBytes() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the byte[] to our byte* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Get the char array to convert char[] arrChar = new char[charCount]; int index; for (index = 0; index < charCount; index++) arrChar[index] = chars[index]; // Get the byte array to fill byte[] arrByte = new byte[byteCount]; // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush); Contract.Assert(result <= byteCount, "Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't // rely on result because it could be a 3rd party implimentation. We need // to make sure we never copy more than byteCount bytes no matter the value // of result if (result < byteCount) byteCount = result; // Don't copy too many bytes! for (index = 0; index < byteCount; index++) bytes[index] = arrByte[index]; return byteCount; } // This method is used to avoid running out of output buffer space. // It will encode until it runs out of chars, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted chars and output bytes used. // It will only throw a buffer overflow exception if the entire lenght of bytes[] is // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [System.Runtime.InteropServices.ComVisible(false)] public virtual void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); charsUsed = charCount; // Its easy to do if it won't overrun our buffer. // Note: We don't want to call unsafe version because that might be an untrusted version // which could be really unsafe and we don't want to mix it up. while (charsUsed > 0) { if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush); completed = (charsUsed == charCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow")); } // Same thing, but using pointers // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Get ready to do it charsUsed = charCount; // Its easy to do if it won't overrun our buffer. while (charsUsed > 0) { if (GetByteCount(chars, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush); completed = (charsUsed == charCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow")); } } }
/* * Copyright 2013 ThirdMotion, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @class strange.extensions.mediation.impl.MediationBinder * * Highest-level abstraction of the MediationBinder. Agnostic as to View and Mediator Type. * * Please read strange.extensions.mediation.api.IMediationBinder * where I've extensively explained the purpose of View mediation */ using System; using strange.extensions.injector.api; using strange.extensions.mediation.api; using strange.framework.api; using strange.framework.impl; using System.Collections.Generic; namespace strange.extensions.mediation.impl { abstract public class AbstractMediationBinder : Binder, IMediationBinder { [Inject] public IInjectionBinder injectionBinder{ get; set;} public override IBinding GetRawBinding () { return new MediationBinding (resolver) as IBinding; } public void Trigger(MediationEvent evt, IView view) { Type viewType = view.GetType(); IMediationBinding binding = GetBinding (viewType) as IMediationBinding; if (binding != null) { switch(evt) { case MediationEvent.AWAKE: InjectViewAndChildren(view); MapView (view, binding); break; case MediationEvent.DESTROYED: UnmapView (view, binding); break; case MediationEvent.ENABLED: EnableView (view, binding); break; case MediationEvent.DISABLED: DisableView (view, binding); break; default: break; } } else if (evt == MediationEvent.AWAKE) { //Even if not mapped, Views (and their children) have potential to be injected InjectViewAndChildren(view); } } /// Add a Mediator to a View. If the mediator is a "true" Mediator (i.e., it /// implements IMediator), perform PreRegister and OnRegister. protected virtual void ApplyMediationToView(IMediationBinding binding, IView view, Type mediatorType) { bool isTrueMediator = IsTrueMediator(mediatorType); if (!isTrueMediator || !HasMediator(view, mediatorType)) { Type viewType = view.GetType(); object mediator = CreateMediator(view, mediatorType); if (mediator == null) ThrowNullMediatorError (viewType, mediatorType); if (isTrueMediator) ((IMediator)mediator).PreRegister(); Type typeToInject = (binding.abstraction == null || binding.abstraction.Equals(BindingConst.NULLOID)) ? viewType : binding.abstraction as Type; injectionBinder.Bind(typeToInject).ToValue(view).ToInject(false); injectionBinder.injector.Inject(mediator); injectionBinder.Unbind(typeToInject); if (isTrueMediator) { ((IMediator)mediator).OnRegister(); } } } /// Add Mediators to Views. We make this virtual to allow for different concrete /// behaviors for different View/Mediation Types (e.g., MonoBehaviours require /// different handling than EditorWindows) protected virtual void InjectViewAndChildren(IView view) { IView[] views = GetViews(view); int aa = views.Length; for (int a = aa - 1; a > -1; a--) { IView iView = views[a] as IView; if (iView != null && iView.shouldRegister) { if (iView.autoRegisterWithContext && iView.registeredWithContext) { continue; } iView.registeredWithContext = true; if (iView.Equals(view) == false) Trigger(MediationEvent.AWAKE, iView); } } injectionBinder.injector.Inject(view, false); } protected virtual bool IsTrueMediator(Type mediatorType) { return typeof(IMediator).IsAssignableFrom(mediatorType); } override protected IBinding performKeyValueBindings(List<object> keyList, List<object> valueList) { IBinding binding = null; // Bind in order foreach (object key in keyList) { Type keyType = Type.GetType (key as string); if (keyType == null) { throw new BinderException ("A runtime Mediation Binding has resolved to null. Did you forget to register its fully-qualified name?\n View:" + key, BinderExceptionType.RUNTIME_NULL_VALUE); } binding = Bind (keyType); } foreach (object value in valueList) { Type valueType = Type.GetType (value as string); if (valueType == null) { throw new BinderException ("A runtime Mediation Binding has resolved to null. Did you forget to register its fully-qualified name?\n Mediator:" + value, BinderExceptionType.RUNTIME_NULL_VALUE); } binding = binding.To (valueType); } return binding; } override protected Dictionary<string, object> ConformRuntimeItem(Dictionary<string, object> dictionary) { Dictionary<string, object> bindItems = new Dictionary<string, object> (); Dictionary<string, object> toItems = new Dictionary<string, object> (); foreach (var item in dictionary) { if (item.Key == "BindView") { bindItems.Add ("Bind", item.Value); } else if (item.Key == "ToMediator") { toItems.Add ("To", item.Value); } } foreach (var item in bindItems) { dictionary.Remove ("BindView"); dictionary.Add ("Bind", item.Value); } foreach (var item in toItems) { dictionary.Remove ("ToMediator"); dictionary.Add ("To", item.Value); } return dictionary; } override protected IBinding ConsumeItem(Dictionary<string, object> item, IBinding testBinding) { IBinding binding = base.ConsumeItem(item, testBinding); foreach (var i in item) { if (i.Key == "ToAbstraction") { Type abstractionType = Type.GetType (i.Value as string); IMediationBinding mediationBinding = (binding as IMediationBinding); if (abstractionType == null) { throw new BinderException ("A runtime abstraction in the MediationBinder returned a null Type. " + i.ToString(), BinderExceptionType.RUNTIME_NULL_VALUE); } if (mediationBinding == null) { throw new MediationException ("During an attempt at runtime abstraction a MediationBinding could not be found. " + i.ToString(), MediationExceptionType.BINDING_RESOLVED_TO_NULL); } mediationBinding.ToAbstraction (abstractionType); } } return binding; } new public IMediationBinding Bind<T> () { return base.Bind<T> () as IMediationBinding; } public IMediationBinding BindView<T>() { return base.Bind<T> () as IMediationBinding; } /// Creates and registers one or more Mediators for a specific View instance. /// Takes a specific View instance and a binding and, if a binding is found for that type, creates and registers a Mediator. virtual protected void MapView(IView view, IMediationBinding binding) { Type viewType = view.GetType(); if (bindings.ContainsKey (viewType)) { object[] values = binding.value as object[]; int aa = values.Length; for (int a = 0; a < aa; a++) { Type mediatorType = values [a] as Type; if (mediatorType == viewType) { throw new MediationException(viewType + "mapped to itself. The result would be a stack overflow.", MediationExceptionType.MEDIATOR_VIEW_STACK_OVERFLOW); } ApplyMediationToView (binding, view, mediatorType); if (view.enabled) EnableMediator(view, mediatorType); } } } /// Removes a mediator when its view is destroyed virtual protected void UnmapView(IView view, IMediationBinding binding) { TriggerInBindings(view, binding, DestroyMediator); } /// Enables a mediator when its view is enabled virtual protected void EnableView(IView view, IMediationBinding binding) { TriggerInBindings(view, binding, EnableMediator); } /// Disables a mediator when its view is disabled virtual protected void DisableView(IView view, IMediationBinding binding) { TriggerInBindings(view, binding, DisableMediator); } /// Triggers given function in all mediators bound to given view virtual protected void TriggerInBindings(IView view, IMediationBinding binding, Func<IView, Type, object> method) { Type viewType = view.GetType(); if (bindings.ContainsKey(viewType)) { object[] values = binding.value as object[]; int aa = values.Length; for (int a = 0; a < aa; a++) { Type mediatorType = values[a] as Type; method (view, mediatorType); } } } /// Create a new Mediator object based on the mediatorType on the provided view protected abstract object CreateMediator(IView view, Type mediatorType); /// Destroy the Mediator on the provided view object based on the mediatorType protected abstract IMediator DestroyMediator(IView view, Type mediatorType); /// Calls the OnEnabled method of the mediator protected abstract object EnableMediator(IView view, Type mediatorType); /// Calls the OnDisabled method of the mediator protected abstract object DisableMediator(IView view, Type mediatorType); /// Retrieve all views including children for this view protected abstract IView[] GetViews(IView view); /// Whether or not an instantiated Mediator of this type exists protected abstract bool HasMediator(IView view, Type mediatorType); /// Error thrown when a Mediator can't be instantiated /// Abstract because this happens for different reasons. Allow implementing /// class to specify the nature of the error. protected abstract void ThrowNullMediatorError(Type viewType, Type mediatorType); } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.txt file at the root of this distribution. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.VisualStudio.Shell; using VSLangProj; namespace Microsoft.VisualStudio.Project.Automation { /// <summary> /// Represents an automation friendly version of a language-specific project. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OAVS")] [ComVisible(true), CLSCompliant(false)] public class OAVSProject : VSProject { #region fields private ProjectNode project; private OAVSProjectEvents events; #endregion #region ctors public OAVSProject(ProjectNode project) { this.project = project; } #endregion #region VSProject Members public virtual ProjectItem AddWebReference(string bstrUrl) { Debug.Fail("VSProject.AddWebReference not implemented"); throw new NotImplementedException(); } public virtual BuildManager BuildManager { get { return new OABuildManager(this.project); } } public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword) { Debug.Fail("VSProject.References not implemented"); throw new NotImplementedException(); } public virtual ProjectItem CreateWebReferencesFolder() { Debug.Fail("VSProject.CreateWebReferencesFolder not implemented"); throw new NotImplementedException(); } public virtual DTE DTE { get { ThreadHelper.ThrowIfNotOnUIThread(); return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE)); } } public virtual VSProjectEvents Events { get { if (events == null) events = new OAVSProjectEvents(this); return events; } } public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut) { Debug.Fail("VSProject.Exec not implemented"); throw new NotImplementedException(); } public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile) { Debug.Fail("VSProject.GenerateKeyPairFiles not implemented"); throw new NotImplementedException(); } public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt) { Debug.Fail("VSProject.GetUniqueFilename not implemented"); throw new NotImplementedException(); } public virtual Imports Imports { get { Debug.Fail("VSProject.Imports not implemented"); throw new NotImplementedException(); } } public virtual EnvDTE.Project Project { get { ThreadHelper.ThrowIfNotOnUIThread(); return this.project.GetAutomationObject() as EnvDTE.Project; } } EnvDTE.Properties _properties = null; public virtual EnvDTE.Properties Properties { get { if (_properties == null) { _properties = new OAProperties(this.project.NodeProperties); } return _properties; } } public virtual References References { get { ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode; if (null == references) { return new OAReferences(null, project); } return references.Object as References; } } public virtual void Refresh() { Debug.Fail("VSProject.Refresh not implemented"); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public virtual string TemplatePath { get { Debug.Fail("VSProject.TemplatePath not implemented"); throw new NotImplementedException(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public virtual ProjectItem WebReferencesFolder { get { Debug.Fail("VSProject.WebReferencesFolder not implemented"); throw new NotImplementedException(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public virtual bool WorkOffline { get { Debug.Fail("VSProject.WorkOffLine not implemented"); throw new NotImplementedException(); } set { Debug.Fail("VSProject.Set_WorkOffLine not implemented"); throw new NotImplementedException(); } } #endregion } /// <summary> /// Provides access to language-specific project events /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OAVS")] [ComVisible(true), CLSCompliant(false)] public class OAVSProjectEvents : VSProjectEvents { #region fields private OAVSProject vsProject; #endregion #region ctors public OAVSProjectEvents(OAVSProject vsProject) { this.vsProject = vsProject; } #endregion #region VSProjectEvents Members public virtual BuildManagerEvents BuildManagerEvents { get { return vsProject.BuildManager as BuildManagerEvents; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public virtual ImportsEvents ImportsEvents { get { //Debug.Fail("VSProjectEvents.ImportsEvents not implemented"); //throw new NotImplementedException(); return null; } } public virtual ReferencesEvents ReferencesEvents { get { return vsProject.References as ReferencesEvents; } } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Windows.Input; using Android.Content; using Android.Util; using Deltatre.Timeline; using Deltatre.Timeline.Core.Interfaces; using Deltatre.Timeline.Timeline; using Point = Android.Graphics.Point; namespace Deltatre.UI.Android.Views { public abstract class TimelineViewBase : VirtualView { DateTime _currentDay; List<ITimelineElement> _elements; DateTime _endDate; List<ITimelineGroup> _groups; int _minuteWidth; DateTime _startDate; string _highlightedTag; protected IObservable<int> CurrentPositions; protected ISubject<TimelineElementContext> ElementContexts; protected ISubject<int> LabelWidths; protected ISubject<DateTime> StartDates; protected ITimeConverter TimeConverter; protected ISubject<IList<ITimelineGroup>> TimelineGroups; protected TimelineViewBase(Context context, IAttributeSet attrs) : base(context, attrs) { Initialize(); } public TimelineOptions TimelineOptions { get; set; } public GroupOptions GroupOptions { get; set; } public ElementOptions ElementOptions { get; set; } public LabelOptions LabelOptions { get; set; } public int MinuteWidth { get { return _minuteWidth; } set { SetMinuteWidth(value); } } public ICommand ElementSelected { get; set; } public ICommand GroupSelected { get; set; } public DateTime CurrentDay { get { return _currentDay.Date; } set { SetCurrentDay(value); } } public DateTime StartDate { get { return _startDate; } set { SetStart(value); } } public DateTime EndDate { get { return _endDate; } set { SetEnd(value); } } public string HighlightedTag { get { return _highlightedTag; } set { SetHighlightedTag(value); } } public IEnumerable<ITimelineGroup> Groups { get { return _groups; } set { SetGroups(value); } } public IEnumerable<ITimelineElement> Elements { get { return _elements; } set { SetElements(value); } } void Initialize() { _elements = new List<ITimelineElement>(); _groups = new List<ITimelineGroup>(); LabelWidths = new ReplaySubject<int>(1); StartDates = new ReplaySubject<DateTime>(1); TimelineGroups = new Subject<IList<ITimelineGroup>>(); ElementContexts = new Subject<TimelineElementContext>(); TimeConverter = CreateTimeConverter(); ConfigureTimeline(); CurrentPositions = CreateCurrentTimeObservable() .CombineLatest(ElementContexts, Tuple.Create) .Where(tuple => tuple.Item2.StartDate > DateTime.MinValue && tuple.Item2.MinuteWidth > 0) .Select(tuple => TimeConverter.ToPosition(tuple.Item1, StartDate, MinuteWidth.ToDp())) .Do(_ => PostInvalidate()) .Publish() .RefCount(); Scrollable = CreateTimelineLayers(); Scrollable.Bounds = new Rectangle((int)GetX(), (int)GetY(), Width, Height); MinuteWidth = 3; Scrolled += (sender, args) => { if (Scrollable == null) return; Scrollable.ScrollTo(ContentOffset.X, ContentOffset.Y); CurrentDay = TimeConverter.ToDate(ContentOffset.X, StartDate, MinuteWidth); PostInvalidate(); }; Scrollable.Touched += (sender, args) => { if(args.Item is ITimelineGroup && GroupSelected != null && GroupSelected.CanExecute(args.Item)) GroupSelected.Execute(args.Item); else if(args.Item is ITimelineElement && ElementSelected != null && ElementSelected.CanExecute(args.Item)) ElementSelected.Execute(args.Item); }; } protected abstract void ConfigureTimeline(); protected abstract IScrollable CreateTimelineLayers(); protected abstract ITimeConverter CreateTimeConverter(); protected abstract IObservable<DateTime> CreateCurrentTimeObservable(); void SetStart(DateTime value) { if(_startDate == value) return; _startDate = value; StartDates.OnNext(_startDate); ElementContexts.OnNext(new TimelineElementContext { Elements = _elements, Groups = _groups, StartDate = StartDate, MinuteWidth = MinuteWidth, HighlightedTag = HighlightedTag }); PostInvalidate(); } void SetEnd(DateTime value) { if(_endDate == value) return; _endDate = value; Scrollable.VirtualWidth = TimeConverter.ToPosition(_endDate, StartDate, MinuteWidth.ToDp()); PostInvalidate(); } void SetHighlightedTag(string value) { if(_highlightedTag == value) return; _highlightedTag = value; ElementContexts.OnNext(new TimelineElementContext { Elements = _elements, Groups = _groups, StartDate = StartDate, MinuteWidth = MinuteWidth, HighlightedTag = HighlightedTag }); } void SetCurrentDay(DateTime value) { if(_currentDay.Date == value.Date) return; _currentDay = value; ContentOffset = new Point(TimeConverter.ToPosition(_currentDay, StartDate, MinuteWidth), ContentOffset.Y); Scrollable.ScrollTo(ContentOffset.X, ContentOffset.Y); PostInvalidate(); if (CurrentDayChanged != null) CurrentDayChanged(this, EventArgs.Empty); } public event EventHandler CurrentDayChanged; void SetMinuteWidth(int value) { if(_minuteWidth == value) return; _minuteWidth = value; LabelWidths.OnNext(TimeConverter.ToWidth(LabelOptions.Interval, _minuteWidth.ToDp())); ElementContexts.OnNext(new TimelineElementContext { Elements = _elements, Groups = _groups, StartDate = StartDate, MinuteWidth = MinuteWidth, HighlightedTag = HighlightedTag }); PostInvalidate(); } void SetGroups(IEnumerable<ITimelineGroup> value) { _groups = value.ToList(); TimelineGroups.OnNext(_groups); Scrollable.VirtualHeight = _groups.Count * GroupOptions.Height; if(_groups.Any()) ElementContexts.OnNext(new TimelineElementContext { Elements = _elements, Groups = _groups, StartDate = StartDate, MinuteWidth = MinuteWidth, HighlightedTag = HighlightedTag }); PostInvalidate(); } void SetElements(IEnumerable<ITimelineElement> value) { _elements = value.ToList(); if(_groups.Any()) ElementContexts.OnNext(new TimelineElementContext { Elements = _elements, Groups = _groups, StartDate = StartDate, MinuteWidth = MinuteWidth, HighlightedTag = HighlightedTag }); PostInvalidate(); } } }
// 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.Reflection; using System.Runtime; using System.Reflection.Runtime.General; using Internal.Runtime; using Internal.Runtime.TypeLoader; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.Runtime.TypeLoader { public sealed partial class TypeLoaderEnvironment { public bool CompareMethodSignatures(RuntimeSignature signature1, RuntimeSignature signature2) { if (signature1.IsNativeLayoutSignature && signature2.IsNativeLayoutSignature) { if(signature1.StructuralEquals(signature2)) return true; NativeFormatModuleInfo module1 = ModuleList.GetModuleInfoByHandle(new TypeManagerHandle(signature1.ModuleHandle)); NativeReader reader1 = GetNativeLayoutInfoReader(signature1); NativeParser parser1 = new NativeParser(reader1, signature1.NativeLayoutOffset); NativeFormatModuleInfo module2 = ModuleList.GetModuleInfoByHandle(new TypeManagerHandle(signature2.ModuleHandle)); NativeReader reader2 = GetNativeLayoutInfoReader(signature2); NativeParser parser2 = new NativeParser(reader2, signature2.NativeLayoutOffset); return CompareMethodSigs(parser1, module1, parser2, module2); } else if (signature1.IsNativeLayoutSignature) { int token = signature2.Token; MetadataReader metadataReader = ModuleList.Instance.GetMetadataReaderForModule(new TypeManagerHandle(signature2.ModuleHandle)); MethodSignatureComparer comparer = new MethodSignatureComparer(metadataReader, token.AsHandle().ToMethodHandle(metadataReader)); return comparer.IsMatchingNativeLayoutMethodSignature(signature1); } else if (signature2.IsNativeLayoutSignature) { int token = signature1.Token; MetadataReader metadataReader = ModuleList.Instance.GetMetadataReaderForModule(new TypeManagerHandle(signature1.ModuleHandle)); MethodSignatureComparer comparer = new MethodSignatureComparer(metadataReader, token.AsHandle().ToMethodHandle(metadataReader)); return comparer.IsMatchingNativeLayoutMethodSignature(signature2); } else { // For now, RuntimeSignatures are only used to compare for method signature equality (along with their Name) // So we can implement this with the simple equals check if (signature1.Token != signature2.Token) return false; if (signature1.ModuleHandle != signature2.ModuleHandle) return false; return true; } } public uint GetGenericArgumentCountFromMethodNameAndSignature(MethodNameAndSignature signature) { if (signature.Signature.IsNativeLayoutSignature) { NativeReader reader = GetNativeLayoutInfoReader(signature.Signature); NativeParser parser = new NativeParser(reader, signature.Signature.NativeLayoutOffset); return GetGenericArgCountFromSig(parser); } else { ModuleInfo module = signature.Signature.GetModuleInfo(); #if ECMA_METADATA_SUPPORT if (module is NativeFormatModuleInfo) #endif { NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module; var metadataReader = nativeFormatModule.MetadataReader; var methodHandle = signature.Signature.Token.AsHandle().ToMethodHandle(metadataReader); var method = methodHandle.GetMethod(metadataReader); var methodSignature = method.Signature.GetMethodSignature(metadataReader); return checked((uint)methodSignature.GenericParameterCount); } #if ECMA_METADATA_SUPPORT else { EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module; var metadataReader = ecmaModuleInfo.MetadataReader; var ecmaHandle = (System.Reflection.Metadata.MethodDefinitionHandle)System.Reflection.Metadata.Ecma335.MetadataTokens.Handle(signature.Signature.Token); var method = metadataReader.GetMethodDefinition(ecmaHandle); var blobHandle = method.Signature; var blobReader = metadataReader.GetBlobReader(blobHandle); byte sigByte = blobReader.ReadByte(); if ((sigByte & (byte)System.Reflection.Metadata.SignatureAttributes.Generic) == 0) return 0; uint genArgCount = checked((uint)blobReader.ReadCompressedInteger()); return genArgCount; } #endif } } public bool TryGetMethodNameAndSignatureFromNativeLayoutSignature(RuntimeSignature signature, out MethodNameAndSignature nameAndSignature) { nameAndSignature = null; NativeReader reader = GetNativeLayoutInfoReader(signature); NativeParser parser = new NativeParser(reader, signature.NativeLayoutOffset); if (parser.IsNull) return false; RuntimeSignature methodSig; RuntimeSignature methodNameSig; nameAndSignature = GetMethodNameAndSignature(ref parser, new TypeManagerHandle(signature.ModuleHandle), out methodNameSig, out methodSig); return true; } public bool TryGetMethodNameAndSignaturePointersFromNativeLayoutSignature(TypeManagerHandle module, uint methodNameAndSigToken, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig) { methodNameSig = default(RuntimeSignature); methodSig = default(RuntimeSignature); NativeReader reader = GetNativeLayoutInfoReader(module); NativeParser parser = new NativeParser(reader, methodNameAndSigToken); if (parser.IsNull) return false; methodNameSig = RuntimeSignature.CreateFromNativeLayoutSignature(module, parser.Offset); string methodName = parser.GetString(); // Signatures are indirected to through a relative offset so that we don't have to parse them // when not comparing signatures (parsing them requires resolving types and is tremendously // expensive). NativeParser sigParser = parser.GetParserFromRelativeOffset(); methodSig = RuntimeSignature.CreateFromNativeLayoutSignature(module, sigParser.Offset); return true; } public bool TryGetMethodNameAndSignatureFromNativeLayoutOffset(TypeManagerHandle moduleHandle, uint nativeLayoutOffset, out MethodNameAndSignature nameAndSignature) { nameAndSignature = null; NativeReader reader = GetNativeLayoutInfoReader(moduleHandle); NativeParser parser = new NativeParser(reader, nativeLayoutOffset); if (parser.IsNull) return false; RuntimeSignature methodSig; RuntimeSignature methodNameSig; nameAndSignature = GetMethodNameAndSignature(ref parser, moduleHandle, out methodNameSig, out methodSig); return true; } internal MethodNameAndSignature GetMethodNameAndSignature(ref NativeParser parser, TypeManagerHandle moduleHandle, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig) { methodNameSig = RuntimeSignature.CreateFromNativeLayoutSignature(moduleHandle, parser.Offset); string methodName = parser.GetString(); // Signatures are indirected to through a relative offset so that we don't have to parse them // when not comparing signatures (parsing them requires resolving types and is tremendously // expensive). NativeParser sigParser = parser.GetParserFromRelativeOffset(); methodSig = RuntimeSignature.CreateFromNativeLayoutSignature(moduleHandle, sigParser.Offset); return new MethodNameAndSignature(methodName, methodSig); } internal bool IsStaticMethodSignature(RuntimeSignature methodSig) { if (methodSig.IsNativeLayoutSignature) { NativeReader reader = GetNativeLayoutInfoReader(methodSig); NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset); MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); return callingConvention.HasFlag(MethodCallingConvention.Static); } else { ModuleInfo module = methodSig.GetModuleInfo(); #if ECMA_METADATA_SUPPORT if (module is NativeFormatModuleInfo) #endif { NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module; var metadataReader = nativeFormatModule.MetadataReader; var methodHandle = methodSig.Token.AsHandle().ToMethodHandle(metadataReader); var method = methodHandle.GetMethod(metadataReader); return (method.Flags & MethodAttributes.Static) != 0; } #if ECMA_METADATA_SUPPORT else { EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module; var metadataReader = ecmaModuleInfo.MetadataReader; var ecmaHandle = (System.Reflection.Metadata.MethodDefinitionHandle)System.Reflection.Metadata.Ecma335.MetadataTokens.Handle(methodSig.Token); var method = metadataReader.GetMethodDefinition(ecmaHandle); var blobHandle = method.Signature; var blobReader = metadataReader.GetBlobReader(blobHandle); byte sigByte = blobReader.ReadByte(); return ((sigByte & (byte)System.Reflection.Metadata.SignatureAttributes.Instance) == 0); } #endif } } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING // Create a TypeSystem.MethodSignature object from a RuntimeSignature that isn't a NativeLayoutSignature private TypeSystem.MethodSignature TypeSystemSigFromRuntimeSignature(TypeSystemContext context, RuntimeSignature signature) { Debug.Assert(!signature.IsNativeLayoutSignature); ModuleInfo module = signature.GetModuleInfo(); #if ECMA_METADATA_SUPPORT if (module is NativeFormatModuleInfo) #endif { NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module; var metadataReader = nativeFormatModule.MetadataReader; var methodHandle = signature.Token.AsHandle().ToMethodHandle(metadataReader); var metadataUnit = ((TypeLoaderTypeSystemContext)context).ResolveMetadataUnit(nativeFormatModule); var parser = new Internal.TypeSystem.NativeFormat.NativeFormatSignatureParser(metadataUnit, metadataReader.GetMethod(methodHandle).Signature, metadataReader); return parser.ParseMethodSignature(); } #if ECMA_METADATA_SUPPORT else { EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module; TypeSystem.Ecma.EcmaModule ecmaModule = context.ResolveEcmaModule(ecmaModuleInfo); var ecmaHandle = System.Reflection.Metadata.Ecma335.MetadataTokens.EntityHandle(signature.Token); MethodDesc ecmaMethod = ecmaModule.GetMethod(ecmaHandle); return ecmaMethod.Signature; } #endif } #endif internal bool GetCallingConverterDataFromMethodSignature(TypeSystemContext context, RuntimeSignature methodSig, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout) { if (methodSig.IsNativeLayoutSignature) return GetCallingConverterDataFromMethodSignature_NativeLayout(context, methodSig, typeInstantiation, methodInstantiation, out hasThis, out parameters, out parametersWithGenericDependentLayout); else { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING var sig = TypeSystemSigFromRuntimeSignature(context, methodSig); return GetCallingConverterDataFromMethodSignature_MethodSignature(sig, typeInstantiation, methodInstantiation, out hasThis, out parameters, out parametersWithGenericDependentLayout); #else parametersWithGenericDependentLayout = null; hasThis = false; parameters = null; return false; #endif } } internal bool GetCallingConverterDataFromMethodSignature_NativeLayout(TypeSystemContext context, RuntimeSignature methodSig, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout) { return GetCallingConverterDataFromMethodSignature_NativeLayout_Common( context, methodSig, typeInstantiation, methodInstantiation, out hasThis, out parameters, out parametersWithGenericDependentLayout, null, null); } internal bool GetCallingConverterDataFromMethodSignature_NativeLayout_Common( TypeSystemContext context, RuntimeSignature methodSig, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout, NativeReader nativeReader, ulong[] debuggerPreparedExternalReferences) { bool isNotDebuggerCall = debuggerPreparedExternalReferences == null ; hasThis = false; parameters = null; NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext(); nativeLayoutContext._module = isNotDebuggerCall ? (NativeFormatModuleInfo)methodSig.GetModuleInfo() : null; nativeLayoutContext._typeSystemContext = context; nativeLayoutContext._typeArgumentHandles = typeInstantiation; nativeLayoutContext._methodArgumentHandles = methodInstantiation; nativeLayoutContext._debuggerPreparedExternalReferences = debuggerPreparedExternalReferences; NativeFormatModuleInfo module = null; NativeReader reader = null; if (isNotDebuggerCall) { reader = GetNativeLayoutInfoReader(methodSig); module = ModuleList.Instance.GetModuleInfoByHandle(new TypeManagerHandle(methodSig.ModuleHandle)); } else { reader = nativeReader; } NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset); MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); hasThis = !callingConvention.HasFlag(MethodCallingConvention.Static); uint numGenArgs = callingConvention.HasFlag(MethodCallingConvention.Generic) ? parser.GetUnsigned() : 0; uint parameterCount = parser.GetUnsigned(); parameters = new TypeDesc[parameterCount + 1]; parametersWithGenericDependentLayout = new bool[parameterCount + 1]; // One extra parameter to account for the return type for (uint i = 0; i <= parameterCount; i++) { // NativeParser is a struct, so it can be copied. NativeParser parserCopy = parser; // Parse the signature twice. The first time to find out the exact type of the signature // The second time to identify if the parameter loaded via the signature should be forced to be // passed byref as part of the universal generic calling convention. parameters[i] = GetConstructedTypeFromParserAndNativeLayoutContext(ref parser, nativeLayoutContext); parametersWithGenericDependentLayout[i] = TypeSignatureHasVarsNeedingCallingConventionConverter(ref parserCopy, module, context, HasVarsInvestigationLevel.Parameter); if (parameters[i] == null) return false; } return true; } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING private static bool GetCallingConverterDataFromMethodSignature_MethodSignature(TypeSystem.MethodSignature methodSignature, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout) { // Compute parameters dependent on generic instantiation for their layout parametersWithGenericDependentLayout = new bool[methodSignature.Length + 1]; parametersWithGenericDependentLayout[0] = UniversalGenericParameterLayout.IsLayoutDependentOnGenericInstantiation(methodSignature.ReturnType); for (int i = 0; i < methodSignature.Length; i++) { parametersWithGenericDependentLayout[i + 1] = UniversalGenericParameterLayout.IsLayoutDependentOnGenericInstantiation(methodSignature[i]); } // Compute hasThis-ness hasThis = !methodSignature.IsStatic; // Compute parameter exact types parameters = new TypeDesc[methodSignature.Length + 1]; parameters[0] = methodSignature.ReturnType.InstantiateSignature(typeInstantiation, methodInstantiation); for (int i = 0; i < methodSignature.Length; i++) { parameters[i + 1] = methodSignature[i].InstantiateSignature(typeInstantiation, methodInstantiation); } return true; } #endif internal bool MethodSignatureHasVarsNeedingCallingConventionConverter(TypeSystemContext context, RuntimeSignature methodSig) { if (methodSig.IsNativeLayoutSignature) return MethodSignatureHasVarsNeedingCallingConventionConverter_NativeLayout(context, methodSig); else { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING var sig = TypeSystemSigFromRuntimeSignature(context, methodSig); return UniversalGenericParameterLayout.MethodSignatureHasVarsNeedingCallingConventionConverter(sig); #else Environment.FailFast("Cannot parse signature"); return false; #endif } } private bool MethodSignatureHasVarsNeedingCallingConventionConverter_NativeLayout(TypeSystemContext context, RuntimeSignature methodSig) { NativeReader reader = GetNativeLayoutInfoReader(methodSig); NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset); NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(new TypeManagerHandle(methodSig.ModuleHandle)); MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); uint numGenArgs = callingConvention.HasFlag(MethodCallingConvention.Generic) ? parser.GetUnsigned() : 0; uint parameterCount = parser.GetUnsigned(); // Check the return type of the method if (TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, module, context, HasVarsInvestigationLevel.Parameter)) return true; // Check the parameters of the method for (uint i = 0; i < parameterCount; i++) { if (TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, module, context, HasVarsInvestigationLevel.Parameter)) return true; } return false; } #region Private Helpers private enum HasVarsInvestigationLevel { Parameter, NotParameter, Ignore } /// <summary> /// IF THESE SEMANTICS EVER CHANGE UPDATE THE LOGIC WHICH DEFINES THIS BEHAVIOR IN /// THE DYNAMIC TYPE LOADER AS WELL AS THE COMPILER. /// (There is a version of this in UniversalGenericParameterLayout.cs that must be kept in sync with this.) /// /// Parameter's are considered to have type layout dependent on their generic instantiation /// if the type of the parameter in its signature is a type variable, or if the type is a generic /// structure which meets 2 characteristics: /// 1. Structure size/layout is affected by the size/layout of one or more of its generic parameters /// 2. One or more of the generic parameters is a type variable, or a generic structure which also recursively /// would satisfy constraint 2. (Note, that in the recursion case, whether or not the structure is affected /// by the size/layout of its generic parameters is not investigated.) /// /// Examples parameter types, and behavior. /// /// T = true /// List[T] = false /// StructNotDependentOnArgsForSize[T] = false /// GenStructDependencyOnArgsForSize[T] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[T]] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[List[T]]]] = false /// /// Example non-parameter type behavior /// T = true /// List[T] = false /// StructNotDependentOnArgsForSize[T] = *true* /// GenStructDependencyOnArgsForSize[T] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[T]] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[List[T]]]] = false /// </summary> private bool TypeSignatureHasVarsNeedingCallingConventionConverter(ref NativeParser parser, NativeFormatModuleInfo moduleHandle, TypeSystemContext context, HasVarsInvestigationLevel investigationLevel) { uint data; var kind = parser.GetTypeSignatureKind(out data); switch (kind) { case TypeSignatureKind.External: return false; case TypeSignatureKind.Variable: return true; case TypeSignatureKind.BuiltIn: return false; case TypeSignatureKind.Lookback: { var lookbackParser = parser.GetLookbackParser(data); return TypeSignatureHasVarsNeedingCallingConventionConverter(ref lookbackParser, moduleHandle, context, investigationLevel); } case TypeSignatureKind.Instantiation: { RuntimeTypeHandle genericTypeDef; if (!TryGetTypeFromSimpleTypeSignature(ref parser, moduleHandle, out genericTypeDef)) { Debug.Assert(false); return true; // Returning true will prevent further reading from the native parser } if (!RuntimeAugments.IsValueType(genericTypeDef)) { // Reference types are treated like pointers. No calling convention conversion needed. Just consume the rest of the signature. for (uint i = 0; i < data; i++) TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore); return false; } else { bool result = false; for (uint i = 0; i < data; i++) result = TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.NotParameter) || result; if ((result == true) && (investigationLevel == HasVarsInvestigationLevel.Parameter)) { if (!TryComputeHasInstantiationDeterminedSize(genericTypeDef, context, out result)) Environment.FailFast("Unable to setup calling convention converter correctly"); return result; } return result; } } case TypeSignatureKind.Modifier: { // Arrays, pointers and byref types signatures are treated as pointers, not requiring calling convention conversion. // Just consume the parameter type from the stream and return false; TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore); return false; } case TypeSignatureKind.MultiDimArray: { // No need for a calling convention converter for this case. Just consume the signature from the stream. TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore); uint boundCount = parser.GetUnsigned(); for (uint i = 0; i < boundCount; i++) parser.GetUnsigned(); uint lowerBoundCount = parser.GetUnsigned(); for (uint i = 0; i < lowerBoundCount; i++) parser.GetUnsigned(); } return false; case TypeSignatureKind.FunctionPointer: { // No need for a calling convention converter for this case. Just consume the signature from the stream. uint argCount = parser.GetUnsigned(); for (uint i = 0; i < argCount; i++) TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore); } return false; default: parser.ThrowBadImageFormatException(); return true; } } private bool TryGetTypeFromSimpleTypeSignature(ref NativeParser parser, NativeFormatModuleInfo moduleHandle, out RuntimeTypeHandle typeHandle) { uint data; TypeSignatureKind kind = parser.GetTypeSignatureKind(out data); if (kind == TypeSignatureKind.Lookback) { var lookbackParser = parser.GetLookbackParser(data); return TryGetTypeFromSimpleTypeSignature(ref lookbackParser, moduleHandle, out typeHandle); } else if (kind == TypeSignatureKind.External) { typeHandle = GetExternalTypeHandle(moduleHandle, data); return true; } else if (kind == TypeSignatureKind.BuiltIn) { typeHandle = ((WellKnownType)data).GetRuntimeTypeHandle(); return true; } // Not a simple type signature... requires more work to skip typeHandle = default(RuntimeTypeHandle); return false; } private RuntimeTypeHandle GetExternalTypeHandle(NativeFormatModuleInfo moduleHandle, uint typeIndex) { Debug.Assert(moduleHandle != null); RuntimeTypeHandle result; TypeSystemContext context = TypeSystemContextFactory.Create(); { NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext(); nativeLayoutContext._module = moduleHandle; nativeLayoutContext._typeSystemContext = context; TypeDesc type = nativeLayoutContext.GetExternalType(typeIndex); result = type.RuntimeTypeHandle; } TypeSystemContextFactory.Recycle(context); Debug.Assert(!result.IsNull()); return result; } private uint GetGenericArgCountFromSig(NativeParser parser) { MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); if ((callingConvention & MethodCallingConvention.Generic) == MethodCallingConvention.Generic) { return parser.GetUnsigned(); } else { return 0; } } private bool CompareMethodSigs(NativeParser parser1, NativeFormatModuleInfo moduleHandle1, NativeParser parser2, NativeFormatModuleInfo moduleHandle2) { MethodCallingConvention callingConvention1 = (MethodCallingConvention)parser1.GetUnsigned(); MethodCallingConvention callingConvention2 = (MethodCallingConvention)parser2.GetUnsigned(); if (callingConvention1 != callingConvention2) return false; if ((callingConvention1 & MethodCallingConvention.Generic) == MethodCallingConvention.Generic) { if (parser1.GetUnsigned() != parser2.GetUnsigned()) return false; } uint parameterCount1 = parser1.GetUnsigned(); uint parameterCount2 = parser2.GetUnsigned(); if (parameterCount1 != parameterCount2) return false; // Compare one extra parameter to account for the return type for (uint i = 0; i <= parameterCount1; i++) { if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; } return true; } private bool CompareTypeSigs(ref NativeParser parser1, NativeFormatModuleInfo moduleHandle1, ref NativeParser parser2, NativeFormatModuleInfo moduleHandle2) { // startOffset lets us backtrack to the TypeSignatureKind for external types since the TypeLoader // expects to read it in. uint data1; uint startOffset1 = parser1.Offset; var typeSignatureKind1 = parser1.GetTypeSignatureKind(out data1); // If the parser is at a lookback type, get a new parser for it and recurse. // Since we haven't read the element type of parser2 yet, we just pass it in unchanged if (typeSignatureKind1 == TypeSignatureKind.Lookback) { NativeParser lookbackParser1 = parser1.GetLookbackParser(data1); return CompareTypeSigs(ref lookbackParser1, moduleHandle1, ref parser2, moduleHandle2); } uint data2; uint startOffset2 = parser2.Offset; var typeSignatureKind2 = parser2.GetTypeSignatureKind(out data2); // If parser2 is a lookback type, we need to rewind parser1 to its startOffset1 // before recursing. if (typeSignatureKind2 == TypeSignatureKind.Lookback) { NativeParser lookbackParser2 = parser2.GetLookbackParser(data2); parser1 = new NativeParser(parser1.Reader, startOffset1); return CompareTypeSigs(ref parser1, moduleHandle1, ref lookbackParser2, moduleHandle2); } if (typeSignatureKind1 != typeSignatureKind2) return false; switch (typeSignatureKind1) { case TypeSignatureKind.Lookback: { // Recursion above better have removed all lookbacks Debug.Assert(false, "Unexpected lookback type"); return false; } case TypeSignatureKind.Modifier: { // Ensure the modifier kind (vector, pointer, byref) is the same if (data1 != data2) return false; return CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2); } case TypeSignatureKind.Variable: { // variable index is in data if (data1 != data2) return false; break; } case TypeSignatureKind.MultiDimArray: { // rank is in data if (data1 != data2) return false; if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; uint boundCount1 = parser1.GetUnsigned(); uint boundCount2 = parser2.GetUnsigned(); if (boundCount1 != boundCount2) return false; for (uint i = 0; i < boundCount1; i++) { if (parser1.GetUnsigned() != parser2.GetUnsigned()) return false; } uint lowerBoundCount1 = parser1.GetUnsigned(); uint lowerBoundCount2 = parser2.GetUnsigned(); if (lowerBoundCount1 != lowerBoundCount2) return false; for (uint i = 0; i < lowerBoundCount1; i++) { if (parser1.GetUnsigned() != parser2.GetUnsigned()) return false; } break; } case TypeSignatureKind.FunctionPointer: { // callingConvention is in data if (data1 != data2) return false; uint argCount1 = parser1.GetUnsigned(); uint argCount2 = parser2.GetUnsigned(); if (argCount1 != argCount2) return false; for (uint i = 0; i < argCount1; i++) { if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; } break; } case TypeSignatureKind.Instantiation: { // Type parameter count is in data if (data1 != data2) return false; if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; for (uint i = 0; i < data1; i++) { if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2)) return false; } break; } case TypeSignatureKind.BuiltIn: RuntimeTypeHandle typeHandle3 = ((WellKnownType)data1).GetRuntimeTypeHandle(); RuntimeTypeHandle typeHandle4 = ((WellKnownType)data2).GetRuntimeTypeHandle(); if (!typeHandle3.Equals(typeHandle4)) return false; break; case TypeSignatureKind.External: { RuntimeTypeHandle typeHandle1 = GetExternalTypeHandle(moduleHandle1, data1); RuntimeTypeHandle typeHandle2 = GetExternalTypeHandle(moduleHandle2, data2); if (!typeHandle1.Equals(typeHandle2)) return false; break; } default: return false; } return true; } #endregion } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using NodaTime.Globalization; using NodaTime.Properties; using NodaTime.Utility; using JetBrains.Annotations; namespace NodaTime.Text.Patterns { /// <summary> /// Builder for a pattern which implements parsing and formatting as a sequence of steps applied /// in turn. /// </summary> internal sealed class SteppedPatternBuilder<TResult, TBucket> where TBucket : ParseBucket<TResult> { internal delegate ParseResult<TResult> ParseAction(ValueCursor cursor, TBucket bucket); private readonly List<Action<TResult, StringBuilder>> formatActions; private readonly List<ParseAction> parseActions; private readonly Func<TBucket> bucketProvider; private PatternFields usedFields; private bool formatOnly = false; internal NodaFormatInfo FormatInfo { get; } internal PatternFields UsedFields => usedFields; internal SteppedPatternBuilder(NodaFormatInfo formatInfo, Func<TBucket> bucketProvider) { this.FormatInfo = formatInfo; formatActions = new List<Action<TResult, StringBuilder>>(); parseActions = new List<ParseAction>(); this.bucketProvider = bucketProvider; } /// <summary> /// Calls the bucket provider and returns a sample bucket. This means that any values /// normally propagated via the bucket can also be used when building the pattern. /// </summary> internal TBucket CreateSampleBucket() { return bucketProvider(); } /// <summary> /// Sets this pattern to only be capable of formatting; any attempt to parse using the /// built pattern will fail immediately. /// </summary> internal void SetFormatOnly() { formatOnly = true; } /// <summary> /// Performs common parsing operations: start with a parse action to move the /// value cursor onto the first character, then call a character handler for each /// character in the pattern to build up the steps. If any handler fails, /// that failure is returned - otherwise the return value is null. /// </summary> internal void ParseCustomPattern(string patternText, Dictionary<char, CharacterHandler<TResult, TBucket>> characterHandlers) { var patternCursor = new PatternCursor(patternText); // Now iterate over the pattern. while (patternCursor.MoveNext()) { CharacterHandler<TResult, TBucket> handler; if (characterHandlers.TryGetValue(patternCursor.Current, out handler)) { handler(patternCursor, this); } else { char current = patternCursor.Current; if ((current >= 'A' && current <= 'Z') || (current >= 'a' && current <= 'z') || current == PatternCursor.EmbeddedPatternStart || current == PatternCursor.EmbeddedPatternStart) { throw new InvalidPatternException(Messages.Parse_UnquotedLiteral, current); } AddLiteral(patternCursor.Current, ParseResult<TResult>.MismatchedCharacter); } } } /// <summary> /// Validates the combination of fields used. /// </summary> internal void ValidateUsedFields() { // We assume invalid combinations are global across all parsers. The way that // the patterns are parsed ensures we never end up with any invalid individual fields // (e.g. time fields within a date pattern). if ((usedFields & (PatternFields.Era | PatternFields.YearOfEra)) == PatternFields.Era) { throw new InvalidPatternException(Messages.Parse_EraWithoutYearOfEra); } const PatternFields calendarAndEra = PatternFields.Era | PatternFields.Calendar; if ((usedFields & calendarAndEra) == calendarAndEra) { throw new InvalidPatternException(Messages.Parse_CalendarAndEra); } } /// <summary> /// Returns a built pattern. This is mostly to keep the API for the builder separate from that of the pattern, /// and for thread safety (publishing a new object, thus leading to a memory barrier). /// Note that this builder *must not* be used after the result has been built. /// </summary> internal IPartialPattern<TResult> Build(TResult sample) { // If we've got an embedded date and any *other* date fields, throw. if (usedFields.HasAny(PatternFields.EmbeddedDate) && usedFields.HasAny(PatternFields.AllDateFields & ~PatternFields.EmbeddedDate)) { throw new InvalidPatternException(Messages.Parse_DateFieldAndEmbeddedDate); } // Ditto for time if (usedFields.HasAny(PatternFields.EmbeddedTime) && usedFields.HasAny(PatternFields.AllTimeFields & ~PatternFields.EmbeddedTime)) { throw new InvalidPatternException(Messages.Parse_TimeFieldAndEmbeddedTime); } Action<TResult, StringBuilder> formatDelegate = null; foreach (Action<TResult, StringBuilder> formatAction in formatActions) { IPostPatternParseFormatAction postAction = formatAction.Target as IPostPatternParseFormatAction; formatDelegate += postAction == null ? formatAction : postAction.BuildFormatAction(usedFields); } return new SteppedPattern(formatDelegate, formatOnly ? null : parseActions.ToArray(), bucketProvider, usedFields, sample); } /// <summary> /// Registers that a pattern field has been used in this pattern, and throws a suitable error /// result if it's already been used. /// </summary> internal void AddField(PatternFields field, char characterInPattern) { PatternFields newUsedFields = usedFields | field; if (newUsedFields == usedFields) { throw new InvalidPatternException(Messages.Parse_RepeatedFieldInPattern, characterInPattern); } usedFields = newUsedFields; } internal void AddParseAction(ParseAction parseAction) => parseActions.Add(parseAction); internal void AddFormatAction(Action<TResult, StringBuilder> formatAction) => formatActions.Add(formatAction); /// <summary> /// Equivalent of <see cref="AddParseValueAction"/> but for 64-bit integers. Currently only /// positive values are supported. /// </summary> internal void AddParseInt64ValueAction(int minimumDigits, int maximumDigits, char patternChar, long minimumValue, long maximumValue, Action<TBucket, long> valueSetter) { Preconditions.DebugCheckArgumentRange(nameof(minimumValue), minimumValue, 0, long.MaxValue); AddParseAction((cursor, bucket) => { int startingIndex = cursor.Index; long value; if (!cursor.ParseInt64Digits(minimumDigits, maximumDigits, out value)) { cursor.Move(startingIndex); return ParseResult<TResult>.MismatchedNumber(cursor, new string(patternChar, minimumDigits)); } if (value < minimumValue || value > maximumValue) { cursor.Move(startingIndex); return ParseResult<TResult>.FieldValueOutOfRange(cursor, value, patternChar); } valueSetter(bucket, value); return null; }); } internal void AddParseValueAction(int minimumDigits, int maximumDigits, char patternChar, int minimumValue, int maximumValue, Action<TBucket, int> valueSetter) { AddParseAction((cursor, bucket) => { int startingIndex = cursor.Index; int value; bool negative = cursor.Match('-'); if (negative && minimumValue >= 0) { cursor.Move(startingIndex); return ParseResult<TResult>.UnexpectedNegative(cursor); } if (!cursor.ParseDigits(minimumDigits, maximumDigits, out value)) { cursor.Move(startingIndex); return ParseResult<TResult>.MismatchedNumber(cursor, new string(patternChar, minimumDigits)); } if (negative) { value = -value; } if (value < minimumValue || value > maximumValue) { cursor.Move(startingIndex); return ParseResult<TResult>.FieldValueOutOfRange(cursor, value, patternChar); } valueSetter(bucket, value); return null; }); } /// <summary> /// Adds text which must be matched exactly when parsing, and appended directly when formatting. /// </summary> internal void AddLiteral(string expectedText, Func<ValueCursor, ParseResult<TResult>> failure) { // Common case - single character literal, often a date or time separator. if (expectedText.Length == 1) { char expectedChar = expectedText[0]; AddParseAction((str, bucket) => str.Match(expectedChar) ? null : failure(str)); AddFormatAction((value, builder) => builder.Append(expectedChar)); return; } AddParseAction((str, bucket) => str.Match(expectedText) ? null : failure(str)); AddFormatAction((value, builder) => builder.Append(expectedText)); } internal static void HandleQuote(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder) { string quoted = pattern.GetQuotedString(pattern.Current); builder.AddLiteral(quoted, ParseResult<TResult>.QuotedStringMismatch); } internal static void HandleBackslash(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder) { if (!pattern.MoveNext()) { throw new InvalidPatternException(Messages.Parse_EscapeAtEndOfString); } builder.AddLiteral(pattern.Current, ParseResult<TResult>.EscapedCharacterMismatch); } /// <summary> /// Handle a leading "%" which acts as a pseudo-escape - it's mostly used to allow format strings such as "%H" to mean /// "use a custom format string consisting of H instead of a standard pattern H". /// </summary> internal static void HandlePercent(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder) { if (pattern.HasMoreCharacters) { if (pattern.PeekNext() != '%') { // Handle the next character as normal return; } throw new InvalidPatternException(Messages.Parse_PercentDoubled); } throw new InvalidPatternException(Messages.Parse_PercentAtEndOfString); } /// <summary> /// Returns a handler for a zero-padded purely-numeric field specifier, such as "seconds", "minutes", "24-hour", "12-hour" etc. /// </summary> /// <param name="maxCount">Maximum permissable count (usually two)</param> /// <param name="field">Field to remember that we've seen</param> /// <param name="minValue">Minimum valid value for the field (inclusive)</param> /// <param name="maxValue">Maximum value value for the field (inclusive)</param> /// <param name="getter">Delegate to retrieve the field value when formatting</param> /// <param name="setter">Delegate to set the field value into a bucket when parsing</param> /// <returns>The pattern parsing failure, or null on success.</returns> internal static CharacterHandler<TResult, TBucket> HandlePaddedField(int maxCount, PatternFields field, int minValue, int maxValue, Func<TResult, int> getter, Action<TBucket, int> setter) { return (pattern, builder) => { int count = pattern.GetRepeatCount(maxCount); builder.AddField(field, pattern.Current); builder.AddParseValueAction(count, maxCount, pattern.Current, minValue, maxValue, setter); builder.AddFormatLeftPad(count, getter, assumeNonNegative: minValue >= 0, assumeFitsInCount: count == maxCount); }; } /// <summary> /// Adds a character which must be matched exactly when parsing, and appended directly when formatting. /// </summary> internal void AddLiteral(char expectedChar, Func<ValueCursor, char, ParseResult<TResult>> failureSelector) { AddParseAction((str, bucket) => str.Match(expectedChar) ? null : failureSelector(str, expectedChar)); AddFormatAction((value, builder) => builder.Append(expectedChar)); } /// <summary> /// Adds parse actions for a list of strings, such as days of the week or month names. /// The parsing is performed case-insensitively. All candidates are tested, and only the longest /// match is used. /// </summary> internal void AddParseLongestTextAction(char field, Action<TBucket, int> setter, CompareInfo compareInfo, IList<string> textValues) { AddParseAction((str, bucket) => { int bestIndex = -1; int longestMatch = 0; FindLongestMatch(compareInfo, str, textValues, ref bestIndex, ref longestMatch); if (bestIndex != -1) { setter(bucket, bestIndex); str.Move(str.Index + longestMatch); return null; } return ParseResult<TResult>.MismatchedText(str, field); }); } /// <summary> /// Adds parse actions for two list of strings, such as non-genitive and genitive month names. /// The parsing is performed case-insensitively. All candidates are tested, and only the longest /// match is used. /// </summary> internal void AddParseLongestTextAction(char field, Action<TBucket, int> setter, CompareInfo compareInfo, IList<string> textValues1, IList<string> textValues2) { AddParseAction((str, bucket) => { int bestIndex = -1; int longestMatch = 0; FindLongestMatch(compareInfo, str, textValues1, ref bestIndex, ref longestMatch); FindLongestMatch(compareInfo, str, textValues2, ref bestIndex, ref longestMatch); if (bestIndex != -1) { setter(bucket, bestIndex); str.Move(str.Index + longestMatch); return null; } return ParseResult<TResult>.MismatchedText(str, field); }); } /// <summary> /// Find the longest match from a given set of candidate strings, updating the index/length of the best value /// accordingly. /// </summary> private static void FindLongestMatch(CompareInfo compareInfo, ValueCursor cursor, IList<string> values, ref int bestIndex, ref int longestMatch) { for (int i = 0; i < values.Count; i++) { string candidate = values[i]; if (candidate == null || candidate.Length <= longestMatch) { continue; } if (cursor.MatchCaseInsensitive(candidate, compareInfo, false)) { bestIndex = i; longestMatch = candidate.Length; } } } /// <summary> /// Adds parse and format actions for a mandatory positive/negative sign. /// </summary> /// <param name="signSetter">Action to take when to set the given sign within the bucket</param> /// <param name="nonNegativePredicate">Predicate to detect whether the value being formatted is non-negative</param> public void AddRequiredSign(Action<TBucket, bool> signSetter, Func<TResult, bool> nonNegativePredicate) { string negativeSign = FormatInfo.NegativeSign; string positiveSign = FormatInfo.PositiveSign; AddParseAction((str, bucket) => { if (str.Match(negativeSign)) { signSetter(bucket, false); return null; } if (str.Match(positiveSign)) { signSetter(bucket, true); return null; } return ParseResult<TResult>.MissingSign(str); }); AddFormatAction((value, sb) => sb.Append(nonNegativePredicate(value) ? positiveSign : negativeSign)); } /// <summary> /// Adds parse and format actions for an "negative only" sign. /// </summary> /// <param name="signSetter">Action to take when to set the given sign within the bucket</param> /// <param name="nonNegativePredicate">Predicate to detect whether the value being formatted is non-negative</param> public void AddNegativeOnlySign(Action<TBucket, bool> signSetter, Func<TResult, bool> nonNegativePredicate) { string negativeSign = FormatInfo.NegativeSign; string positiveSign = FormatInfo.PositiveSign; AddParseAction((str, bucket) => { if (str.Match(negativeSign)) { signSetter(bucket, false); return null; } if (str.Match(positiveSign)) { return ParseResult<TResult>.PositiveSignInvalid(str); } signSetter(bucket, true); return null; }); AddFormatAction((value, builder) => { if (!nonNegativePredicate(value)) { builder.Append(negativeSign); } }); } /// <summary> /// Adds an action to pad a selected value to a given minimum lenth. /// </summary> /// <param name="count">The minimum length to pad to</param> /// <param name="selector">The selector function to apply to obtain a value to format</param> /// <param name="assumeNonNegative">Whether it is safe to assume the value will be non-negative</param> /// <param name="assumeFitsInCount">Whether it is safe to assume the value will not exceed the specified length</param> internal void AddFormatLeftPad(int count, Func<TResult, int> selector, bool assumeNonNegative, bool assumeFitsInCount) { if (count == 2 && assumeNonNegative && assumeFitsInCount) { AddFormatAction((value, sb) => FormatHelper.Format2DigitsNonNegative(selector(value), sb)); } else if (count == 4 && assumeFitsInCount) { AddFormatAction((value, sb) => FormatHelper.Format4DigitsValueFits(selector(value), sb)); } else if (assumeNonNegative) { AddFormatAction((value, sb) => FormatHelper.LeftPadNonNegative(selector(value), count, sb)); } else { AddFormatAction((value, sb) => FormatHelper.LeftPad(selector(value), count, sb)); } } internal void AddFormatFraction(int width, int scale, Func<TResult, int> selector) => AddFormatAction((value, sb) => FormatHelper.AppendFraction(selector(value), width, scale, sb)); internal void AddFormatFractionTruncate(int width, int scale, Func<TResult, int> selector) => AddFormatAction((value, sb) => FormatHelper.AppendFractionTruncate(selector(value), width, scale, sb)); /// <summary> /// Handles date, time and date/time embedded patterns. /// </summary> internal void AddEmbeddedLocalPartial( PatternCursor pattern, Func<TBucket, LocalDatePatternParser.LocalDateParseBucket> dateBucketExtractor, Func<TBucket, LocalTimePatternParser.LocalTimeParseBucket> timeBucketExtractor, Func<TResult, LocalDate> dateExtractor, Func<TResult, LocalTime> timeExtractor, // null if date/time embedded patterns are invalid Func<TResult, LocalDateTime> dateTimeExtractor) { // This will be d (date-only), t (time-only), or < (date and time) // If it's anything else, we'll see the problem when we try to get the pattern. var patternType = pattern.PeekNext(); if (patternType == 'd' || patternType == 't') { pattern.MoveNext(); } string embeddedPatternText = pattern.GetEmbeddedPattern(); var sampleBucket = CreateSampleBucket(); var templateTime = timeBucketExtractor(sampleBucket).TemplateValue; var templateDate = dateBucketExtractor(sampleBucket).TemplateValue; switch (patternType) { case '<': if (dateTimeExtractor == null) { throw new InvalidPatternException(Messages.Parse_InvalidEmbeddedPatternType); } AddField(PatternFields.EmbeddedDate, 'l'); AddField(PatternFields.EmbeddedTime, 'l'); AddEmbeddedPattern( LocalDateTimePattern.Create(embeddedPatternText, FormatInfo, templateDate + templateTime).UnderlyingPattern, (bucket, value) => { var dateBucket = dateBucketExtractor(bucket); var timeBucket = timeBucketExtractor(bucket); dateBucket.Calendar = value.Calendar; dateBucket.Year = value.Year; dateBucket.MonthOfYearNumeric = value.Month; dateBucket.DayOfMonth = value.Day; timeBucket.Hours24 = value.Hour; timeBucket.Minutes = value.Minute; timeBucket.Seconds = value.Second; timeBucket.FractionalSeconds = value.NanosecondOfSecond; }, dateTimeExtractor); break; case 'd': AddField(PatternFields.EmbeddedDate, 'l'); AddEmbeddedPattern( LocalDatePattern.Create(embeddedPatternText, FormatInfo, templateDate).UnderlyingPattern, (bucket, value) => { var dateBucket = dateBucketExtractor(bucket); dateBucket.Calendar = value.Calendar; dateBucket.Year = value.Year; dateBucket.MonthOfYearNumeric = value.Month; dateBucket.DayOfMonth = value.Day; }, dateExtractor); break; case 't': AddField(PatternFields.EmbeddedTime, 'l'); AddEmbeddedPattern( LocalTimePattern.Create(embeddedPatternText, FormatInfo, templateTime).UnderlyingPattern, (bucket, value) => { var timeBucket = timeBucketExtractor(bucket); timeBucket.Hours24 = value.Hour; timeBucket.Minutes = value.Minute; timeBucket.Seconds = value.Second; timeBucket.FractionalSeconds = value.NanosecondOfSecond; }, timeExtractor); break; default: throw new InvalidOperationException("Bug in Noda Time: embedded pattern type wasn't date, time, or date+time"); } } /// <summary> /// Adds parsing/formatting of an embedded pattern, e.g. an offset within a ZonedDateTime/OffsetDateTime. /// </summary> internal void AddEmbeddedPattern<TEmbedded>( IPartialPattern<TEmbedded> embeddedPattern, Action<TBucket, TEmbedded> parseAction, Func<TResult, TEmbedded> valueExtractor) { AddParseAction((value, bucket) => { var result = embeddedPattern.ParsePartial(value); if (!result.Success) { return result.ConvertError<TResult>(); } parseAction(bucket, result.Value); return null; }); AddFormatAction((value, sb) => embeddedPattern.AppendFormat(valueExtractor(value), sb)); } /// <summary> /// Hack to handle genitive month names - we only know what we need to do *after* we've parsed the whole pattern. /// </summary> internal interface IPostPatternParseFormatAction { Action<TResult, StringBuilder> BuildFormatAction(PatternFields finalFields); } private sealed class SteppedPattern : IPartialPattern<TResult> { private readonly Action<TResult, StringBuilder> formatActions; // This will be null if the pattern is only capable of formatting. private readonly ParseAction[] parseActions; private readonly Func<TBucket> bucketProvider; private readonly PatternFields usedFields; private readonly int expectedLength; public SteppedPattern(Action<TResult, StringBuilder> formatActions, ParseAction[] parseActions, Func<TBucket> bucketProvider, PatternFields usedFields, TResult sample) { this.formatActions = formatActions; this.parseActions = parseActions; this.bucketProvider = bucketProvider; this.usedFields = usedFields; // Format the sample value to work out the expected length, so we // can use that when creating a StringBuilder. This will definitely not always // be appropriate, but it's a start. StringBuilder builder = new StringBuilder(); formatActions(sample, builder); expectedLength = builder.Length; } public ParseResult<TResult> Parse(string text) { if (parseActions == null) { return ParseResult<TResult>.FormatOnlyPattern; } if (text == null) { return ParseResult<TResult>.ArgumentNull("text"); } if (text.Length == 0) { return ParseResult<TResult>.ValueStringEmpty; } var valueCursor = new ValueCursor(text); // Prime the pump... the value cursor ends up *before* the first character, but // our steps always assume it's *on* the right character. valueCursor.MoveNext(); var result = ParsePartial(valueCursor); if (!result.Success) { return result; } // Check that we've used up all the text if (valueCursor.Current != TextCursor.Nul) { return ParseResult<TResult>.ExtraValueCharacters(valueCursor, valueCursor.Remainder); } return result; } public string Format(TResult value) { StringBuilder builder = new StringBuilder(expectedLength); // This will call all the actions in the multicast delegate. formatActions(value, builder); return builder.ToString(); } public ParseResult<TResult> ParsePartial(ValueCursor cursor) { TBucket bucket = bucketProvider(); foreach (var action in parseActions) { ParseResult<TResult> failure = action(cursor, bucket); if (failure != null) { return failure; } } return bucket.CalculateValue(usedFields, cursor.Value); } public StringBuilder AppendFormat(TResult value, [NotNull] StringBuilder builder) { Preconditions.CheckNotNull(builder, nameof(builder)); formatActions(value, builder); return builder; } } } }
using System; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using BTDB.Collections; namespace BTDB.IL.Caching; class CachingILGen : IILGen { interface IReplayILGen { void ReplayTo(IILGen target); void FreeTemps(); bool Equals(IReplayILGen other); } StructList<IReplayILGen> _instructions; int _lastLocalIndex; int _lastLabelIndex; internal void ReplayTo(IILGen target) { foreach (var inst in _instructions) { inst.ReplayTo(target); } } public override bool Equals(object obj) { if (!(obj is CachingILGen v)) return false; if (_instructions.Count != v._instructions.Count) return false; for (var i = 0; i < _instructions.Count; i++) { if (!_instructions[i].Equals(v._instructions[i])) return false; } return true; } public override int GetHashCode() { // ReSharper disable once NonReadonlyMemberInGetHashCode return (int)_instructions.Count; } public IILLabel DefineLabel(string? name = null) { var result = new ILLabel(name, _lastLabelIndex); _lastLabelIndex++; _instructions.Add(result); return result; } class ILLabel : IILLabel, IReplayILGen { readonly string? _name; internal readonly int Index; internal IILLabel? Label; public ILLabel(string? name, int index) { _name = name; Index = index; } public void ReplayTo(IILGen target) { Label = target.DefineLabel(_name); } public void FreeTemps() { Label = null; } public bool Equals(IReplayILGen other) { if (!(other is ILLabel v)) return false; return _name == v._name; } } public IILLocal DeclareLocal(Type type, string? name = null, bool pinned = false) { var result = new ILLocal(type, name, pinned, _lastLocalIndex); _lastLocalIndex++; _instructions.Add(result); return result; } class ILLocal : IILLocal, IReplayILGen { readonly string? _name; internal IILLocal? Local; public ILLocal(Type type, string? name, bool pinned, int index) { LocalType = type; _name = name; Pinned = pinned; Index = index; } public int Index { get; } public bool Pinned { get; } public Type LocalType { get; } public void ReplayTo(IILGen target) { Local = target.DeclareLocal(LocalType, _name, Pinned); Debug.Assert(Local.Index == Index); } public void FreeTemps() { Local = null; } public bool Equals(IReplayILGen other) { if (!(other is ILLocal v)) return false; if (_name != v._name) return false; if (LocalType != v.LocalType) return false; return Pinned == v.Pinned; } } public IILGen Comment(string text) { _instructions.Add(new CommentInst(text)); return this; } class CommentInst : IReplayILGen { readonly string _text; public CommentInst(string text) { _text = text; } public void ReplayTo(IILGen target) { target.Comment(_text); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is CommentInst v)) return false; return _text == v._text; } } public IILGen Mark(IILLabel label) { _instructions.Add(new MarkInst(label)); return this; } class MarkInst : IReplayILGen { readonly IILLabel _label; public MarkInst(IILLabel label) { _label = label; } public void ReplayTo(IILGen target) { target.Mark(((ILLabel)_label).Label!); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is MarkInst v)) return false; return ((ILLabel)_label).Index == ((ILLabel)v._label).Index; } } public IILGen Ldftn(IILMethod method) { _instructions.Add(new LdftnInst(method)); return this; } class LdftnInst : IReplayILGen { readonly IILMethod _method; public LdftnInst(IILMethod method) { _method = method; } public void ReplayTo(IILGen target) { target.Ldftn(_method); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is LdftnInst v)) return false; return ReferenceEquals(_method, v._method); } } public IILGen Ldstr(string str) { _instructions.Add(new LdstrInst(str)); return this; } class LdstrInst : IReplayILGen { readonly string _str; public LdstrInst(string str) { _str = str; } public void ReplayTo(IILGen target) { target.Ldstr(_str); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is LdstrInst v)) return false; return _str == v._str; } } public IILGen Try() { _instructions.Add(new TryInst()); return this; } class TryInst : IReplayILGen { public void ReplayTo(IILGen target) { target.Try(); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { return other is TryInst; } } public IILGen Catch(Type exceptionType) { _instructions.Add(new CatchInst(exceptionType)); return this; } class CatchInst : IReplayILGen { readonly Type _exceptionType; public CatchInst(Type exceptionType) { _exceptionType = exceptionType; } public void ReplayTo(IILGen target) { target.Catch(_exceptionType); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is CatchInst v)) return false; return _exceptionType == v._exceptionType; } } public IILGen Finally() { _instructions.Add(new FinallyInst()); return this; } class FinallyInst : IReplayILGen { public void ReplayTo(IILGen target) { target.Finally(); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { return other is FinallyInst; } } public IILGen EndTry() { _instructions.Add(new EndTryInst()); return this; } class EndTryInst : IReplayILGen { public void ReplayTo(IILGen target) { target.EndTry(); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { return other is EndTryInst; } } public void Emit(OpCode opCode) { _instructions.Add(new EmitInst(opCode)); } class EmitInst : IReplayILGen { readonly OpCode _opCode; public EmitInst(OpCode opCode) { _opCode = opCode; } public void ReplayTo(IILGen target) { target.Emit(_opCode); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitInst v)) return false; return _opCode == v._opCode; } } public void Emit(OpCode opCode, sbyte param) { _instructions.Add(new EmitSbyteInst(opCode, param)); } class EmitSbyteInst : IReplayILGen { readonly OpCode _opCode; readonly sbyte _param; public EmitSbyteInst(OpCode opCode, sbyte param) { _opCode = opCode; _param = param; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _param); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitSbyteInst v)) return false; return _opCode == v._opCode && _param == v._param; } } public void Emit(OpCode opCode, byte param) { _instructions.Add(new EmitByteInst(opCode, param)); } class EmitByteInst : IReplayILGen { readonly OpCode _opCode; readonly byte _param; public EmitByteInst(OpCode opCode, byte param) { _opCode = opCode; _param = param; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _param); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitByteInst v)) return false; return _opCode == v._opCode && _param == v._param; } } public void Emit(OpCode opCode, ushort param) { _instructions.Add(new EmitUshortInst(opCode, param)); } class EmitUshortInst : IReplayILGen { readonly OpCode _opCode; readonly ushort _param; public EmitUshortInst(OpCode opCode, ushort param) { _opCode = opCode; _param = param; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _param); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitUshortInst v)) return false; return _opCode == v._opCode && _param == v._param; } } public void Emit(OpCode opCode, int param) { _instructions.Add(new EmitIntInst(opCode, param)); } class EmitIntInst : IReplayILGen { readonly OpCode _opCode; readonly int _param; public EmitIntInst(OpCode opCode, int param) { _opCode = opCode; _param = param; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _param); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitIntInst v)) return false; return _opCode == v._opCode && _param == v._param; } } public void Emit(OpCode opCode, FieldInfo param) { _instructions.Add(new EmitFieldInfoInst(opCode, param)); } class EmitFieldInfoInst : IReplayILGen { readonly OpCode _opCode; readonly FieldInfo _fieldInfo; public EmitFieldInfoInst(OpCode opCode, FieldInfo fieldInfo) { _opCode = opCode; _fieldInfo = fieldInfo; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _fieldInfo); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitFieldInfoInst v)) return false; return _opCode == v._opCode && _fieldInfo == v._fieldInfo; } } public void Emit(OpCode opCode, ConstructorInfo param) { if (param == null) throw new ArgumentNullException(nameof(param)); _instructions.Add(new EmitConstructorInfoInst(opCode, param)); } class EmitConstructorInfoInst : IReplayILGen { readonly OpCode _opCode; readonly ConstructorInfo _constructorInfo; public EmitConstructorInfoInst(OpCode opCode, ConstructorInfo constructorInfo) { _opCode = opCode; _constructorInfo = constructorInfo; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _constructorInfo); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitConstructorInfoInst v)) return false; return _opCode == v._opCode && _constructorInfo == v._constructorInfo; } } public void Emit(OpCode opCode, MethodInfo param) { if (param == null) throw new ArgumentNullException(nameof(param)); _instructions.Add(new EmitMethodInfoInst(opCode, param)); } class EmitMethodInfoInst : IReplayILGen { readonly OpCode _opCode; readonly MethodInfo _methodInfo; public EmitMethodInfoInst(OpCode opCode, MethodInfo methodInfo) { _opCode = opCode; _methodInfo = methodInfo; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _methodInfo); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitMethodInfoInst v)) return false; return _opCode == v._opCode && _methodInfo == v._methodInfo; } } public void Emit(OpCode opCode, Type type) { _instructions.Add(new EmitTypeInst(opCode, type)); } class EmitTypeInst : IReplayILGen { readonly OpCode _opCode; readonly Type _type; public EmitTypeInst(OpCode opCode, Type type) { _opCode = opCode; _type = type; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _type); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitTypeInst v)) return false; return _opCode == v._opCode && _type == v._type; } } public void Emit(OpCode opCode, IILLocal ilLocal) { _instructions.Add(new EmitILLocal(opCode, ilLocal)); } class EmitILLocal : IReplayILGen { readonly OpCode _opCode; readonly IILLocal _ilLocal; public EmitILLocal(OpCode opCode, IILLocal ilLocal) { _opCode = opCode; _ilLocal = ilLocal; } public void ReplayTo(IILGen target) { target.Emit(_opCode, ((ILLocal)_ilLocal).Local!); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitILLocal v)) return false; return _opCode == v._opCode && ((ILLocal)_ilLocal).Index == ((ILLocal)v._ilLocal).Index; } } public void Emit(OpCode opCode, IILLabel ilLabel) { _instructions.Add(new EmitILLabel(opCode, ilLabel)); } class EmitILLabel : IReplayILGen { readonly OpCode _opCode; readonly IILLabel _ilLabel; public EmitILLabel(OpCode opCode, IILLabel ilLabel) { _opCode = opCode; _ilLabel = ilLabel; } public void ReplayTo(IILGen target) { target.Emit(_opCode, ((ILLabel)_ilLabel).Label!); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitILLabel v)) return false; return _opCode == v._opCode && ((ILLabel)_ilLabel).Index == ((ILLabel)v._ilLabel).Index; } } internal void FreeTemps() { foreach (var inst in _instructions) { inst.FreeTemps(); } } public void Emit(OpCode opCode, IILField ilField) { _instructions.Add(new EmitILField(opCode, ilField)); } class EmitILField : IReplayILGen { readonly OpCode _opCode; readonly IILField _ilField; public EmitILField(OpCode opCode, IILField ilField) { _opCode = opCode; _ilField = ilField; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _ilField); } public void FreeTemps() { ((IILFieldPrivate)_ilField).FreeTemps(); } public bool Equals(IReplayILGen other) { if (!(other is EmitILField v)) return false; return _opCode == v._opCode && _ilField.Equals(v._ilField); } } public void Emit(OpCode opCode, long value) { _instructions.Add(new EmitLongInst(opCode, value)); } class EmitLongInst : IReplayILGen { readonly OpCode _opCode; readonly long _param; public EmitLongInst(OpCode opCode, long param) { _opCode = opCode; _param = param; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _param); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitLongInst v)) return false; return _opCode == v._opCode && _param == v._param; } } public void Emit(OpCode opCode, float value) { _instructions.Add(new EmitFloatInst(opCode, value)); } class EmitFloatInst : IReplayILGen { readonly OpCode _opCode; readonly float _param; public EmitFloatInst(OpCode opCode, float param) { _opCode = opCode; _param = param; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _param); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitFloatInst v)) return false; // ReSharper disable once CompareOfFloatsByEqualityOperator return _opCode == v._opCode && _param == v._param; } } public void Emit(OpCode opCode, double value) { _instructions.Add(new EmitDoubleInst(opCode, value)); } class EmitDoubleInst : IReplayILGen { readonly OpCode _opCode; readonly double _param; public EmitDoubleInst(OpCode opCode, double param) { _opCode = opCode; _param = param; } public void ReplayTo(IILGen target) { target.Emit(_opCode, _param); } public void FreeTemps() { } public bool Equals(IReplayILGen other) { if (!(other is EmitDoubleInst v)) return false; // ReSharper disable once CompareOfFloatsByEqualityOperator return _opCode == v._opCode && _param == v._param; } } }
using System; using System.Collections; using System.Web.UI.WebControls; using Cuyahoga.Core.Domain; using Cuyahoga.Core.Service.Membership; using Cuyahoga.Core.Service.SiteStructure; using Cuyahoga.Core.Util; using Cuyahoga.Web.Admin.UI; using Cuyahoga.Web.UI; using Cuyahoga.Web.Util; namespace Cuyahoga.Web.Admin { /// <summary> /// Summary description for SiteEdit. /// </summary> public class SiteEdit : AdminBasePage { private Site _activeSite; private ITemplateService _templateService; private IUserService _userService; protected TextBox txtName; protected RequiredFieldValidator rfvName; protected TextBox txtSiteUrl; protected DropDownList ddlTemplates; protected DropDownList ddlCultures; protected Button btnSave; protected Button btnCancel; protected Button btnDelete; protected DropDownList ddlPlaceholders; protected DropDownList ddlRoles; protected TextBox txtWebmasterEmail; protected RequiredFieldValidator rfvWebmasterEmail; protected HyperLink hplNewAlias; protected Panel pnlAliases; protected Repeater rptAliases; protected CheckBox chkUseFriendlyUrls; protected RequiredFieldValidator rfvSiteUrl; protected TextBox txtMetaDescription; protected TextBox txtMetaKeywords; protected DropDownList ddlOfflinePageTemplate; /// <summary> /// Constructor. /// </summary> public SiteEdit() { this._templateService = Container.Resolve<ITemplateService>(); this._userService = Container.Resolve<IUserService>(); } private void Page_Load(object sender, EventArgs e) { base.Title = "Edit site"; if (Context.Request.QueryString["SiteId"] != null) { if (Int32.Parse(Context.Request.QueryString["SiteId"]) == -1) { // Create a new site instance this._activeSite = new Site(); this.btnDelete.Visible = false; this.hplNewAlias.Visible = false; } else { // Get site data this._activeSite = base.SiteService.GetSiteById(Int32.Parse(Context.Request.QueryString["SiteId"])); this.btnDelete.Visible = true; this.btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?')"); } if (! this.IsPostBack) { BindSiteControls(); BindTemplates(); BindCultures(); BindRoles(); if (this._activeSite.Id > 0) { BindAliases(); } } } } private void BindSiteControls() { this.txtName.Text = this._activeSite.Name; this.txtSiteUrl.Text = this._activeSite.SiteUrl; this.txtWebmasterEmail.Text = this._activeSite.WebmasterEmail; this.chkUseFriendlyUrls.Checked = this._activeSite.UseFriendlyUrls; this.txtMetaDescription.Text = this._activeSite.MetaDescription; this.txtMetaKeywords.Text = this._activeSite.MetaKeywords; } private void BindTemplates() { IList templates = this._templateService.GetAllTemplates(); // Insert option for no template Template emptyTemplate = new Template(); emptyTemplate.Id = -1; emptyTemplate.Name = "No template"; templates.Insert(0, emptyTemplate); // Bind this.ddlTemplates.DataSource = templates; this.ddlTemplates.DataValueField = "Id"; this.ddlTemplates.DataTextField = "Name"; this.ddlTemplates.DataBind(); if (this._activeSite.DefaultTemplate != null) { ddlTemplates.Items.FindByValue(this._activeSite.DefaultTemplate.Id.ToString()).Selected = true; BindPlaceholders(); } this.ddlTemplates.Visible = true; ddlOfflinePageTemplate.DataSource = templates; ddlOfflinePageTemplate.DataValueField = "Id"; ddlOfflinePageTemplate.DataTextField = "Name"; ddlOfflinePageTemplate.DataBind(); if (_activeSite.OfflineTemplate != null) { ddlOfflinePageTemplate.Items.FindByValue(_activeSite.OfflineTemplate.Id.ToString()).Selected = true; } } private void BindPlaceholders() { // Try to find the placeholder in the selected template. if (this.ddlTemplates.SelectedIndex > 0) { try { Template template = this._templateService.GetTemplateById(Int32.Parse(this.ddlTemplates.SelectedValue)); // Read template control and get the containers (placeholders) string templatePath = UrlHelper.GetApplicationPath() + template.Path; BaseTemplate templateControl = (BaseTemplate)this.LoadControl(templatePath); this.ddlPlaceholders.DataSource = templateControl.Containers; this.ddlPlaceholders.DataValueField = "Key"; this.ddlPlaceholders.DataTextField = "Key"; this.ddlPlaceholders.DataBind(); if (this._activeSite.DefaultPlaceholder != null && this._activeSite.DefaultPlaceholder != String.Empty) { this.ddlPlaceholders.Items.FindByValue(this._activeSite.DefaultPlaceholder).Selected = true; } } catch (Exception ex) { ShowError(ex.Message); } } else { this.ddlPlaceholders.Items.Clear(); } } private void BindCultures() { this.ddlCultures.DataSource = Globalization.GetOrderedCultures(); this.ddlCultures.DataValueField = "Key"; this.ddlCultures.DataTextField = "Value"; this.ddlCultures.DataBind(); if (this._activeSite.DefaultCulture != null) { ListItem li = ddlCultures.Items.FindByValue(this._activeSite.DefaultCulture); if (li != null) { ddlCultures.Items.FindByValue(this._activeSite.DefaultCulture).Selected = true; } } } private void BindRoles() { this.ddlRoles.DataSource = this._userService.GetAllRoles(); this.ddlRoles.DataValueField = "Id"; this.ddlRoles.DataTextField = "Name"; this.ddlRoles.DataBind(); if (this._activeSite.DefaultRole != null) { ddlRoles.Items.FindByValue(this._activeSite.DefaultRole.Id.ToString()).Selected = true; } } private void BindAliases() { this.rptAliases.DataSource = base.SiteService.GetSiteAliasesBySite(this._activeSite); this.rptAliases.DataBind(); this.hplNewAlias.NavigateUrl = String.Format("~/Admin/SiteAliasEdit.aspx?SiteId={0}&SiteAliasId=-1", this._activeSite.Id); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.ddlTemplates.SelectedIndexChanged += new System.EventHandler(this.ddlTemplates_SelectedIndexChanged); this.rptAliases.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.rptAliases_ItemDataBound); this.btnSave.Click += new System.EventHandler(this.btnSave_Click); this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void btnSave_Click(object sender, EventArgs e) { if (this.IsValid) { this._activeSite.Name = txtName.Text; this._activeSite.SiteUrl = txtSiteUrl.Text; this._activeSite.WebmasterEmail = txtWebmasterEmail.Text; this._activeSite.UseFriendlyUrls = this.chkUseFriendlyUrls.Checked; if (this.ddlTemplates.SelectedValue != "-1") { int templateId = Int32.Parse(this.ddlTemplates.SelectedValue); Template template = this._templateService.GetTemplateById(templateId); this._activeSite.DefaultTemplate = template; if (this.ddlPlaceholders.SelectedIndex > -1) { this._activeSite.DefaultPlaceholder = this.ddlPlaceholders.SelectedValue; } } else if (this.ddlTemplates.SelectedValue == "-1") { this._activeSite.DefaultTemplate = null; this._activeSite.DefaultPlaceholder = null; } // marcot 180607 if (ddlOfflinePageTemplate.SelectedValue != "-1") { int offlineTemplateId = Int32.Parse(ddlOfflinePageTemplate.SelectedValue); Template offlinetemplate = _templateService.GetTemplateById(offlineTemplateId); _activeSite.OfflineTemplate = offlinetemplate; } else if (ddlOfflinePageTemplate.SelectedValue == "-1") { _activeSite.OfflineTemplate = null; } // marcot 180607 this._activeSite.DefaultCulture = this.ddlCultures.SelectedValue; int defaultRoleId = Int32.Parse(this.ddlRoles.SelectedValue); this._activeSite.DefaultRole = this._userService.GetRoleById(defaultRoleId); this._activeSite.MetaDescription = this.txtMetaDescription.Text.Trim().Length > 0 ? this.txtMetaDescription.Text.Trim() : null; this._activeSite.MetaKeywords = this.txtMetaKeywords.Text.Trim().Length > 0 ? this.txtMetaKeywords.Text.Trim() : null; try { base.SiteService.SaveSite(this._activeSite); ShowMessage("Site saved."); } catch (Exception ex) { ShowError(ex.Message); } } } private void btnCancel_Click(object sender, EventArgs e) { Response.Redirect("Default.aspx"); } private void btnDelete_Click(object sender, EventArgs e) { try { base.SiteService.DeleteSite(this._activeSite); Response.Redirect("Default.aspx"); } catch (Exception ex) { ShowError(ex.Message); } } private void ddlTemplates_SelectedIndexChanged(object sender, EventArgs e) { BindPlaceholders(); } private void rptAliases_ItemDataBound(object sender, RepeaterItemEventArgs e) { SiteAlias sa = (SiteAlias)e.Item.DataItem; HyperLink hplEdit = e.Item.FindControl("hplEdit") as HyperLink; if (hplEdit != null) { hplEdit.NavigateUrl = String.Format("~/Admin/SiteAliasEdit.aspx?SiteId={0}&SiteAliasId={1}", this._activeSite.Id, sa.Id); } Label lblEntryNode = e.Item.FindControl("lblEntryNode") as Label; if (lblEntryNode != null) { if (sa.EntryNode == null) { lblEntryNode.Text = "Inherited from site"; } else { lblEntryNode.Text = sa.EntryNode.Title + " (" + sa.EntryNode.Culture + ")"; } } } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Diagnostics; using System.Windows.Forms; using System.IO; namespace Zelous { // Constants copied from game code public class GameConstants { public const int HwScreenSizeX = 256; public const int HwScreenSizeY = 192; public const int GameMetaTileSizeX = 16; // Doesn't need to be fixed for all - can be just background-specific... public const int GameMetaTileSizeY = 16; public const int GameNumScreenMetaTilesX = (HwScreenSizeX / GameMetaTileSizeX); public const int GameNumScreenMetaTilesY = (HwScreenSizeY / GameMetaTileSizeY); public static int EventLayerIndex = 4; //@TODO: Should we have an enum with all of these? } //@TODO: Move to BitOps.cs public class BitOps { // Returns an int with numBits 1s set // ex: GetNumBits(5) returns 11111b == 0x1F == 31 public static int GenNumBits(int numBits) { return (1 << numBits) - 1; } } // A grouped set of tiles, 1 per layer public class TileSet { private string mFilePath; private Size mTileSize; private Point mNumTiles; private Image mImage; public TileSet(string filePath, int tileWidth, int tileHeight) { mFilePath = filePath; mTileSize = new Size(tileWidth, tileHeight); LoadImage(filePath); Debug.Assert(mImage.Size.Width % mTileSize.Width == 0); Debug.Assert(mImage.Size.Height % mTileSize.Height == 0); mNumTiles.X = mImage.Size.Width / mTileSize.Width; mNumTiles.Y = mImage.Size.Height / mTileSize.Height; } public void GetTileRect(int tileIndex, ref Rectangle rect) { Debug.Assert(rect != null); int numTilesX = Image.Width / TileSize.Width; int tileY = tileIndex / numTilesX; int tileX = tileIndex % numTilesX; rect.X = tileX * TileSize.Width; rect.Y = tileY * TileSize.Height; rect.Width = TileSize.Width; rect.Height = TileSize.Height; } public string FilePath { get { return mFilePath; } } public Image Image { get { return mImage; } } public Point NumTiles { get { return mNumTiles; } } public Size TileSize { get { return mTileSize; } } public Size ImageSize { get { return mImage.Size; } } public float AspectRatio { get { return ImageSize.Width / ImageSize.Height; } } private void LoadImage(string filePath) { // For optimal speed, we want to make sure we load the bitmap into an Image that // matches the pixel format the default Graphics instance used to render everything. Bitmap origBitmap = (Bitmap)Image.FromFile(mFilePath); mImage = new Bitmap(origBitmap.Width, origBitmap.Height, MainForm.Instance.CreateGraphics()); // Now render the original image into mImage at target pixel format Graphics gfx = Graphics.FromImage(mImage); GraphicsHelpers.PrepareGraphics(gfx); // Also set the transparent color ImageAttributes imgAttr = new ImageAttributes(); Color magenta = Color.FromArgb(255, 0, 255); imgAttr.SetColorKey(magenta, magenta); Rectangle r = new Rectangle(0, 0, origBitmap.Width, origBitmap.Height); gfx.DrawImage(origBitmap, r, r.X, r.Y, r.Width, r.Height, GraphicsUnit.Pixel, imgAttr); } } // Represents a single Tile // It's a struct because we allocate large 2d arrays of these - consider making this a class, // as it's a pain that we can't pass references to Tiles around. public struct Tile : IEquatable<Tile> { // Index of this tile in the current tile set public int Index { get; set; } // Optional metadata tied to this Tile (ex: GameEvent). public object Metadata { get; set; } public override int GetHashCode() { Debug.Fail("not implemented"); return base.GetHashCode(); } public bool Equals(Tile rhs) { return Index == rhs.Index && ((Metadata != null && rhs.Metadata != null && Metadata.Equals(rhs.Metadata) || Metadata == rhs.Metadata)); } } // A single layer of tiles, which includes a TileSet and a 2d array of Tiles public class TileLayer { private Tile[,] mTileMap; private TileSet mTileSet; public void Init(int numTilesX, int numTilesY, TileSet tileSet) { mTileSet = tileSet; mTileMap = new Tile[numTilesX, numTilesY]; } public TileSet TileSet { get { return mTileSet; } } public Tile[,] TileMap { get { return mTileMap; } } public Size SizePixels { get { return new Size(TileMap.GetLength(0) * TileSet.TileSize.Width, TileMap.GetLength(1) * TileSet.TileSize.Height); } } }; // The world map, which is a collection of TileLayers public class WorldMap { public const int NumLayers = 5; private TileLayer[] mTileLayers = new TileLayer[NumLayers]; int mNumScreensX, mNumScreensY; int mNumTilesX, mNumTilesY; int mTileSetGroupIndex; public TileLayer[] TileLayers { get { return mTileLayers; } } public void NewMap(int numScreensX, int numScreensY, int tileSetGroupIndex) { Size tileSize = new Size(16, 16); mNumScreensX = numScreensX; mNumScreensY = numScreensY; mNumTilesX = mNumScreensX * GameConstants.GameNumScreenMetaTilesX; mNumTilesY = mNumScreensY * GameConstants.GameNumScreenMetaTilesY; mTileSetGroupIndex = tileSetGroupIndex; GameTileSetGroup tileSetGroup = MainForm.Instance.GameTileSetGroupMgr.GetGroup(mTileSetGroupIndex); string[] tileSetFiles = new string[NumLayers]; tileSetFiles[0] = tileSetGroup.BackgroundTiles; tileSetFiles[1] = tileSetGroup.ForegroundTiles; tileSetFiles[2] = "collision_tileset.bmp"; tileSetFiles[3] = "editor_characters.bmp"; tileSetFiles[4] = "editor_events.bmp"; for (int i = 0; i < NumLayers; ++i) { TileSet tileSet = new TileSet(tileSetFiles[i], tileSize.Width, tileSize.Height); mTileLayers[i] = new TileLayer(); mTileLayers[i].Init(mNumTilesX, mNumTilesY, tileSet); } } // Save/Load constants private const string MapTag = "WMAP"; private const UInt32 MapVer = 3; private const UInt16 NumGameLayers = 3; // Doesn't match number of layers in editor private const UInt16 ValidationMarker = 0xFFFF; //@TODO: Rename - "serialization" is now confusing because of XML serialization via the SerializationMgr (Save/LoadGameMap?) //@TODO: Move this code out into a WorldMapSerializer class (or a partial class) //@TODO: Return success status //@TODO: Save to a temp file, then replace target file if successful (to avoid losing old map data if we fail during save) public void SaveMap(string fileName) { // Note: When saving, we always save the latest version, but loading must be backwards // compatible with any version so that changes can be made to the map format without // deprecating existing maps. The game, however, only supports loading the latest // version, so old maps must be loaded and resaved within Zelous before loading in the // game. //================================================================= // Version | Changes //================================================================= // 0 | initial (no versioning) // 1 | versioning (tag+version), character spawners // 2 | events // 3 | tile set group index, num screens FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter w = new BinaryWriter(fs); // Header w.Write((char[])MapTag.ToCharArray()); w.Write((UInt32)MapVer); // Map data w.Write((UInt16)mTileSetGroupIndex); w.Write((UInt16)mNumScreensX); w.Write((UInt16)mNumScreensY); w.Write((UInt16)NumGameLayers); // Write out tile layers for (int layerIdx = 0; layerIdx < NumGameLayers; ++layerIdx) { w.Write((UInt16)mNumTilesX); w.Write((UInt16)mNumTilesY); for (int y = 0; y < mNumTilesY; ++y) { for (int x = 0; x < mNumTilesX; ++x) { if (layerIdx < 2) { TileLayer tileLayer = TileLayers[layerIdx]; int tileIndex = tileLayer.TileMap[x, y].Index; w.Write((UInt16)tileIndex); } else if (layerIdx == 2) { TileLayer collLayer = TileLayers[layerIdx]; TileLayer charLayer = TileLayers[layerIdx + 1]; // Write out data layer (collisions + spawners) UInt16 collValue = (UInt16)collLayer.TileMap[x, y].Index; UInt16 charValue = (UInt16)charLayer.TileMap[x, y].Index; collValue <<= 0; charValue <<= 2; UInt16 dataLayerEntry = (UInt16)(collValue | charValue); w.Write((UInt16)dataLayerEntry); } else { Debug.Fail("Invalid layer index"); } } } w.Write((UInt16)ValidationMarker); } // Event data // Collect all events Dictionary<Point, GameEvent> gameEvents = new Dictionary<Point, GameEvent>(); TileLayer eventLayer = TileLayers[GameConstants.EventLayerIndex]; for (int y = 0; y < mNumTilesY; ++y) { for (int x = 0; x < mNumTilesX; ++x) { if (eventLayer.TileMap[x, y].Index > 0) { GameEvent gameEvent = eventLayer.TileMap[x, y].Metadata as GameEvent; Debug.Assert(gameEvent != null); gameEvents[new Point(x, y)] = gameEvent; } } } // Write event data w.Write((UInt16)gameEvents.Count); foreach (KeyValuePair<Point, GameEvent> kvp in gameEvents) { // Format: x(16) y(16) (event data) w.Write((UInt16)kvp.Key.X); w.Write((UInt16)kvp.Key.Y); SaveGameEvent(w, kvp.Value); } w.Write((UInt16)ValidationMarker); w.Close(); fs.Close(); } public void LoadMap(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); // Header string fileTag = new string(r.ReadChars(4)); UInt32 fileVer = r.ReadUInt32(); if (fileTag != MapTag) { fileVer = 0; // First version had no map tag fs.Position = 0; // Reset stream position } // Map data int tileSetGroupIndex = 0; int numScreensX = 20; int numScreensY = 10; if (fileVer >= 3) { tileSetGroupIndex = r.ReadUInt16(); Debug.Assert(tileSetGroupIndex >= 0); //&& tileSetGroupIndex < NumTileSetGroups); numScreensX = r.ReadUInt16(); numScreensY = r.ReadUInt16(); } // Create a new map with current settings, then populate it NewMap(numScreensX, numScreensY, tileSetGroupIndex); UInt16 numLayers = r.ReadUInt16(); Debug.Assert(numLayers == NumGameLayers); for (int layerIdx = 0; layerIdx < NumGameLayers; ++layerIdx) { UInt16 numTilesX = r.ReadUInt16(); UInt16 numTilesY = r.ReadUInt16(); Debug.Assert(numTilesX == mNumTilesX && numTilesY == mNumTilesY); for (int y = 0; y < numTilesY; ++y) { for (int x = 0; x < numTilesX; ++x) { if (layerIdx < 2) { UInt16 tileIndex = r.ReadUInt16(); TileLayer tileLayer = TileLayers[layerIdx]; tileLayer.TileMap[x, y].Index = tileIndex; } else if (layerIdx == 2) { // Parse out collision + spawner value UInt16 dataLayerEntry = r.ReadUInt16(); int collValue = (dataLayerEntry >> 0) & BitOps.GenNumBits(2); int charValue = (dataLayerEntry >> 2) & BitOps.GenNumBits(6); TileLayer collLayer = TileLayers[layerIdx]; TileLayer charLayer = TileLayers[layerIdx + 1]; collLayer.TileMap[x, y].Index = collValue; charLayer.TileMap[x, y].Index = charValue; } else { Debug.Fail("Invalid layer index"); } } } UInt16 marker = r.ReadUInt16(); Debug.Assert(marker == ValidationMarker); } // Load events TileLayer eventLayer = TileLayers[GameConstants.EventLayerIndex]; if (fileVer >= 2) { UInt16 numEvents = r.ReadUInt16(); for (int i = 0; i < numEvents; ++i) { Point tilePos = new Point(); tilePos.X = r.ReadUInt16(); tilePos.Y = r.ReadUInt16(); GameEvent gameEvent = LoadGameEvent(r); eventLayer.TileMap[tilePos.X, tilePos.Y].Index = gameEvent.TypeId; eventLayer.TileMap[tilePos.X, tilePos.Y].Metadata = gameEvent; } UInt16 marker = r.ReadUInt16(); Debug.Assert(marker == ValidationMarker); } r.Close(); fs.Close(); } void SaveGameEvent(BinaryWriter w, GameEvent gameEvent) { // Format: id(16) version(16) numElems(16) elems* w.Write((UInt16)gameEvent.TypeId); w.Write((UInt16)gameEvent.Version); w.Write((UInt16)gameEvent.Elements.Count); foreach (GameEventElement elem in gameEvent.Elements) { if (elem.Value.GetType() == typeof(string)) { w.Write((char)'s'); string s = (string)elem.Value; w.Write((UInt16)s.Length); w.Write((char[])s.ToCharArray()); } else if (elem.Value.GetType() == typeof(int)) { w.Write((char)'u'); w.Write((UInt16)((int)elem.Value)); } else { Debug.Fail("Unexpected value type"); } } } GameEvent LoadGameEvent(BinaryReader r) { // For game events elements, we only store the data type and value, but not the name; // therefore, we can always load events as long as the order is matched. This means we // automatically support loading older events (version is older than current), as long // as old elements remain untouched, and new ones are added after the old ones. // We may want to provide a hook that allows game event specific code to load older // versions. UInt16 typeId = r.ReadUInt16(); UInt16 version = r.ReadUInt16(); // We always create the latest version of GameEvent, then update its elements // from the map file. GameEventFactory factory = MainForm.Instance.GameEventFactory; GameEvent gameEvent = factory.CreateNewGameEventFromPrototype(typeId); //@TODO: if (gameEvent.Version > version) call handler UInt16 numElems = r.ReadUInt16(); List<GameEventElement> elements = gameEvent.GetElementsCopy(); // Copy for (int i = 0; i < numElems; ++i) { char elemType = r.ReadChar(); object elemValue = null; switch (elemType) { case 's': UInt16 len = r.ReadUInt16(); elemValue = new string(r.ReadChars(len)); break; case 'u': elemValue = (int)r.ReadUInt16(); // Cast to supported GameEventElement type break; } //@TODO: Throw an exception, catch outside of Serialize() Debug.Assert( elements[i].Value.GetType() == elemValue.GetType() ); // Does this work? elements[i] = elements[i].SetValue(elemValue); // Update } gameEvent = gameEvent.SetElements(elements); // Update return gameEvent; } }; }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; //////////////////////////////////////////////////////////////////////////////// // Get the latest version of SplitButton at: http://wyday.com/splitbutton/ // // Copyright (c) 2010, wyDay // 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 OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////// #if __SampleComment To drop a MenuButton into a form, you have to do a little hacking on the back-end. Here's what you do in three easy steps: 1. Drop a button on your form. 2. Open up the form's .Designer.cs file, and look for where the button is declared. Replace this line: private System.Windows.Forms.Button button1; with this: private FeralNerd.WinForms.MenuButton button1; 3. Now find out where button1 gets created in .Designer.cs. Replace this line: this.button1 = new System.Windows.Forms.Button(); with this line: this.button1 = new FeralNerd.WinForms.MenuButton(); In default mode, clicking the button will fire the Xxx_Click handler, and clicking an item on the drop-down menu will fire a different set of events. Now you need to populate the button with menu items: button1.MenuItems.Add("Do some main thing", null, button1_MainThing_Click); button1.MenuItems.Add(new ToolStripSeparator()); button1.MenuItems.Add("Other thing", null, button1_OtherThing_Click); button1.MenuItems.Add("Something else", null, button1_SomethingElse_Click); If you want the menu button to ALWAYS show the drop-down menu when you click it, set the ShowMenuOnClick property to true. button1.ShowMenuOnClick = true; #endif namespace FeralNerd.WinForms { public class MenuButton : Button { #region ### Private (fields) ########################################### static int BorderSize = SystemInformation.Border3DSize.Width * 2; const int SplitSectionWidth = 18; PushButtonState _state; bool _skipNextOpen; Rectangle _dropDownRectangle; bool _isSplitMenuVisible; ContextMenuStrip _contextMenuStrip; TextFormatFlags _textFormatFlags = TextFormatFlags.Default; #endregion public MenuButton() { AutoSize = true; // Set up the new context menu-strip _contextMenuStrip = new ContextMenuStrip(); _contextMenuStrip.Closing += SplitMenuStrip_Closing; _contextMenuStrip.Opening += SplitMenuStrip_Opening; Invalidate(); } #region ### Public ##################################################### //////////////////////////////////////////////////// /// <summary> /// This exposes the collection of menu items. /// </summary> public ToolStripItemCollection MenuItems { get { return _contextMenuStrip.Items; } } //////////////////////////////////////////////////// /// <summary> /// Causes the context menu to show no matter where on the button /// the user clicks.<para/> /// <para/> /// If this property is false, then clicking the button fires the /// Click event, and clicking the down-arrow opens the context menu.<para/> /// <para/> /// If this property is true, then clicking anywhere on the button /// causes the context menu to open. The Click event is never /// fired. /// </summary> [DefaultValue(false)] public bool ShowMenuOnClick { get; set; } #endregion Properties #region ### Private (internal guts) #################################### private PushButtonState State { get { return _state; } set { if (!_state.Equals(value)) { _state = value; Invalidate(); } } } protected override bool IsInputKey(Keys keyData) { if (keyData.Equals(Keys.Down)) return true; return base.IsInputKey(keyData); } protected override void OnGotFocus(EventArgs e) { //if (!showSplit) //{ // base.OnGotFocus(e); // return; //} if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { State = PushButtonState.Default; } } protected override void OnKeyDown(KeyEventArgs kevent) { //if (showSplit) //{ if (kevent.KeyCode.Equals(Keys.Down) && !_isSplitMenuVisible) { ShowContextMenuStrip(); } else if (kevent.KeyCode.Equals(Keys.Space) && kevent.Modifiers == Keys.None) { State = PushButtonState.Pressed; } //} base.OnKeyDown(kevent); } protected override void OnKeyUp(KeyEventArgs kevent) { if (kevent.KeyCode.Equals(Keys.Space)) { if (MouseButtons == MouseButtons.None) { State = PushButtonState.Normal; } } else if (kevent.KeyCode.Equals(Keys.Apps)) { if (MouseButtons == MouseButtons.None && !_isSplitMenuVisible) { ShowContextMenuStrip(); } } base.OnKeyUp(kevent); } protected override void OnEnabledChanged(EventArgs e) { State = Enabled ? PushButtonState.Normal : PushButtonState.Disabled; base.OnEnabledChanged(e); } protected override void OnLostFocus(EventArgs e) { //if (!showSplit) //{ // base.OnLostFocus(e); // return; //} if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { State = PushButtonState.Normal; } } bool isMouseEntered; protected override void OnMouseEnter(EventArgs e) { //if (!showSplit) //{ // base.OnMouseEnter(e); // return; //} isMouseEntered = true; if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { State = PushButtonState.Hot; } } protected override void OnMouseLeave(EventArgs e) { //if (!showSplit) //{ // base.OnMouseLeave(e); // return; //} isMouseEntered = false; if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { State = Focused ? PushButtonState.Default : PushButtonState.Normal; } } protected override void OnMouseDown(MouseEventArgs e) { //if (!showSplit) //{ // base.OnMouseDown(e); // return; //} //handle ContextMenu re-clicking the drop-down region to close the menu if (_contextMenuStrip != null && e.Button == MouseButtons.Left && !isMouseEntered) _skipNextOpen = true; if ((ShowMenuOnClick || _dropDownRectangle.Contains(e.Location)) && !_isSplitMenuVisible && e.Button == MouseButtons.Left) { ShowContextMenuStrip(); } else { State = PushButtonState.Pressed; } } protected override void OnMouseUp(MouseEventArgs mevent) { //if (!showSplit) //{ // base.OnMouseUp(mevent); // return; //} // if the right button was released inside the button if (mevent.Button == MouseButtons.Right && ClientRectangle.Contains(mevent.Location) && !_isSplitMenuVisible) { ShowContextMenuStrip(); } else if (_contextMenuStrip == null || !_isSplitMenuVisible) { SetButtonDrawState(); if (ClientRectangle.Contains(mevent.Location) && !_dropDownRectangle.Contains(mevent.Location)) { OnClick(new EventArgs()); } } } protected override void OnPaint(PaintEventArgs pevent) { base.OnPaint(pevent); //if (!showSplit) // return; Graphics g = pevent.Graphics; Rectangle bounds = ClientRectangle; // draw the button background as according to the current state. if (State != PushButtonState.Pressed && IsDefault && !Application.RenderWithVisualStyles) { Rectangle backgroundBounds = bounds; backgroundBounds.Inflate(-1, -1); ButtonRenderer.DrawButton(g, backgroundBounds, State); // button renderer doesnt draw the black frame when themes are off g.DrawRectangle(SystemPens.WindowFrame, 0, 0, bounds.Width - 1, bounds.Height - 1); } else { ButtonRenderer.DrawButton(g, bounds, State); } // calculate the current dropdown rectangle. _dropDownRectangle = new Rectangle(bounds.Right - SplitSectionWidth, 0, SplitSectionWidth, bounds.Height); int internalBorder = BorderSize; Rectangle focusRect = new Rectangle(internalBorder - 1, internalBorder - 1, bounds.Width - _dropDownRectangle.Width - internalBorder, bounds.Height - (internalBorder * 2) + 2); bool drawSplitLine = (State == PushButtonState.Hot || State == PushButtonState.Pressed || !Application.RenderWithVisualStyles); if (RightToLeft == RightToLeft.Yes) { _dropDownRectangle.X = bounds.Left + 1; focusRect.X = _dropDownRectangle.Right; if (drawSplitLine) { // draw two lines at the edge of the dropdown button g.DrawLine(SystemPens.ButtonShadow, bounds.Left + SplitSectionWidth, BorderSize, bounds.Left + SplitSectionWidth, bounds.Bottom - BorderSize); g.DrawLine(SystemPens.ButtonFace, bounds.Left + SplitSectionWidth + 1, BorderSize, bounds.Left + SplitSectionWidth + 1, bounds.Bottom - BorderSize); } } else { if (drawSplitLine) { // draw two lines at the edge of the dropdown button g.DrawLine(SystemPens.ButtonShadow, bounds.Right - SplitSectionWidth, BorderSize, bounds.Right - SplitSectionWidth, bounds.Bottom - BorderSize); g.DrawLine(SystemPens.ButtonFace, bounds.Right - SplitSectionWidth - 1, BorderSize, bounds.Right - SplitSectionWidth - 1, bounds.Bottom - BorderSize); } } // Draw an arrow in the correct location PaintArrow(g, _dropDownRectangle); //paint the image and text in the "button" part of the splitButton PaintTextandImage(g, new Rectangle(0, 0, ClientRectangle.Width - SplitSectionWidth, ClientRectangle.Height)); // draw the focus rectangle. if (State != PushButtonState.Pressed && Focused && ShowFocusCues) { ControlPaint.DrawFocusRectangle(g, focusRect); } } private void PaintTextandImage(Graphics g, Rectangle bounds) { // Figure out where our text and image should go Rectangle text_rectangle; Rectangle image_rectangle; CalculateButtonTextAndImageLayout(ref bounds, out text_rectangle, out image_rectangle); //draw the image if (Image != null) { if (Enabled) g.DrawImage(Image, image_rectangle.X, image_rectangle.Y, Image.Width, Image.Height); else ControlPaint.DrawImageDisabled(g, Image, image_rectangle.X, image_rectangle.Y, BackColor); } // If we dont' use mnemonic, set formatFlag to NoPrefix as this will show ampersand. if (!UseMnemonic) _textFormatFlags = _textFormatFlags | TextFormatFlags.NoPrefix; else if (!ShowKeyboardCues) _textFormatFlags = _textFormatFlags | TextFormatFlags.HidePrefix; //draw the text if (!string.IsNullOrEmpty(Text)) { if (Enabled) TextRenderer.DrawText(g, Text, Font, text_rectangle, ForeColor, _textFormatFlags); else ControlPaint.DrawStringDisabled(g, Text, Font, BackColor, text_rectangle, _textFormatFlags); } } private void PaintArrow(Graphics g, Rectangle dropDownRect) { Point middle = new Point(Convert.ToInt32(dropDownRect.Left + dropDownRect.Width / 2), Convert.ToInt32(dropDownRect.Top + dropDownRect.Height / 2)); //if the width is odd - favor pushing it over one pixel right. middle.X += (dropDownRect.Width % 2); Point[] arrow = new[] { new Point(middle.X - 2, middle.Y - 1), new Point(middle.X + 3, middle.Y - 1), new Point(middle.X, middle.Y + 2) }; if (Enabled) g.FillPolygon(SystemBrushes.ControlText, arrow); else g.FillPolygon(SystemBrushes.ButtonShadow, arrow); } public override Size GetPreferredSize(Size proposedSize) { Size preferredSize = base.GetPreferredSize(proposedSize); //autosize correctly for splitbuttons //if (showSplit) //{ if (AutoSize) return CalculateButtonAutoSize(); if (!string.IsNullOrEmpty(Text) && TextRenderer.MeasureText(Text, Font).Width + SplitSectionWidth > preferredSize.Width) return preferredSize + new Size(SplitSectionWidth + BorderSize * 2, 0); //} return preferredSize; } private Size CalculateButtonAutoSize() { Size ret_size = Size.Empty; Size text_size = TextRenderer.MeasureText(Text, Font); Size image_size = Image == null ? Size.Empty : Image.Size; // Pad the text size if (Text.Length != 0) { text_size.Height += 4; text_size.Width += 4; } switch (TextImageRelation) { case TextImageRelation.Overlay: ret_size.Height = Math.Max(Text.Length == 0 ? 0 : text_size.Height, image_size.Height); ret_size.Width = Math.Max(text_size.Width, image_size.Width); break; case TextImageRelation.ImageAboveText: case TextImageRelation.TextAboveImage: ret_size.Height = text_size.Height + image_size.Height; ret_size.Width = Math.Max(text_size.Width, image_size.Width); break; case TextImageRelation.ImageBeforeText: case TextImageRelation.TextBeforeImage: ret_size.Height = Math.Max(text_size.Height, image_size.Height); ret_size.Width = text_size.Width + image_size.Width; break; } // Pad the result ret_size.Height += (Padding.Vertical + 6); ret_size.Width += (Padding.Horizontal + 6); //pad the splitButton arrow region //if (showSplit) ret_size.Width += SplitSectionWidth; return ret_size; } #region Button Layout Calculations //The following layout functions were taken from Mono's Windows.Forms //implementation, specifically "ThemeWin32Classic.cs", //then modified to fit the context of this splitButton private void CalculateButtonTextAndImageLayout(ref Rectangle content_rect, out Rectangle textRectangle, out Rectangle imageRectangle) { Size text_size = TextRenderer.MeasureText(Text, Font, content_rect.Size, _textFormatFlags); Size image_size = Image == null ? Size.Empty : Image.Size; textRectangle = Rectangle.Empty; imageRectangle = Rectangle.Empty; switch (TextImageRelation) { case TextImageRelation.Overlay: // Overlay is easy, text always goes here textRectangle = OverlayObjectRect(ref content_rect, ref text_size, TextAlign); // Rectangle.Inflate(content_rect, -4, -4); //Offset on Windows 98 style when button is pressed if (_state == PushButtonState.Pressed && !Application.RenderWithVisualStyles) textRectangle.Offset(1, 1); // Image is dependent on ImageAlign if (Image != null) imageRectangle = OverlayObjectRect(ref content_rect, ref image_size, ImageAlign); break; case TextImageRelation.ImageAboveText: content_rect.Inflate(-4, -4); LayoutTextAboveOrBelowImage(content_rect, false, text_size, image_size, out textRectangle, out imageRectangle); break; case TextImageRelation.TextAboveImage: content_rect.Inflate(-4, -4); LayoutTextAboveOrBelowImage(content_rect, true, text_size, image_size, out textRectangle, out imageRectangle); break; case TextImageRelation.ImageBeforeText: content_rect.Inflate(-4, -4); LayoutTextBeforeOrAfterImage(content_rect, false, text_size, image_size, out textRectangle, out imageRectangle); break; case TextImageRelation.TextBeforeImage: content_rect.Inflate(-4, -4); LayoutTextBeforeOrAfterImage(content_rect, true, text_size, image_size, out textRectangle, out imageRectangle); break; } } private static Rectangle OverlayObjectRect(ref Rectangle container, ref Size sizeOfObject, System.Drawing.ContentAlignment alignment) { int x, y; switch (alignment) { case System.Drawing.ContentAlignment.TopLeft: x = 4; y = 4; break; case System.Drawing.ContentAlignment.TopCenter: x = (container.Width - sizeOfObject.Width) / 2; y = 4; break; case System.Drawing.ContentAlignment.TopRight: x = container.Width - sizeOfObject.Width - 4; y = 4; break; case System.Drawing.ContentAlignment.MiddleLeft: x = 4; y = (container.Height - sizeOfObject.Height) / 2; break; case System.Drawing.ContentAlignment.MiddleCenter: x = (container.Width - sizeOfObject.Width) / 2; y = (container.Height - sizeOfObject.Height) / 2; break; case System.Drawing.ContentAlignment.MiddleRight: x = container.Width - sizeOfObject.Width - 4; y = (container.Height - sizeOfObject.Height) / 2; break; case System.Drawing.ContentAlignment.BottomLeft: x = 4; y = container.Height - sizeOfObject.Height - 4; break; case System.Drawing.ContentAlignment.BottomCenter: x = (container.Width - sizeOfObject.Width) / 2; y = container.Height - sizeOfObject.Height - 4; break; case System.Drawing.ContentAlignment.BottomRight: x = container.Width - sizeOfObject.Width - 4; y = container.Height - sizeOfObject.Height - 4; break; default: x = 4; y = 4; break; } return new Rectangle(x, y, sizeOfObject.Width, sizeOfObject.Height); } private void LayoutTextBeforeOrAfterImage(Rectangle totalArea, bool textFirst, Size textSize, Size imageSize, out Rectangle textRect, out Rectangle imageRect) { int element_spacing = 0; // Spacing between the Text and the Image int total_width = textSize.Width + element_spacing + imageSize.Width; if (!textFirst) element_spacing += 2; // If the text is too big, chop it down to the size we have available to it if (total_width > totalArea.Width) { textSize.Width = totalArea.Width - element_spacing - imageSize.Width; total_width = totalArea.Width; } int excess_width = totalArea.Width - total_width; int offset = 0; Rectangle final_text_rect; Rectangle final_image_rect; HorizontalAlignment h_text = GetHorizontalAlignment(TextAlign); HorizontalAlignment h_image = GetHorizontalAlignment(ImageAlign); if (h_image == HorizontalAlignment.Left) offset = 0; else if (h_image == HorizontalAlignment.Right && h_text == HorizontalAlignment.Right) offset = excess_width; else if (h_image == HorizontalAlignment.Center && (h_text == HorizontalAlignment.Left || h_text == HorizontalAlignment.Center)) offset += excess_width / 3; else offset += 2 * (excess_width / 3); if (textFirst) { final_text_rect = new Rectangle(totalArea.Left + offset, AlignInRectangle(totalArea, textSize, TextAlign).Top, textSize.Width, textSize.Height); final_image_rect = new Rectangle(final_text_rect.Right + element_spacing, AlignInRectangle(totalArea, imageSize, ImageAlign).Top, imageSize.Width, imageSize.Height); } else { final_image_rect = new Rectangle(totalArea.Left + offset, AlignInRectangle(totalArea, imageSize, ImageAlign).Top, imageSize.Width, imageSize.Height); final_text_rect = new Rectangle(final_image_rect.Right + element_spacing, AlignInRectangle(totalArea, textSize, TextAlign).Top, textSize.Width, textSize.Height); } textRect = final_text_rect; imageRect = final_image_rect; } private void LayoutTextAboveOrBelowImage(Rectangle totalArea, bool textFirst, Size textSize, Size imageSize, out Rectangle textRect, out Rectangle imageRect) { int element_spacing = 0; // Spacing between the Text and the Image int total_height = textSize.Height + element_spacing + imageSize.Height; if (textFirst) element_spacing += 2; if (textSize.Width > totalArea.Width) textSize.Width = totalArea.Width; // If the there isn't enough room and we're text first, cut out the image if (total_height > totalArea.Height && textFirst) { imageSize = Size.Empty; total_height = totalArea.Height; } int excess_height = totalArea.Height - total_height; int offset = 0; Rectangle final_text_rect; Rectangle final_image_rect; VerticalAlignment v_text = GetVerticalAlignment(TextAlign); VerticalAlignment v_image = GetVerticalAlignment(ImageAlign); if (v_image == VerticalAlignment.Top) offset = 0; else if (v_image == VerticalAlignment.Bottom && v_text == VerticalAlignment.Bottom) offset = excess_height; else if (v_image == VerticalAlignment.Center && (v_text == VerticalAlignment.Top || v_text == VerticalAlignment.Center)) offset += excess_height / 3; else offset += 2 * (excess_height / 3); if (textFirst) { final_text_rect = new Rectangle(AlignInRectangle(totalArea, textSize, TextAlign).Left, totalArea.Top + offset, textSize.Width, textSize.Height); final_image_rect = new Rectangle(AlignInRectangle(totalArea, imageSize, ImageAlign).Left, final_text_rect.Bottom + element_spacing, imageSize.Width, imageSize.Height); } else { final_image_rect = new Rectangle(AlignInRectangle(totalArea, imageSize, ImageAlign).Left, totalArea.Top + offset, imageSize.Width, imageSize.Height); final_text_rect = new Rectangle(AlignInRectangle(totalArea, textSize, TextAlign).Left, final_image_rect.Bottom + element_spacing, textSize.Width, textSize.Height); if (final_text_rect.Bottom > totalArea.Bottom) final_text_rect.Y = totalArea.Top; } textRect = final_text_rect; imageRect = final_image_rect; } private static HorizontalAlignment GetHorizontalAlignment(System.Drawing.ContentAlignment align) { switch (align) { case System.Drawing.ContentAlignment.BottomLeft: case System.Drawing.ContentAlignment.MiddleLeft: case System.Drawing.ContentAlignment.TopLeft: return HorizontalAlignment.Left; case System.Drawing.ContentAlignment.BottomCenter: case System.Drawing.ContentAlignment.MiddleCenter: case System.Drawing.ContentAlignment.TopCenter: return HorizontalAlignment.Center; case System.Drawing.ContentAlignment.BottomRight: case System.Drawing.ContentAlignment.MiddleRight: case System.Drawing.ContentAlignment.TopRight: return HorizontalAlignment.Right; } return HorizontalAlignment.Left; } private static VerticalAlignment GetVerticalAlignment(System.Drawing.ContentAlignment align) { switch (align) { case System.Drawing.ContentAlignment.TopLeft: case System.Drawing.ContentAlignment.TopCenter: case System.Drawing.ContentAlignment.TopRight: return VerticalAlignment.Top; case System.Drawing.ContentAlignment.MiddleLeft: case System.Drawing.ContentAlignment.MiddleCenter: case System.Drawing.ContentAlignment.MiddleRight: return VerticalAlignment.Center; case System.Drawing.ContentAlignment.BottomLeft: case System.Drawing.ContentAlignment.BottomCenter: case System.Drawing.ContentAlignment.BottomRight: return VerticalAlignment.Bottom; } return VerticalAlignment.Top; } internal static Rectangle AlignInRectangle(Rectangle outer, Size inner, System.Drawing.ContentAlignment align) { int x = 0; int y = 0; if (align == System.Drawing.ContentAlignment.BottomLeft || align == System.Drawing.ContentAlignment.MiddleLeft || align == System.Drawing.ContentAlignment.TopLeft) x = outer.X; else if (align == System.Drawing.ContentAlignment.BottomCenter || align == System.Drawing.ContentAlignment.MiddleCenter || align == System.Drawing.ContentAlignment.TopCenter) x = Math.Max(outer.X + ((outer.Width - inner.Width) / 2), outer.Left); else if (align == System.Drawing.ContentAlignment.BottomRight || align == System.Drawing.ContentAlignment.MiddleRight || align == System.Drawing.ContentAlignment.TopRight) x = outer.Right - inner.Width; if (align == System.Drawing.ContentAlignment.TopCenter || align == System.Drawing.ContentAlignment.TopLeft || align == System.Drawing.ContentAlignment.TopRight) y = outer.Y; else if (align == System.Drawing.ContentAlignment.MiddleCenter || align == System.Drawing.ContentAlignment.MiddleLeft || align == System.Drawing.ContentAlignment.MiddleRight) y = outer.Y + (outer.Height - inner.Height) / 2; else if (align == System.Drawing.ContentAlignment.BottomCenter || align == System.Drawing.ContentAlignment.BottomRight || align == System.Drawing.ContentAlignment.BottomLeft) y = outer.Bottom - inner.Height; return new Rectangle(x, y, Math.Min(inner.Width, outer.Width), Math.Min(inner.Height, outer.Height)); } #endregion Button Layout Calculations private void ShowContextMenuStrip() { if (_skipNextOpen) { // we were called because we're closing the context menu strip // when clicking the dropdown button. _skipNextOpen = false; return; } State = PushButtonState.Pressed; if (_contextMenuStrip != null) { _contextMenuStrip.Show(this, new Point(0, Height), ToolStripDropDownDirection.BelowRight); } } void SplitMenuStrip_Opening(object sender, CancelEventArgs e) { _isSplitMenuVisible = true; } void SplitMenuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e) { _isSplitMenuVisible = false; SetButtonDrawState(); if (e.CloseReason == ToolStripDropDownCloseReason.AppClicked) { _skipNextOpen = (_dropDownRectangle.Contains(PointToClient(Cursor.Position))) && MouseButtons == MouseButtons.Left; } } void SplitMenu_Popup(object sender, EventArgs e) { _isSplitMenuVisible = true; } protected override void WndProc(ref Message m) { //0x0212 == WM_EXITMENULOOP if (m.Msg == 0x0212) { //this message is only sent when a ContextMenu is closed (not a ContextMenuStrip) _isSplitMenuVisible = false; SetButtonDrawState(); } base.WndProc(ref m); } private void SetButtonDrawState() { if (Bounds.Contains(Parent.PointToClient(Cursor.Position))) { State = PushButtonState.Hot; } else if (Focused) { State = PushButtonState.Default; } else if (!Enabled) { State = PushButtonState.Disabled; } else { State = PushButtonState.Normal; } } #endregion } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Threading; using System.Collections.Generic; using MLifter.Properties; using MLifter.DAL.Interfaces; using MLifter.Controls; using MLifter.Components; namespace MLifter { /// <summary> /// Allows the user to select chapters and print their content with or without multimedia (uses Internet Explorer). /// </summary> public class PrintForm : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox GBChapters; private System.Windows.Forms.Button btnCancel; private MLifter.Controls.ChapterFrame Chapters; private WebBrowser Browser; private Button btnPreview; private ComboBox comboBoxPrintStyle; private ComboBox comboBoxCardOrder; private Label lblPrintStyle; private ListView listViewBoxesSelection; private CheckBox checkBoxAllBoxes; private LoadStatusMessage statusDialog; private GroupBox GBBoxes; private CheckBox cbReverseOrder; private Label lblCardOrder; private Label lblCurSelVal; private GroupBox GBPrintOptions; private System.Windows.Forms.Timer timerUpdateStatistics; private Button buttonWizard; private HelpProvider MainHelp; private IContainer components; public PrintForm() { // // Required for Windows Form Designer support // InitializeComponent(); // MLifter.Classes.Help.SetHelpNameSpace(MainHelp); } private MLifter.BusinessLayer.Dictionary Dictionary { get { return MainForm.LearnLogic.Dictionary; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PrintForm)); this.GBChapters = new System.Windows.Forms.GroupBox(); this.Chapters = new MLifter.Controls.ChapterFrame(); this.btnCancel = new System.Windows.Forms.Button(); this.Browser = new System.Windows.Forms.WebBrowser(); this.btnPreview = new System.Windows.Forms.Button(); this.comboBoxPrintStyle = new System.Windows.Forms.ComboBox(); this.comboBoxCardOrder = new System.Windows.Forms.ComboBox(); this.lblPrintStyle = new System.Windows.Forms.Label(); this.listViewBoxesSelection = new System.Windows.Forms.ListView(); this.checkBoxAllBoxes = new System.Windows.Forms.CheckBox(); this.lblCardOrder = new System.Windows.Forms.Label(); this.GBBoxes = new System.Windows.Forms.GroupBox(); this.cbReverseOrder = new System.Windows.Forms.CheckBox(); this.lblCurSelVal = new System.Windows.Forms.Label(); this.GBPrintOptions = new System.Windows.Forms.GroupBox(); this.timerUpdateStatistics = new System.Windows.Forms.Timer(this.components); this.buttonWizard = new System.Windows.Forms.Button(); this.MainHelp = new System.Windows.Forms.HelpProvider(); this.GBChapters.SuspendLayout(); this.GBBoxes.SuspendLayout(); this.GBPrintOptions.SuspendLayout(); this.SuspendLayout(); // // GBChapters // this.GBChapters.Controls.Add(this.Chapters); resources.ApplyResources(this.GBChapters, "GBChapters"); this.GBChapters.Name = "GBChapters"; this.GBChapters.TabStop = false; // // Chapters // resources.ApplyResources(this.Chapters, "Chapters"); this.Chapters.Name = "Chapters"; this.Chapters.OnUpdate += new MLifter.Controls.ChapterFrame.FieldEventHandler(this.Chapters_OnUpdate); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // Browser // resources.ApplyResources(this.Browser, "Browser"); this.Browser.MinimumSize = new System.Drawing.Size(20, 20); this.Browser.Name = "Browser"; this.Browser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.Browser_DocumentCompleted); // // btnPreview // resources.ApplyResources(this.btnPreview, "btnPreview"); this.btnPreview.Name = "btnPreview"; this.btnPreview.Click += new System.EventHandler(this.btnPreview_Click); // // comboBoxPrintStyle // this.comboBoxPrintStyle.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxPrintStyle.FormattingEnabled = true; resources.ApplyResources(this.comboBoxPrintStyle, "comboBoxPrintStyle"); this.comboBoxPrintStyle.Name = "comboBoxPrintStyle"; // // comboBoxCardOrder // this.comboBoxCardOrder.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxCardOrder.FormattingEnabled = true; resources.ApplyResources(this.comboBoxCardOrder, "comboBoxCardOrder"); this.comboBoxCardOrder.Name = "comboBoxCardOrder"; this.comboBoxCardOrder.SelectedIndexChanged += new System.EventHandler(this.comboBoxCardOrder_SelectedIndexChanged); // // lblPrintStyle // resources.ApplyResources(this.lblPrintStyle, "lblPrintStyle"); this.lblPrintStyle.Name = "lblPrintStyle"; // // listViewBoxesSelection // this.listViewBoxesSelection.BackColor = System.Drawing.SystemColors.Control; this.listViewBoxesSelection.BorderStyle = System.Windows.Forms.BorderStyle.None; this.listViewBoxesSelection.CheckBoxes = true; resources.ApplyResources(this.listViewBoxesSelection, "listViewBoxesSelection"); this.listViewBoxesSelection.GridLines = true; this.listViewBoxesSelection.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.listViewBoxesSelection.MultiSelect = false; this.listViewBoxesSelection.Name = "listViewBoxesSelection"; this.listViewBoxesSelection.Scrollable = false; this.listViewBoxesSelection.ShowItemToolTips = true; this.listViewBoxesSelection.UseCompatibleStateImageBehavior = false; this.listViewBoxesSelection.View = System.Windows.Forms.View.List; this.listViewBoxesSelection.ItemActivate += new System.EventHandler(this.listViewBoxesSelection_ItemActivate); this.listViewBoxesSelection.EnabledChanged += new System.EventHandler(this.listViewBoxesSelection_EnabledChanged); this.listViewBoxesSelection.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.listViewBoxesSelection_ItemChecked); // // checkBoxAllBoxes // resources.ApplyResources(this.checkBoxAllBoxes, "checkBoxAllBoxes"); this.checkBoxAllBoxes.Checked = true; this.checkBoxAllBoxes.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxAllBoxes.Name = "checkBoxAllBoxes"; this.checkBoxAllBoxes.UseVisualStyleBackColor = true; this.checkBoxAllBoxes.CheckedChanged += new System.EventHandler(this.checkBoxAllBoxes_CheckedChanged); // // lblCardOrder // resources.ApplyResources(this.lblCardOrder, "lblCardOrder"); this.lblCardOrder.Name = "lblCardOrder"; // // GBBoxes // this.GBBoxes.Controls.Add(this.listViewBoxesSelection); resources.ApplyResources(this.GBBoxes, "GBBoxes"); this.GBBoxes.Name = "GBBoxes"; this.GBBoxes.TabStop = false; // // cbReverseOrder // resources.ApplyResources(this.cbReverseOrder, "cbReverseOrder"); this.cbReverseOrder.Name = "cbReverseOrder"; this.cbReverseOrder.UseVisualStyleBackColor = true; // // lblCurSelVal // resources.ApplyResources(this.lblCurSelVal, "lblCurSelVal"); this.lblCurSelVal.Name = "lblCurSelVal"; // // GBPrintOptions // this.GBPrintOptions.Controls.Add(this.lblCardOrder); this.GBPrintOptions.Controls.Add(this.comboBoxPrintStyle); this.GBPrintOptions.Controls.Add(this.lblPrintStyle); this.GBPrintOptions.Controls.Add(this.cbReverseOrder); this.GBPrintOptions.Controls.Add(this.comboBoxCardOrder); resources.ApplyResources(this.GBPrintOptions, "GBPrintOptions"); this.GBPrintOptions.Name = "GBPrintOptions"; this.GBPrintOptions.TabStop = false; // // timerUpdateStatistics // this.timerUpdateStatistics.Interval = 250; this.timerUpdateStatistics.Tick += new System.EventHandler(this.timerUpdateStatistics_Tick); // // buttonWizard // resources.ApplyResources(this.buttonWizard, "buttonWizard"); this.buttonWizard.Name = "buttonWizard"; this.buttonWizard.UseVisualStyleBackColor = true; this.buttonWizard.Click += new System.EventHandler(this.buttonWizard_Click); // // PrintForm // this.AcceptButton = this.btnPreview; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.checkBoxAllBoxes); this.Controls.Add(this.buttonWizard); this.Controls.Add(this.GBPrintOptions); this.Controls.Add(this.lblCurSelVal); this.Controls.Add(this.GBBoxes); this.Controls.Add(this.btnPreview); this.Controls.Add(this.btnCancel); this.Controls.Add(this.GBChapters); this.Controls.Add(this.Browser); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MainHelp.SetHelpKeyword(this, resources.GetString("$this.HelpKeyword")); this.MainHelp.SetHelpNavigator(this, ((System.Windows.Forms.HelpNavigator)(resources.GetObject("$this.HelpNavigator")))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "PrintForm"; this.MainHelp.SetShowHelp(this, ((bool)(resources.GetObject("$this.ShowHelp")))); this.ShowInTaskbar = false; this.Load += new System.EventHandler(this.TPrintForm_Load); this.GBChapters.ResumeLayout(false); this.GBBoxes.ResumeLayout(false); this.GBPrintOptions.ResumeLayout(false); this.ResumeLayout(false); } #endregion public readonly string[] QueryOrders = new string[5] { Properties.Resources.PRINT_QUERYORDER_Question, Properties.Resources.PRINT_QUERYORDER_Answer, Properties.Resources.PRINT_QUERYORDER_Box, Properties.Resources.PRINT_QUERYORDER_Chapter, Properties.Resources.PRINT_QUERYORDER_None }; public readonly DAL.Interfaces.QueryOrder[] QueryOrdersEnum = new DAL.Interfaces.QueryOrder[5] { QueryOrder.Question, QueryOrder.Answer, QueryOrder.Box, QueryOrder.Chapter, QueryOrder.None }; /// <summary> /// Prepares the chapter selector on startup. /// </summary> /// <param name="sender">Event Sender, unused.</param> /// <param name="e">Event Arguments, unused.</param> /// <remarks>Documented by Dev01, 2007-07-19</remarks> /// <remarks>Documented by Dev02, 2007-11-22</remarks> private void TPrintForm_Load(object sender, System.EventArgs e) { Browser.Visible = false; //add chapters Chapters.Prepare(Dictionary); //add boxes for (int index = 0; index < Dictionary.Boxes.Count; index++) { ListViewItem box = new ListViewItem(); box.Text = (index == 0 ? Properties.Resources.PRINT_BOXNO_0 : string.Format(Properties.Resources.PRINT_BOXNO, index)); box.ToolTipText = string.Format(Properties.Resources.PRINT_BOX_TOOLTIP, Dictionary.Boxes[index].Size); box.Checked = false; listViewBoxesSelection.Items.Add(box); } //add queryorders foreach (string queryOrder in QueryOrders) { comboBoxCardOrder.Items.Add(queryOrder); } //add printstyles comboBoxPrintStyle.Items.Clear(); foreach (StyleInfo styleinfo in MainForm.styleHandler.CurrentStyle.PrintStyles) comboBoxPrintStyle.Items.Add(styleinfo); //select default values comboBoxPrintStyle.SelectedIndex = 0; comboBoxCardOrder.SelectedIndex = 0; checkBoxAllBoxes_CheckedChanged(this, new EventArgs()); listViewBoxesSelection_EnabledChanged(this, new EventArgs()); } /// <summary> /// Checks the chapter and multimedia (stylesheet) selection, generates the HTML page by arrayList function call and loads the page. /// </summary> /// <param name="sender">Event Sender, unused.</param> /// <param name="e">Event Arguments, unused.</param> /// <remarks>Documented by Dev01, 2007-07-19</remarks> /// <remarks>Documented by Dev02, 2007-11-23</remarks> private void btnPreview_Click(object sender, EventArgs e) { // Only start the query when at least one chapter and box has been selected if (Chapters.GetItemCount() < 1 || (listViewBoxesSelection.CheckedItems.Count < 1 && !checkBoxAllBoxes.Checked)) { MessageBox.Show(Resources.PRINT_SELECT_TEXT, Resources.PRINT_SELECT_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { this.Enabled = false; statusDialog = new LoadStatusMessage(Properties.Resources.PRINT_STATUS_FETCHINGCARDS, 100, false); statusDialog.Show(); statusDialog.SetProgress(0); BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); BackgroundWorker prepareworker = new BackgroundWorker(); prepareworker.WorkerReportsProgress = true; prepareworker.ProgressChanged += new ProgressChangedEventHandler(prepareworker_ProgressChanged); System.Collections.Generic.List<int> boxes; QueryOrder cardorder; QueryOrderDir cardorderdir; QueryCardState cardstate; GetGUISelection(out boxes, out cardorder, out cardorderdir, out cardstate); List<QueryStruct> querystructs = GetQueryStructs(Chapters.SelChapters, boxes, cardstate); string stylesheet = ((StyleInfo)comboBoxPrintStyle.SelectedItem).Path; List<ICard> cards = Dictionary.GetPrintOutCards(querystructs, cardorder, cardorderdir); string htmlContent = Dictionary.GeneratePrintOut( cards, stylesheet, worker, prepareworker); statusDialog.InfoMessage = Resources.PRINT_STATUS_RENDERING; statusDialog.EnableProgressbar = false; Browser.DocumentText = htmlContent; } } /// <summary> /// Gets the query structs. /// </summary> /// <param name="boxes">The boxes.</param> /// <param name="cardstate">The cardstate.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-01-03</remarks> private List<MLifter.DAL.Interfaces.QueryStruct> GetQueryStructs(List<int> chapters, List<int> boxes, QueryCardState cardstate) { if (chapters.Count < 1 || boxes.Count < 1) return null; //get cards with desired selection and ordering List<QueryStruct> querystructs = new List<QueryStruct>(); foreach (int chapter in chapters) foreach (int box in boxes) querystructs.Add(new QueryStruct(chapter, box, cardstate)); return querystructs; } /// <summary> /// Gets the selection of the form controls. /// </summary> /// <param name="boxes">The boxes.</param> /// <param name="cardorder">The cardorder.</param> /// <param name="cardorderdir">The cardorderdir.</param> /// <param name="cardstate">The cardstate.</param> /// <remarks>Documented by Dev02, 2007-11-26</remarks> private void GetGUISelection(out List<int> boxes, out QueryOrder cardorder, out QueryOrderDir cardorderdir, out QueryCardState cardstate) { boxes = new System.Collections.Generic.List<int>(); if (checkBoxAllBoxes.Checked) { for (int index = 0; index <= Dictionary.Boxes.Count; index++) boxes.Add(index); } else { foreach (int index in listViewBoxesSelection.CheckedIndices) boxes.Add(index); } cardorder = QueryOrdersEnum[comboBoxCardOrder.SelectedIndex < 0 ? 0 : comboBoxCardOrder.SelectedIndex]; cardorderdir = cbReverseOrder.Checked ? QueryOrderDir.Descending : QueryOrderDir.Ascending; cardstate = QueryCardState.Active; } /// <summary> /// Handles the ProgressChanged event of the worker control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.ProgressChangedEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2007-11-23</remarks> void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (statusDialog != null) { if (statusDialog.InfoMessage != Properties.Resources.PRINT_STATUS_PAGES) { statusDialog.InfoMessage = Properties.Resources.PRINT_STATUS_PAGES; statusDialog.EnableProgressbar = true; statusDialog.SetProgress(0); } statusDialog.SetProgress(e.ProgressPercentage); } } /// <summary> /// Handles the ProgressChanged event of the prepareworker control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.ProgressChangedEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-01-24</remarks> void prepareworker_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (statusDialog != null) { if (statusDialog.InfoMessage != Properties.Resources.PRINT_STATUS_MEDIA) { statusDialog.InfoMessage = Properties.Resources.PRINT_STATUS_MEDIA; statusDialog.EnableProgressbar = true; statusDialog.SetProgress(0); } statusDialog.SetProgress(e.ProgressPercentage); } } /// <summary> /// Shows the print preview dialog of Internet Explorer as soon as the document has been loaded in the (invisible) browser. /// </summary> /// <param name="sender">Event Sender, unused.</param> /// <param name="e">Event Arguments, unused.</param> /// <remarks>Documented by Dev01, 2007-07-19</remarks> private void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (statusDialog != null && statusDialog.Visible) statusDialog.Close(); //little hack to resize the PreviewDialog Window - without that, it would be shown in the size of this dialog //if there is any other way, let me know ;-) AWE this.Hide(); Size size = this.Size; this.Size = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height); Browser.ShowPrintPreviewDialog(); Application.DoEvents(); this.WindowState = FormWindowState.Normal; this.Size = size; this.Show(); this.Enabled = true; } /// <summary> /// Handles the CheckedChanged event of the checkBoxAllBoxes control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2007-11-22</remarks> private void checkBoxAllBoxes_CheckedChanged(object sender, EventArgs e) { foreach (ListViewItem box in listViewBoxesSelection.Items) box.Checked = checkBoxAllBoxes.Checked; listViewBoxesSelection.Enabled = !checkBoxAllBoxes.Checked; UpdateSelectionStatistics(); } /// <summary> /// Updates the displayed selection statistics. /// </summary> /// <remarks>Documented by Dev02, 2007-11-26</remarks> private void UpdateSelectionStatistics() { timerUpdateStatistics.Enabled = true; } /// <summary> /// Handles the ItemChecked event of the listViewBoxesSelection control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.ItemCheckedEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2007-11-23</remarks> private void listViewBoxesSelection_ItemChecked(object sender, ItemCheckedEventArgs e) { UpdateSelectionStatistics(); } /// <summary> /// Handles the OnUpdate event of the ChaptersFrm control. /// </summary> /// <param name="sender">The sender.</param> /// <remarks>Documented by Dev02, 2007-11-23</remarks> private void Chapters_OnUpdate(object sender) { UpdateSelectionStatistics(); } /// <summary> /// Handles the CheckedChanged event of the rbState controls. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2007-11-26</remarks> private void rbState_CheckedChanged(object sender, EventArgs e) { UpdateSelectionStatistics(); } /// <summary> /// Handles the EnabledChanged event of the listViewBoxesSelection control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2007-11-26</remarks> private void listViewBoxesSelection_EnabledChanged(object sender, EventArgs e) { if (listViewBoxesSelection.Enabled) { listViewBoxesSelection.ForeColor = SystemColors.WindowText; } else { listViewBoxesSelection.ForeColor = SystemColors.GrayText; } } /// <summary> /// Handles the Tick event of the timerUpdateStatistics control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2007-11-27</remarks> private void timerUpdateStatistics_Tick(object sender, EventArgs e) { timerUpdateStatistics.Enabled = false; int selected = 0; int total = 0; System.Collections.Generic.List<int> boxes; QueryOrder cardorder; QueryOrderDir cardorderdir; QueryCardState cardstate; GetGUISelection(out boxes, out cardorder, out cardorderdir, out cardstate); List<QueryStruct> querystructs = GetQueryStructs(Chapters.SelChapters, boxes, cardstate); List<ICard> cards = Dictionary.GetPrintOutCards(querystructs, MLifter.DAL.Interfaces.QueryOrder.None, MLifter.DAL.Interfaces.QueryOrderDir.Ascending); if (cards != null && cards.Count > 0) selected = cards.Count; else selected = 0; total = Dictionary.Cards.ActiveCardsCount; lblCurSelVal.Text = string.Format(Properties.Resources.PRINT_SELECTED, selected, total); } /// <summary> /// Handles the ItemActivate event of the listViewBoxesSelection control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2007-12-07</remarks> private void listViewBoxesSelection_ItemActivate(object sender, EventArgs e) { foreach (ListViewItem box in listViewBoxesSelection.SelectedItems) box.Checked = true; } /// <summary> /// Handles the Click event of the buttonWizard control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-01-04</remarks> private void buttonWizard_Click(object sender, EventArgs e) { DialogResult = DialogResult.Ignore; this.Close(); return; } /// <summary> /// Handles the SelectedIndexChanged event of the comboBoxCardOrder control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-01-24</remarks> private void comboBoxCardOrder_SelectedIndexChanged(object sender, EventArgs e) { QueryOrder cardorder; QueryOrderDir cardorderdir; QueryCardState cardstate; List<int> boxes; GetGUISelection(out boxes, out cardorder, out cardorderdir, out cardstate); cbReverseOrder.Enabled = cardorder != QueryOrder.None; } } }
//Copyright 2010 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. namespace System.Data.Services.Client { #region Namespaces. using System; using System.Collections.Generic; using System.Data.Services.Common; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; #endregion Namespaces. [DebuggerDisplay("{ElementTypeName}")] internal sealed class ClientType { internal readonly string ElementTypeName; internal readonly Type ElementType; internal readonly bool IsEntityType; internal readonly int KeyCount; #region static fields private static readonly Dictionary<Type, ClientType> types = new Dictionary<Type, ClientType>(EqualityComparer<Type>.Default); private static readonly Dictionary<TypeName, Type> namedTypes = new Dictionary<TypeName, Type>(new TypeNameEqualityComparer()); #endregion #if ASTORIA_OPEN_OBJECT private readonly ClientProperty openProperties; #endif private ArraySet<ClientProperty> properties; private ClientProperty mediaDataMember; private bool mediaLinkEntry; private EpmSourceTree epmSourceTree; private EpmTargetTree epmTargetTree; private ClientType(Type type, string typeName, bool skipSettableCheck) { Debug.Assert(null != type, "null type"); Debug.Assert(!String.IsNullOrEmpty(typeName), "empty typeName"); this.ElementTypeName = typeName; this.ElementType = Nullable.GetUnderlyingType(type) ?? type; #if ASTORIA_OPEN_OBJECT string openObjectPropertyName = null; #endif if (!ClientConvert.IsKnownType(this.ElementType)) { #if ASTORIA_OPEN_OBJECT #region OpenObject determined by walking type hierarchy and looking for [OpenObjectAttribute("PropertyName")] Type openObjectDeclared = this.ElementType; for (Type tmp = openObjectDeclared; (null != tmp) && (typeof(object) != tmp); tmp = tmp.BaseType) { object[] attributes = openObjectDeclared.GetCustomAttributes(typeof(OpenObjectAttribute), false); if (1 == attributes.Length) { if (null != openObjectPropertyName) { throw Error.InvalidOperation(Strings.Clienttype_MultipleOpenProperty(this.ElementTypeName)); } openObjectPropertyName = ((OpenObjectAttribute)attributes[0]).OpenObjectPropertyName; openObjectDeclared = tmp; } } #endregion #endif Type keyPropertyDeclaredType = null; bool isEntity = type.GetCustomAttributes(true).OfType<DataServiceEntityAttribute>().Any(); DataServiceKeyAttribute dska = type.GetCustomAttributes(true).OfType<DataServiceKeyAttribute>().FirstOrDefault(); foreach (PropertyInfo pinfo in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { Type ptype = pinfo.PropertyType; ptype = Nullable.GetUnderlyingType(ptype) ?? ptype; if (ptype.IsPointer || (ptype.IsArray && (typeof(byte[]) != ptype) && typeof(char[]) != ptype) || (typeof(IntPtr) == ptype) || (typeof(UIntPtr) == ptype)) { continue; } Debug.Assert(!ptype.ContainsGenericParameters, "remove when test case is found that encounters this"); if (pinfo.CanRead && (!ptype.IsValueType || pinfo.CanWrite) && !ptype.ContainsGenericParameters && (0 == pinfo.GetIndexParameters().Length)) { #region IsKey? bool keyProperty = dska != null ? dska.KeyNames.Contains(pinfo.Name) : false; if (keyProperty) { if (null == keyPropertyDeclaredType) { keyPropertyDeclaredType = pinfo.DeclaringType; } else if (keyPropertyDeclaredType != pinfo.DeclaringType) { throw Error.InvalidOperation(Strings.ClientType_KeysOnDifferentDeclaredType(this.ElementTypeName)); } if (!ClientConvert.IsKnownType(ptype)) { throw Error.InvalidOperation(Strings.ClientType_KeysMustBeSimpleTypes(this.ElementTypeName)); } this.KeyCount++; } #endregion #if ASTORIA_OPEN_OBJECT #region IsOpenObjectProperty? bool openProperty = (openObjectPropertyName == pinfo.Name) && typeof(IDictionary<string, object>).IsAssignableFrom(ptype); Debug.Assert(keyProperty != openProperty || (!keyProperty && !openProperty), "key can't be open type"); #endregion ClientProperty property = new ClientProperty(pinfo, ptype, keyProperty, openProperty); if (!property.OpenObjectProperty) #else ClientProperty property = new ClientProperty(pinfo, ptype, keyProperty); #endif { if (!this.properties.Add(property, ClientProperty.NameEquality)) { int shadow = this.IndexOfProperty(property.PropertyName); if (!property.DeclaringType.IsAssignableFrom(this.properties[shadow].DeclaringType)) { this.properties.RemoveAt(shadow); this.properties.Add(property, null); } } } #if ASTORIA_OPEN_OBJECT else { if (pinfo.DeclaringType == openObjectDeclared) { this.openProperties = property; } } #endif } } #region No KeyAttribute, discover key by name pattern { DeclaringType.Name+ID, ID } if (null == keyPropertyDeclaredType) { ClientProperty key = null; for (int i = this.properties.Count - 1; 0 <= i; --i) { string propertyName = this.properties[i].PropertyName; if (propertyName.EndsWith("ID", StringComparison.Ordinal)) { string declaringTypeName = this.properties[i].DeclaringType.Name; if ((propertyName.Length == (declaringTypeName.Length + 2)) && propertyName.StartsWith(declaringTypeName, StringComparison.Ordinal)) { if ((null == keyPropertyDeclaredType) || this.properties[i].DeclaringType.IsAssignableFrom(keyPropertyDeclaredType)) { keyPropertyDeclaredType = this.properties[i].DeclaringType; key = this.properties[i]; } } else if ((null == keyPropertyDeclaredType) && (2 == propertyName.Length)) { keyPropertyDeclaredType = this.properties[i].DeclaringType; key = this.properties[i]; } } } if (null != key) { Debug.Assert(0 == this.KeyCount, "shouldn't have a key yet"); key.KeyProperty = true; this.KeyCount++; } } else if (this.KeyCount != dska.KeyNames.Count) { var m = (from string a in dska.KeyNames where null == (from b in this.properties where b.PropertyName == a select b).FirstOrDefault() select a).First<string>(); throw Error.InvalidOperation(Strings.ClientType_MissingProperty(this.ElementTypeName, m)); } #endregion this.IsEntityType = (null != keyPropertyDeclaredType) || isEntity; Debug.Assert(this.KeyCount == this.Properties.Where(k => k.KeyProperty).Count(), "KeyCount mismatch"); this.WireUpMimeTypeProperties(); this.CheckMediaLinkEntry(); if (!skipSettableCheck) { #if ASTORIA_OPEN_OBJECT if ((0 == this.properties.Count) && (null == this.openProperties)) #else if (0 == this.properties.Count) #endif { throw Error.InvalidOperation(Strings.ClientType_NoSettableFields(this.ElementTypeName)); } } } this.properties.TrimToSize(); this.properties.Sort<string>(ClientProperty.GetPropertyName, String.CompareOrdinal); #if ASTORIA_OPEN_OBJECT #region Validate OpenObjectAttribute was used if ((null != openObjectPropertyName) && (null == this.openProperties)) { throw Error.InvalidOperation(Strings.ClientType_MissingOpenProperty(this.ElementTypeName, openObjectPropertyName)); } Debug.Assert((null != openObjectPropertyName) == (null != this.openProperties), "OpenProperties mismatch"); #endregion #endif this.BuildEpmInfo(type); } internal ArraySet<ClientProperty> Properties { get { return this.properties; } } internal ClientProperty MediaDataMember { get { return this.mediaDataMember; } } internal bool IsMediaLinkEntry { get { return this.mediaLinkEntry; } } internal EpmSourceTree EpmSourceTree { get { if (this.epmSourceTree == null) { this.epmTargetTree = new EpmTargetTree(); this.epmSourceTree = new EpmSourceTree(this.epmTargetTree); } return this.epmSourceTree; } } internal EpmTargetTree EpmTargetTree { get { Debug.Assert(this.epmTargetTree != null, "Must have valid target tree"); return this.epmTargetTree; } } internal bool HasEntityPropertyMappings { get { return this.epmSourceTree != null; } } internal bool EpmIsV1Compatible { get { return !this.HasEntityPropertyMappings || this.EpmTargetTree.IsV1Compatible; } } internal static bool CanAssignNull(Type type) { Debug.Assert(type != null, "type != null"); return !type.IsValueType || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>))); } internal static bool CheckElementTypeIsEntity(Type t) { t = TypeSystem.GetElementType(t); t = Nullable.GetUnderlyingType(t) ?? t; return ClientType.Create(t, false).IsEntityType; } internal static ClientType Create(Type type) { return Create(type, true); } internal static ClientType Create(Type type, bool expectModelType) { ClientType clientType; lock (ClientType.types) { ClientType.types.TryGetValue(type, out clientType); } if (null == clientType) { if (CommonUtil.IsUnsupportedType(type)) { throw new InvalidOperationException(Strings.ClientType_UnsupportedType(type)); } bool skipSettableCheck = !expectModelType; clientType = new ClientType(type, type.ToString(), skipSettableCheck); if (expectModelType) { lock (ClientType.types) { ClientType existing; if (ClientType.types.TryGetValue(type, out existing)) { clientType = existing; } else { ClientType.types.Add(type, clientType); } } } } return clientType; } #if !ASTORIA_LIGHT internal static Type ResolveFromName(string wireName, Type userType) #else internal static Type ResolveFromName(string wireName, Type userType, Type contextType) #endif { Type foundType; TypeName typename; typename.Type = userType; typename.Name = wireName; bool foundInCache; lock (ClientType.namedTypes) { foundInCache = ClientType.namedTypes.TryGetValue(typename, out foundType); } if (!foundInCache) { string name = wireName; int index = wireName.LastIndexOf('.'); if ((0 <= index) && (index < wireName.Length - 1)) { name = wireName.Substring(index + 1); } if (userType.Name == name) { foundType = userType; } else { #if !ASTORIA_LIGHT foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) #else foreach (Assembly assembly in new Assembly[] { userType.Assembly, contextType.Assembly }.Distinct()) #endif { Type found = assembly.GetType(wireName, false); ResolveSubclass(name, userType, found, ref foundType); if (null == found) { Type[] types = null; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException) { } if (null != types) { foreach (Type t in types) { ResolveSubclass(name, userType, t, ref foundType); } } } } } lock (ClientType.namedTypes) { ClientType.namedTypes[typename] = foundType; } } return foundType; } internal static Type GetImplementationType(Type propertyType, Type genericTypeDefinition) { if (IsConstructedGeneric(propertyType, genericTypeDefinition)) { return propertyType; } else { Type implementationType = null; foreach (Type interfaceType in propertyType.GetInterfaces()) { if (IsConstructedGeneric(interfaceType, genericTypeDefinition)) { if (null == implementationType) { implementationType = interfaceType; } else { throw Error.NotSupported(Strings.ClientType_MultipleImplementationNotSupported); } } } return implementationType; } } internal static MethodInfo GetAddToCollectionMethod(Type collectionType, out Type type) { return GetCollectionMethod(collectionType, typeof(ICollection<>), "Add", out type); } internal static MethodInfo GetRemoveFromCollectionMethod(Type collectionType, out Type type) { return GetCollectionMethod(collectionType, typeof(ICollection<>), "Remove", out type); } internal static MethodInfo GetCollectionMethod(Type propertyType, Type genericTypeDefinition, string methodName, out Type type) { Debug.Assert(null != propertyType, "null propertyType"); Debug.Assert(null != genericTypeDefinition, "null genericTypeDefinition"); Debug.Assert(genericTypeDefinition.IsGenericTypeDefinition, "!IsGenericTypeDefinition"); type = null; Type implementationType = GetImplementationType(propertyType, genericTypeDefinition); if (null != implementationType) { Type[] genericArguments = implementationType.GetGenericArguments(); MethodInfo methodInfo = implementationType.GetMethod(methodName); Debug.Assert(null != methodInfo, "should have found the method"); #if DEBUG Debug.Assert(null != genericArguments, "null genericArguments"); ParameterInfo[] parameters = methodInfo.GetParameters(); if (0 < parameters.Length) { Debug.Assert(genericArguments.Length == parameters.Length, "genericArguments don't match parameters"); for (int i = 0; i < genericArguments.Length; ++i) { Debug.Assert(genericArguments[i] == parameters[i].ParameterType, "parameter doesn't match generic argument"); } } #endif type = genericArguments[genericArguments.Length - 1]; return methodInfo; } return null; } internal object CreateInstance() { return Activator.CreateInstance(this.ElementType); } internal ClientProperty GetProperty(string propertyName, bool ignoreMissingProperties) { int index = this.IndexOfProperty(propertyName); if (0 <= index) { return this.properties[index]; } #if ASTORIA_OPEN_OBJECT else if (null != this.openProperties) { return this.openProperties; } #endif else if (!ignoreMissingProperties) { throw Error.InvalidOperation(Strings.ClientType_MissingProperty(this.ElementTypeName, propertyName)); } return null; } private static bool IsConstructedGeneric(Type type, Type genericTypeDefinition) { Debug.Assert(type != null, "type != null"); Debug.Assert(!type.ContainsGenericParameters, "remove when test case is found that encounters this"); Debug.Assert(genericTypeDefinition != null, "genericTypeDefinition != null"); return type.IsGenericType && (type.GetGenericTypeDefinition() == genericTypeDefinition) && !type.ContainsGenericParameters; } private static void ResolveSubclass(string wireClassName, Type userType, Type type, ref Type existing) { if ((null != type) && type.IsVisible && (wireClassName == type.Name) && userType.IsAssignableFrom(type)) { if (null != existing) { throw Error.InvalidOperation(Strings.ClientType_Ambiguous(wireClassName, userType)); } existing = type; } } private void BuildEpmInfo(Type type) { if (type.BaseType != null && type.BaseType != typeof(object)) { this.BuildEpmInfo(type.BaseType); } foreach (EntityPropertyMappingAttribute epmAttr in type.GetCustomAttributes(typeof(EntityPropertyMappingAttribute), false)) { this.BuildEpmInfo(epmAttr, type); } } private void BuildEpmInfo(EntityPropertyMappingAttribute epmAttr, Type definingType) { this.EpmSourceTree.Add(new EntityPropertyMappingInfo(epmAttr, definingType, this)); } private int IndexOfProperty(string propertyName) { return this.properties.IndexOf(propertyName, ClientProperty.GetPropertyName, String.Equals); } private void WireUpMimeTypeProperties() { MimeTypePropertyAttribute attribute = (MimeTypePropertyAttribute)this.ElementType.GetCustomAttributes(typeof(MimeTypePropertyAttribute), true).SingleOrDefault(); if (null != attribute) { int dataIndex, mimeTypeIndex; if ((0 > (dataIndex = this.IndexOfProperty(attribute.DataPropertyName))) || (0 > (mimeTypeIndex = this.IndexOfProperty(attribute.MimeTypePropertyName)))) { throw Error.InvalidOperation(Strings.ClientType_MissingMimeTypeProperty(attribute.DataPropertyName, attribute.MimeTypePropertyName)); } Debug.Assert(0 <= dataIndex, "missing data property"); Debug.Assert(0 <= mimeTypeIndex, "missing mime type property"); this.Properties[dataIndex].MimeTypeProperty = this.Properties[mimeTypeIndex]; } } private void CheckMediaLinkEntry() { object[] attributes = this.ElementType.GetCustomAttributes(typeof(MediaEntryAttribute), true); if (attributes != null && attributes.Length > 0) { Debug.Assert(attributes.Length == 1, "The AttributeUsage in the attribute definition should be preventing more than 1 per property"); MediaEntryAttribute mediaEntryAttribute = (MediaEntryAttribute)attributes[0]; this.mediaLinkEntry = true; int index = this.IndexOfProperty(mediaEntryAttribute.MediaMemberName); if (index < 0) { throw Error.InvalidOperation(Strings.ClientType_MissingMediaEntryProperty( mediaEntryAttribute.MediaMemberName)); } this.mediaDataMember = this.properties[index]; } attributes = this.ElementType.GetCustomAttributes(typeof(HasStreamAttribute), true); if (attributes != null && attributes.Length > 0) { Debug.Assert(attributes.Length == 1, "The AttributeUsage in the attribute definition should be preventing more than 1 per property"); this.mediaLinkEntry = true; } } private struct TypeName { internal Type Type; internal string Name; } [DebuggerDisplay("{PropertyName}")] internal sealed class ClientProperty { internal readonly string PropertyName; internal readonly Type NullablePropertyType; internal readonly Type PropertyType; internal readonly Type CollectionType; internal readonly bool IsKnownType; #if ASTORIA_OPEN_OBJECT internal readonly bool OpenObjectProperty; #endif private readonly MethodInfo propertyGetter; private readonly MethodInfo propertySetter; private readonly MethodInfo setMethod; private readonly MethodInfo addMethod; private readonly MethodInfo removeMethod; private readonly MethodInfo containsMethod; private bool keyProperty; private ClientProperty mimeTypeProperty; #if ASTORIA_OPEN_OBJECT internal ClientProperty(PropertyInfo property, Type propertyType, bool keyProperty, bool openObjectProperty) #else internal ClientProperty(PropertyInfo property, Type propertyType, bool keyProperty) #endif { Debug.Assert(null != property, "null property"); Debug.Assert(null != propertyType, "null propertyType"); Debug.Assert(null == Nullable.GetUnderlyingType(propertyType), "should already have been denullified"); this.PropertyName = property.Name; this.NullablePropertyType = property.PropertyType; this.PropertyType = propertyType; this.propertyGetter = property.GetGetMethod(); this.propertySetter = property.GetSetMethod(); this.keyProperty = keyProperty; #if ASTORIA_OPEN_OBJECT this.OpenObjectProperty = openObjectProperty; #endif this.IsKnownType = ClientConvert.IsKnownType(propertyType); if (!this.IsKnownType) { this.setMethod = GetCollectionMethod(this.PropertyType, typeof(IDictionary<,>), "set_Item", out this.CollectionType); if (null == this.setMethod) { this.containsMethod = GetCollectionMethod(this.PropertyType, typeof(ICollection<>), "Contains", out this.CollectionType); this.addMethod = GetAddToCollectionMethod(this.PropertyType, out this.CollectionType); this.removeMethod = GetRemoveFromCollectionMethod(this.PropertyType, out this.CollectionType); } } Debug.Assert(!this.keyProperty || this.IsKnownType, "can't have an random type as key"); } internal Type DeclaringType { get { return this.propertyGetter.DeclaringType; } } internal bool KeyProperty { get { return this.keyProperty; } set { this.keyProperty = value; } } internal ClientProperty MimeTypeProperty { get { return this.mimeTypeProperty; } set { this.mimeTypeProperty = value; } } internal static bool GetKeyProperty(ClientProperty x) { return x.KeyProperty; } internal static string GetPropertyName(ClientProperty x) { return x.PropertyName; } internal static bool NameEquality(ClientProperty x, ClientProperty y) { return String.Equals(x.PropertyName, y.PropertyName); } internal object GetValue(object instance) { Debug.Assert(null != instance, "null instance"); Debug.Assert(null != this.propertyGetter, "null propertyGetter"); return this.propertyGetter.Invoke(instance, null); } internal void RemoveValue(object instance, object value) { Debug.Assert(null != instance, "null instance"); Debug.Assert(null != this.removeMethod, "missing removeMethod"); Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected collection instance"); Debug.Assert((null == value) || this.CollectionType.IsAssignableFrom(value.GetType()), "unexpected collection value to add"); this.removeMethod.Invoke(instance, new object[] { value }); } #if ASTORIA_OPEN_OBJECT internal void SetValue(object instance, object value, string propertyName, ref object openProperties, bool allowAdd) #else internal void SetValue(object instance, object value, string propertyName, bool allowAdd) #endif { Debug.Assert(null != instance, "null instance"); if (null != this.setMethod) { #if ASTORIA_OPEN_OBJECT if (this.OpenObjectProperty) { if (null == openProperties) { if (null == (openProperties = this.propertyGetter.Invoke(instance, null))) { throw Error.NotSupported(Strings.ClientType_NullOpenProperties(this.PropertyName)); } } ((IDictionary<string, object>)openProperties)[propertyName] = value; } else #endif { Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected dictionary instance"); Debug.Assert((null == value) || this.CollectionType.IsAssignableFrom(value.GetType()), "unexpected dictionary value to set"); this.setMethod.Invoke(instance, new object[] { propertyName, value }); } } else if (allowAdd && (null != this.addMethod)) { Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected collection instance"); Debug.Assert((null == value) || this.CollectionType.IsAssignableFrom(value.GetType()), "unexpected collection value to add"); if (!(bool)this.containsMethod.Invoke(instance, new object[] { value })) { this.addMethod.Invoke(instance, new object[] { value }); } } else if (null != this.propertySetter) { Debug.Assert((null == value) || this.PropertyType.IsAssignableFrom(value.GetType()), "unexpected property value to set"); this.propertySetter.Invoke(instance, new object[] { value }); } else { throw Error.InvalidOperation(Strings.ClientType_MissingProperty(value.GetType().ToString(), propertyName)); } } } private sealed class TypeNameEqualityComparer : IEqualityComparer<TypeName> { public bool Equals(TypeName x, TypeName y) { return (x.Type == y.Type && x.Name == y.Name); } public int GetHashCode(TypeName obj) { return obj.Type.GetHashCode() ^ obj.Name.GetHashCode(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; namespace System.Reflection { #if CORERT public // Needs to be public so that Reflection.Core can see it. #else internal #endif static class SignatureTypeExtensions { /// <summary> /// This is semantically identical to /// /// parameter.ParameterType == pattern.TryResolveAgainstGenericMethod(parameter.Member) /// /// but without the allocation overhead of TryResolve. /// </summary> public static bool MatchesParameterTypeExactly(this Type pattern, ParameterInfo parameter) { if (pattern is SignatureType signatureType) return signatureType.MatchesExactly(parameter.ParameterType); else return pattern == (object)(parameter.ParameterType); } /// <summary> /// This is semantically identical to /// /// actual == pattern.TryResolveAgainstGenericMethod(parameterMember) /// /// but without the allocation overhead of TryResolve. /// </summary> internal static bool MatchesExactly(this SignatureType pattern, Type actual) { if (pattern.IsSZArray) { return actual.IsSZArray && pattern.ElementType.MatchesExactly(actual.GetElementType()); } else if (pattern.IsVariableBoundArray) { return actual.IsVariableBoundArray && pattern.GetArrayRank() == actual.GetArrayRank() && pattern.ElementType.MatchesExactly(actual.GetElementType()); } else if (pattern.IsByRef) { return actual.IsByRef && pattern.ElementType.MatchesExactly(actual.GetElementType()); } else if (pattern.IsPointer) { return actual.IsPointer && pattern.ElementType.MatchesExactly(actual.GetElementType()); } else if (pattern.IsConstructedGenericType) { if (!actual.IsConstructedGenericType) return false; if (!(pattern.GetGenericTypeDefinition() == actual.GetGenericTypeDefinition())) return false; Type[] patternGenericTypeArguments = pattern.GenericTypeArguments; Type[] actualGenericTypeArguments = actual.GenericTypeArguments; int count = patternGenericTypeArguments.Length; if (count != actualGenericTypeArguments.Length) return false; for (int i = 0; i < count; i++) { Type patternGenericTypeArgument = patternGenericTypeArguments[i]; if (patternGenericTypeArgument is SignatureType signatureType) { if (!signatureType.MatchesExactly(actualGenericTypeArguments[i])) return false; } else { if (patternGenericTypeArgument != actualGenericTypeArguments[i]) return false; } } return true; } else if (pattern.IsGenericMethodParameter) { if (!actual.IsGenericMethodParameter) return false; if (pattern.GenericParameterPosition != actual.GenericParameterPosition) return false; return true; } else { return false; } } /// <summary> /// Translates a SignatureType into its equivalent resolved Type by recursively substituting all generic parameter references /// with its corresponding generic parameter definition. This is slow so MatchesExactly or MatchesParameterTypeExactly should be /// substituted instead whenever possible. This is only used by the DefaultBinder when its fast-path checks have been exhausted and /// it needs to call non-trivial methods like IsAssignableFrom which SignatureTypes will never support. /// /// Because this method is used to eliminate method candidates in a GetMethod() lookup, it is entirely possible that the Type /// might not be creatable due to conflicting generic constraints. Since this merely implies that this candidate is not /// the method we're looking for, we return null rather than let the TypeLoadException bubble up. The DefaultBinder will catch /// the null and continue its search for a better candidate. /// </summary> internal static Type TryResolveAgainstGenericMethod(this SignatureType signatureType, MethodInfo genericMethod) { return signatureType.TryResolve(genericMethod.GetGenericArguments()); } private static Type TryResolve(this SignatureType signatureType, Type[] genericMethodParameters) { if (signatureType.IsSZArray) { return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeArrayType(); } else if (signatureType.IsVariableBoundArray) { return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeArrayType(signatureType.GetArrayRank()); } else if (signatureType.IsByRef) { return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeByRefType(); } else if (signatureType.IsPointer) { return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakePointerType(); } else if (signatureType.IsConstructedGenericType) { Type[] genericTypeArguments = signatureType.GenericTypeArguments; int count = genericTypeArguments.Length; Type[] newGenericTypeArguments = new Type[count]; for (int i = 0; i < count; i++) { Type genericTypeArgument = genericTypeArguments[i]; if (genericTypeArgument is SignatureType signatureGenericTypeArgument) { newGenericTypeArguments[i] = signatureGenericTypeArgument.TryResolve(genericMethodParameters); if (newGenericTypeArguments[i] == null) return null; } else { newGenericTypeArguments[i] = genericTypeArgument; } } return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments); } else if (signatureType.IsGenericMethodParameter) { int position = signatureType.GenericParameterPosition; if (position >= genericMethodParameters.Length) return null; return genericMethodParameters[position]; } else { return null; } } private static Type TryMakeArrayType(this Type type) { try { return type.MakeArrayType(); } catch { return null; } } private static Type TryMakeArrayType(this Type type, int rank) { try { return type.MakeArrayType(rank); } catch { return null; } } private static Type TryMakeByRefType(this Type type) { try { return type.MakeByRefType(); } catch { return null; } } private static Type TryMakePointerType(this Type type) { try { return type.MakePointerType(); } catch { return null; } } private static Type TryMakeGenericType(this Type type, Type[] instantiation) { try { return type.MakeGenericType(instantiation); } catch { return null; } } } }
/* * 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.Collections; using PdxTests; using System.Reflection; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using DUnitFramework; using Client; using Region = IRegion<object, object>; [TestFixture] [Category("group4")] [Category("unicast_only")] [Category("generics")] internal class ThinClientPdxTests2 : ThinClientRegionSteps { private static bool m_useWeakHashMap = false; #region Private members private UnitProcess m_client1, m_client2; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); return new ClientBase[] {m_client1, m_client2}; } [TestFixtureTearDown] public override void EndTests() { CacheHelper.StopJavaServers(); base.EndTests(); } [TearDown] public override void EndTest() { try { m_client1.Call(DestroyRegions); m_client2.Call(DestroyRegions); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } finally { CacheHelper.StopJavaServers(); CacheHelper.StopJavaLocators(); } base.EndTest(); } private void cleanup() { { CacheHelper.SetExtraPropertiesFile(null); if (m_clients != null) { foreach (var client in m_clients) { try { client.Call(CacheHelper.Close); } catch (System.Runtime.Remoting.RemotingException) { } catch (System.Net.Sockets.SocketException) { } } } CacheHelper.Close(); } } private Assembly m_pdxVesionOneAsm; private Assembly m_pdxVesionTwoAsm; private IPdxSerializable registerPdxUIV1() { var pt = m_pdxVesionOneAsm.GetType("PdxVersionTests.PdxTypesIgnoreUnreadFields"); var ob = pt.InvokeMember("CreateDeserializable", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, null); return (IPdxSerializable) ob; } private void initializePdxUIAssemblyOne(bool useWeakHashmap) { m_pdxVesionOneAsm = Assembly.LoadFrom("PdxVersion1Lib.dll"); CacheHelper.DCache.TypeRegistry.RegisterPdxType(registerPdxUIV1); var pt = m_pdxVesionOneAsm.GetType("PdxVersionTests.PdxTypesIgnoreUnreadFields"); var ob = pt.InvokeMember("Reset", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] {useWeakHashmap}); } private void putV1PdxUI(bool useWeakHashmap) { initializePdxUIAssemblyOne(useWeakHashmap); var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var pt = m_pdxVesionOneAsm.GetType("PdxVersionTests.PdxTypesIgnoreUnreadFields"); var np = pt.InvokeMember("PdxTypesIgnoreUnreadFields", BindingFlags.CreateInstance, null, null, null); var pRet = region0[1]; region0[1] = pRet; Console.WriteLine(np); Console.WriteLine(pRet); //Assert.AreEqual(np, pRet); } private IPdxSerializable registerPdxUIV2() { var pt = m_pdxVesionTwoAsm.GetType("PdxVersionTests.PdxTypesIgnoreUnreadFields"); var ob = pt.InvokeMember("CreateDeserializable", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, null); return (IPdxSerializable) ob; } private void initializePdxUIAssemblyTwo(bool useWeakHashmap) { m_pdxVesionTwoAsm = Assembly.LoadFrom("PdxVersion2Lib.dll"); CacheHelper.DCache.TypeRegistry.RegisterPdxType(registerPdxUIV2); var pt = m_pdxVesionTwoAsm.GetType("PdxVersionTests.PdxTypesIgnoreUnreadFields"); var ob = pt.InvokeMember("Reset", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] {useWeakHashmap}); } private void putV2PdxUI(bool useWeakHashmap) { initializePdxUIAssemblyTwo(useWeakHashmap); var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var pt = m_pdxVesionTwoAsm.GetType("PdxVersionTests.PdxTypesIgnoreUnreadFields"); var np = pt.InvokeMember("PdxTypesIgnoreUnreadFields", BindingFlags.CreateInstance, null, null, null); region0[1] = np; var pRet = region0[1]; Console.WriteLine(np); Console.WriteLine(pRet); Assert.AreEqual(np, pRet); region0[1] = pRet; Console.WriteLine(" " + pRet); } private void getV2PdxUI() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var pt = m_pdxVesionTwoAsm.GetType("PdxVersionTests.PdxTypesIgnoreUnreadFields"); var np = pt.InvokeMember("PdxTypesIgnoreUnreadFields", BindingFlags.CreateInstance, null, null, null); var pRet = region0[1]; Console.WriteLine(np); Console.WriteLine(pRet); Assert.AreEqual(np, pRet); } private void runPdxIgnoreUnreadFieldTest() { CacheHelper.SetupJavaServers(true, "cacheserver.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CreateTCRegions_Pool_PDX, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepOne (pool locators) complete."); m_client2.Call(CreateTCRegions_Pool_PDX, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepTwo (pool locators) complete."); m_client2.Call(putV2PdxUI, m_useWeakHashMap); Util.Log("StepThree complete."); m_client1.Call(putV1PdxUI, m_useWeakHashMap); Util.Log("StepFour complete."); m_client2.Call(getV2PdxUI); Util.Log("StepFive complete."); m_client1.Call(Close); Util.Log("Client 1 closed"); m_client2.Call(Close); //Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void putFromPool1() { CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxTypes1.CreateDeserializable); Util.Log("Put from pool-1 started"); var region0 = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]); region0[1] = new PdxTypes1(); region0[2] = new PdxType(); Util.Log("Put from pool-1 Completed"); } private void putFromPool2() { Util.Log("Put from pool-21 started"); var region0 = CacheHelper.GetVerifyRegion<object, object>(RegionNames[1]); region0[1] = new PdxTypes1(); region0[2] = new PdxType(); var ret = region0[1]; ret = region0[2]; Util.Log("Put from pool-2 completed"); var pdxIds = CacheHelper.DCache.GetPdxTypeRegistry().testGetNumberOfPdxIds(); Assert.AreEqual(3, pdxIds); } private void runMultipleDSTest() { Util.Log("Starting runMultipleDSTest. "); CacheHelper.SetupJavaServers(true, "cacheserverMDS1.xml", "cacheserverMDS2.xml"); CacheHelper.StartJavaLocator_MDS(1, "GFELOC", null, 1 /*ds id is one*/); Util.Log("Locator 1 started."); CacheHelper.StartJavaLocator_MDS(2, "GFELOC2", null, 2 /*ds id is one*/); Util.Log("Locator 2 started."); CacheHelper.StartJavaServerWithLocator_MDS(1, "GFECS1", 1); Util.Log("Server 1 started with locator 1."); CacheHelper.StartJavaServerWithLocator_MDS(2, "GFECS2", 2); Util.Log("Server 2 started with locator 2."); //client intialization /* * CreateTCRegion_Pool(string name, bool ack, bool caching, ICacheListener listener, string endpoints, string locators, string poolName, bool clientNotification, bool ssl, bool cloningEnabled) * */ m_client1.Call(CacheHelper.CreateTCRegion_Pool_MDS, RegionNames[0], true, false, CacheHelper.LocatorFirst, "__TESTPOOL1_", false, false, false); Util.Log("StepOne (pool-1 locators) complete. " + CacheHelper.LocatorFirst); m_client1.Call(CacheHelper.CreateTCRegion_Pool_MDS, RegionNames[1], false, false, CacheHelper.LocatorSecond, "__TESTPOOL2_", false, false, false); Util.Log("StepTwo (pool-2 locators) complete. " + CacheHelper.LocatorSecond); m_client1.Call(putFromPool1); m_client1.Call(putFromPool2); m_client1.Call(Close); Util.Log("Client 1 closed"); //m_client2.Call(Close); //Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.StopJavaLocator(2); Util.Log("Locator 2 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void initializePdxSerializer() { CacheHelper.DCache.TypeRegistry.PdxSerializer = new PdxSerializer(); //Serializable.RegisterTypeForPdxSerializer(SerializePdx1.CreateDeserializable); } private void doPutGetWithPdxSerializer() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); for (var i = 0; i < 10; i++) { object put = new SerializePdx1(true); ; region0[i] = put; var ret = region0[i]; Assert.AreEqual(put, ret); put = new SerializePdx2(true); region0[i + 10] = put; ret = region0[i + 10]; Assert.AreEqual(put, ret); put = new SerializePdx3(true, i % 2); region0[i + 20] = put; ret = region0[i + 20]; Assert.AreEqual(put, ret); } } private void doGetWithPdxSerializerC2() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var sp3Even = new SerializePdx3(true, 0); var sp3Odd = new SerializePdx3(true, 1); for (var i = 0; i < 10; i++) { object local = new SerializePdx1(true); ; var ret = region0[i]; Assert.AreEqual(local, ret); ret = region0[i + 10]; Assert.AreEqual(new SerializePdx2(true), ret); ret = region0[i + 20]; if (i % 2 == 0) { Assert.AreEqual(ret, sp3Even); Assert.AreNotEqual(ret, sp3Odd); } else { Assert.AreEqual(ret, sp3Odd); Assert.AreNotEqual(ret, sp3Even); } } } private void doQueryTest() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); for (var i = 0; i < 10; i++) { var result = region0.Query<object>("i1 = " + i); Util.Log(" query result size " + result.Size); } var result2 = region0.Query<object>("1 = 1"); Util.Log(" query result size " + result2.Size); //private Address[] _addressArray; //private int arrayCount = 10; //private ArrayList _addressList; //private Address _address; //private Hashtable _hashTable; //var qs = PoolManager/*<object, object>*/.Find("__TESTPOOL1_").GetQueryService(); //Query<object> qry = qs.NewQuery<object>("select _addressArray from /" + m_regionNames[0] + " where arrayCount = 10"); //ISelectResults<object> results = qry.Execute(); //Assert.Greater(results.Size, 5, "query should have result"); //IEnumerator<object> ie = results.GetEnumerator(); //Address[] ad; //while (ie.MoveNext()) //{ // Address[] ar = (Address[])ie.Current; // Assert.AreEqual(ar.Length, 10, "Array size should be 10"); //} } private void runPdxSerializerTest() { Util.Log("Starting iteration for pool locator runPdxSerializerTest"); CacheHelper.SetupJavaServers(true, "cacheserver.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CreateTCRegions_Pool_PDX, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepOne (pool locators) complete."); m_client2.Call(CreateTCRegions_Pool_PDX, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepTwo (pool locators) complete."); m_client1.Call(initializePdxSerializer); m_client2.Call(initializePdxSerializer); Util.Log("StepThree complete."); m_client1.Call(doPutGetWithPdxSerializer); Util.Log("StepFour complete."); m_client2.Call(doGetWithPdxSerializerC2); Util.Log("StepFive complete."); m_client1.Call(Close); Util.Log("Client 1 closed"); m_client2.Call(Close); //Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void initializeReflectionPdxSerializer() { CacheHelper.DCache.TypeRegistry.PdxSerializer = new AutoSerializerEx(); //Serializable.RegisterTypeForPdxSerializer(SerializePdx1.CreateDeserializable); } private void doPutGetWithPdxSerializerR() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); for (var i = 0; i < 10; i++) { object put = new SerializePdx1(true); ; region0[i] = put; var ret = region0[i]; Assert.AreEqual(put, ret); put = new SerializePdx2(true); region0[i + 10] = put; ret = region0[i + 10]; Assert.AreEqual(put, ret); put = new PdxTypesReflectionTest(true); region0[i + 20] = put; ret = region0[i + 20]; Assert.AreEqual(put, ret); put = new SerializePdx3(true, i % 2); region0[i + 30] = put; ret = region0[i + 30]; Assert.AreEqual(put, ret); put = new SerializePdx4(true); region0[i + 40] = put; ret = region0[i + 40]; Assert.AreEqual(put, ret); var p1 = region0[i + 30]; var p2 = region0[i + 40]; Assert.AreNotEqual(p1, p2, "This should NOt be equals"); var pft = new PdxFieldTest(true); region0[i + 50] = pft; ret = region0[i + 50]; Assert.AreNotEqual(pft, ret); pft.NotInclude = "default_value"; Assert.AreEqual(pft, ret); } IDictionary<object, object> putall = new Dictionary<object, object>(); putall.Add(100, new SerializePdx3(true, 0)); putall.Add(200, new SerializePdx3(true, 1)); putall.Add(300, new SerializePdx4(true)); region0.PutAll(putall); } private void doGetWithPdxSerializerC2R() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); for (var i = 0; i < 10; i++) { object local = new SerializePdx1(true); ; var ret = region0[i]; Assert.AreEqual(local, ret); ret = region0[i + 10]; Assert.AreEqual(new SerializePdx2(true), ret); ret = region0[i + 20]; Assert.AreEqual(new PdxTypesReflectionTest(true), ret); var sp3Odd = new SerializePdx3(true, 1); var sp3Even = new SerializePdx3(true, 0); ret = region0[i + 30]; if (i % 2 == 0) { Assert.AreEqual(sp3Even, ret); Assert.AreNotEqual(sp3Odd, ret); } else { Assert.AreEqual(sp3Odd, ret); Assert.AreNotEqual(sp3Even, ret); } ret = region0[i + 40]; var sp4 = new SerializePdx4(true); Assert.AreEqual(sp4, ret); Console.WriteLine(sp4 + "===" + ret); var p1 = region0[i + 30]; var p2 = region0[i + 40]; Assert.AreNotEqual(p1, p2, "This should NOt be equal"); } IDictionary<object, object> getall = new Dictionary<object, object>(); ICollection<object> keys = new List<object>(); keys.Add(100); keys.Add(200); keys.Add(300); //putall.Add(100, new SerializePdx3(true, 0)); //putall.Add(200, new SerializePdx3(true, 1)); //putall.Add(300, new SerializePdx4(true)); region0.GetAll(keys, getall, null); Assert.AreEqual(getall[100], new SerializePdx3(true, 0)); Assert.AreEqual(getall[200], new SerializePdx3(true, 1)); Assert.AreEqual(getall[300], new SerializePdx4(true)); } private void runReflectionPdxSerializerTest() { Util.Log("Starting iteration for pool locator runPdxSerializerTest"); CacheHelper.SetupJavaServers(true, "cacheserver.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CreateTCRegions_Pool_PDX, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepOne (pool locators) complete."); m_client2.Call(CreateTCRegions_Pool_PDX, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepTwo (pool locators) complete."); m_client1.Call(initializeReflectionPdxSerializer); m_client2.Call(initializeReflectionPdxSerializer); Util.Log("StepThree complete."); m_client1.Call(doPutGetWithPdxSerializerR); Util.Log("StepFour complete."); m_client2.Call(doGetWithPdxSerializerC2R); Util.Log("StepFive complete."); m_client2.Call(doQueryTest); Util.Log("StepSix complete."); m_client1.Call(Close); Util.Log("Client 1 closed"); m_client2.Call(Close); //Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void dinitPdxSerializer() { CacheHelper.DCache.TypeRegistry.PdxSerializer = null; } private void doPutGetWithPdxSerializerNoReg() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); for (var i = 0; i < 10; i++) { object put = new SerializePdxNoRegister(true); ; region0[i] = put; var ret = region0[i]; Assert.AreEqual(put, ret); } } private void doGetWithPdxSerializerC2NoReg() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); for (var i = 0; i < 10; i++) { object local = new SerializePdxNoRegister(true); ; var ret = region0[i]; Assert.AreEqual(local, ret); } } private void runPdxTestWithNoTypeRegister() { Util.Log("Starting iteration for pool locator runPdxTestWithNoTypeRegister"); CacheHelper.SetupJavaServers(true, "cacheserver.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CreateTCRegions_Pool_PDX, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepOne (pool locators) complete."); m_client2.Call(CreateTCRegions_Pool_PDX, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepTwo (pool locators) complete."); Util.Log("StepThree complete."); m_client1.Call(dinitPdxSerializer); m_client2.Call(dinitPdxSerializer); m_client1.Call(doPutGetWithPdxSerializerNoReg); Util.Log("StepFour complete."); m_client2.Call(doGetWithPdxSerializerC2NoReg); Util.Log("StepFive complete."); m_client2.Call(doQueryTest); Util.Log("StepSix complete."); m_client1.Call(Close); Util.Log("Client 1 closed"); m_client2.Call(Close); //Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void pdxPut() { CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxType.CreateDeserializable); var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); region0["pdxput"] = new PdxType(); region0["pdxput2"] = new ParentPdx(1); } private void getObject() { CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxType.CreateDeserializable); var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var ret = (IPdxInstance) region0["pdxput"]; Assert.AreEqual(ret.GetClassName(), "PdxTests.PdxType", "PdxInstance.GetClassName should return PdxTests.PdxType"); var pt = (PdxType) ret.GetObject(); var ptorig = new PdxType(); Assert.AreEqual(pt, ptorig, "PdxInstance.getObject not equals original object."); ret = (IPdxInstance) region0["pdxput2"]; var pp = (ParentPdx) ret.GetObject(); var ppOrig = new ParentPdx(1); Assert.AreEqual(pp, ppOrig, "Parent pdx should be equal "); } private void verifyPdxInstanceEquals() { CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxType.CreateDeserializable); var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var ret = (IPdxInstance) region0["pdxput"]; var ret2 = (IPdxInstance) region0["pdxput"]; Assert.AreEqual(ret, ret2, "PdxInstance equals are not matched."); Util.Log(ret.ToString()); Util.Log(ret2.ToString()); ret = (IPdxInstance) region0["pdxput2"]; ret2 = (IPdxInstance) region0["pdxput2"]; Assert.AreEqual(ret, ret2, "parent pdx equals are not matched."); } private void verifyPdxInstanceHashcode() { CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxType.CreateDeserializable); var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var ret = (IPdxInstance) region0["pdxput"]; var dPdxType = new PdxType(); var pdxInstHashcode = ret.GetHashCode(); Util.Log("pdxinstance hash code " + pdxInstHashcode); var javaPdxHC = (int) region0["javaPdxHC"]; //TODO: need to fix this is beacause Enum hashcode is different in java and .net //Assert.AreEqual(javaPdxHC, pdxInstHashcode, "Pdxhashcode hashcode not matched with java padx hash code."); //for parent pdx ret = (IPdxInstance) region0["pdxput2"]; pdxInstHashcode = ret.GetHashCode(); Assert.AreEqual(javaPdxHC, pdxInstHashcode, "Pdxhashcode hashcode not matched with java padx hash code for Parentpdx class."); } private void accessPdxInstance() { CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxType.CreateDeserializable); var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var ret = (IPdxInstance) region0["pdxput"]; var dPdxType = new PdxType(); var retStr = (string) ret.GetField("m_string"); Assert.AreEqual(dPdxType.PString, retStr); PdxType.GenericValCompare((char) ret.GetField("m_char"), dPdxType.Char); var baa = (byte[][]) ret.GetField("m_byteByteArray"); PdxType.compareByteByteArray(baa, dPdxType.ByteByteArray); PdxType.GenericCompare((char[]) ret.GetField("m_charArray"), dPdxType.CharArray); var bl = (bool) ret.GetField("m_bool"); PdxType.GenericValCompare(bl, dPdxType.Bool); PdxType.GenericCompare((bool[]) ret.GetField("m_boolArray"), dPdxType.BoolArray); PdxType.GenericValCompare((sbyte) ret.GetField("m_byte"), dPdxType.Byte); PdxType.GenericCompare((byte[]) ret.GetField("m_byteArray"), dPdxType.ByteArray); var tmpl = (List<object>) ret.GetField("m_arraylist"); PdxType.compareCompareCollection(tmpl, dPdxType.Arraylist); var tmpM = (IDictionary<object, object>) ret.GetField("m_map"); if (tmpM.Count != dPdxType.Map.Count) throw new IllegalStateException("Not got expected value for type: " + dPdxType.Map.GetType().ToString()); var tmpH = (Hashtable) ret.GetField("m_hashtable"); if (tmpH.Count != dPdxType.Hashtable.Count) throw new IllegalStateException("Not got expected value for type: " + dPdxType.Hashtable.GetType().ToString()); var arrAl = (ArrayList) ret.GetField("m_vector"); if (arrAl.Count != dPdxType.Vector.Count) throw new IllegalStateException("Not got expected value for type: " + dPdxType.Vector.GetType().ToString()); var rmpChs = (CacheableHashSet) ret.GetField("m_chs"); if (rmpChs.Count != dPdxType.Chs.Count) throw new IllegalStateException("Not got expected value for type: " + dPdxType.Chs.GetType().ToString()); var rmpClhs = (CacheableLinkedHashSet) ret.GetField("m_clhs"); if (rmpClhs.Count != dPdxType.Clhs.Count) throw new IllegalStateException("Not got expected value for type: " + dPdxType.Clhs.GetType().ToString()); PdxType.GenericValCompare((string) ret.GetField("m_string"), dPdxType.String); PdxType.compareData((DateTime) ret.GetField("m_dateTime"), dPdxType.DateTime); PdxType.GenericValCompare((double) ret.GetField("m_double"), dPdxType.Double); PdxType.GenericCompare((long[]) ret.GetField("m_longArray"), dPdxType.LongArray); PdxType.GenericCompare((short[]) ret.GetField("m_int16Array"), dPdxType.Int16Array); PdxType.GenericValCompare((sbyte) ret.GetField("m_sbyte"), dPdxType.Sbyte); PdxType.GenericCompare((byte[]) ret.GetField("m_sbyteArray"), dPdxType.SbyteArray); PdxType.GenericCompare((string[]) ret.GetField("m_stringArray"), dPdxType.StringArray); PdxType.GenericValCompare((short) ret.GetField("m_uint16"), dPdxType.Uint16); PdxType.GenericValCompare((int) ret.GetField("m_uint32"), dPdxType.Uint32); PdxType.GenericValCompare((long) ret.GetField("m_ulong"), dPdxType.Ulong); PdxType.GenericCompare((int[]) ret.GetField("m_uint32Array"), dPdxType.Uint32Array); PdxType.GenericCompare((double[]) ret.GetField("m_doubleArray"), dPdxType.DoubleArray); PdxType.GenericValCompare((float) ret.GetField("m_float"), dPdxType.Float); PdxType.GenericCompare((float[]) ret.GetField("m_floatArray"), dPdxType.FloatArray); PdxType.GenericValCompare((short) ret.GetField("m_int16"), dPdxType.Int16); PdxType.GenericValCompare((int) ret.GetField("m_int32"), dPdxType.Int32); PdxType.GenericValCompare((long) ret.GetField("m_long"), dPdxType.Long); PdxType.GenericCompare((int[]) ret.GetField("m_int32Array"), dPdxType.Int32Array); PdxType.GenericCompare((long[]) ret.GetField("m_ulongArray"), dPdxType.UlongArray); PdxType.GenericCompare((short[]) ret.GetField("m_uint16Array"), dPdxType.Uint16Array); var retbA = (byte[]) ret.GetField("m_byte252"); if (retbA.Length != 252) throw new Exception("Array len 252 not found"); retbA = (byte[]) ret.GetField("m_byte253"); if (retbA.Length != 253) throw new Exception("Array len 253 not found"); retbA = (byte[]) ret.GetField("m_byte65535"); if (retbA.Length != 65535) throw new Exception("Array len 65535 not found"); retbA = (byte[]) ret.GetField("m_byte65536"); if (retbA.Length != 65536) throw new Exception("Array len 65536 not found"); var ev = (pdxEnumTest) ret.GetField("m_pdxEnum"); if (ev != dPdxType.PdxEnum) throw new Exception("Pdx enum is not equal"); var addreaaPdxI = (IPdxInstance[]) ret.GetField("m_address"); Assert.AreEqual(addreaaPdxI.Length, dPdxType.AddressArray.Length); Assert.AreEqual(addreaaPdxI[0].GetObject(), dPdxType.AddressArray[0]); var objArr = (List<object>) ret.GetField("m_objectArray"); Assert.AreEqual(objArr.Count, dPdxType.ObjectArray.Count); Assert.AreEqual(((IPdxInstance) objArr[0]).GetObject(), dPdxType.ObjectArray[0]); ret = (IPdxInstance) region0["pdxput2"]; var cpi = (IPdxInstance) ret.GetField("_childPdx"); var cpo = (ChildPdx) cpi.GetObject(); Assert.AreEqual(cpo, new ChildPdx(1393), "child pdx should be equal"); } private void modifyPdxInstance() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); IPdxInstance newpdxins; var pdxins = (IPdxInstance) region0["pdxput"]; var oldVal = (int) pdxins.GetField("m_int32"); var iwpi = pdxins.CreateWriter(); iwpi.SetField("m_int32", oldVal + 1); iwpi.SetField("m_string", "change the string"); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; var newVal = (int) newpdxins.GetField("m_int32"); Assert.AreEqual(oldVal + 1, newVal); var cStr = (string) newpdxins.GetField("m_string"); Assert.AreEqual("change the string", cStr); var arr = (List<object>) newpdxins.GetField("m_arraylist"); Assert.AreEqual(arr.Count, 2); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_char", 'D'); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((char) newpdxins.GetField("m_char"), 'D', "Char is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_bool", false); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((bool) newpdxins.GetField("m_bool"), false, "bool is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_byte", (sbyte) 0x75); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((sbyte) newpdxins.GetField("m_byte"), (sbyte) 0x75, "sbyte is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_sbyte", (sbyte) 0x57); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((sbyte) newpdxins.GetField("m_sbyte"), (sbyte) 0x57, "sbyte is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_int16", (short) 0x5678); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((short) newpdxins.GetField("m_int16"), (short) 0x5678, "int16 is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_long", (long) 0x56787878); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((long) newpdxins.GetField("m_long"), (long) 0x56787878, "long is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_float", 18389.34f); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((float) newpdxins.GetField("m_float"), 18389.34f, "float is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_float", 18389.34f); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((float) newpdxins.GetField("m_float"), 18389.34f, "float is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_double", 18389.34d); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((double) newpdxins.GetField("m_double"), 18389.34d, "double is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_boolArray", new bool[] {true, false, true, false, true, true, false, true}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((bool[]) newpdxins.GetField("m_boolArray"), new bool[] {true, false, true, false, true, true, false, true}, "bool array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_byteArray", new byte[] {0x34, 0x64, 0x34, 0x64}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((byte[]) newpdxins.GetField("m_byteArray"), new byte[] {0x34, 0x64, 0x34, 0x64}, "byte array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_charArray", new char[] {'c', 'v', 'c', 'v'}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((char[]) newpdxins.GetField("m_charArray"), new char[] {'c', 'v', 'c', 'v'}, "char array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); var ticks = 634460644691580000L; var tdt = new DateTime(ticks); iwpi.SetField("m_dateTime", tdt); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((DateTime) newpdxins.GetField("m_dateTime"), tdt, "datetime is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_int16Array", new short[] {0x2332, 0x4545, 0x88, 0x898}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((short[]) newpdxins.GetField("m_int16Array"), new short[] {0x2332, 0x4545, 0x88, 0x898}, "short array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_int32Array", new int[] {23, 676868, 34343}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((int[]) newpdxins.GetField("m_int32Array"), new int[] {23, 676868, 34343}, "int32 array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_longArray", new long[] {3245435, 3425435}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((long[]) newpdxins.GetField("m_longArray"), new long[] {3245435, 3425435}, "long array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_floatArray", new float[] {232.565f, 234323354.67f}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((float[]) newpdxins.GetField("m_floatArray"), new float[] {232.565f, 234323354.67f}, "float array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_doubleArray", new double[] {23423432d, 43242354315d}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((double[]) newpdxins.GetField("m_doubleArray"), new double[] {23423432d, 43242354315d}, "double array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); var tmpbb = new byte[][] { new byte[] {0x23}, new byte[] {0x34, 0x55}, new byte[] {0x23}, new byte[] {0x34, 0x55} }; iwpi = pdxins.CreateWriter(); iwpi.SetField("m_byteByteArray", tmpbb); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; var retbb = (byte[][]) newpdxins.GetField("m_byteByteArray"); PdxType.compareByteByteArray(tmpbb, retbb); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_stringArray", new string[] {"one", "two", "eeeee"}); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual((string[]) newpdxins.GetField("m_stringArray"), new string[] {"one", "two", "eeeee"}, "string array is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); var tl = new List<object>(); tl.Add(new PdxType()); tl.Add(new byte[] {0x34, 0x55}); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_arraylist", tl); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual(((List<object>) newpdxins.GetField("m_arraylist")).Count, tl.Count, "list<object> is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); var map = new Dictionary<object, object>(); map.Add(1, new bool[] {true, false, true, false, true, true, false, true}); map.Add(2, new string[] {"one", "two", "eeeee"}); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_map", map); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual(((Dictionary<object, object>) newpdxins.GetField("m_map")).Count, map.Count, "map is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); var hashtable = new Hashtable(); hashtable.Add(1, new string[] {"one", "two", "eeeee"}); hashtable.Add(2, new int[] {23, 676868, 34343}); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_hashtable", hashtable); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual(((Hashtable) newpdxins.GetField("m_hashtable")).Count, hashtable.Count, "hashtable is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_pdxEnum", pdxEnumTest.pdx1); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual(((pdxEnumTest) newpdxins.GetField("m_pdxEnum")), pdxEnumTest.pdx1, "pdx enum is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); var vector = new ArrayList(); vector.Add(1); vector.Add(2); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_vector", vector); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual(((ArrayList) newpdxins.GetField("m_vector")).Count, vector.Count, "vector is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); var chm = CacheableHashSet.Create(); chm.Add(1); chm.Add("jkfdkjdsfl"); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_chs", chm); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.True(chm.Equals(newpdxins.GetField("m_chs")), "CacheableHashSet is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); var clhs = CacheableLinkedHashSet.Create(); clhs.Add(111); clhs.Add(111343); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_clhs", clhs); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.True(clhs.Equals(newpdxins.GetField("m_clhs")), "CacheableLinkedHashSet is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); var aa = new PdxTests.Address[2]; for (var i = 0; i < aa.Length; i++) { aa[i] = new PdxTests.Address(i + 1, "street" + i.ToString(), "city" + i.ToString()); } iwpi = pdxins.CreateWriter(); iwpi.SetField("m_address", aa); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; var iaa = (IPdxInstance[]) newpdxins.GetField("m_address"); Assert.AreEqual(iaa.Length, aa.Length, "address array length should equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal for address array"); var oa = new List<object>(); oa.Add(new PdxTests.Address(1, "1", "12")); oa.Add(new PdxTests.Address(1, "1", "12")); iwpi = pdxins.CreateWriter(); iwpi.SetField("m_objectArray", oa); region0["pdxput"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput"]; Assert.AreEqual(((List<object>) newpdxins.GetField("m_objectArray")).Count, oa.Count, "Object arary is not equal"); Assert.AreNotEqual(pdxins, newpdxins, "PdxInstance should not be equal"); pdxins = (IPdxInstance) region0["pdxput2"]; var cpi = (IPdxInstance) pdxins.GetField("_childPdx"); iwpi = pdxins.CreateWriter(); iwpi.SetField("_childPdx", new ChildPdx(2)); region0["pdxput2"] = iwpi; newpdxins = (IPdxInstance) region0["pdxput2"]; Console.WriteLine(pdxins); Console.WriteLine(newpdxins); Assert.AreNotEqual(pdxins, newpdxins, "parent pdx should be not equal"); Assert.AreNotEqual(cpi, newpdxins.GetField("_childPdx"), "child pdx instance should be equal"); Assert.AreEqual(new ChildPdx(2), ((IPdxInstance) (newpdxins.GetField("_childPdx"))).GetObject(), "child pdx instance should be equal"); } private void runPdxInstanceTest() { Util.Log("Starting iteration for pool locator runPdxInstanceTest"); CacheHelper.SetupJavaServers(true, "cacheserver_pdxinstance_hashcode.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CreateTCRegions_Pool_PDX2, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepOne (pool locators) complete."); m_client2.Call(CreateTCRegions_Pool_PDX2, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, false /*local caching false*/); Util.Log("StepTwo (pool locators) complete."); m_client1.Call(pdxPut); m_client2.Call(getObject); m_client2.Call(verifyPdxInstanceEquals); m_client2.Call(verifyPdxInstanceHashcode); m_client2.Call(accessPdxInstance); m_client2.Call(modifyPdxInstance); m_client1.Call(Close); Util.Log("Client 1 closed"); m_client2.Call(Close); //Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void InitClientXml(string cacheXml, int serverport1, int serverport2) { CacheHelper.HOST_PORT_1 = serverport1; CacheHelper.HOST_PORT_2 = serverport2; CacheHelper.InitConfig(cacheXml); } private void testReadSerializedXMLProperty() { Assert.AreEqual(CacheHelper.DCache.GetPdxReadSerialized(), true); } private void putPdxWithIdentityField() { CacheHelper.DCache.TypeRegistry.RegisterPdxType(SerializePdx.Create); var sp = new SerializePdx(true); var region0 = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]); region0[1] = sp; } private void verifyPdxIdentityField() { var region0 = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]); var pi = (IPdxInstance) region0[1]; Assert.AreEqual(pi.GetFieldNames().Count, 4, "number of fields should be four in SerializePdx"); Assert.AreEqual(pi.IsIdentityField("i1"), true, "SerializePdx1.i1 should be identity field"); Assert.AreEqual(pi.IsIdentityField("i2"), false, "SerializePdx1.i2 should NOT be identity field"); Assert.AreEqual(pi.HasField("i1"), true, "SerializePdx1.i1 should be in PdxInstance stream"); Assert.AreEqual(pi.HasField("i3"), false, "There is no field i3 in SerializePdx1's PdxInstance stream"); var javaPdxHC = (int) region0["javaPdxHC"]; Assert.AreEqual(javaPdxHC, pi.GetHashCode(), "Pdxhashcode for identity field object SerializePdx1 not matched with java pdx hash code."); var pi2 = (IPdxInstance) region0[1]; Assert.AreEqual(pi, pi2, "Both pdx instance should equal."); } private void putPdxWithNullIdentityFields() { var sp = new SerializePdx(false); //not initialized var region0 = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]); region0[2] = sp; } private void verifyPdxNullIdentityFieldHC() { var region0 = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]); var pi = (IPdxInstance) region0[2]; var javaPdxHC = (int) region0["javaPdxHC"]; Assert.AreEqual(javaPdxHC, pi.GetHashCode(), "Pdxhashcode for identity field object SerializePdx1 not matched with java pdx hash code."); var pi2 = (IPdxInstance) region0[2]; Assert.AreEqual(pi, pi2, "Both pdx instance should equal."); var values = new Dictionary<object, object>(); var keys = new List<object>(); keys.Add(1); keys.Add(2); region0.GetAll(keys, values, null); Assert.AreEqual(values.Count, 2, "Getall count should be two"); } private void runPdxReadSerializedTest() { Util.Log("runPdxReadSerializedTest"); CacheHelper.SetupJavaServers(false, "cacheserver_pdxinstance_hashcode.xml"); CacheHelper.StartJavaServer(1, "GFECS1"); Util.Log("Cacheserver 1 started."); m_client1.Call(InitClientXml, "client_pdx.xml", CacheHelper.HOST_PORT_1, CacheHelper.HOST_PORT_2); m_client2.Call(InitClientXml, "client_pdx.xml", CacheHelper.HOST_PORT_1, CacheHelper.HOST_PORT_2); m_client1.Call(testReadSerializedXMLProperty); m_client2.Call(testReadSerializedXMLProperty); m_client1.Call(putPdxWithIdentityField); m_client2.Call(verifyPdxIdentityField); m_client1.Call(putPdxWithNullIdentityFields); m_client2.Call(verifyPdxNullIdentityFieldHC); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } #region Tests [Test] public void PdxIgnoreUnreadFieldTest() { m_useWeakHashMap = true; runPdxIgnoreUnreadFieldTest(); m_useWeakHashMap = false; runPdxIgnoreUnreadFieldTest(); } [Test] public void MultipleDSTest() { runMultipleDSTest(); } [Test] public void PdxSerializerTest() { runPdxSerializerTest(); } [Test] public void ReflectionPdxSerializerTest() { runReflectionPdxSerializerTest(); } [Test] public void PdxTestWithNoTypeRegister() { runPdxTestWithNoTypeRegister(); } [Test] public void PdxInstanceTest() { runPdxInstanceTest(); } [Test] public void PdxReadSerializedTest() { runPdxReadSerializedTest(); } #endregion } }
// Utility.cs // Script#/Core/Compiler // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace ScriptSharp { internal static class Utility { private static readonly string Base64Alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_"; private static readonly string Base54Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_"; private static readonly string[] ScriptKeywords = new string[] { // Current keywords "break", "delete", "function", "return", "typeof", "case", "do", "if", "switch", "var", "catch", "else", "in", "this", "void", "continue", "false", "instanceof", "throw", "while", "debugger", "finally", "new", "true", "with", "default", "for", "null", "try", // Future reserved words "abstract", "double", "goto", "native", "static", "boolean", "enum", "implements", "package", "super", "byte", "export", "import", "private", "synchronized", "char", "extends", "int", "protected", "throws", "class", "final", "interface", "public", "transient", "const", "float", "long", "short", "volatile", // Script#-specific words "ss", "global" }; private static Hashtable _keywordTable; public static string CreateCamelCaseName(string name) { if (String.IsNullOrEmpty(name)) { return name; } // Some exceptions that simply need to be special cased if (name.Equals("ID", StringComparison.Ordinal)) { return "id"; } bool hasLowerCase = false; int conversionLength = 0; for (int i = 0; i < name.Length; i++) { if (Char.IsUpper(name, i)) { conversionLength++; } else { hasLowerCase = true; break; } } if (((hasLowerCase == false) && (name.Length != 1)) || (conversionLength == 0)) { // Name is all upper case, or all lower case; // leave it as-is. return name; } if (conversionLength > 1) { // Convert the leading uppercase segment, except the last character // which is assumed to be the first letter of the next word return name.Substring(0, conversionLength - 1).ToLower(CultureInfo.InvariantCulture) + name.Substring(conversionLength - 1); } else if (name.Length == 1) { return name.ToLower(CultureInfo.InvariantCulture); } else { // Convert the leading upper case character to lower case return Char.ToLower(name[0], CultureInfo.InvariantCulture) + name.Substring(1); } } public static string CreateEncodedName(int number, bool useDigits) { string alphabet = useDigits ? Base64Alphabet : Base54Alphabet; if (number == 0) { return alphabet[0].ToString(); } string name = String.Empty; while (number > 0) { int remainder = number % alphabet.Length; number = (int)(number / alphabet.Length); name = alphabet[remainder] + name; } return name; } public static string GetResourceFileLocale(string fileName) { string extension = Path.GetExtension(fileName); if (String.Compare(extension, ".resx", StringComparison.OrdinalIgnoreCase) == 0) { fileName = Path.GetFileNameWithoutExtension(fileName); extension = Path.GetExtension(fileName); if (String.IsNullOrEmpty(extension) == false) { return extension.Substring(1); } } return String.Empty; } public static string GetResourceFileName(string fileName) { string extension = Path.GetExtension(fileName); if (String.Compare(extension, ".resx", StringComparison.OrdinalIgnoreCase) == 0) { fileName = Path.GetFileNameWithoutExtension(fileName); extension = Path.GetExtension(fileName); if (String.IsNullOrEmpty(extension) == false) { fileName = Path.GetFileNameWithoutExtension(fileName); } } return fileName; } public static bool IsKeyword(string identifier) { return IsKeyword(identifier, /* testCamelCase */ false); } public static bool IsKeyword(string identifier, bool testCamelCase) { Debug.Assert(String.IsNullOrEmpty(identifier) == false); if (_keywordTable == null) { _keywordTable = new Hashtable(StringComparer.Ordinal); foreach (string word in ScriptKeywords) { _keywordTable.Add(word, null); } } if (testCamelCase) { identifier = CreateCamelCaseName(identifier); } return _keywordTable.ContainsKey(identifier); } public static bool IsValidIdentifier(string name) { if (String.IsNullOrEmpty(name)) { return false; } if (IsKeyword(name)) { return false; } if (Char.IsDigit(name[0])) { return false; } for (int i = 0; i < name.Length; i++) { char ch = name[i]; if ((ch != '_') && (ch != '$') && (Char.IsLetterOrDigit(ch) == false)) { return false; } } return true; } public static bool IsValidScriptNamespace(string name) { if (String.IsNullOrEmpty(name)) { return false; } foreach (string part in name.Split('.')) { if (!IsValidIdentifier(part)) { return false; } } return true; } public static bool IsValidScriptName(string name) { if (String.IsNullOrEmpty(name)) { return true; } if (IsKeyword(name)) { return false; } if (Char.IsDigit(name[0])) { return false; } for (int i = 0; i < name.Length; i++) { char ch = name[i]; if ((Char.IsLetterOrDigit(ch) == false) && (ch != '.') && (ch != '_')) { return false; } } return true; } public static string QuoteString(string s) { if (String.IsNullOrEmpty(s)) { return "''"; } bool useDoubleQuotes = (s.IndexOf('\'') >= 0); StringBuilder b = null; int startIndex = 0; int count = 0; for (int i = 0; i < s.Length; i++) { char c = s[i]; // Append the unhandled characters (that do not require special treament) // to the string builder when special characters are detected. if (c == '\r' || c == '\t' || c == '\\' || c == '\r' || c < ' ' || c > 0x7F || ((c == '\"') && useDoubleQuotes) || ((c == '\'') && (useDoubleQuotes == false))) { if (b == null) { b = new StringBuilder(s.Length + 6); } if (count > 0) { b.Append(s, startIndex, count); } startIndex = i + 1; count = 0; } switch (c) { case '\r': b.Append("\\r"); break; case '\t': b.Append("\\t"); break; case '\\': b.Append("\\\\"); break; case '\n': b.Append("\\n"); break; case '\"': if (useDoubleQuotes) { b.Append("\\\""); break; } goto default; case '\'': if (!useDoubleQuotes) { b.Append("\\\'"); break; } goto default; default: if ((c < ' ') || (c > 0x7F)) { b.AppendFormat(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)c); } else { count++; } break; } } string processedString = s; if (b != null) { if (count > 0) { b.Append(s, startIndex, count); } processedString = b.ToString(); } if (useDoubleQuotes) { return "\"" + processedString + "\""; } return "'" + processedString + "'"; } } }
using System; using System.Drawing; using System.Collections.Generic; using Foundation; using UIKit; using MapKit; using SDWebImage; namespace SDWebImageSample { public partial class MasterViewController : UITableViewController { public DetailViewController DetailViewController { get; set; } public List<string> objects; public MasterViewController () : base ("MasterViewController", null) { InitListOfImages (); Title = "SDWebImage"; NavigationItem.RightBarButtonItem = new UIBarButtonItem ("Clear Cache", UIBarButtonItemStyle.Plain, ClearCache); SDWebImageManager.SharedManager.ImageDownloader.SetValueforHTTPHeaderField ("SDWebImage Demo", "AppName"); SDWebImageManager.SharedManager.ImageDownloader.ExecutionOrder = SDWebImageDownloaderExecutionOrder.LastInFirstOut; TableView.Source = new MyTableViewSource (this); } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. } void ClearCache (object sender, EventArgs e) { SDWebImageManager.SharedManager.ImageCache.ClearMemory (); SDWebImageManager.SharedManager.ImageCache.ClearDisk (); } public class MyTableViewSource : UITableViewSource { MasterViewController ctrl; public MyTableViewSource (MasterViewController ctrl) { this.ctrl = ctrl; } public override nint NumberOfSections (UITableView tableView) { return 1; } public override nint RowsInSection (UITableView tableview, nint section) { return ctrl.objects.Count; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { string CellIdentifier = @"Cell"; UITableViewCell cell = tableView.DequeueReusableCell (CellIdentifier); if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier); } cell.TextLabel.Text = string.Format ("Image #{0}", indexPath.Row); cell.ImageView.SetImage (new NSUrl (ctrl.objects [indexPath.Row]), UIImage.FromBundle ("placeholder")); return cell; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { ctrl.DetailViewController = null; ctrl.DetailViewController = new DetailViewController (); string largeImageURL = ctrl.objects [indexPath.Row].Replace ("small", "source"); ctrl.DetailViewController.ImageUrl = new NSUrl (largeImageURL); ctrl.NavigationController.PushViewController (ctrl.DetailViewController, true); } } void InitListOfImages () { objects = new List<string> () { @"http://static2.dmcdn.net/static/video/451/838/44838154:jpeg_preview_small.jpg?20120509163826", @"http://static2.dmcdn.net/static/video/656/177/44771656:jpeg_preview_small.jpg?20120509154705", @"http://static2.dmcdn.net/static/video/629/228/44822926:jpeg_preview_small.jpg?20120509181018", @"http://static2.dmcdn.net/static/video/116/367/44763611:jpeg_preview_small.jpg?20120509101749", @"http://static2.dmcdn.net/static/video/340/086/44680043:jpeg_preview_small.jpg?20120509180118", @"http://static2.dmcdn.net/static/video/666/645/43546666:jpeg_preview_small.jpg?20120412153140", @"http://static2.dmcdn.net/static/video/771/577/44775177:jpeg_preview_small.jpg?20120509183230", @"http://static2.dmcdn.net/static/video/810/508/44805018:jpeg_preview_small.jpg?20120508125339", @"http://static2.dmcdn.net/static/video/152/008/44800251:jpeg_preview_small.jpg?20120508103336", @"http://static2.dmcdn.net/static/video/694/741/35147496:jpeg_preview_small.jpg?20120508111445", @"http://static2.dmcdn.net/static/video/988/667/44766889:jpeg_preview_small.jpg?20120508130425", @"http://static2.dmcdn.net/static/video/282/467/44764282:jpeg_preview_small.jpg?20120507130637", @"http://static2.dmcdn.net/static/video/754/657/44756457:jpeg_preview_small.jpg?20120507093012", @"http://static2.dmcdn.net/static/video/831/107/44701138:jpeg_preview_small.jpg?20120506133917", @"http://static2.dmcdn.net/static/video/411/057/44750114:jpeg_preview_small.jpg?20120507014914", @"http://static2.dmcdn.net/static/video/894/547/44745498:jpeg_preview_small.jpg?20120509183004", @"http://static2.dmcdn.net/static/video/082/947/44749280:jpeg_preview_small.jpg?20120507015022", @"http://static2.dmcdn.net/static/video/833/347/44743338:jpeg_preview_small.jpg?20120509183004", @"http://static2.dmcdn.net/static/video/683/666/44666386:jpeg_preview_small.jpg?20120505111208", @"http://static2.dmcdn.net/static/video/595/946/44649595:jpeg_preview_small.jpg?20120507194104", @"http://static2.dmcdn.net/static/video/984/935/44539489:jpeg_preview_small.jpg?20120501184650", @"http://static2.dmcdn.net/static/video/440/416/44614044:jpeg_preview_small.jpg?20120505174152", @"http://static2.dmcdn.net/static/video/561/977/20779165:jpeg_preview_small.jpg?20120423161805", @"http://static2.dmcdn.net/static/video/104/546/44645401:jpeg_preview_small.jpg?20120507185246", @"http://static2.dmcdn.net/static/video/671/636/44636176:jpeg_preview_small.jpg?20120504021339", @"http://static2.dmcdn.net/static/video/142/746/44647241:jpeg_preview_small.jpg?20120504104451", @"http://static2.dmcdn.net/static/video/776/860/44068677:jpeg_preview_small.jpg?20120507185251", @"http://static2.dmcdn.net/static/video/026/626/44626620:jpeg_preview_small.jpg?20120503203036", @"http://static2.dmcdn.net/static/video/364/663/39366463:jpeg_preview_small.jpg?20120509163505", @"http://static2.dmcdn.net/static/video/392/895/44598293:jpeg_preview_small.jpg?20120503165252", @"http://static2.dmcdn.net/static/video/620/865/44568026:jpeg_preview_small.jpg?20120507185121", @"http://static2.dmcdn.net/static/video/031/395/44593130:jpeg_preview_small.jpg?20120507185139", @"http://static2.dmcdn.net/static/video/676/495/44594676:jpeg_preview_small.jpg?20120503121341", @"http://static2.dmcdn.net/static/video/025/195/44591520:jpeg_preview_small.jpg?20120503132132", @"http://static2.dmcdn.net/static/video/993/665/44566399:jpeg_preview_small.jpg?20120503182623", @"http://static2.dmcdn.net/static/video/137/635/44536731:jpeg_preview_small.jpg?20120501165940", @"http://static2.dmcdn.net/static/video/611/794/44497116:jpeg_preview_small.jpg?20120507184954", @"http://static2.dmcdn.net/static/video/732/790/44097237:jpeg_preview_small.jpg?20120430162348", @"http://static2.dmcdn.net/static/video/064/991/44199460:jpeg_preview_small.jpg?20120430101250", @"http://static2.dmcdn.net/static/video/404/094/44490404:jpeg_preview_small.jpg?20120507184948", @"http://static2.dmcdn.net/static/video/413/120/44021314:jpeg_preview_small.jpg?20120507180850", @"http://static2.dmcdn.net/static/video/200/584/44485002:jpeg_preview_small.jpg?20120507184941", @"http://static2.dmcdn.net/static/video/551/318/42813155:jpeg_preview_small.jpg?20120412153202", @"http://static2.dmcdn.net/static/video/524/750/44057425:jpeg_preview_small.jpg?20120501220912", @"http://static2.dmcdn.net/static/video/124/843/44348421:jpeg_preview_small.jpg?20120507184551", @"http://static2.dmcdn.net/static/video/496/394/42493694:jpeg_preview_small.jpg?20120430105337", @"http://static2.dmcdn.net/static/video/548/883/44388845:jpeg_preview_small.jpg?20120428212713", @"http://static2.dmcdn.net/static/video/282/533/44335282:jpeg_preview_small.jpg?20120427102844", @"http://static2.dmcdn.net/static/video/257/132/44231752:jpeg_preview_small.jpg?20120428212609", @"http://static2.dmcdn.net/static/video/480/193/44391084:jpeg_preview_small.jpg?20120501143214", @"http://static2.dmcdn.net/static/video/903/432/44234309:jpeg_preview_small.jpg?20120427200002", @"http://static2.dmcdn.net/static/video/646/573/44375646:jpeg_preview_small.jpg?20120507184652", @"http://static2.dmcdn.net/static/video/709/573/44375907:jpeg_preview_small.jpg?20120507184652", @"http://static2.dmcdn.net/static/video/885/633/44336588:jpeg_preview_small.jpg?20120507184540", @"http://static2.dmcdn.net/static/video/732/523/44325237:jpeg_preview_small.jpg?20120426110308", @"http://static2.dmcdn.net/static/video/935/132/44231539:jpeg_preview_small.jpg?20120426115744", @"http://static2.dmcdn.net/static/video/941/129/43921149:jpeg_preview_small.jpg?20120426094640", @"http://static2.dmcdn.net/static/video/775/942/44249577:jpeg_preview_small.jpg?20120425011228", @"http://static2.dmcdn.net/static/video/868/332/44233868:jpeg_preview_small.jpg?20120429152901", @"http://static2.dmcdn.net/static/video/959/732/44237959:jpeg_preview_small.jpg?20120425133534", @"http://static2.dmcdn.net/static/video/383/402/44204383:jpeg_preview_small.jpg?20120424185842", @"http://static2.dmcdn.net/static/video/971/932/44239179:jpeg_preview_small.jpg?20120424154419", @"http://static2.dmcdn.net/static/video/096/991/44199690:jpeg_preview_small.jpg?20120423162001", @"http://static2.dmcdn.net/static/video/661/450/44054166:jpeg_preview_small.jpg?20120507180921", @"http://static2.dmcdn.net/static/video/419/322/44223914:jpeg_preview_small.jpg?20120424112858", @"http://static2.dmcdn.net/static/video/673/391/44193376:jpeg_preview_small.jpg?20120507181450", @"http://static2.dmcdn.net/static/video/907/781/44187709:jpeg_preview_small.jpg?20120423103507", @"http://static2.dmcdn.net/static/video/446/571/44175644:jpeg_preview_small.jpg?20120423033122", @"http://static2.dmcdn.net/static/video/146/671/44176641:jpeg_preview_small.jpg?20120428235503", @"http://static2.dmcdn.net/static/video/463/571/44175364:jpeg_preview_small.jpg?20120428235503", @"http://static2.dmcdn.net/static/video/442/471/44174244:jpeg_preview_small.jpg?20120428235502", @"http://static2.dmcdn.net/static/video/523/471/44174325:jpeg_preview_small.jpg?20120422205107", @"http://static2.dmcdn.net/static/video/977/159/43951779:jpeg_preview_small.jpg?20120420182100", @"http://static2.dmcdn.net/static/video/875/880/40088578:jpeg_preview_small.jpg?20120501131026", @"http://static2.dmcdn.net/static/video/434/992/38299434:jpeg_preview_small.jpg?20120503193356", @"http://static2.dmcdn.net/static/video/448/798/42897844:jpeg_preview_small.jpg?20120418155203", @"http://static2.dmcdn.net/static/video/374/690/44096473:jpeg_preview_small.jpg?20120507181124", @"http://static2.dmcdn.net/static/video/284/313/43313482:jpeg_preview_small.jpg?20120420184511", @"http://static2.dmcdn.net/static/video/682/060/44060286:jpeg_preview_small.jpg?20120421122436", @"http://static2.dmcdn.net/static/video/701/750/44057107:jpeg_preview_small.jpg?20120420112918", @"http://static2.dmcdn.net/static/video/790/850/44058097:jpeg_preview_small.jpg?20120424114522", @"http://static2.dmcdn.net/static/video/153/617/43716351:jpeg_preview_small.jpg?20120419190650", @"http://static2.dmcdn.net/static/video/394/633/37336493:jpeg_preview_small.jpg?20111109151109", @"http://static2.dmcdn.net/static/video/893/330/44033398:jpeg_preview_small.jpg?20120419123322", @"http://static2.dmcdn.net/static/video/395/046/42640593:jpeg_preview_small.jpg?20120418103546", @"http://static2.dmcdn.net/static/video/913/040/44040319:jpeg_preview_small.jpg?20120419164908", @"http://static2.dmcdn.net/static/video/090/020/44020090:jpeg_preview_small.jpg?20120418185934", @"http://static2.dmcdn.net/static/video/349/299/43992943:jpeg_preview_small.jpg?20120418112749", @"http://static2.dmcdn.net/static/video/530/189/43981035:jpeg_preview_small.jpg?20120419013834", @"http://static2.dmcdn.net/static/video/763/469/43964367:jpeg_preview_small.jpg?20120425111931", @"http://static2.dmcdn.net/static/video/961/455/43554169:jpeg_preview_small.jpg?20120418110127", @"http://static2.dmcdn.net/static/video/666/889/43988666:jpeg_preview_small.jpg?20120507180735", @"http://static2.dmcdn.net/static/video/160/459/43954061:jpeg_preview_small.jpg?20120501202847", @"http://static2.dmcdn.net/static/video/352/069/43960253:jpeg_preview_small.jpg?20120503175747", @"http://static2.dmcdn.net/static/video/096/502/43205690:jpeg_preview_small.jpg?20120417142655", @"http://static2.dmcdn.net/static/video/257/119/43911752:jpeg_preview_small.jpg?20120416101238", @"http://static2.dmcdn.net/static/video/874/098/43890478:jpeg_preview_small.jpg?20120415193608", @"http://static2.dmcdn.net/static/video/406/148/43841604:jpeg_preview_small.jpg?20120416123145", @"http://static2.dmcdn.net/static/video/463/885/43588364:jpeg_preview_small.jpg?20120409130206", @"http://static2.dmcdn.net/static/video/176/845/38548671:jpeg_preview_small.jpg?20120414200742", @"http://static2.dmcdn.net/static/video/447/848/51848744:jpeg_preview_small.jpg?20121105223446", @"http://static2.dmcdn.net/static/video/337/848/51848733:jpeg_preview_small.jpg?20121105223433", @"http://static2.dmcdn.net/static/video/707/848/51848707:jpeg_preview_small.jpg?20121105223428", @"http://static2.dmcdn.net/static/video/102/848/51848201:jpeg_preview_small.jpg?20121105223411", @"http://static2.dmcdn.net/static/video/817/848/51848718:jpeg_preview_small.jpg?20121105223402", @"http://static2.dmcdn.net/static/video/007/848/51848700:jpeg_preview_small.jpg?20121105223345", @"http://static2.dmcdn.net/static/video/696/848/51848696:jpeg_preview_small.jpg?20121105223355", @"http://static2.dmcdn.net/static/video/296/848/51848692:jpeg_preview_small.jpg?20121105223337", @"http://static2.dmcdn.net/static/video/080/848/51848080:jpeg_preview_small.jpg?20121105223653", @"http://static2.dmcdn.net/static/video/386/848/51848683:jpeg_preview_small.jpg?20121105223343", @"http://static2.dmcdn.net/static/video/876/848/51848678:jpeg_preview_small.jpg?20121105223301", @"http://static2.dmcdn.net/static/video/866/848/51848668:jpeg_preview_small.jpg?20121105223244", @"http://static2.dmcdn.net/static/video/572/548/51845275:jpeg_preview_small.jpg?20121105223229", @"http://static2.dmcdn.net/static/video/972/548/51845279:jpeg_preview_small.jpg?20121105223227", @"http://static2.dmcdn.net/static/video/112/548/51845211:jpeg_preview_small.jpg?20121105223226", @"http://static2.dmcdn.net/static/video/549/448/51844945:jpeg_preview_small.jpg?20121105223223", @"http://static2.dmcdn.net/static/video/166/848/51848661:jpeg_preview_small.jpg?20121105223228", @"http://static2.dmcdn.net/static/video/856/848/51848658:jpeg_preview_small.jpg?20121105223223", @"http://static2.dmcdn.net/static/video/746/848/51848647:jpeg_preview_small.jpg?20121105223204", @"http://static2.dmcdn.net/static/video/446/848/51848644:jpeg_preview_small.jpg?20121105223204", @"http://static2.dmcdn.net/static/video/726/848/51848627:jpeg_preview_small.jpg?20121105223221", @"http://static2.dmcdn.net/static/video/436/848/51848634:jpeg_preview_small.jpg?20121105223445", @"http://static2.dmcdn.net/static/video/836/848/51848638:jpeg_preview_small.jpg?20121105223144", @"http://static2.dmcdn.net/static/video/036/848/51848630:jpeg_preview_small.jpg?20121105223125", @"http://static2.dmcdn.net/static/video/026/848/51848620:jpeg_preview_small.jpg?20121105223102", @"http://static2.dmcdn.net/static/video/895/848/51848598:jpeg_preview_small.jpg?20121105223112", @"http://static2.dmcdn.net/static/video/116/848/51848611:jpeg_preview_small.jpg?20121105223052", @"http://static2.dmcdn.net/static/video/006/848/51848600:jpeg_preview_small.jpg?20121105223043", @"http://static2.dmcdn.net/static/video/432/548/51845234:jpeg_preview_small.jpg?20121105223022", @"http://static2.dmcdn.net/static/video/785/848/51848587:jpeg_preview_small.jpg?20121105223031", @"http://static2.dmcdn.net/static/video/975/848/51848579:jpeg_preview_small.jpg?20121105223012", @"http://static2.dmcdn.net/static/video/965/848/51848569:jpeg_preview_small.jpg?20121105222952", @"http://static2.dmcdn.net/static/video/365/848/51848563:jpeg_preview_small.jpg?20121105222943", @"http://static2.dmcdn.net/static/video/755/848/51848557:jpeg_preview_small.jpg?20121105222943", @"http://static2.dmcdn.net/static/video/722/248/51842227:jpeg_preview_small.jpg?20121105222908", @"http://static2.dmcdn.net/static/video/155/848/51848551:jpeg_preview_small.jpg?20121105222913", @"http://static2.dmcdn.net/static/video/345/848/51848543:jpeg_preview_small.jpg?20121105222907", @"http://static2.dmcdn.net/static/video/535/848/51848535:jpeg_preview_small.jpg?20121105222848", @"http://static2.dmcdn.net/static/video/035/848/51848530:jpeg_preview_small.jpg?20121105222837", @"http://static2.dmcdn.net/static/video/525/848/51848525:jpeg_preview_small.jpg?20121105222826", @"http://static2.dmcdn.net/static/video/233/848/51848332:jpeg_preview_small.jpg?20121105223414", @"http://static2.dmcdn.net/static/video/125/848/51848521:jpeg_preview_small.jpg?20121105222809", @"http://static2.dmcdn.net/static/video/005/848/51848500:jpeg_preview_small.jpg?20121105222802", @"http://static2.dmcdn.net/static/video/015/848/51848510:jpeg_preview_small.jpg?20121105222755", @"http://static2.dmcdn.net/static/video/121/548/51845121:jpeg_preview_small.jpg?20121105222850", @"http://static2.dmcdn.net/static/video/205/848/51848502:jpeg_preview_small.jpg?20121105222737", @"http://static2.dmcdn.net/static/video/697/448/51844796:jpeg_preview_small.jpg?20121105222818", @"http://static2.dmcdn.net/static/video/494/848/51848494:jpeg_preview_small.jpg?20121105222724", @"http://static2.dmcdn.net/static/video/806/448/51844608:jpeg_preview_small.jpg?20121105222811", @"http://static2.dmcdn.net/static/video/729/348/51843927:jpeg_preview_small.jpg?20121105222805", @"http://static2.dmcdn.net/static/video/865/148/51841568:jpeg_preview_small.jpg?20121105222803", @"http://static2.dmcdn.net/static/video/481/548/51845184:jpeg_preview_small.jpg?20121105222700", @"http://static2.dmcdn.net/static/video/190/548/51845091:jpeg_preview_small.jpg?20121105222656", @"http://static2.dmcdn.net/static/video/128/448/51844821:jpeg_preview_small.jpg?20121105222656", @"http://static2.dmcdn.net/static/video/784/848/51848487:jpeg_preview_small.jpg?20121105222704", @"http://static2.dmcdn.net/static/video/182/448/51844281:jpeg_preview_small.jpg?20121105222652", @"http://static2.dmcdn.net/static/video/801/848/51848108:jpeg_preview_small.jpg?20121105222907", @"http://static2.dmcdn.net/static/video/974/848/51848479:jpeg_preview_small.jpg?20121105222657", @"http://static2.dmcdn.net/static/video/274/848/51848472:jpeg_preview_small.jpg?20121105222644", @"http://static2.dmcdn.net/static/video/954/848/51848459:jpeg_preview_small.jpg?20121105222637", @"http://static2.dmcdn.net/static/video/554/848/51848455:jpeg_preview_small.jpg?20121105222615", @"http://static2.dmcdn.net/static/video/944/848/51848449:jpeg_preview_small.jpg?20121105222558", @"http://static2.dmcdn.net/static/video/144/848/51848441:jpeg_preview_small.jpg?20121105222556", @"http://static2.dmcdn.net/static/video/134/848/51848431:jpeg_preview_small.jpg?20121105222539", @"http://static2.dmcdn.net/static/video/624/848/51848426:jpeg_preview_small.jpg?20121105222523", @"http://static2.dmcdn.net/static/video/281/448/51844182:jpeg_preview_small.jpg?20121105222502", @"http://static2.dmcdn.net/static/video/414/848/51848414:jpeg_preview_small.jpg?20121105222516", @"http://static2.dmcdn.net/static/video/171/848/51848171:jpeg_preview_small.jpg?20121105223449", @"http://static2.dmcdn.net/static/video/904/848/51848409:jpeg_preview_small.jpg?20121105222514", @"http://static2.dmcdn.net/static/video/004/848/51848400:jpeg_preview_small.jpg?20121105222443", @"http://static2.dmcdn.net/static/video/693/848/51848396:jpeg_preview_small.jpg?20121105222439", @"http://static2.dmcdn.net/static/video/401/848/51848104:jpeg_preview_small.jpg?20121105222832", @"http://static2.dmcdn.net/static/video/957/648/51846759:jpeg_preview_small.jpg?20121105223109", @"http://static2.dmcdn.net/static/video/603/848/51848306:jpeg_preview_small.jpg?20121105222324", @"http://static2.dmcdn.net/static/video/990/848/51848099:jpeg_preview_small.jpg?20121105222807", @"http://static2.dmcdn.net/static/video/929/448/51844929:jpeg_preview_small.jpg?20121105222216", @"http://static2.dmcdn.net/static/video/320/548/51845023:jpeg_preview_small.jpg?20121105222214", @"http://static2.dmcdn.net/static/video/387/448/51844783:jpeg_preview_small.jpg?20121105222212", @"http://static2.dmcdn.net/static/video/833/248/51842338:jpeg_preview_small.jpg?20121105222209", @"http://static2.dmcdn.net/static/video/993/348/51843399:jpeg_preview_small.jpg?20121105222012", @"http://static2.dmcdn.net/static/video/660/848/51848066:jpeg_preview_small.jpg?20121105222754", @"http://static2.dmcdn.net/static/video/471/848/51848174:jpeg_preview_small.jpg?20121105223419", @"http://static2.dmcdn.net/static/video/255/748/51847552:jpeg_preview_small.jpg?20121105222420", @"http://static2.dmcdn.net/static/video/257/448/51844752:jpeg_preview_small.jpg?20121105221728", @"http://static2.dmcdn.net/static/video/090/848/51848090:jpeg_preview_small.jpg?20121105223020", @"http://static2.dmcdn.net/static/video/807/448/51844708:jpeg_preview_small.jpg?20121105221654", @"http://static2.dmcdn.net/static/video/196/448/51844691:jpeg_preview_small.jpg?20121105222110", @"http://static2.dmcdn.net/static/video/406/448/51844604:jpeg_preview_small.jpg?20121105221647", @"http://static2.dmcdn.net/static/video/865/348/51843568:jpeg_preview_small.jpg?20121105221644", @"http://static2.dmcdn.net/static/video/932/448/51844239:jpeg_preview_small.jpg?20121105221309", @"http://static2.dmcdn.net/static/video/967/438/51834769:jpeg_preview_small.jpg?20121105221020", @"http://static2.dmcdn.net/static/video/362/348/51843263:jpeg_preview_small.jpg?20121105220855", @"http://static2.dmcdn.net/static/video/777/448/51844777:jpeg_preview_small.jpg?20121105220715", @"http://static2.dmcdn.net/static/video/567/348/51843765:jpeg_preview_small.jpg?20121105220708", @"http://static2.dmcdn.net/static/video/905/248/51842509:jpeg_preview_small.jpg?20121105220640", @"http://static2.dmcdn.net/static/video/857/748/51847758:jpeg_preview_small.jpg?20121105221003", @"http://static2.dmcdn.net/static/video/578/348/51843875:jpeg_preview_small.jpg?20121105220350", @"http://static2.dmcdn.net/static/video/214/448/51844412:jpeg_preview_small.jpg?20121105220415", @"http://static2.dmcdn.net/static/video/264/748/51847462:jpeg_preview_small.jpg?20121105220635", @"http://static2.dmcdn.net/static/video/817/748/51847718:jpeg_preview_small.jpg?20121105220233", @"http://static2.dmcdn.net/static/video/784/848/51848487:jpeg_preview_small.jpg?20121105222704", @"http://static2.dmcdn.net/static/video/182/448/51844281:jpeg_preview_small.jpg?20121105222652", @"http://static2.dmcdn.net/static/video/801/848/51848108:jpeg_preview_small.jpg?20121105222907", @"http://static2.dmcdn.net/static/video/974/848/51848479:jpeg_preview_small.jpg?20121105222657", @"http://static2.dmcdn.net/static/video/274/848/51848472:jpeg_preview_small.jpg?20121105222644", @"http://static2.dmcdn.net/static/video/954/848/51848459:jpeg_preview_small.jpg?20121105222637", @"http://static2.dmcdn.net/static/video/554/848/51848455:jpeg_preview_small.jpg?20121105222615", @"http://static2.dmcdn.net/static/video/944/848/51848449:jpeg_preview_small.jpg?20121105222558", @"http://static2.dmcdn.net/static/video/144/848/51848441:jpeg_preview_small.jpg?20121105222556", @"http://static2.dmcdn.net/static/video/134/848/51848431:jpeg_preview_small.jpg?20121105222539", @"http://static2.dmcdn.net/static/video/624/848/51848426:jpeg_preview_small.jpg?20121105222523", @"http://static2.dmcdn.net/static/video/281/448/51844182:jpeg_preview_small.jpg?20121105222502", @"http://static2.dmcdn.net/static/video/414/848/51848414:jpeg_preview_small.jpg?20121105222516", @"http://static2.dmcdn.net/static/video/171/848/51848171:jpeg_preview_small.jpg?20121105223449", @"http://static2.dmcdn.net/static/video/904/848/51848409:jpeg_preview_small.jpg?20121105222514", @"http://static2.dmcdn.net/static/video/004/848/51848400:jpeg_preview_small.jpg?20121105222443", @"http://static2.dmcdn.net/static/video/693/848/51848396:jpeg_preview_small.jpg?20121105222439", @"http://static2.dmcdn.net/static/video/401/848/51848104:jpeg_preview_small.jpg?20121105222832", @"http://static2.dmcdn.net/static/video/957/648/51846759:jpeg_preview_small.jpg?20121105223109", @"http://static2.dmcdn.net/static/video/603/848/51848306:jpeg_preview_small.jpg?20121105222324", @"http://static2.dmcdn.net/static/video/990/848/51848099:jpeg_preview_small.jpg?20121105222807", @"http://static2.dmcdn.net/static/video/929/448/51844929:jpeg_preview_small.jpg?20121105222216", @"http://static2.dmcdn.net/static/video/320/548/51845023:jpeg_preview_small.jpg?20121105222214", @"http://static2.dmcdn.net/static/video/387/448/51844783:jpeg_preview_small.jpg?20121105222212", @"http://static2.dmcdn.net/static/video/833/248/51842338:jpeg_preview_small.jpg?20121105222209", @"http://static2.dmcdn.net/static/video/993/348/51843399:jpeg_preview_small.jpg?20121105222012", @"http://static2.dmcdn.net/static/video/660/848/51848066:jpeg_preview_small.jpg?20121105222754", @"http://static2.dmcdn.net/static/video/471/848/51848174:jpeg_preview_small.jpg?20121105223419", @"http://static2.dmcdn.net/static/video/255/748/51847552:jpeg_preview_small.jpg?20121105222420", @"http://static2.dmcdn.net/static/video/257/448/51844752:jpeg_preview_small.jpg?20121105221728", @"http://static2.dmcdn.net/static/video/090/848/51848090:jpeg_preview_small.jpg?20121105224514", @"http://static2.dmcdn.net/static/video/807/448/51844708:jpeg_preview_small.jpg?20121105221654", @"http://static2.dmcdn.net/static/video/196/448/51844691:jpeg_preview_small.jpg?20121105222110", @"http://static2.dmcdn.net/static/video/406/448/51844604:jpeg_preview_small.jpg?20121105221647", @"http://static2.dmcdn.net/static/video/865/348/51843568:jpeg_preview_small.jpg?20121105221644", @"http://static2.dmcdn.net/static/video/932/448/51844239:jpeg_preview_small.jpg?20121105221309", @"http://static2.dmcdn.net/static/video/967/438/51834769:jpeg_preview_small.jpg?20121105221020", @"http://static2.dmcdn.net/static/video/362/348/51843263:jpeg_preview_small.jpg?20121105220855", @"http://static2.dmcdn.net/static/video/777/448/51844777:jpeg_preview_small.jpg?20121105220715", @"http://static2.dmcdn.net/static/video/567/348/51843765:jpeg_preview_small.jpg?20121105220708", @"http://static2.dmcdn.net/static/video/905/248/51842509:jpeg_preview_small.jpg?20121105220640", @"http://static2.dmcdn.net/static/video/857/748/51847758:jpeg_preview_small.jpg?20121105221003", @"http://static2.dmcdn.net/static/video/578/348/51843875:jpeg_preview_small.jpg?20121105220350", @"http://static2.dmcdn.net/static/video/214/448/51844412:jpeg_preview_small.jpg?20121105220415", @"http://static2.dmcdn.net/static/video/264/748/51847462:jpeg_preview_small.jpg?20121105220635", @"http://static2.dmcdn.net/static/video/817/748/51847718:jpeg_preview_small.jpg?20121105220233", @"http://static2.dmcdn.net/static/video/807/748/51847708:jpeg_preview_small.jpg?20121105220241", @"http://static2.dmcdn.net/static/video/199/838/51838991:jpeg_preview_small.jpg?20121105220605", @"http://static2.dmcdn.net/static/video/776/748/51847677:jpeg_preview_small.jpg?20121105220150", @"http://static2.dmcdn.net/static/video/986/748/51847689:jpeg_preview_small.jpg?20121105224514", @"http://static2.dmcdn.net/static/video/915/748/51847519:jpeg_preview_small.jpg?20121105222216", @"http://static2.dmcdn.net/static/video/983/448/51844389:jpeg_preview_small.jpg?20121105220116", @"http://static2.dmcdn.net/static/video/751/348/51843157:jpeg_preview_small.jpg?20121105220104", @"http://static2.dmcdn.net/static/video/192/538/51835291:jpeg_preview_small.jpg?20121105220103", @"http://static2.dmcdn.net/static/video/596/448/51844695:jpeg_preview_small.jpg?20121105220033", @"http://static2.dmcdn.net/static/video/750/648/51846057:jpeg_preview_small.jpg?20121105221259", @"http://static2.dmcdn.net/static/video/441/148/51841144:jpeg_preview_small.jpg?20121105215911", @"http://static2.dmcdn.net/static/video/860/448/51844068:jpeg_preview_small.jpg?20121105215905", @"http://static2.dmcdn.net/static/video/995/748/51847599:jpeg_preview_small.jpg?20121105215939", @"http://static2.dmcdn.net/static/video/774/748/51847477:jpeg_preview_small.jpg?20121105223414", @"http://static2.dmcdn.net/static/video/498/648/51846894:jpeg_preview_small.jpg?20121105221807", @"http://static2.dmcdn.net/static/video/011/748/51847110:jpeg_preview_small.jpg?20121105221118", @"http://static2.dmcdn.net/static/video/794/748/51847497:jpeg_preview_small.jpg?20121105220829", @"http://static2.dmcdn.net/static/video/988/648/51846889:jpeg_preview_small.jpg?20121105222149", @"http://static2.dmcdn.net/static/video/769/548/51845967:jpeg_preview_small.jpg?20121105215601", @"http://static2.dmcdn.net/static/video/225/448/51844522:jpeg_preview_small.jpg?20121105215552", @"http://static2.dmcdn.net/static/video/172/308/51803271:jpeg_preview_small.jpg?20121105215455", @"http://static2.dmcdn.net/static/video/994/748/51847499:jpeg_preview_small.jpg?20121105220343", @"http://static2.dmcdn.net/static/video/852/748/51847258:jpeg_preview_small.jpg?20121105221031", @"http://static2.dmcdn.net/static/video/671/838/51838176:jpeg_preview_small.jpg?20121105215421", @"http://static2.dmcdn.net/static/video/172/448/51844271:jpeg_preview_small.jpg?20121105215420", @"http://static2.dmcdn.net/static/video/735/448/51844537:jpeg_preview_small.jpg?20121105215437", @"http://static2.dmcdn.net/static/video/834/448/51844438:jpeg_preview_small.jpg?20121105215431", @"http://static2.dmcdn.net/static/video/613/448/51844316:jpeg_preview_small.jpg?20121105215431", @"http://static2.dmcdn.net/static/video/581/748/51847185:jpeg_preview_small.jpg?20121105220637", @"http://static2.dmcdn.net/static/video/407/648/51846704:jpeg_preview_small.jpg?20121105220316", @"http://static2.dmcdn.net/static/video/460/448/51844064:jpeg_preview_small.jpg?20121105215245", @"http://static2.dmcdn.net/static/video/298/648/51846892:jpeg_preview_small.jpg?20121105220953", @"http://static2.dmcdn.net/static/video/053/748/51847350:jpeg_preview_small.jpg?20121105221113", @"http://static2.dmcdn.net/static/video/996/448/51844699:jpeg_preview_small.jpg?20121105222807", @"http://static2.dmcdn.net/static/video/451/448/51844154:jpeg_preview_small.jpg?20121105221955", @"http://static2.dmcdn.net/static/video/049/648/51846940:jpeg_preview_small.jpg?20121105215910", @"http://static2.dmcdn.net/static/video/091/748/51847190:jpeg_preview_small.jpg?20121105215617", @"http://static2.dmcdn.net/static/video/573/748/51847375:jpeg_preview_small.jpg?20121105223420", @"http://static2.dmcdn.net/static/video/103/248/51842301:jpeg_preview_small.jpg?20121105215014", @"http://static2.dmcdn.net/static/video/991/548/51845199:jpeg_preview_small.jpg?20121105215407", @"http://static2.dmcdn.net/static/video/872/648/51846278:jpeg_preview_small.jpg?20121105220635", @"http://static2.dmcdn.net/static/video/813/748/51847318:jpeg_preview_small.jpg?20121105214729", @"http://static2.dmcdn.net/static/video/153/448/51844351:jpeg_preview_small.jpg?20121105214622", @"http://static2.dmcdn.net/static/video/328/648/51846823:jpeg_preview_small.jpg?20121105214944", @"http://static2.dmcdn.net/static/video/892/748/51847298:jpeg_preview_small.jpg?20121105224514", @"http://static2.dmcdn.net/static/video/640/048/51840046:jpeg_preview_small.jpg?20121105214430", @"http://static2.dmcdn.net/static/video/153/648/51846351:jpeg_preview_small.jpg?20121105214426", @"http://static2.dmcdn.net/static/video/769/248/51842967:jpeg_preview_small.jpg?20121105214255", @"http://static2.dmcdn.net/static/video/720/448/51844027:jpeg_preview_small.jpg?20121105214248", @"http://static2.dmcdn.net/static/video/895/048/51840598:jpeg_preview_small.jpg?20121105214234", @"http://static2.dmcdn.net/static/video/893/348/51843398:jpeg_preview_small.jpg?20121105214157", @"http://static2.dmcdn.net/static/video/351/748/51847153:jpeg_preview_small.jpg?20121105214106", @"http://static2.dmcdn.net/static/video/364/648/51846463:jpeg_preview_small.jpg?20121105215005", @"http://static2.dmcdn.net/static/video/269/938/51839962:jpeg_preview_small.jpg?20121105214014" }; } } }
using System; using System.Collections.Generic; namespace Koishi.BanBuff { public static class Utils { public static List<string> BuffID; static Utils() { BuffID = new List<string>() { "", "Obsidian Skin", "Regeneration", "Swiftness", "Gills", "Ironskin", "Mana Regeneration", "Magic Power", "Featherfall", "Spelunker", "Invisibility", "Shine", "Night Owl", "Battle", "Thorns", "Water Walking", "Archery", "Hunter", "Gravitation", "Shadow Orb", "Poisoned", "Potion Sickness", "Darkness", "Cursed", "On Fire!", "Tipsy", "Well Fed", "Fairy", "Werewolf", "Clairvoyance", "Bleeding", "Confused", "Slow", "Weak", "Merfolk", "Silenced", "Broken Armor", "Horrified", "The Tongue", "Cursed Inferno", "Pet Bunny", "Baby Penguin", "Pet Turtle", "Paladin's Shield", "Frostburn", "Baby Eater", "Chilled", "Frozen", "Honey", "Pygmies", "Baby Skeletron Head", "Baby Hornet", "Tiki Spirit", "Pet Lizard", "Pet Parrot", "Baby Truffle", "Pet Sapling", "Wisp", "Rapid Healing", "Shadow Dodge", "Leaf Crystal", "Baby Dinosaur", "Ice Barrier", "Panic!", "Baby Slime", "Eyeball Spring", "Baby Snowman", "Burning", "Suffocation", "Ichor", "Venom", "Weapon Imbue: Venom", "Midas", "Weapon Imbue: Cursed Flames", "Weapon Imbue: Fire", "Weapon Imbue: Gold", "Weapon Imbue: Ichor", "Weapon Imbue: Nanites", "Weapon Imbue: Confetti", "Weapon Imbue: Poison", "Blackout", "Pet Spider", "Squashling", "Ravens", "Black Cat", "Cursed Sapling", "Water Candle", "Cozy Fire", "Chaos State", "Heart Lamp", "Rudolph", "Puppy", "Baby Grinch", "Ammo Box", "Mana Sickness", "Beetle Endurance", "Beetle Endurance", "Beetle Endurance", "Beetle Might", "Beetle Might", "Beetle Might", "Fairy", "Fairy", "Wet", "Mining", "Heartreach", "Calm", "Builder", "Titan", "Flipper", "Summoning", "Dangersense", "Ammo Reservation", "Lifeforce", "Endurance", "Rage", "Inferno", "Wrath", "Minecart", "Lovestruck", "Stinky", "Fishing", "Sonar", "Crate", "Warmth", "Hornet", "Imp", "Zephyr Fish", "Bunny Mount", "Pigron Mount", "Slime Mount", "Turtle Mount", "Bee Mount", "Spider", "Twins", "Pirate", "Mini Minotaur", "Slime", "Minecart", "Sharknado", "UFO", "UFO Mount", "Drill Mount", "Scutlix Mount", "Electrified", "Moon Bite", "Happy!", "Banner", "Feral Bite", "Webbed", "Bewitched", "Life Drain", "Magic Lantern", "Shadowflame", "Baby Face Monster", "Crimson Heart", "Stoned", "Peace Candle", "Star in a Bottle", "Sharpened", "Dazed", "Deadly Sphere", "Unicorn Mount", "Obstructed", "Distorted", "Dryad's Blessing", "Minecart", "Minecart", "Cute Fishron Mount", "Penetrated", "Solar Blaze", "Solar Blaze", "Solar Blaze", "Life Nebula", "Life Nebula", "Life Nebula", "Mana Nebula", "Mana Nebula", "Mana Nebula", "Damage Nebula", "Damage Nebula", "Damage Nebula", "Stardust Cell", "Celled", "Minecart", "Minecart", "Dryad's Bane", "Stardust Guardian", "Stardust Dragon", "Daybroken", "Suspicious Looking Eye", "Companion Cube" }; } public static BuffBan GetBuffBanById(int id) { for (int i = 0; i < Koishi.BanBuff.BanBuffPlugin.BuffManager.BuffBans.Count; i++) { if (Koishi.BanBuff.BanBuffPlugin.BuffManager.BuffBans[i].ID == id) { return Koishi.BanBuff.BanBuffPlugin.BuffManager.BuffBans[i]; } } return null; } public static List<int> GetBuffByIdOrName(string text) { int num = -1; if (!int.TryParse(text, out num)) { return Utils.GetBuffByName(text); } return new List<int>() { num }; } public static List<int> GetBuffByName(string name) { List<int> nums = new List<int>(); string lower = name.ToLower(); foreach (string current in Utils.BuffID) { if (string.IsNullOrEmpty(current)) { continue; } if (current.ToLower() == lower) { return new List<int>() { Utils.BuffID.IndexOf(current) }; } else { if (current.ToLower().StartsWith(lower)) { nums.Add(Utils.BuffID.IndexOf(current)); } } } return nums; } public static string Name(int id) { if (id < 1 || id >= BuffID.Count) { return string.Format("Unknown Buff ({0})", id); } return string.Format("{0} ({1})", BuffID[id], id); } } }
using DotVVM.Framework.Binding; using DotVVM.Framework.Hosting; using System; using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Compilation.ControlTree; namespace DotVVM.Framework.Controls { public abstract class GridViewColumn : DotvvmBindableObject { [PopDataContextManipulationAttribute] public string HeaderText { get { return (string)GetValue(HeaderTextProperty); } set { SetValue(HeaderTextProperty, value); } } public static readonly DotvvmProperty HeaderTextProperty = DotvvmProperty.Register<string, GridViewColumn>(c => c.HeaderText, null); [MarkupOptions(MappingMode = MappingMode.InnerElement)] [PopDataContextManipulationAttribute] public ITemplate HeaderTemplate { get { return (ITemplate)GetValue(HeaderTemplateProperty); } set { SetValue(HeaderTemplateProperty, value); } } public static readonly DotvvmProperty HeaderTemplateProperty = DotvvmProperty.Register<ITemplate, GridViewColumn>(c => c.HeaderTemplate, null); [MarkupOptions(MappingMode = MappingMode.InnerElement)] [PopDataContextManipulationAttribute] public ITemplate FilterTemplate { get { return (ITemplate)GetValue(FilterTemplateProperty); } set { SetValue(FilterTemplateProperty, value); } } public static readonly DotvvmProperty FilterTemplateProperty = DotvvmProperty.Register<ITemplate, GridViewColumn>(c => c.FilterTemplate, null); [MarkupOptions(AllowBinding = false)] public string SortExpression { get { return (string)GetValue(SortExpressionProperty); } set { SetValue(SortExpressionProperty, value); } } public static readonly DotvvmProperty SortExpressionProperty = DotvvmProperty.Register<string, GridViewColumn>(c => c.SortExpression); [MarkupOptions(AllowBinding = false)] public string SortAscendingHeaderCssClass { get { return (string)GetValue(SortAscendingHeaderCssClassProperty); } set { SetValue(SortAscendingHeaderCssClassProperty, value); } } public static readonly DotvvmProperty SortAscendingHeaderCssClassProperty = DotvvmProperty.Register<string, GridViewColumn>(c => c.SortAscendingHeaderCssClass, "sort-asc"); [MarkupOptions(AllowBinding = false)] public string SortDescendingHeaderCssClass { get { return (string)GetValue(SortDescendingHeaderCssClassProperty); } set { SetValue(SortDescendingHeaderCssClassProperty, value); } } public static readonly DotvvmProperty SortDescendingHeaderCssClassProperty = DotvvmProperty.Register<string, GridViewColumn>(c => c.SortDescendingHeaderCssClass, "sort-desc"); [MarkupOptions(AllowBinding = false)] public bool AllowSorting { get { return (bool)GetValue(AllowSortingProperty); } set { SetValue(AllowSortingProperty, value); } } public static readonly DotvvmProperty AllowSortingProperty = DotvvmProperty.Register<bool, GridViewColumn>(c => c.AllowSorting, false); public string CssClass { get { return (string)GetValue(CssClassProperty); } set { SetValue(CssClassProperty, value); } } public static readonly DotvvmProperty CssClassProperty = DotvvmProperty.Register<string, GridViewColumn>(c => c.CssClass); [MarkupOptions(AllowBinding = false)] public bool IsEditable { get { return (bool)GetValue(IsEditableProperty); } set { SetValue(IsEditableProperty, value); } } public static readonly DotvvmProperty IsEditableProperty = DotvvmProperty.Register<bool, GridViewColumn>(t => t.IsEditable, true); [PopDataContextManipulationAttribute] public string HeaderCssClass { get { return (string)GetValue(HeaderCssClassProperty); } set { SetValue(HeaderCssClassProperty, value); } } public static readonly DotvvmProperty HeaderCssClassProperty = DotvvmProperty.Register<string, GridViewColumn>(c => c.HeaderCssClass); [MarkupOptions(AllowBinding = false)] public string Width { get { return (string)GetValue(WidthProperty); } set { SetValue(WidthProperty, value); } } public static readonly DotvvmProperty WidthProperty = DotvvmProperty.Register<string, GridViewColumn>(c => c.Width, null); [PopDataContextManipulationAttribute] [MarkupOptions(AllowHardCodedValue = false)] public bool Visible { get { return (bool)GetValue(VisibleProperty); } set { SetValue(VisibleProperty, value); } } public static readonly DotvvmProperty VisibleProperty = DotvvmProperty.Register<bool, GridViewColumn>(c => c.Visible, true); public abstract void CreateControls(IDotvvmRequestContext context, DotvvmControl container); public abstract void CreateEditControls(IDotvvmRequestContext context, DotvvmControl container); public virtual void CreateHeaderControls(IDotvvmRequestContext context, GridView gridView, Action<string> sortCommand, HtmlGenericControl cell, IGridViewDataSet gridViewDataSet) { if (HeaderTemplate != null) { HeaderTemplate.BuildContent(context, cell); return; } if (AllowSorting) { if (sortCommand == null) { throw new DotvvmControlException(this, "Cannot use column sorting where no sort command is specified. Either put IGridViewDataSet in the DataSource property of the GridView, or set the SortChanged command on the GridView to implement custom sorting logic!"); } var sortExpression = GetSortExpression(); var linkButton = new LinkButton(); linkButton.SetValue(LinkButton.TextProperty, GetValueRaw(HeaderTextProperty)); cell.Children.Add(linkButton); var bindingId = linkButton.GetValue(Internal.UniqueIDProperty) + "_sortBinding"; var binding = new CommandBindingExpression(h => sortCommand(sortExpression), bindingId); linkButton.SetBinding(ButtonBase.ClickProperty, binding); SetSortedCssClass(cell, gridViewDataSet); } else { var literal = new Literal(); literal.SetValue(Literal.TextProperty, GetValueRaw(HeaderTextProperty)); cell.Children.Add(literal); } } public virtual void CreateFilterControls(IDotvvmRequestContext context, GridView gridView, HtmlGenericControl cell, IGridViewDataSet gridViewDataSet) { if (FilterTemplate != null) { var placeholder = new PlaceHolder(); cell.Children.Add(placeholder); FilterTemplate.BuildContent(context, placeholder); } } private void SetSortedCssClass(HtmlGenericControl cell, IGridViewDataSet gridViewDataSet) { if (RenderOnServer) { if (gridViewDataSet != null) { if (gridViewDataSet.SortExpression == GetSortExpression()) { if (gridViewDataSet.SortDescending) { cell.Attributes["class"] = SortDescendingHeaderCssClass; } else { cell.Attributes["class"] = SortAscendingHeaderCssClass; } } } } else { cell.Attributes["data-bind"] = $"css: {{ '{SortDescendingHeaderCssClass}': ko.unwrap(ko.unwrap($gridViewDataSet).SortExpression) == '{GetSortExpression()}' && ko.unwrap(ko.unwrap($gridViewDataSet).SortDescending), '{SortAscendingHeaderCssClass}': ko.unwrap(ko.unwrap($gridViewDataSet).SortExpression) == '{GetSortExpression()}' && !ko.unwrap(ko.unwrap($gridViewDataSet).SortDescending)}}"; } } protected virtual string GetSortExpression() { // TODO: verify that sortExpression is a single property name return SortExpression; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Xml; using SIL.Code; namespace Bloom.Book { public interface IPage { string Id { get; } string Caption { get; } string CaptionI18nId { get; } Image Thumbnail { get; } string XPathToDiv { get; } XmlElement GetDivNodeForThisPage(); bool Required { get; } bool CanRelocate { get;} Book Book { get; set; } bool IsBackMatter { get; } bool IsXMatter { get; } string GetCaptionOrPageNumber(ref int pageNumber, out string captionI18nId); int GetIndex(); string IdOfFirstAncestor { get;} } public class Page : IPage { private readonly string _id; private readonly Func<IPage, Image> _getThumbnail; private readonly Func<IPage, XmlElement> _getDivNodeForThisPageMethod; private List<string> _classes; private List<string> _tags; private string[] _pageLineage; public Page(Book book, XmlElement sourcePage, string caption, string captionI18nId, /*Func<IPage, Image> getThumbnail,*/ Func<IPage, XmlElement> getDivNodeForThisPageMethod) { _id = FixPageId(sourcePage.Attributes["id"].Value); var lineage = sourcePage.Attributes["data-pagelineage"]; _pageLineage = lineage == null ? new string[] {} : lineage.Value.Split(new[] { ',' }); Guard.AgainstNull(book,"Book"); Book = book; _getDivNodeForThisPageMethod = getDivNodeForThisPageMethod; Caption = caption; CaptionI18nId = captionI18nId; ReadClasses(sourcePage); ReadPageTags(sourcePage); } //in the beta, 0.8, the ID of the page in the front-matter template was used for the 1st //page of every book. This screws up thumbnail caching. private string FixPageId(string id) { //Note: there were 4 other xmatter pages with teh same problem, but I'm only fixing //the cover page one a the moment. We've solved the larger problem for new books (or those //with rebuilt front matter). const string guidMistakenlyUsedForEveryCoverPage = "74731b2d-18b0-420f-ac96-6de20f659810"; if (id == guidMistakenlyUsedForEveryCoverPage) { return Guid.NewGuid().ToString(); } return id; } // // private void ReadPageLabel(XmlElement sourcePage) // { // PageLabel = "Foobar"; // } // protected string PageLabel { get; set; } private void ReadClasses(XmlElement sourcePage) { _classes = new List<string>(); var classesString = sourcePage.GetAttribute("class"); if (!string.IsNullOrEmpty(classesString)) { _classes.AddRange(classesString.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)); } } private void ReadPageTags(XmlElement sourcePage) { _tags = new List<string>(); var tags = sourcePage.GetAttribute("data-page"); if (!string.IsNullOrEmpty(tags)) { _tags.AddRange(tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); } } public bool Required { get { return _tags.Contains("required"); } } public bool CanRelocate { get { if(Required) //review: for now, we're conflating "required" with "can't move" return false; // front and back matter and similar can't move // For now, can't move pages while translating a book. // Enhance: possibly we may want to allow moving pages ADDED to the original book? if (Book.LockedDown) return false; return true; } } public Book Book { get; set; } public bool IsBackMatter { get { return XMatterHelper.IsBackMatterPage(_getDivNodeForThisPageMethod(this)); } } public bool IsFrontMatter { get { return XMatterHelper.IsFrontMatterPage(_getDivNodeForThisPageMethod(this)); } } public bool IsXMatter { get { return IsBackMatter || IsFrontMatter;} } public string GetCaptionOrPageNumber(ref int pageNumber, out string captionI18nId) { string outerXml = _getDivNodeForThisPageMethod(this).OuterXml; //at the moment, I can't remember why this is even needed (it works fine without it), but we might as well honor it in code if (outerXml.Contains("bloom-startPageNumbering")) { pageNumber = 1; } if (outerXml.Contains("numberedPage") || outerXml.Contains("countPageButDoNotShowNumber")) { pageNumber++; } if(outerXml.Contains("numberedPage")) { captionI18nId = pageNumber.ToString(); return pageNumber.ToString(); } // This phrase is too long to use as a page label. // We can generalize this if we get others. if (Caption == "Comprehension Questions") { Caption = "Quiz"; } if (CaptionI18nId == null) { if (string.IsNullOrEmpty(Caption)) captionI18nId = null; else captionI18nId = "TemplateBooks.PageLabel." + Caption; } else captionI18nId = CaptionI18nId; return Caption; } public string Id{get { return _id; }} public string Caption { get; private set; } public string CaptionI18nId { get; private set; } public Image Thumbnail { get { return _getThumbnail(this); } } public string XPathToDiv { get { return "/html/body/div[@id='"+_id+"']";} } public XmlElement GetDivNodeForThisPage() { return _getDivNodeForThisPageMethod(this); } public static string GetPageSelectorXPath(XmlDocument pageDom) { // var id = pageDom.SelectSingleNodeHonoringDefaultNS("/html/body/div").Attributes["id"].Value; var id = pageDom.SelectSingleNode("/html/body/div").Attributes["id"].Value; return string.Format("/html/body/div[@id='{0}']", id); } /// <summary> /// Return the index of this page in the IEnumerable of pages /// </summary> /// <returns>Index of the page, or -1 if the page was not found</returns> public int GetIndex() { var i = 0; foreach (var page in Book.GetPages()) { if (page == this) return i; i++; } return -1; } public string IdOfFirstAncestor { get { return _pageLineage.FirstOrDefault(); } } internal void UpdateLineage(string[] lineage) { _pageLineage = lineage; } } }
using System; using System.Collections; using System.IO; using SharpVectors.Dom.Events; using NUnit.Framework; using SharpVectors.Dom; [TestFixture] public class EventTests { public class EventMonitor { public int AtEvents = 0; public int BubbledEvents = 0; public int CapturedEvents = 0; public int Events = 0; public void EventHandler( IEvent @event) { switch (@event.EventPhase) { case EventPhase.AtTarget: AtEvents++; break; case EventPhase.BubblingPhase: BubbledEvents++; break; case EventPhase.CapturingPhase: CapturedEvents++; break; } Events++; } } public class ListenerRemover { public ArrayList events; public ArrayList listeners; public ListenerRemover( ArrayList events, ArrayList listeners) { this.events = events; this.listeners = listeners; } public void EventHandler( IEvent @event) { IEventTarget target = @event.CurrentTarget; events.Add(@event); foreach (ListenerRemover listener in listeners) { target.RemoveEventListener("foo", new EventListener(listener.EventHandler), false); } } } public IDocument LoadDocument( string uri) { Document document = new Document(); document.Load(new FileInfo(uri).FullName); return document; } [Test] public void TestConstructor() { Event e = new Event("mousemove", true, false); Assert.AreEqual(null, e.NamespaceUri); Assert.AreEqual("mousemove", e.Type); Assert.AreEqual(true, e.Bubbles); Assert.AreEqual(false, e.Cancelable); e = new Event("dummy", false, true); Assert.AreEqual(null, e.NamespaceUri); Assert.AreEqual("dummy", e.Type); Assert.AreEqual(false, e.Bubbles); Assert.AreEqual(true, e.Cancelable); } [Test] public void TestConstructorNs() { Event e = new Event("uievents", "mousemove", true, false); Assert.AreEqual("uievents", e.NamespaceUri); Assert.AreEqual("mousemove", e.Type); Assert.AreEqual(true, e.Bubbles); Assert.AreEqual(false, e.Cancelable); e = new Event("namespace", "dummy", false, true); Assert.AreEqual("namespace", e.NamespaceUri); Assert.AreEqual("dummy", e.Type); Assert.AreEqual(false, e.Bubbles); Assert.AreEqual(true, e.Cancelable); } [Test] public void TestConstructorEmptyType() { Event e = new Event("", true, false); Assert.AreEqual(null, e.NamespaceUri); Assert.AreEqual("", e.Type); Assert.AreEqual(true, e.Bubbles); Assert.AreEqual(false, e.Cancelable); } [Test] public void TestConstructorEmptyTypeNs() { Event e = new Event("namespaceUri", "", true, false); Assert.AreEqual("namespaceUri", e.NamespaceUri); Assert.AreEqual("", e.Type); Assert.AreEqual(true, e.Bubbles); Assert.AreEqual(false, e.Cancelable); } [Test] public void TestConstructorNullType() { Event e = new Event("namespaceUri", null, true, false); Assert.AreEqual("namespaceUri", e.NamespaceUri); Assert.AreEqual(null, e.Type); Assert.AreEqual(true, e.Bubbles); Assert.AreEqual(false, e.Cancelable); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="createEvent01"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent-createEvent"/> /// An object implementing the Event interface is created by using /// DocumentEvent.createEvent method with eventType equals "Events". /// </test> [Test] public void W3CTS_CreateEvent01() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("MutationEvents"); Assert.IsNotNull(@event); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="createEvent02"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent-createEvent"/> /// An object implementing the Event interface is created by using /// DocumentEvent.createEvent method with eventType equals "MutationEvents". /// Only applicable if implementation supports MutationEvents. /// </test> [Test] public void W3CTS_CreateEvent02() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); Assert.IsNotNull(@event); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="createEvent03"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent-createEvent"/> /// An object implementing the Event interface is created by using /// DocumentEvent.createEvent method with eventType equals "UIEvents". /// Only applicable if implementation supports the "UIEvents" feature. /// </test> [Test] public void W3CTS_CreateEvent03() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("UIEvent"); Assert.IsNotNull(@event); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="createEvent04"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent-createEvent"/> /// An object implementing the Event interface is created by using /// DocumentEvent.createEvent method with eventType equals "MouseEvent". /// Only applicable if implementation supports the "MouseEvent" feature. /// </test> [Test] public void W3CTS_CreateEvent04() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("MouseEvent"); Assert.IsNotNull(@event); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="createEvent05"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent-createEvent"/> /// An object implementing the Event interface is created by using /// DocumentEvent.createEvent method with eventType equals "HTMLEvents". /// Only applicable if implementation supports the "HTMLEvents" feature. /// </test> [Test] public void W3CTS_CreateEvent05() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("HTMLEvents"); Assert.IsNotNull(@event); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="DocumentEventCast01"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent"/> /// A document is created using implementation.createDocument and /// cast to a DocumentEvent interface. /// </test> [Test] public void W3CTS_DocumentEventCast01() { IDocument document = LoadDocument("hc_staff.xml"); IDocumentEvent documentEvent = (IDocumentEvent)document; } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="EventTargetCast01"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent"/> /// A document is created using implementation.createDocument and /// cast to a EventTarget interface. /// </test> [Test] public void W3CTS_EventTargetCast01() { IDocument document = LoadDocument("hc_staff.xml"); IDocumentEvent documentEvent = (IDocumentEvent)document; } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent01"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-17189187"/> /// A null reference is passed to EventTarget.dispatchEvent(). Should raise implementation /// specific exception per file:///D:/apache-xml/2001/DOM-Test-Suite/lib/specs/Level-2/Core/core.html#ID-17189187 /// </test> [Test] public void W3CTS_DispatchEvent01() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = null; try { ((IEventTarget)document).DispatchEvent(@event); } catch (NullReferenceException) { return; } Assert.IsTrue(false); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent02"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// An created but not initialized event is passed to EventTarget.dispatchEvent(). Should raise /// UNSPECIFIED_EVENT_TYPE_ERR EventException. /// </test> [Test] public void W3CTS_DispatchEvent02() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); try { ((IEventTarget)document).DispatchEvent(@event); } catch (EventException e) { Assert.IsTrue(e.Code == EventExceptionCode.UnspecifiedEventTypeErr); return; } Assert.IsTrue(false); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent03"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// An created but not initialized event is passed to EventTarget.dispatchEvent(). Should raise /// UNSPECIFIED_EVENT_TYPE_ERR EventException. /// </test> [Test] public void W3CTS_DispatchEvent03() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("MutationEvents"); try { ((IEventTarget)document).DispatchEvent(@event); } catch (EventException e) { Assert.IsTrue(e.Code == EventExceptionCode.UnspecifiedEventTypeErr); return; } Assert.IsTrue(false); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent04"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// An created but not initialized event is passed to EventTarget.dispatchEvent(). Should raise /// UNSPECIFIED_EVENT_TYPE_ERR EventException. /// </test> [Test] public void W3CTS_DispatchEvent04() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("UIEvents"); try { ((IEventTarget)document).DispatchEvent(@event); } catch (EventException e) { Assert.IsTrue(e.Code == EventExceptionCode.UnspecifiedEventTypeErr); return; } Assert.IsTrue(false); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent05"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// An created but not initialized event is passed to EventTarget.dispatchEvent(). Should raise /// UNSPECIFIED_EVENT_TYPE_ERR EventException. /// </test> [Test] public void W3CTS_DispatchEvent05() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("MouseEvents"); try { ((IEventTarget)document).DispatchEvent(@event); } catch (EventException e) { Assert.IsTrue(e.Code == EventExceptionCode.UnspecifiedEventTypeErr); return; } Assert.IsTrue(false); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent06"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// An created but not initialized event is passed to EventTarget.dispatchEvent(). Should raise /// UNSPECIFIED_EVENT_TYPE_ERR EventException. /// </test> [Test] public void W3CTS_DispatchEvent06() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("HTMLEvents"); try { ((IEventTarget)document).DispatchEvent(@event); } catch (EventException e) { Assert.IsTrue(e.Code == EventExceptionCode.UnspecifiedEventTypeErr); return; } Assert.IsTrue(false); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent07"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// An Event initialized with a empty name is passed to EventTarget.dispatchEvent(). Should raise /// UNSPECIFIED_EVENT_TYPE_ERR EventException. /// </test> [Test] public void W3CTS_DispatchEvent07() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); @event.InitEvent("", false, false); try { ((IEventTarget)document).DispatchEvent(@event); } catch (EventException e) { Assert.IsTrue(e.Code == EventExceptionCode.UnspecifiedEventTypeErr); return; } Assert.IsTrue(false, "Didn't fail as expected"); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent08"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// An EventListener registered on the target node with capture false, should /// recieve any event fired on that node. /// </test> [Test] public void W3CTS_DispatchEvent08() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); EventMonitor eventMonitor = new EventMonitor(); @event.InitEvent("foo", true, false); ((IEventTarget)document).AddEventListener("foo", new EventListener(eventMonitor.EventHandler), false); ((IEventTarget)document).DispatchEvent(@event); Assert.AreEqual(1, eventMonitor.AtEvents); Assert.AreEqual(0, eventMonitor.BubbledEvents); Assert.AreEqual(0, eventMonitor.CapturedEvents); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent09"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// An event is dispatched to the document with a capture listener attached. /// A capturing EventListener will not be triggered by events dispatched directly /// to the EventTarget upon which it is registered. /// </test> [Test] public void W3CTS_DispatchEvent09() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); EventMonitor eventMonitor = new EventMonitor(); @event.InitEvent("foo", true, false); ((IEventTarget)document).AddEventListener("foo", new EventListener(eventMonitor.EventHandler), true); ((IEventTarget)document).DispatchEvent(@event); Assert.AreEqual(eventMonitor.AtEvents, 0); Assert.AreEqual(eventMonitor.BubbledEvents, 0); Assert.AreEqual(eventMonitor.CapturedEvents, 0); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent10"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// The same monitor is registered twice and an event is dispatched. The monitor should /// recieve only one handleEvent call. /// </test> [Test] public void W3CTS_DispatchEvent10() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); EventMonitor eventMonitor = new EventMonitor(); @event.InitEvent("foo", true, false); ((IEventTarget)document).AddEventListener("foo", new EventListener(eventMonitor.EventHandler), false); ((IEventTarget)document).AddEventListener("foo", new EventListener(eventMonitor.EventHandler), false); ((IEventTarget)document).DispatchEvent(@event); Assert.AreEqual(eventMonitor.AtEvents, 1); Assert.AreEqual(eventMonitor.BubbledEvents, 0); Assert.AreEqual(eventMonitor.CapturedEvents, 0); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent11"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// The same monitor is registered twice, removed once, and an event is dispatched. /// The monitor should recieve only no handleEvent calls. /// </test> [Test] public void W3CTS_DispatchEvent11() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); EventMonitor eventMonitor = new EventMonitor(); @event.InitEvent("foo", true, false); ((IEventTarget)document).AddEventListener("foo", new EventListener(eventMonitor.EventHandler), false); ((IEventTarget)document).AddEventListener("foo", new EventListener(eventMonitor.EventHandler), false); ((IEventTarget)document).RemoveEventListener("foo", new EventListener(eventMonitor.EventHandler), false); ((IEventTarget)document).DispatchEvent(@event); Assert.AreEqual(eventMonitor.AtEvents, 0); Assert.AreEqual(eventMonitor.BubbledEvents, 0); Assert.AreEqual(eventMonitor.CapturedEvents, 0); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent12"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// A monitor is added, multiple calls to removeEventListener /// are mde with similar but not identical arguments, and an event is dispatched. /// The monitor should recieve handleEvent calls. /// </test> [Test] public void W3CTS_DispatchEvent12() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); EventMonitor eventMonitor = new EventMonitor(); EventMonitor otherMonitor = new EventMonitor(); @event.InitEvent("foo", true, false); ((IEventTarget)document).AddEventListener("foo", new EventListener(eventMonitor.EventHandler), false); ((IEventTarget)document).RemoveEventListener("foo", new EventListener(eventMonitor.EventHandler), true); ((IEventTarget)document).RemoveEventListener("food", new EventListener(eventMonitor.EventHandler), false); ((IEventTarget)document).RemoveEventListener("foo", new EventListener(otherMonitor.EventHandler), true); ((IEventTarget)document).DispatchEvent(@event); Assert.AreEqual(eventMonitor.Events, 1); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="dispatchEvent13"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent"/> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#xpointer(id('Events-EventTarget-dispatchEvent')/raises/exception[@name='EventException']/descr/p[substring-before(.,':')='UNSPECIFIED_EVENT_TYPE_ERR'])"/> /// Two listeners are registered on the same target, each of which will remove both itself and /// the other on the first event. Only one should see the event since event listeners /// can never be invoked after being removed. /// </test> [Test] public void W3CTS_DispatchEvent13() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); EventMonitor eventMonitor = new EventMonitor(); EventMonitor otherMonitor = new EventMonitor(); @event.InitEvent("foo", true, false); ArrayList listeners = new ArrayList(); ArrayList events = new ArrayList(); ListenerRemover listenerRemover1 = new ListenerRemover(events, listeners); ListenerRemover listenerRemover2 = new ListenerRemover(events, listeners); listeners.Add(listenerRemover1); listeners.Add(listenerRemover2); ((IEventTarget)document).AddEventListener("foo", new EventListener(listenerRemover1.EventHandler), false); ((IEventTarget)document).AddEventListener("foo", new EventListener(listenerRemover2.EventHandler), false); ((IEventTarget)document).DispatchEvent(@event); Assert.AreEqual(events.Count, 1); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="initEvent01"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-Event-initEvent"/> /// The Event.initEvent method is called for event returned by DocumentEvent.createEvent("events") /// and the state is checked to see if it reflects the parameters. /// </test> [Test] public void W3CTS_InitEvent01() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); Assert.IsTrue(@event != null); @event.InitEvent("rotate", true, false); Assert.AreEqual("rotate", @event.Type); Assert.AreEqual(true, @event.Bubbles); Assert.AreEqual(false, @event.Cancelable); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="initEvent02"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-Event-initEvent"/> /// The IEvent.InitEvent method is called for event returned by IDocumentEvent.CreateEvent("events") /// and the state is checked to see if it reflects the parameters. /// </test> [Test] public void W3CTS_InitEvent02() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); Assert.IsTrue(@event != null); @event.InitEvent("rotate", false, true); Assert.AreEqual(false, @event.Bubbles); Assert.AreEqual(true, @event.Cancelable); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="initEvent03"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-Event-initEvent"/> /// The IEvent.InitEvent method is called for event returned by IDocumentEvent.CreateEvent("events") /// and the state is checked to see if it reflects the parameters. InitEvent may be /// called multiple times and the last time is definitive. /// </test> [Test] public void W3CTS_InitEvent03() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("Events"); Assert.IsTrue(@event != null); @event.InitEvent("rotate", true, true); Assert.AreEqual("rotate", @event.Type); Assert.AreEqual(true, @event.Bubbles); Assert.AreEqual(true, @event.Cancelable); @event.InitEvent("shear", false, false); Assert.AreEqual("shear", @event.Type); Assert.AreEqual(false, @event.Bubbles); Assert.AreEqual(false, @event.Cancelable); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="initEvent04"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-Event-initEvent"/> /// The IEvent.InitEvent method is called for event returned by /// IDocumentEvent.CreateEvent("MutationEvents") /// and the state is checked to see if it reflects the parameters. /// </test> [Test] public void W3CTS_InitEvent04() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("MutationEvents"); Assert.IsTrue(@event != null); @event.InitEvent("rotate", true, false); Assert.AreEqual("rotate", @event.Type); Assert.AreEqual(true, @event.Bubbles); Assert.AreEqual(false, @event.Cancelable); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="initEvent05"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-Event-initEvent"/> /// The IEvent.InitEvent method is called for event returned by /// IDocumentEvent.CreateEvent("MutationEvents") /// and the state is checked to see if it reflects the parameters. /// </test> [Test] public void W3CTS_InitEvent05() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("MutationEvents"); Assert.IsTrue(@event != null); @event.InitEvent("rotate", false, true); Assert.AreEqual("rotate", @event.Type); Assert.AreEqual(false, @event.Bubbles); Assert.AreEqual(true, @event.Cancelable); } /// <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-2" name="initEvent06"> /// <subject resource="http://www.w3.org/TR/DOM-Level-2-Events/events#Events-Event-initEvent"/> /// The IEvent.InitEvent method is called for event returned by /// IDocumentEvent.CreateEvent("MutationEvents") /// and the state is checked to see if it reflects the parameters. InitEvent may be /// called multiple times and the last time is definitive. /// </test> [Test] public void W3CTS_InitEvent06() { IDocument document = LoadDocument("hc_staff.xml"); IEvent @event = ((IDocumentEvent)document).CreateEvent("MutationEvents"); Assert.IsTrue(@event != null); @event.InitEvent("rotate", true, true); Assert.AreEqual("rotate", @event.Type); Assert.AreEqual(true, @event.Bubbles); Assert.AreEqual(true, @event.Cancelable); @event.InitEvent("shear", false, false); Assert.AreEqual("shear", @event.Type); Assert.AreEqual(false, @event.Bubbles); Assert.AreEqual(false, @event.Cancelable); } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.DynamoDBv2.Model { /// <summary> /// <para>Contains the properties of a table.</para> /// </summary> public class TableDescription { private List<AttributeDefinition> attributeDefinitions = new List<AttributeDefinition>(); private string tableName; private List<KeySchemaElement> keySchema = new List<KeySchemaElement>(); private string tableStatus; private DateTime? creationDateTime; private ProvisionedThroughputDescription provisionedThroughput; private long? tableSizeBytes; private long? itemCount; private List<LocalSecondaryIndexDescription> localSecondaryIndexes = new List<LocalSecondaryIndexDescription>(); /// <summary> /// An array of <i>AttributeDefinition</i> objects. Each of these objects describes one attribute in the table and index key schema. Each /// <i>AttributeDefinition</i> object in this array is composed of: <ul> <li> <i>AttributeName</i> - The name of the attribute. </li> <li> /// <i>AttributeType</i> - The data type for the attribute. </li> </ul> /// /// </summary> public List<AttributeDefinition> AttributeDefinitions { get { return this.attributeDefinitions; } set { this.attributeDefinitions = value; } } /// <summary> /// Adds elements to the AttributeDefinitions collection /// </summary> /// <param name="attributeDefinitions">The values to add to the AttributeDefinitions collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithAttributeDefinitions(params AttributeDefinition[] attributeDefinitions) { foreach (AttributeDefinition element in attributeDefinitions) { this.attributeDefinitions.Add(element); } return this; } /// <summary> /// Adds elements to the AttributeDefinitions collection /// </summary> /// <param name="attributeDefinitions">The values to add to the AttributeDefinitions collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithAttributeDefinitions(IEnumerable<AttributeDefinition> attributeDefinitions) { foreach (AttributeDefinition element in attributeDefinitions) { this.attributeDefinitions.Add(element); } return this; } // Check to see if AttributeDefinitions property is set internal bool IsSetAttributeDefinitions() { return this.attributeDefinitions.Count > 0; } /// <summary> /// The name of the table. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>3 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[a-zA-Z0-9_.-]+</description> /// </item> /// </list> /// </para> /// </summary> public string TableName { get { return this.tableName; } set { this.tableName = value; } } /// <summary> /// Sets the TableName property /// </summary> /// <param name="tableName">The value to set for the TableName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithTableName(string tableName) { this.tableName = tableName; return this; } // Check to see if TableName property is set internal bool IsSetTableName() { return this.tableName != null; } /// <summary> /// The primary key structure for the table. Each <i>KeySchemaElement</i> consists of: <ul> <li> <i>AttributeName</i> - The name of the /// attribute. </li> <li> <i>KeyType</i> - The key type for the attribute. Can be either <c>HASH</c> or <c>RANGE</c>. </li> </ul> For more /// information about primary keys, see <a /// href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelPrimaryKey">Primary Key</a> in the <i>Amazon /// DynamoDB Developer Guide</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 2</description> /// </item> /// </list> /// </para> /// </summary> public List<KeySchemaElement> KeySchema { get { return this.keySchema; } set { this.keySchema = value; } } /// <summary> /// Adds elements to the KeySchema collection /// </summary> /// <param name="keySchema">The values to add to the KeySchema collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithKeySchema(params KeySchemaElement[] keySchema) { foreach (KeySchemaElement element in keySchema) { this.keySchema.Add(element); } return this; } /// <summary> /// Adds elements to the KeySchema collection /// </summary> /// <param name="keySchema">The values to add to the KeySchema collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithKeySchema(IEnumerable<KeySchemaElement> keySchema) { foreach (KeySchemaElement element in keySchema) { this.keySchema.Add(element); } return this; } // Check to see if KeySchema property is set internal bool IsSetKeySchema() { return this.keySchema.Count > 0; } /// <summary> /// Represents the current state of the table: <ul> <li> <i>CREATING</i> - The table is being created, as the result of a <i>CreateTable</i> /// operation. </li> <li> <i>UPDATING</i> - The table is being updated, as the result of an <i>UpdateTable</i> operation. </li> <li> /// <i>DELETING</i> - The table is being deleted, as the result of a <i>DeleteTable</i> operation. </li> <li> <i>ACTIVE</i> - The table is ready /// for use. </li> </ul> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>CREATING, UPDATING, DELETING, ACTIVE</description> /// </item> /// </list> /// </para> /// </summary> public string TableStatus { get { return this.tableStatus; } set { this.tableStatus = value; } } /// <summary> /// Sets the TableStatus property /// </summary> /// <param name="tableStatus">The value to set for the TableStatus property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithTableStatus(string tableStatus) { this.tableStatus = tableStatus; return this; } // Check to see if TableStatus property is set internal bool IsSetTableStatus() { return this.tableStatus != null; } /// <summary> /// Represents the date and time when the table was created, in <a href="http://www.epochconverter.com/">UNIX epoch time</a> format. /// /// </summary> public DateTime CreationDateTime { get { return this.creationDateTime ?? default(DateTime); } set { this.creationDateTime = value; } } /// <summary> /// Sets the CreationDateTime property /// </summary> /// <param name="creationDateTime">The value to set for the CreationDateTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithCreationDateTime(DateTime creationDateTime) { this.creationDateTime = creationDateTime; return this; } // Check to see if CreationDateTime property is set internal bool IsSetCreationDateTime() { return this.creationDateTime.HasValue; } /// <summary> /// Represents the provisioned throughput settings for the table, consisting of read and write capacity units, along with data about increases /// and decreases. /// /// </summary> public ProvisionedThroughputDescription ProvisionedThroughput { get { return this.provisionedThroughput; } set { this.provisionedThroughput = value; } } /// <summary> /// Sets the ProvisionedThroughput property /// </summary> /// <param name="provisionedThroughput">The value to set for the ProvisionedThroughput property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithProvisionedThroughput(ProvisionedThroughputDescription provisionedThroughput) { this.provisionedThroughput = provisionedThroughput; return this; } // Check to see if ProvisionedThroughput property is set internal bool IsSetProvisionedThroughput() { return this.provisionedThroughput != null; } /// <summary> /// Represents the total size of the specified table, in bytes. Amazon DynamoDB updates this value approximately every six hours. Recent changes /// might not be reflected in this value. /// /// </summary> public long TableSizeBytes { get { return this.tableSizeBytes ?? default(long); } set { this.tableSizeBytes = value; } } /// <summary> /// Sets the TableSizeBytes property /// </summary> /// <param name="tableSizeBytes">The value to set for the TableSizeBytes property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithTableSizeBytes(long tableSizeBytes) { this.tableSizeBytes = tableSizeBytes; return this; } // Check to see if TableSizeBytes property is set internal bool IsSetTableSizeBytes() { return this.tableSizeBytes.HasValue; } /// <summary> /// Represents the number of items in the specified table. Amazon DynamoDB updates this value approximately every six hours. Recent changes /// might not be reflected in this value. /// /// </summary> public long ItemCount { get { return this.itemCount ?? default(long); } set { this.itemCount = value; } } /// <summary> /// Sets the ItemCount property /// </summary> /// <param name="itemCount">The value to set for the ItemCount property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithItemCount(long itemCount) { this.itemCount = itemCount; return this; } // Check to see if ItemCount property is set internal bool IsSetItemCount() { return this.itemCount.HasValue; } /// <summary> /// Represents one or more secondary indexes on the table. Each index is scoped to a given hash key value. Tables with one or more local /// secondary indexes are subject to an item collection size limit, where the amount of data within a given item collection cannot exceed 10 GB. /// Each element is composed of: <ul> <li> <i>IndexName</i> - The name of the secondary index. </li> <li> <i>KeySchema</i> - Specifies the /// complete index key schema. The attribute names in the key schema must be between 1 and 255 characters (inclusive). The key schema must begin /// with the same hash key attribute as the table. </li> <li> <i>Projection</i> - Specifies attributes that are copied (projected) from the /// table into the index. These are in addition to the primary key attributes and index key attributes, which are automatically projected. Each /// attribute specification is composed of: <ul> <li> <i>ProjectionType</i> - One of the following: <ul> <li> <c>KEYS_ONLY</c> - Only the index /// and primary keys are projected into the index. </li> <li> <c>INCLUDE</c> - Only the specified table attributes are projected into the index. /// The list of projected attributes are in <i>NonKeyAttributes</i>. </li> <li> <c>ALL</c> - All of the table attributes are projected into the /// index. </li> </ul> </li> <li> <i>NonKeyAttributes</i> - A list of one or more non-key attribute names that are projected into the index. The /// total count of attributes specified in <i>NonKeyAttributes</i>, summed across all of the local secondary indexes, must not exceed 20. If you /// project the same attribute into two different indexes, this counts as two distinct attributes when determining the total. </li> </ul> </li> /// <li> <i>IndexSizeBytes</i> - Represents the total size of the index, in bytes. Amazon DynamoDB updates this value approximately every six /// hours. Recent changes might not be reflected in this value.</li> <li> <i>ItemCount</i> - Represents the number of items in the index. Amazon /// DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value. </li> </ul> If the table is /// in the <c>DELETING</c> state, no information about indexes will be returned. /// /// </summary> public List<LocalSecondaryIndexDescription> LocalSecondaryIndexes { get { return this.localSecondaryIndexes; } set { this.localSecondaryIndexes = value; } } /// <summary> /// Adds elements to the LocalSecondaryIndexes collection /// </summary> /// <param name="localSecondaryIndexes">The values to add to the LocalSecondaryIndexes collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithLocalSecondaryIndexes(params LocalSecondaryIndexDescription[] localSecondaryIndexes) { foreach (LocalSecondaryIndexDescription element in localSecondaryIndexes) { this.localSecondaryIndexes.Add(element); } return this; } /// <summary> /// Adds elements to the LocalSecondaryIndexes collection /// </summary> /// <param name="localSecondaryIndexes">The values to add to the LocalSecondaryIndexes collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public TableDescription WithLocalSecondaryIndexes(IEnumerable<LocalSecondaryIndexDescription> localSecondaryIndexes) { foreach (LocalSecondaryIndexDescription element in localSecondaryIndexes) { this.localSecondaryIndexes.Add(element); } return this; } // Check to see if LocalSecondaryIndexes property is set internal bool IsSetLocalSecondaryIndexes() { return this.localSecondaryIndexes.Count > 0; } } }
/* ==================================================================== 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 NPOI.HSSF.Util; namespace NPOI.HSSF.UserModel { using System; using NPOI.HSSF.Record; using NPOI.SS.UserModel; /// <summary> /// Represents a Font used in a workbook. /// @version 1.0-pre /// @author Andrew C. Oliver /// </summary> public class HSSFFont:NPOI.SS.UserModel.IFont { public const String FONT_ARIAL = "Arial"; private FontRecord font; private short index; /// <summary> /// Initializes a new instance of the <see cref="HSSFFont"/> class. /// </summary> /// <param name="index">The index.</param> /// <param name="rec">The record.</param> public HSSFFont(short index, FontRecord rec) { font = rec; this.index = index; } /// <summary> /// Get the name for the font (i.e. Arial) /// </summary> /// <value>the name of the font to use</value> public String FontName { get { return font.FontName; } set { font.FontName = value; } } /// <summary> /// Get the index within the HSSFWorkbook (sequence within the collection of Font objects) /// </summary> /// <value>Unique index number of the Underlying record this Font represents (probably you don't care /// Unless you're comparing which one is which)</value> public short Index { get { return index; } } /// <summary> /// Get or sets the font height in Unit's of 1/20th of a point. Maybe you might want to /// use the GetFontHeightInPoints which matches to the familiar 10, 12, 14 etc.. /// </summary> /// <value>height in 1/20ths of a point.</value> public double FontHeight { get { return font.FontHeight; } set { font.FontHeight = (short)value; } } /// <summary> /// Gets or sets the font height in points. /// </summary> /// <value>height in the familiar Unit of measure - points.</value> public short FontHeightInPoints { get { return (short)(font.FontHeight / 20); } set { font.FontHeight=(short)(value * 20); } } /// <summary> /// Gets or sets whether to use italics or not /// </summary> /// <value><c>true</c> if this instance is italic; otherwise, <c>false</c>.</value> public bool IsItalic { get { return font.IsItalic; } set { font.IsItalic=value; } } /// <summary> /// Get whether to use a strikeout horizontal line through the text or not /// </summary> /// <value> /// strikeout or not /// </value> public bool IsStrikeout { get { return font.IsStrikeout; } set { font.IsStrikeout=value; } } /// <summary> /// Gets or sets the color for the font. /// </summary> /// <value>The color to use.</value> public short Color { get { return font.ColorPaletteIndex; } set { font.ColorPaletteIndex=value; } } /// <summary> /// get the color value for the font /// </summary> /// <param name="wb">HSSFWorkbook</param> /// <returns></returns> public HSSFColor GetHSSFColor(HSSFWorkbook wb) { HSSFPalette pallette = wb.GetCustomPalette(); return pallette.GetColor(Color); } /// <summary> /// Gets or sets the boldness to use /// </summary> /// <value>The boldweight.</value> public short Boldweight { get { return font.BoldWeight; } set { font.BoldWeight=value; } } /// <summary> /// Gets or sets normal,base or subscript. /// </summary> /// <value>offset type to use (none,base,sub)</value> public FontSuperScript TypeOffset { get { return font.SuperSubScript; } set { font.SuperSubScript = value; } } /// <summary> /// Gets or sets the type of text Underlining to use /// </summary> /// <value>The Underlining type.</value> public FontUnderlineType Underline { get { return font.Underline; } set { font.Underline = value; } } /// <summary> /// Gets or sets the char set to use. /// </summary> /// <value>The char set.</value> public short Charset { get { return font.Charset; } set { font.Charset = (byte)value; } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { return "NPOI.HSSF.UserModel.HSSFFont{" + font + "}"; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { int prime = 31; int result = 1; result = prime * result + ((font == null) ? 0 : font.GetHashCode()); result = prime * result + index; return result; } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj is HSSFFont) { HSSFFont other = (HSSFFont)obj; if (font == null) { if (other.font != null) return false; } else if (!font.Equals(other.font)) return false; if (index != other.index) return false; return true; } return false; } } }
/* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Specialized; using Spring.Util; namespace Spring.Collections { /// <summary> /// Synchronized <see cref="Hashtable"/> that, unlike hashtable created /// using <see cref="Hashtable.Synchronized"/> method, synchronizes /// reads from the underlying hashtable in addition to writes. /// </summary> /// <remarks> /// <p> /// In addition to synchronizing reads, this implementation also fixes /// IEnumerator/ICollection issue described at /// http://msdn.microsoft.com/en-us/netframework/aa570326.aspx /// (search for SynchronizedHashtable for issue description), by implementing /// <see cref="IEnumerator"/> interface explicitly, and returns thread safe enumerator /// implementations as well. /// </p> /// <p> /// This class should be used whenever a truly synchronized <see cref="Hashtable"/> /// is needed. /// </p> /// </remarks> /// <author>Aleksandar Seovic</author> [Serializable] public class SynchronizedHashtable : IDictionary, ICollection, IEnumerable, ICloneable { private readonly bool _ignoreCase; private readonly Hashtable _table; /// <summary> /// Initializes a new instance of <see cref="SynchronizedHashtable"/> /// </summary> public SynchronizedHashtable() : this(new Hashtable(), false) { } /// <summary> /// Initializes a new instance of <see cref="SynchronizedHashtable"/> /// </summary> public SynchronizedHashtable(bool ignoreCase) : this(new Hashtable(), ignoreCase) { } /// <summary> /// Initializes a new instance of <see cref="SynchronizedHashtable"/>, copying initial entries from <param name="dictionary"/> /// handling keys depending on <param name="ignoreCase"/>. /// </summary> public SynchronizedHashtable(IDictionary dictionary, bool ignoreCase) { AssertUtils.ArgumentNotNull(dictionary, "dictionary"); this._table = (ignoreCase) ? CollectionsUtil.CreateCaseInsensitiveHashtable(dictionary) : new Hashtable(dictionary); this._ignoreCase = ignoreCase; } /// <summary> /// Creates a <see cref="SynchronizedHashtable"/> instance that /// synchronizes access to the underlying <see cref="Hashtable"/>. /// </summary> /// <param name="other">the hashtable to be synchronized</param> protected SynchronizedHashtable(Hashtable other) { AssertUtils.ArgumentNotNull(other, "other"); this._table = other; } /// <summary> /// Creates a <see cref="SynchronizedHashtable"/> wrapper that synchronizes /// access to the passed <see cref="Hashtable"/>. /// </summary> /// <param name="other">the hashtable to be synchronized</param> public static SynchronizedHashtable Wrap(Hashtable other) { return new SynchronizedHashtable(other); } ///<summary> ///Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"></see> object is read-only. ///</summary> ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> object is read-only; otherwise, false. ///</returns> public bool IsReadOnly { get { lock (SyncRoot) { return _table.IsReadOnly; } } } ///<summary> ///Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"></see> object has a fixed size. ///</summary> ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> object has a fixed size; otherwise, false. ///</returns> public bool IsFixedSize { get { lock (SyncRoot) { return _table.IsFixedSize; } } } ///<summary> ///Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"></see> is synchronized (thread safe). ///</summary> ///<returns> ///true if access to the <see cref="T:System.Collections.ICollection"></see> is synchronized (thread safe); otherwise, false. ///</returns> public bool IsSynchronized { get { return true; } } ///<summary> ///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> ///<returns> ///An <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> public ICollection Keys { get { lock (SyncRoot) { return _table.Keys; } } } ///<summary> ///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> ///<returns> ///An <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> public ICollection Values { get { lock (SyncRoot) { return _table.Values; } } } ///<summary> ///Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"></see>. ///</summary> ///<returns> ///An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"></see>. ///</returns> public object SyncRoot { get { return _table.SyncRoot; } } ///<summary> ///Gets the number of elements contained in the <see cref="T:System.Collections.ICollection"></see>. ///</summary> ///<returns> ///The number of elements contained in the <see cref="T:System.Collections.ICollection"></see>. ///</returns> public int Count { get { lock (SyncRoot) { return _table.Count; } } } ///<summary> ///Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> ///<param name="value">The <see cref="T:System.Object"></see> to use as the value of the element to add. </param> ///<param name="key">The <see cref="T:System.Object"></see> to use as the key of the element to add. </param> ///<exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.IDictionary"></see> object. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> is read-only.-or- The <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception><filterpriority>2</filterpriority> public void Add(object key, object value) { lock (SyncRoot) { _table.Add(key, value); } } ///<summary> ///Removes all elements from the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> object is read-only. </exception><filterpriority>2</filterpriority> public void Clear() { lock (SyncRoot) { _table.Clear(); } } ///<summary> ///Creates a new object that is a copy of the current instance. ///</summary> ///<returns> ///A new object that is a copy of this instance. ///</returns> public object Clone() { lock (SyncRoot) { return new SynchronizedHashtable(this, _ignoreCase); } } ///<summary> ///Determines whether the <see cref="T:System.Collections.IDictionary"></see> object contains an element with the specified key. ///</summary> ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> contains an element with the key; otherwise, false. ///</returns> ///<param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary"></see> object.</param> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public bool Contains(object key) { lock (SyncRoot) { return _table.Contains(key); } } ///<summary> /// Returns, whether this <see cref="IDictionary"/> contains an entry with the specified <paramref name="key"/>. ///</summary> ///<param name="key">The key to look for</param> ///<returns><see lang="true"/>, if this <see cref="IDictionary"/> contains an entry with this <paramref name="key"/></returns> public bool ContainsKey(object key) { lock (SyncRoot) { return _table.ContainsKey(key); } } ///<summary> /// Returns, whether this <see cref="IDictionary"/> contains an entry with the specified <paramref name="value"/>. ///</summary> ///<param name="value">The value to look for</param> ///<returns><see lang="true"/>, if this <see cref="IDictionary"/> contains an entry with this <paramref name="value"/></returns> public bool ContainsValue(object value) { lock (SyncRoot) { return _table.ContainsValue(value); } } ///<summary> ///Copies the elements of the <see cref="T:System.Collections.ICollection"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index. ///</summary> ///<param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing. </param> ///<param name="index">The zero-based index in array at which copying begins. </param> ///<exception cref="T:System.ArgumentNullException">array is null. </exception> ///<exception cref="T:System.ArgumentException">The type of the source <see cref="T:System.Collections.ICollection"></see> cannot be cast automatically to the type of the destination array. </exception> ///<exception cref="T:System.ArgumentOutOfRangeException">index is less than zero. </exception> ///<exception cref="T:System.ArgumentException">array is multidimensional.-or- index is equal to or greater than the length of array.-or- The number of elements in the source <see cref="T:System.Collections.ICollection"></see> is greater than the available space from index to the end of the destination array. </exception><filterpriority>2</filterpriority> public void CopyTo(Array array, int index) { lock (SyncRoot) { _table.CopyTo(array, index); } } ///<summary> ///Returns an <see cref="T:System.Collections.IDictionaryEnumerator"></see> object for the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> ///<returns> ///An <see cref="T:System.Collections.IDictionaryEnumerator"></see> object for the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> public IDictionaryEnumerator GetEnumerator() { lock (SyncRoot) { return new SynchronizedDictionaryEnumerator(SyncRoot, _table.GetEnumerator()); } } ///<summary> ///Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> ///<param name="key">The key of the element to remove. </param> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> object is read-only.-or- The <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public void Remove(object key) { lock (SyncRoot) { _table.Remove(key); } } ///<summary> ///Returns an enumerator that iterates through a collection. ///</summary> ///<returns> ///An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection. ///</returns> IEnumerator IEnumerable.GetEnumerator() { lock (SyncRoot) { return new SynchronizedEnumerator(SyncRoot, ((IEnumerable)_table).GetEnumerator()); } } ///<summary> ///Gets or sets the element with the specified key. ///</summary> ///<returns> ///The element with the specified key. ///</returns> ///<param name="key">The key of the element to get or set. </param> ///<exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.IDictionary"></see> object is read-only.-or- The property is set, key does not exist in the collection, and the <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public object this[object key] { get { lock (SyncRoot) { return _table[key]; } } set { lock (SyncRoot) { _table[key] = value; } } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls.Generators; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Layout; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.VisualTree; namespace Avalonia.Controls { /// <summary> /// A drop-down list control. /// </summary> public class DropDown : SelectingItemsControl { /// <summary> /// Defines the <see cref="IsDropDownOpen"/> property. /// </summary> public static readonly DirectProperty<DropDown, bool> IsDropDownOpenProperty = AvaloniaProperty.RegisterDirect<DropDown, bool>( nameof(IsDropDownOpen), o => o.IsDropDownOpen, (o, v) => o.IsDropDownOpen = v); /// <summary> /// Defines the <see cref="MaxDropDownHeight"/> property. /// </summary> public static readonly StyledProperty<double> MaxDropDownHeightProperty = AvaloniaProperty.Register<DropDown, double>(nameof(MaxDropDownHeight), 200); /// <summary> /// Defines the <see cref="SelectionBoxItem"/> property. /// </summary> public static readonly DirectProperty<DropDown, object> SelectionBoxItemProperty = AvaloniaProperty.RegisterDirect<DropDown, object>(nameof(SelectionBoxItem), o => o.SelectionBoxItem); private bool _isDropDownOpen; private Popup _popup; private object _selectionBoxItem; /// <summary> /// Initializes static members of the <see cref="DropDown"/> class. /// </summary> static DropDown() { FocusableProperty.OverrideDefaultValue<DropDown>(true); SelectedItemProperty.Changed.AddClassHandler<DropDown>(x => x.SelectedItemChanged); } /// <summary> /// Gets or sets a value indicating whether the dropdown is currently open. /// </summary> public bool IsDropDownOpen { get { return _isDropDownOpen; } set { SetAndRaise(IsDropDownOpenProperty, ref _isDropDownOpen, value); } } /// <summary> /// Gets or sets the maximum height for the dropdown list. /// </summary> public double MaxDropDownHeight { get { return GetValue(MaxDropDownHeightProperty); } set { SetValue(MaxDropDownHeightProperty, value); } } /// <summary> /// Gets or sets the item to display as the control's content. /// </summary> protected object SelectionBoxItem { get { return _selectionBoxItem; } set { SetAndRaise(SelectionBoxItemProperty, ref _selectionBoxItem, value); } } /// <inheritdoc/> protected override IItemContainerGenerator CreateItemContainerGenerator() { return new ItemContainerGenerator<DropDownItem>( this, DropDownItem.ContentProperty, DropDownItem.ContentTemplateProperty); } /// <inheritdoc/> protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); this.UpdateSelectionBoxItem(this.SelectedItem); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); if (!e.Handled && e.NavigationMethod == NavigationMethod.Directional) { e.Handled = UpdateSelectionFromEventSource(e.Source); } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled) { if (e.Key == Key.F4 || ((e.Key == Key.Down || e.Key == Key.Up) && ((e.Modifiers & InputModifiers.Alt) != 0))) { IsDropDownOpen = !IsDropDownOpen; e.Handled = true; } else if (IsDropDownOpen && (e.Key == Key.Escape || e.Key == Key.Enter)) { IsDropDownOpen = false; e.Handled = true; } if (!IsDropDownOpen) { if (e.Key == Key.Down) { if (SelectedIndex == -1) SelectedIndex = 0; if (++SelectedIndex >= ItemCount) SelectedIndex = 0; e.Handled = true; } else if (e.Key == Key.Up) { if (--SelectedIndex < 0) SelectedIndex = ItemCount - 1; e.Handled = true; } } } } /// <inheritdoc/> protected override void OnPointerPressed(PointerPressedEventArgs e) { if (!e.Handled) { if (((IVisual)e.Source).GetVisualRoot() is PopupRoot) { if (UpdateSelectionFromEventSource(e.Source)) { _popup?.Close(); e.Handled = true; } } else { IsDropDownOpen = !IsDropDownOpen; e.Handled = true; } } base.OnPointerPressed(e); } /// <inheritdoc/> protected override void OnTemplateApplied(TemplateAppliedEventArgs e) { if (_popup != null) { _popup.Opened -= PopupOpened; } _popup = e.NameScope.Get<Popup>("PART_Popup"); _popup.Opened += PopupOpened; } private void PopupOpened(object sender, EventArgs e) { var selectedIndex = SelectedIndex; if (selectedIndex != -1) { var container = ItemContainerGenerator.ContainerFromIndex(selectedIndex); container?.Focus(); } } private void SelectedItemChanged(AvaloniaPropertyChangedEventArgs e) { UpdateSelectionBoxItem(e.NewValue); } private void UpdateSelectionBoxItem(object item) { var contentControl = item as IContentControl; if (contentControl != null) { item = contentControl.Content; } var control = item as IControl; if (control != null) { control.Measure(Size.Infinity); SelectionBoxItem = new Rectangle { Width = control.DesiredSize.Width, Height = control.DesiredSize.Height, Fill = new VisualBrush { Visual = control, Stretch = Stretch.None, AlignmentX = AlignmentX.Left, } }; } else { SelectionBoxItem = item; } } } }
// 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; using Xunit; namespace Tests.Collections { public enum CollectionOrder { Unspecified, Sequential } public abstract class IEnumerableTest<T> { private const int EnumerableSize = 16; protected T DefaultValue { get { return default(T); } } protected bool MoveNextAtEndThrowsOnModifiedCollection { get { return true; } } protected virtual CollectionOrder CollectionOrder { get { return CollectionOrder.Sequential; } } protected abstract bool IsResetNotSupported { get; } protected abstract bool IsGenericCompatibility { get; } protected abstract object GenerateItem(); protected object[] GenerateItems(int size) { var ret = new object[size]; for (var i = 0; i < size; i++) { ret[i] = GenerateItem(); } return ret; } /// <summary> /// When overridden in a derived class, Gets an instance of the enumerable under test containing the given items. /// </summary> /// <param name="items">The items to initialize the enumerable with.</param> /// <returns>An instance of the enumerable under test containing the given items.</returns> protected abstract IEnumerable GetEnumerable(object[] items); /// <summary> /// When overridden in a derived class, invalidates any enumerators for the given IEnumerable. /// </summary> /// <param name="enumerable">The <see cref="IEnumerable" /> to invalidate enumerators for.</param> /// <returns>The new set of items in the <see cref="IEnumerable" /></returns> protected abstract object[] InvalidateEnumerator( IEnumerable enumerable); private void RepeatTest( Action<IEnumerator, object[], int> testCode, int iters = 3) { object[] items = GenerateItems(32); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); for (var i = 0; i < iters; i++) { testCode(enumerator, items, i); if (IsResetNotSupported) { enumerator = enumerable.GetEnumerator(); } else { enumerator.Reset(); } } } private void RepeatTest( Action<IEnumerator, object[]> testCode, int iters = 3) { RepeatTest((e, i, it) => testCode(e, i), iters); } [Fact] public void MoveNextHitsAllItems() { RepeatTest( (enumerator, items) => { var iterations = 0; while (enumerator.MoveNext()) { iterations++; } Assert.Equal(items.Length, iterations); }); } [Fact] public void CurrentThrowsAfterEndOfCollection() { if (IsGenericCompatibility) { return; // apparently it is okay if enumerator.Current doesn't throw when the collection is generic. } RepeatTest( (enumerator, items) => { while (enumerator.MoveNext()) { } Assert.Throws<InvalidOperationException>( () => enumerator.Current); }); } [Fact] public void MoveNextFalseAfterEndOfCollection() { RepeatTest( (enumerator, items) => { while (enumerator.MoveNext()) { } Assert.False(enumerator.MoveNext()); }); } [Fact] public void Current() { // Verify that current returns proper result. RepeatTest( (enumerator, items, iteration) => { if (iteration == 1) { VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); } else { VerifyEnumerator(enumerator, items); } }); } [Fact] public void Reset() { if (IsResetNotSupported) { RepeatTest( (enumerator, items) => { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); }); RepeatTest( (enumerator, items, iter) => { if (iter == 1) { VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); for (var i = 0; i < 3; i++) { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); } VerifyEnumerator( enumerator, items, items.Length/2, items.Length - (items.Length/2), false, true); } else if (iter == 2) { VerifyEnumerator(enumerator, items); for (var i = 0; i < 3; i++) { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); } VerifyEnumerator( enumerator, items, 0, 0, false, true); } else { VerifyEnumerator(enumerator, items); } }); } else { RepeatTest( (enumerator, items, iter) => { if (iter == 1) { VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); enumerator.Reset(); enumerator.Reset(); } else if (iter == 3) { VerifyEnumerator(enumerator, items); enumerator.Reset(); enumerator.Reset(); } else { VerifyEnumerator(enumerator, items); } }, 5); } } [Fact] public void ModifyCollectionWithNewEnumerator() { IEnumerable enumerable = GetEnumerable(GenerateItems(EnumerableSize)); IEnumerator enumerator = enumerable.GetEnumerator(); InvalidateEnumerator(enumerable); VerifyModifiedEnumerator(enumerator, null, true, false); } [Fact] public void EnumerateFirstItemThenModify() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); VerifyEnumerator(enumerator, items, 0, 1, true, false); object currentItem = enumerator.Current; InvalidateEnumerator(enumerable); VerifyModifiedEnumerator( enumerator, currentItem, false, false); } [Fact] public void EnumeratePartOfCollectionThenModify() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); object currentItem = enumerator.Current; InvalidateEnumerator(enumerable); VerifyModifiedEnumerator( enumerator, currentItem, false, false); } [Fact] public void EnumerateEntireCollectionThenModify() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); VerifyEnumerator( enumerator, items, 0, items.Length, true, false); object currentItem = enumerator.Current; InvalidateEnumerator(enumerable); VerifyModifiedEnumerator( enumerator, currentItem, false, true); } [Fact] public void EnumerateThenModifyThrows() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); object currentItem = enumerator.Current; InvalidateEnumerator(enumerable); Assert.Equal(currentItem, enumerator.Current); Assert.Throws<InvalidOperationException>( () => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>( () => enumerator.Reset()); } [Fact] [ActiveIssue(1170)] public void EnumeratePastEndThenModify() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); // enumerate to the end VerifyEnumerator(enumerator, items); // add elements to the collection InvalidateEnumerator(enumerable); // check that it throws proper exceptions VerifyModifiedEnumerator( enumerator, DefaultValue, true, true); } private void VerifyModifiedEnumerator( IEnumerator enumerator, object expectedCurrent, bool expectCurrentThrow, bool atEnd) { if (expectCurrentThrow) { Assert.Throws<InvalidOperationException>( () => enumerator.Current); } else { object current = enumerator.Current; for (var i = 0; i < 3; i++) { Assert.Equal(expectedCurrent, current); current = enumerator.Current; } } if (!atEnd || MoveNextAtEndThrowsOnModifiedCollection) { Assert.Throws<InvalidOperationException>( () => enumerator.MoveNext()); } else { Assert.False(enumerator.MoveNext()); } if (!IsResetNotSupported) { Assert.Throws<InvalidOperationException>( () => enumerator.Reset()); } } private void VerifyEnumerator( IEnumerator enumerator, object[] expectedItems) { VerifyEnumerator( enumerator, expectedItems, 0, expectedItems.Length, true, true); } private void VerifyEnumerator( IEnumerator enumerator, object[] expectedItems, int startIndex, int count, bool validateStart, bool validateEnd) { bool needToMatchAllExpectedItems = count - startIndex == expectedItems.Length; if (validateStart) { for (var i = 0; i < 3; i++) { Assert.Throws<InvalidOperationException>( () => enumerator.Current); } } int iterations; if (CollectionOrder == CollectionOrder.Unspecified) { var itemsVisited = new BitArray( needToMatchAllExpectedItems ? count : expectedItems.Length, false); for (iterations = 0; iterations < count && enumerator.MoveNext(); iterations++) { object currentItem = enumerator.Current; var itemFound = false; for (var i = 0; i < itemsVisited.Length; ++i) { if (!itemsVisited[i] && Equals( currentItem, expectedItems[ i + (needToMatchAllExpectedItems ? startIndex : 0)])) { itemsVisited[i] = true; itemFound = true; break; } } Assert.True(itemFound, "itemFound"); for (var i = 0; i < 3; i++) { object tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } } if (needToMatchAllExpectedItems) { for (var i = 0; i < itemsVisited.Length; i++) { Assert.True(itemsVisited[i]); } } else { var visitedItemCount = 0; for (var i = 0; i < itemsVisited.Length; i++) { if (itemsVisited[i]) { ++visitedItemCount; } } Assert.Equal(count, visitedItemCount); } } else if (CollectionOrder == CollectionOrder.Sequential) { for (iterations = 0; iterations < count && enumerator.MoveNext(); iterations++) { object currentItem = enumerator.Current; Assert.Equal(expectedItems[iterations], currentItem); for (var i = 0; i < 3; i++) { object tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } } } else { throw new ArgumentException( "CollectionOrder is invalid."); } Assert.Equal(count, iterations); if (validateEnd) { for (var i = 0; i < 3; i++) { Assert.False( enumerator.MoveNext(), "enumerator.MoveNext() returned true past the expected end."); } if (IsGenericCompatibility) { return; } // apparently it is okay if enumerator.Current doesn't throw when the collection is generic. for (var i = 0; i < 3; i++) { Assert.Throws<InvalidOperationException>( () => enumerator.Current); } } } } }
// 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.Text; using System.Text.RegularExpressions; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudioTools; namespace Microsoft.PythonTools.Commands { /// <summary> /// Provides the command to send selected text from a buffer to the remote REPL window. /// </summary> class FillParagraphCommand : Command { private readonly System.IServiceProvider _serviceProvider; private const string _sentenceTerminators = ".!?"; private static Regex _startDocStringRegex = new Regex("^[\t ]*('''|\"\"\")[\t ]*$"); private static Regex _endDocStringRegex = new Regex("('''|\"\"\")[\t ]*$"); private static Regex _commentRegex = new Regex("^[\t ]*#+[\t ]*"); private static Regex _whitespaceRegex = new Regex("^[\t ]+"); public FillParagraphCommand(System.IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public override void DoCommand(object sender, EventArgs args) { FillCommentParagraph(CommonPackage.GetActiveTextView(_serviceProvider)); } /// <summary> /// FillCommentParagraph fills the text in a contiguous block of comment lines, /// each having the same [whitespace][commentchars][whitespace] prefix. Each /// resulting line is as long as possible without exceeding the /// Config.CodeWidth.Width column. This function also works on paragraphs /// within doc strings, each having the same leading whitespace. Leading /// whitespace must be space characters. /// </summary> public void FillCommentParagraph(ITextView view) { var caret = view.Caret; var txtbuf = view.TextBuffer; // don't clone Caret, need point that works at buffer level not view. var bufpt = caret.Position.BufferPosition; //txtbuf.GetTextPoint(caret.CurrentPosition); var fillPrefix = GetFillPrefix(view, bufpt); // TODO: Fix doc string parsing if (fillPrefix.Prefix == null || fillPrefix.Prefix.Length == 0 || fillPrefix.IsDocString) { System.Windows.MessageBox.Show(Strings.FillCommentSelectionError, Strings.ProductTitle); return; } var start = FindParagraphStart(bufpt, fillPrefix); var end = FindParagraphEnd(bufpt, fillPrefix); string newLine = view.Options.GetNewLineCharacter(); using (var edit = view.TextBuffer.CreateEdit()) { int startLine = start.GetContainingLine().LineNumber; string[] lines = new string[end.GetContainingLine().LineNumber - startLine + 1]; for (int i = 0; i < lines.Length; i++) { lines[i] = start.Snapshot.GetLineFromLineNumber(startLine + i).GetText(); } int curLine = 0, curOffset = fillPrefix.Prefix.Length; int columnCutoff = 80 - fillPrefix.Prefix.Length; int defaultColumnCutoff = columnCutoff; StringBuilder newText = new StringBuilder(end.Position - start.Position); while (curLine < lines.Length) { string curLineText = lines[curLine]; int lastSpace = curLineText.Length; // skip leading white space while (curOffset < curLineText.Length && Char.IsWhiteSpace(curLineText[curOffset])) { curOffset++; } // find next word for (int i = curOffset; i < curLineText.Length; i++) { if (Char.IsWhiteSpace(curLineText[i])) { lastSpace = i; break; } } if (lastSpace - curOffset < columnCutoff || columnCutoff == defaultColumnCutoff) { // we found a like break in the region and it's a reasonable size or // we have a really long word that we need to append unbroken if (columnCutoff == defaultColumnCutoff) { // first time we're appending to this line newText.Append(fillPrefix.Prefix); } newText.Append(curLineText, curOffset, lastSpace - curOffset); // append appropriate spacing if (_sentenceTerminators.IndexOf(curLineText[lastSpace - 1]) != -1 || // we end in punctuation ((lastSpace - curOffset) > 1 && // we close a paren that ends in punctuation curLineText[lastSpace - curOffset] == ')' && _sentenceTerminators.IndexOf(curLineText[lastSpace - 2]) != -1)) { newText.Append(" "); columnCutoff -= lastSpace - curOffset + 2; } else { newText.Append(' '); columnCutoff -= lastSpace - curOffset + 1; } curOffset = lastSpace + 1; } else { // current word is too long to append. Start the next line. while (newText.Length > 0 && newText[newText.Length - 1] == ' ') { newText.Length = newText.Length - 1; } newText.Append(newLine); columnCutoff = defaultColumnCutoff; } if (curOffset >= lines[curLine].Length) { // we're not reading from the next line curLine++; curOffset = fillPrefix.Prefix.Length; } } while (newText.Length > 0 && newText[newText.Length - 1] == ' ') { newText.Length = newText.Length - 1; } // commit the new text edit.Delete(start.Position, end.Position - start.Position); edit.Insert(start.Position, newText.ToString()); edit.Apply(); } } private static int GetFirstNonWhiteSpaceCharacterOnLine(ITextSnapshotLine line) { var text = line.GetText(); for (int i = 0; i < text.Length; i++) { if (!Char.IsWhiteSpace(text[i])) { return line.Start.Position + i; } } return line.End.Position; } private bool PrevNotParaStart(FillPrefix prefix, int prev_num, int ln_num, string prev_txt, Regex regexp) { var notBufFirstLn = prev_num != ln_num; var notFileDocStrAndHasPrefix = !string.IsNullOrEmpty(prefix.Prefix) && prev_txt.StartsWithOrdinal(prefix.Prefix); var isFileDocStrAndNotEmptyLine = string.IsNullOrEmpty(prefix.Prefix) && !string.IsNullOrEmpty(prev_txt); var notDocStringOrNoTripleQuotesYet = !(prefix.IsDocString && regexp.Match(prev_txt).Success); return (notBufFirstLn && (notFileDocStrAndHasPrefix || isFileDocStrAndNotEmptyLine) && notDocStringOrNoTripleQuotesYet); } // Finds first contiguous line that has the same prefix as the current line. // If the prefix is not a comment start prefix, then this function stops at // the first line with triple quotes or that is empty. It returns the point // positioned at the start of the first line. private SnapshotPoint FindParagraphStart(SnapshotPoint point, FillPrefix prefix) { var buf = point.Snapshot.TextBuffer; Regex regexp = null; if (prefix.IsDocString) { regexp = new Regex(prefix + "('''|\"\"\")"); // Check for edge case of being on first line of docstring with quotes. if (regexp.Match(point.GetContainingLine().GetText()).Success) { return point.GetContainingLine().Start; } } var line = point.GetContainingLine(); var ln_num = line.LineNumber; var prev_num = ln_num - 1; if (prev_num < 0) { return line.Start; } var prev_txt = point.Snapshot.GetLineFromLineNumber(prev_num).GetText(); while (PrevNotParaStart(prefix, prev_num, ln_num, prev_txt, regexp)) { ln_num = prev_num; prev_num--; if (prev_num < 0) { return new SnapshotPoint(point.Snapshot, 0); } prev_txt = point.Snapshot.GetLineFromLineNumber(prev_num).GetText(); } SnapshotPoint res; if (!prefix.IsDocString || string.IsNullOrEmpty(prev_txt) || _startDocStringRegex.IsMatch(prev_txt)) { // Normally ln is the start for filling, prev line stopped the loop. res = point.Snapshot.GetLineFromLineNumber(ln_num).Start; } else { // If we're in a doc string, and prev is not just the triple quotes // line, and prev is not empty, then we use prev line because it // has text on it we need to fill. Point is already on prev line. res = point.Snapshot.GetLineFromLineNumber(prev_num).Start; } return res; } private bool NextNotParaEnd(FillPrefix prefix, int next_num, int ln_num, string next_txt, Regex regexp) { var notBufLastLn = next_num != ln_num; var notFileDocStrAndHasPrefix = !string.IsNullOrEmpty(prefix.Prefix) && next_txt.StartsWithOrdinal(prefix.Prefix); var isFileDocStrAndNotEmptyLine = string.IsNullOrEmpty(prefix.Prefix) && string.IsNullOrEmpty(next_txt); var notDocStringOrNoTripleQuotesYet = !(prefix.IsDocString && regexp.Match(next_txt).Success); return (notBufLastLn && (notFileDocStrAndHasPrefix || isFileDocStrAndNotEmptyLine) && notDocStringOrNoTripleQuotesYet); } // Finds last contiguous line that has the same prefix as the current line. If // the prefix is not a comment start prefix, then this function stops at the // last line with triple quotes or that is empty. It returns the point // positioned at the start of the last line. private SnapshotPoint FindParagraphEnd(SnapshotPoint point, FillPrefix prefix) { Regex regexp = null; if (prefix.IsDocString) { regexp = _endDocStringRegex; // Check for edge case of being on last line of doc string with quotes. if (regexp.Match(point.GetContainingLine().GetText()).Success) { return point.GetContainingLine().Start; } } var line = point.GetContainingLine(); var ln_num = line.LineNumber; var next_num = ln_num + 1; if (next_num >= point.Snapshot.LineCount) { return line.End; } var next_txt = point.Snapshot.GetLineFromLineNumber(next_num).GetText(); while (NextNotParaEnd(prefix, next_num, ln_num, next_txt, regexp)) { ln_num = next_num; next_num++; if (next_num == point.Snapshot.LineCount) { break; } next_txt = point.Snapshot.GetLineFromLineNumber(next_num).GetText(); } SnapshotPoint res; if (!prefix.IsDocString || string.IsNullOrEmpty(next_txt) || _startDocStringRegex.IsMatch(next_txt)) { // Normally ln is the last line to fill, next line stopped the loop. res = point.Snapshot.GetLineFromLineNumber(ln_num).End; } else { // If we're in a doc string, and next is not just the triple quotes // line, and next is not empty, then we use next line because it has // text on it we need to fill. Point is on next line. res = point.Snapshot.GetLineFromLineNumber(next_num).End; } return res; } struct FillPrefix { public readonly string Prefix; public readonly bool IsDocString; public FillPrefix(string prefix, bool isDocString) { Prefix = prefix; IsDocString = isDocString; } } /// <summary> /// Returns the <whitespace><commentchars><whitespace> or the <whitespace> /// prefix on point's line. Returns None if not on a suitable line for filling. /// </summary> private FillPrefix GetFillPrefix(ITextView textWindow, SnapshotPoint point) { var regexp = _commentRegex; var line = point.GetContainingLine(); var lntxt = point.GetContainingLine().GetText(); var match = regexp.Match(lntxt); if (match.Success) { return new FillPrefix(lntxt.Substring(0, match.Length), false); } else if (string.IsNullOrEmpty(lntxt.Trim())) { return new FillPrefix(null, false); } else { regexp = _whitespaceRegex; match = regexp.Match(lntxt); if (match.Success && IsDocString(textWindow, point)) { return new FillPrefix(lntxt.Substring(0, match.Length), true); } else if (/*GetFirstNonWhiteSpaceCharacterOnLine(line) == 0 && */IsDocString(textWindow, point)) { return new FillPrefix("", true); } else { return new FillPrefix(null, false); } } } private bool IsDocString(ITextView textWindow, SnapshotPoint point) { var aggregator = _serviceProvider.GetComponentModel().GetService<IClassifierAggregatorService>(); IClassifier classifier = aggregator.GetClassifier(textWindow.TextBuffer); var curLine = point.GetContainingLine(); var tokens = classifier.GetClassificationSpans(curLine.Extent); // TODO: Is null the right check for not having tokens? for (int i = curLine.LineNumber - 1; i >= 0 && tokens == null; i--) { tokens = classifier.GetClassificationSpans(curLine.Extent); if (tokens != null) { break; } i = i - 1; } if (tokens == null) { return false; } // Tokens is NOT None here. // If first token found on a line is only token and is string literal, // we're in a doc string. Because multiline, can't be "" or ''. return tokens.Count == 1 && tokens[0].ClassificationType.IsOfType(PredefinedClassificationTypeNames.String); } public override int? EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText) { var activeView = CommonPackage.GetActiveTextView(_serviceProvider); if (activeView != null && activeView.TextBuffer.ContentType.IsOfType(PythonCoreConstants.ContentType)) { cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); } else { cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE); } return VSConstants.S_OK; } public override EventHandler BeforeQueryStatus { get { return (sender, args) => { ((OleMenuCommand)sender).Visible = false; ((OleMenuCommand)sender).Supported = false; }; } } public override int CommandId { get { return (int)PkgCmdIDList.cmdidFillParagraph; } } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace WebsitePanel.Setup { public class Global { public const string SilentInstallerShell = "SilentInstallerShell"; public const string DefaultInstallPathRoot = @"C:\WebsitePanel"; public const string LoopbackIPv4 = "127.0.0.1"; public const string InstallerProductCode = "cfg core"; public const string DefaultProductName = "WebsitePanel"; public abstract class Parameters { public const string ComponentId = "ComponentId"; public const string EnterpriseServerUrl = "EnterpriseServerUrl"; public const string ShellMode = "ShellMode"; public const string ShellVersion = "ShellVersion"; public const string IISVersion = "IISVersion"; public const string BaseDirectory = "BaseDirectory"; public const string Installer = "Installer"; public const string InstallerType = "InstallerType"; public const string InstallerPath = "InstallerPath"; public const string InstallerFolder = "InstallerFolder"; public const string Version = "Version"; public const string ComponentDescription = "ComponentDescription"; public const string ComponentCode = "ComponentCode"; public const string ApplicationName = "ApplicationName"; public const string ComponentName = "ComponentName"; public const string WebSiteIP = "WebSiteIP"; public const string WebSitePort = "WebSitePort"; public const string WebSiteDomain = "WebSiteDomain"; public const string ServerPassword = "ServerPassword"; public const string UserDomain = "UserDomain"; public const string UserAccount = "UserAccount"; public const string UserPassword = "UserPassword"; public const string CryptoKey = "CryptoKey"; public const string ServerAdminPassword = "ServerAdminPassword"; public const string SetupXml = "SetupXml"; public const string ParentForm = "ParentForm"; public const string Component = "Component"; public const string FullFilePath = "FullFilePath"; public const string DatabaseServer = "DatabaseServer"; public const string DbServerAdmin = "DbServerAdmin"; public const string DbServerAdminPassword = "DbServerAdminPassword"; public const string DatabaseName = "DatabaseName"; public const string ConnectionString = "ConnectionString"; public const string InstallConnectionString = "InstallConnectionString"; public const string Release = "Release"; public const string SchedulerServiceFileName = "WebsitePanel.SchedulerService.exe"; public const string SchedulerServiceName = "WebsitePanel Scheduler"; public const string DatabaseUser = "DatabaseUser"; public const string DatabaseUserPassword = "DatabaseUserPassword"; } public abstract class Messages { public const string NotEnoughPermissionsError = "You do not have the appropriate permissions to perform this operation. Make sure you are running the application from the local disk and you have local system administrator privileges."; public const string InstallerVersionIsObsolete = "WebsitePanel Installer {0} or higher required."; public const string ComponentIsAlreadyInstalled = "Component or its part is already installed."; public const string AnotherInstanceIsRunning = "Another instance of the installation process is already running."; public const string NoInputParametersSpecified = "No input parameters specified"; public const int InstallationError = -1000; public const int UnknownComponentCodeError = -999; public const int SuccessInstallation = 0; public const int AnotherInstanceIsRunningError = -998; public const int NotEnoughPermissionsErrorCode = -997; public const int NoInputParametersSpecifiedError = -996; public const int ComponentIsAlreadyInstalledError = -995; } public abstract class Server { public abstract class CLI { public const string ServerPassword = "passw"; }; public const string ComponentName = "Server"; public const string ComponentCode = "server"; public const string ComponentDescription = "WebsitePanel Server is a set of services running on the remote server to be controlled. Server application should be reachable from Enterprise Server one."; public const string ServiceAccount = "WPServer"; public const string DefaultPort = "9003"; public const string DefaultIP = "127.0.0.1"; public const string SetupController = "Server"; public static string[] ServiceUserMembership { get { if (IISVersion.Major >= 7) { return new string[] { "AD:Domain Admins", "SID:" + SystemSID.ADMINISTRATORS, "IIS_IUSRS" }; } // return new string[] { "AD:Domain Admins", "SID:" + SystemSID.ADMINISTRATORS, "IIS_WPG" }; } } } public abstract class StandaloneServer { public const string SetupController = "StandaloneServerSetup"; public const string ComponentCode = "standalone"; public const string ComponentName = "Standalone Server Setup"; } public abstract class WebPortal { public const string ComponentName = "Portal"; public const string ComponentDescription = "WebsitePanel Portal is a control panel itself with user interface which allows managing user accounts, hosting spaces, web sites, FTP accounts, files, etc."; public const string ServiceAccount = "WPPortal"; public const string DefaultPort = "9001"; public const string DefaultIP = ""; public const string DefaultEntServURL = "http://127.0.0.1:9002"; public const string ComponentCode = "portal"; public const string SetupController = "Portal"; public static string[] ServiceUserMembership { get { if (IISVersion.Major >= 7) { return new string[] { "IIS_IUSRS" }; } // return new string[] { "IIS_WPG" }; } } public abstract class CLI { public const string EnterpriseServerUrl = "esurl"; } } public abstract class EntServer { public const string ComponentName = "Enterprise Server"; public const string ComponentDescription = "Enterprise Server is the heart of WebsitePanel system. It includes all business logic of the application. Enterprise Server should have access to Server and be accessible from Portal applications."; public const string ServiceAccount = "WPEnterpriseServer"; public const string DefaultPort = "9002"; public const string DefaultIP = "127.0.0.1"; public const string DefaultDbServer = @"localhost\sqlexpress"; public const string DefaultDatabase = "WebsitePanel"; public const string AspNetConnectionStringFormat = "server={0};database={1};uid={2};pwd={3};"; public const string ComponentCode = "enterprise server"; public const string SetupController = "EnterpriseServer"; public static string[] ServiceUserMembership { get { if (IISVersion.Major >= 7) { return new string[] { "IIS_IUSRS" }; } // return new string[] { "IIS_WPG" }; } } public abstract class CLI { public const string ServeradminPassword = "passw"; public const string DatabaseName = "dbname"; public const string DatabaseServer = "dbserver"; public const string DbServerAdmin = "dbadmin"; public const string DbServerAdminPassword = "dbapassw"; } } public abstract class Scheduler { public const string ComponentName = "Scheduler Service"; public const string ComponentCode = "scheduler service"; } public abstract class CLI { public const string WebSiteIP = "webip"; public const string ServiceAccountPassword = "upassw"; public const string ServiceAccountDomain = "udomaim"; public const string ServiceAccountName = "uname"; public const string WebSitePort = "webport"; public const string WebSiteDomain = "webdom"; } private Global() { } private static Version iisVersion; // public static Version IISVersion { get { if (iisVersion == null) { iisVersion = RegistryUtils.GetIISVersion(); } // return iisVersion; } } // private static OS.WindowsVersion osVersion = OS.WindowsVersion.Unknown; /// <summary> /// Represents Setup Control Panel Accounts system settings set (SCPA) /// </summary> public class SCPA { public const string SettingsKeyName = "EnabledSCPA"; } public static OS.WindowsVersion OSVersion { get { if (osVersion == OS.WindowsVersion.Unknown) { osVersion = OS.GetVersion(); } // return osVersion; } } public static XmlDocument SetupXmlDocument { get; set; } } public class SetupEventArgs<T> : EventArgs { public T EventData { get; set; } public string EventMessage { get; set; } } }
//MIT, 2014-present, WinterDev using System; using System.Runtime.InteropServices; namespace Win32 { [StructLayout(LayoutKind.Sequential)] struct BlendFunction { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; public BlendFunction(byte alpha) { BlendOp = 0; BlendFlags = 0; AlphaFormat = 0; SourceConstantAlpha = alpha; } } [StructLayout(LayoutKind.Sequential)] public struct BitMapInfo { public int biSize; public int biWidth; public int biHeight; public short biPlanes; public short biBitCount; public int biCompression; public int biSizeImage; public int biXPelsPerMeter; public int biYPelsPerMeter; public int biClrUsed; public int biClrImportant; public byte bmiColors_rgbBlue; public byte bmiColors_rgbGreen; public byte bmiColors_rgbRed; public byte bmiColors_rgbReserved; } [StructLayout(LayoutKind.Sequential)] unsafe struct BITMAP { public int bmType; public int bmWidth; public int bmHeight; public int bmWidthBytes; public short bmPlanes; public short bmBitsPixel; public void* bmBits; } [StructLayout(LayoutKind.Sequential)] struct RGBQUAD { public int bmType; public int bmWidth; public int bmHeight; public int bmWidthBytes; public short bmPlanes; public short bmBitsPixel; public IntPtr bmBits; } [StructLayout(LayoutKind.Sequential)] public struct Rectangle { public int X; public int Y; public int W; public int H; public int Right { get { return X + W; } } public int Bottom { get { return Y + H; } } public Rectangle(int x, int y, int w, int h) { X = x; Y = y; W = w; H = h; } private bool IntersectsWithInclusive(Rectangle r) { return !((X > r.Right) || (Right < r.X) || (Y > r.Bottom) || (Bottom < r.Y)); } public static Rectangle Intersect(Rectangle a, Rectangle b) { // MS.NET returns a non-empty rectangle if the two rectangles // touch each other if (!a.IntersectsWithInclusive(b)) return new Rectangle();//empty return new Rectangle() { X = Math.Max(a.X, b.X), Y = Math.Max(a.Y, b.Y), W = Math.Min(a.Right, b.Right), H = Math.Min(a.Bottom, b.Bottom) }; } } [StructLayout(LayoutKind.Sequential)] public struct Size { public int W; public int H; } [StructLayout(LayoutKind.Sequential)] public struct Point { public int X; public int Y; } [System.Security.SuppressUnmanagedCodeSecurity] public static partial class MyWin32 { //this is platform specific *** [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl)] public static unsafe extern void memset(byte* dest, byte c, int byteCount); [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl)] public static unsafe extern void memcpy(byte* dest, byte* src, int byteCount); [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl)] public static unsafe extern int memcmp(byte* dest, byte* src, int byteCount); [DllImport("kernel32.dll")] public static extern int GetLastError(); //---------- [StructLayout(LayoutKind.Sequential)] public struct BLENDFUNCTION { public byte BlendOp; //the only source and destination blend operation that has been defined is AC_SRC_OVER public byte BlendFlags; //Must be zero. public byte SourceConstantAlpha; public byte AlphaFormat; //AC_SRC_ALPHA //Specifies an alpha transparency value to be used on the entire source bitmap. //The SourceConstantAlpha value is combined with any per-pixel alpha values in the source bitmap. //If you set SourceConstantAlpha to 0, it is assumed that your image is transparent. //Set the SourceConstantAlpha value to 255 (opaque) when you only want to use per-pixel alpha values. } [DllImport("Msimg32.dll", EntryPoint = "AlphaBlend", CallingConvention = CallingConvention.Cdecl)] public static extern bool AlphaBlend( IntPtr hdcDest, int xoriginDest, int yoriginDest, int wDest, int hDest, IntPtr hdcSrc, int xoriginSrc, int yoriginSrc, int wSrc, int hSrc, BLENDFUNCTION ftn ); //---------- //DC [DllImport("gdi32.dll", ExactSpelling = true)] public static extern bool DeleteDC(IntPtr hdc); [DllImport("gdi32.dll", ExactSpelling = true)] public static extern bool DeleteObject(IntPtr obj); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hDc, IntPtr obj); [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDc); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref Win32.BitMapInfo pbmi, uint iUsage, out IntPtr ppvBits, IntPtr hSection, uint dwOffset); [DllImport("gdi32.dll")] public static extern unsafe int GetObject( IntPtr hgdiobj, int cbBuffer, void* lpvObject ); [DllImport("gdi32.dll", SetLastError = true)] internal static extern IntPtr GetStockObject(int index); // [DllImport("gdi32.dll")] public static extern IntPtr CreateRectRgn(int left, int top, int right, int bottom); [DllImport("gdi32.dll")] public static extern int OffsetRgn(IntPtr hdc, int xoffset, int yoffset); [DllImport("gdi32.dll")] public static extern bool SetRectRgn(IntPtr hrgn, int left, int top, int right, int bottom); [DllImport("gdi32.dll")] public static extern int GetRgnBox(IntPtr hrgn, ref Rectangle lprc); [DllImport("gdi32.dll")] public static extern int SelectClipRgn(IntPtr hdc, IntPtr hrgn); public const int NULLREGION = 1; public const int SIMPLEREGION = 2; public const int COMPLEXREGION = 3; [DllImport("gdi32.dll")] public static unsafe extern bool SetViewportOrgEx(IntPtr hdc, int x, int y, IntPtr expoint); [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSource, int dwRop); [DllImport("gdi32.dll")] public static extern bool PatBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, int dwRop); // public const int AC_SRC_OVER = 0x00; // public const int AC_SRC_ALPHA = 0x01; [DllImport("gdi32.dll")] public static extern bool OffsetViewportOrgEx(IntPtr hdc, int nXOffset, int nYOffset, out IntPtr lpPoint); [DllImport("gdi32.dll")] public static unsafe extern bool GetViewportOrgEx(IntPtr hdc, Point* p); public const int SRCCOPY = 0x00CC0020;/* dest = source */ public const int SRCPAINT = 0x00EE0086;/* dest = source OR dest */ public const int SRCAND = 0x008800C6; /* dest = source AND dest */ public const int SRCINVERT = 0x008800C6;/* dest = source XOR dest */ public const int SRCERASE = 0x00440328; /* dest = source AND (NOT dest ) */ public const int NOTSRCCOPY = 0x00330008; /* dest = (NOT source) */ public const int NOTSRCERASE = 0x001100A6; /* dest = (NOT src) AND (NOT dest) */ public const int MERGECOPY = 0x00C000CA;/* dest = (source AND pattern) */ public const int MERGEPAINT = 0x00BB0226; /* dest = (NOT source) OR dest */ public const int PATCOPY = 0x00F00021; /* dest = pattern */ public const int PATPAINT = 0x00FB0A09; /* dest = DPSnoo */ public const int PATINVERT = 0x005A0049; /* dest = pattern XOR dest */ public const int DSTINVERT = 0x00550009; /* dest = (NOT dest) */ public const int BLACKNESS = 0x00000042;/* dest = BLACK */ public const int WHITENESS = 0x00FF0062;/* dest = WHITE */ public const int CBM_Init = 0x04; [DllImport("gdi32.dll")] public static extern bool Rectangle(IntPtr hDC, int l, int t, int r, int b); [DllImport("gdi32.dll")] public static extern bool GetTextExtentPoint32(IntPtr hdc, string lpstring, int c, out Size size); [DllImport("gdi32.dll")] public static extern IntPtr CreateSolidBrush(int crColor); [DllImport("gdi32.dll")] public extern static int SetTextColor(IntPtr hdc, int newcolorRef); [StructLayout(LayoutKind.Sequential)] public struct RECT { public int left; public int top; public int right; public int bottom; } /// <summary> /// request font /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public unsafe struct LOGFONT { public int lfHeight; public int lfWidth; public int lfEscapement; public int lfOrientation; public int lfWeight; public byte lfItalic; public byte lfUnderline; public byte lfStrikeOut; public byte lfCharSet; public byte lfOutPrecision; public byte lfClipPrecision; public byte lfQuality; public byte lfPitchAndFamily; public fixed char lfFaceName[32];//[LF_FACESIZE = 32]; } [DllImport("gdi32.dll", CharSet = CharSet.Unicode)] //need -> unicode public extern static IntPtr CreateFontIndirect(ref LOGFONT logFont); public static unsafe void SetFontName(ref LOGFONT logFont, string fontName) { //font name not longer than 32 chars char[] fontNameChars = fontName.ToCharArray(); int j = Math.Min(fontNameChars.Length, 31); fixed (char* c = logFont.lfFaceName) { char* c1 = c; for (int i = 0; i < j; ++i) { *c1 = fontNameChars[i]; c1++; } } } //LOGFONT's font weight public enum LOGFONT_FontWeight { FW_DONTCARE = 0, FW_THIN = 100, FW_EXTRALIGHT = 200, FW_ULTRALIGHT = 200, FW_LIGHT = 300, FW_NORMAL = 400, FW_REGULAR = 400, FW_MEDIUM = 500, FW_SEMIBOLD = 600, FW_DEMIBOLD = 600, FW_BOLD = 700, FW_EXTRABOLD = 800, FW_ULTRABOLD = 800, FW_HEAVY = 900, FW_BLACK = 900, } public const int TA_LEFT = 0; public const int TA_RIGHT = 2; public const int TA_CENTER = 6; public const int TA_TOP = 0; public const int TA_BOTTOM = 8; public const int TA_BASELINE = 24; [DllImport("gdi32.dll")] public extern static uint SetTextAlign(IntPtr hdc, uint fMode); [DllImport("gdi32.dll")] public extern static uint GetTextAlign(IntPtr hdc); [DllImport("gdi32.dll")] public extern static int SetBkMode(IntPtr hdc, int mode); /* Background Modes */ public const int _SetBkMode_TRANSPARENT = 1; public const int _SetBkMode_OPAQUE = 2; [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern int LineTo(IntPtr hdc, int nXEnd, int nYEnd); [DllImport("gdi32.dll")] public static extern bool MoveToEx(IntPtr hdc, int X, int Y, int lpPoint); [DllImport("user32.dll")] public static extern IntPtr GetTopWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport("user32.dll")] public static extern int SetWindowText(IntPtr hWnd, string text); [DllImport("user32.dll")] public static extern void ShowCaret(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool FlashWindow(IntPtr hwnd, bool bInvert); [DllImport("user32.dll")] public static extern short GetKeyState(int nVirtualKey); [DllImport("user32.dll")] public static extern bool GetUpdateRect(IntPtr hWnd, ref RECT rect, bool bErase); [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect); [DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hWnd, ref RECT rect, bool bErase); [DllImport("user32.dll")] public static extern bool SetWindowPos( IntPtr handle, IntPtr insertAfter, int x, int y, int cx, int cy, SetWindowPosFlags flags ); [DllImport("user32.dll")] public static extern IntPtr SetParent( IntPtr hwndChild, IntPtr hwndParent ); [DllImport("user32.dll")] public static extern bool MoveWindow( IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint ); [Flags] public enum SetWindowPosFlags : int { /// <summary> /// Retains the current size (ignores the cx and cy parameters). /// </summary> NOSIZE = 0x0001, /// <summary> /// Retains the current position (ignores the x and y parameters). /// </summary> NOMOVE = 0x0002, /// <summary> /// Retains the current Z order (ignores the hwndInsertAfter parameter). /// </summary> NOZORDER = 0x0004, /// <summary> /// Does not redraw changes. If this flag is set, no repainting of any kind occurs. /// This applies to the client area, the nonclient area (including the title bar and scroll bars), /// and any part of the parent window uncovered as a result of the window being moved. /// When this flag is set, the application must explicitly invalidate or redraw any parts /// of the window and parent window that need redrawing. /// </summary> NOREDRAW = 0x0008, /// <summary> /// Does not activate the window. If this flag is not set, /// the window is activated and moved to the top of either the topmost or non-topmost group /// (depending on the setting of the hwndInsertAfter member). /// </summary> NOACTIVATE = 0x0010, /// <summary> /// Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. /// If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed. /// </summary> FRAMECHANGED = 0x0020, /* The frame changed: send WM_NCCALCSIZE */ /// <summary> /// Displays the window. /// </summary> SHOWWINDOW = 0x0040, /// <summary> /// Hides the window. /// </summary> HIDEWINDOW = 0x0080, /// <summary> /// Discards the entire contents of the client area. If this flag is not specified, /// the valid contents of the client area are saved and copied back into the client area /// after the window is sized or repositioned. /// </summary> NOCOPYBITS = 0x0100, /// <summary> /// Does not change the owner window's position in the Z order. /// </summary> NOOWNERZORDER = 0x0200, /* Don't do owner Z ordering */ /// <summary> /// Prevents the window from receiving the WM_WINDOWPOSCHANGING message. /// </summary> NOSENDCHANGING = 0x0400, /* Don't send WM_WINDOWPOSCHANGING */ /// <summary> /// Draws a frame (defined in the window's class description) around the window. /// </summary> DRAWFRAME = FRAMECHANGED, /// <summary> /// Same as the NOOWNERZORDER flag. /// </summary> NOREPOSITION = NOOWNERZORDER, DEFERERASE = 0x2000, ASYNCWINDOWPOS = 0x4000 } [StructLayout(LayoutKind.Sequential)] public struct WndClass { public uint cbSize; public uint style; public IntPtr lpfnWndProc; public int cbClsExtra; public int cbWndExtra; public IntPtr hInstance; public IntPtr hIcon; public IntPtr hCursor; public IntPtr hbrBackground; public string lpszMenuName; public string lpszClassName; public IntPtr hIconSm; } [DllImport("user32.dll")] public static extern IntPtr RegisterClassEx(ref WndClass wndClass); [DllImport("user32.dll")] public static extern bool OpenClipboard(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool CloseClipboard(); [DllImport("user32.dll")] public static extern bool EmptyClipboard(); [DllImport("user32.dll")] public static extern IntPtr SetClipboardData(uint uFormet, IntPtr hMem); //from WinUser.h public const int WM_GETDLGCODE = 0x0087; public const int WM_KEYDOWN = 0x0100; public const int WM_KEYUP = 0x0101; public const int WM_CHAR = 0x0102; public const int WM_DEADCHAR = 0x0103; public const int WM_SYSKEYDOWN = 0x0104; public const int WM_SYSKEYUP = 0x0105; public const int WM_SYSCHAR = 0x0106; public const int WM_SYSDEADCHAR = 0x0107; //------------- public const int WM_SIZE = 0x0005; public const int SIZE_RESTORED = 0; public const int SIZE_MINIMIZED = 1; public const int SIZE_MAXIMIZED = 2; public const int SIZE_MAXSHOW = 3; public const int SIZE_MAXHIDE = 4; //------------- public const int WM_ACTIVATE = 0x0006; /* * WM_ACTIVATE state values */ public const int WA_INACTIVE = 0; public const int WA_ACTIVE = 1; public const int WA_CLICKACTIVE = 2; /// <summary> /// Sent to a window after it has gained the keyboard focus. /// </summary> /// <remarks> /// To display a caret, an application should call the appropriate caret functions when it receives the WM_SETFOCUS message. /// </remarks> public const int WM_SETFOCUS = 0x0007; /// <summary> /// Sent to a window immediately before it loses the keyboard focus. /// </summary> //If an application is displaying a caret, the caret should be destroyed at this point. // While processing this message, do not make any function calls that display or // activate a window. //This causes the thread to yield control and can cause the application //to stop responding to messages. //For more information, see Message Deadlocks. public const int WM_KILLFOCUS = 0x0008; public const int WM_SHOWWINDOW = 0x0018; //#define WM_KEYDOWN 0x0100 //#define WM_KEYUP 0x0101 //#define WM_CHAR 0x0102 //#define WM_DEADCHAR 0x0103 //#define WM_SYSKEYDOWN 0x0104 //#define WM_SYSKEYUP 0x0105 //#define WM_SYSCHAR 0x0106 //#define WM_SYSDEADCHAR 0x0107 //#if (_WIN32_WINNT >= 0x0501) //#define WM_UNICHAR 0x0109 //#define WM_KEYLAST 0x0109 //#define UNICODE_NOCHAR 0xFFFF //#else //#define WM_KEYLAST 0x0108 //#endif /* _WIN32_WINNT >= 0x0501 */ public const int WM_MOUSEMOVE = 0x0200; public const int WM_LBUTTONDOWN = 0x0201; public const int WM_LBUTTONUP = 0x0202; public const int WM_LBUTTONDBLCLK = 0x0203; public const int WM_RBUTTONDOWN = 0x0204; public const int WM_RBUTTONUP = 0x0205; public const int WM_RBUTTONDBLCLK = 0x0206; public const int WM_MBUTTONDOWN = 0x0207; public const int WM_MBUTTONUP = 0x0208; public const int WM_MBUTTONDBLCLK = 0x0209; public const int WM_MOUSEWHEEL = 0x020A; public const int WM_MOUSEHWHEEL = 0x020E; public const int WM_MOUSELEAVE = 0x02A3; //#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) //#define WM_MOUSEWHEEL 0x020A //#endif //#if (_WIN32_WINNT >= 0x0500) //#define WM_XBUTTONDOWN 0x020B //#define WM_XBUTTONUP 0x020C //#define WM_XBUTTONDBLCLK 0x020D //#endif //#if (_WIN32_WINNT >= 0x0600) //#define WM_MOUSEHWHEEL 0x020E //#endif public const int WM_PAINT = 0x000F; public const int WM_ERASEBKGND = 0x0014; public const int WM_SETCURSOR = 0x0020; //#define WM_DEVMODECHANGE 0x001B //#define WM_ACTIVATEAPP 0x001C //#define WM_FONTCHANGE 0x001D //#define WM_TIMECHANGE 0x001E //#define WM_CANCELMODE 0x001F //#define WM_SETCURSOR 0x0020 //#define WM_MOUSEACTIVATE 0x0021 //#define WM_CHILDACTIVATE 0x0022 //#define WM_QUEUESYNC 0x0023 //#define VK_SHIFT 0x10 //#define VK_CONTROL 0x11 //#define VK_MENU 0x12 //#define VK_PAUSE 0x13 //#define VK_CAPITAL 0x14 public const int VK_SHIFT = 0x10; public const int VK_CONTROL = 0x11; public const int VK_MENU = 0x12; public const int VK_F2 = 0x71; public const int VK_F3 = 0x72; public const int VK_LEFT = 0x25; public const int VK_RIGHT = 0x27; public const int VK_F4 = 0x73; public const int VK_F5 = 0x74; public const int VK_F6 = 0x75; public const int VK_ESCAPE = 0x1B; public const int GW_HWNDFIRST = 0; public const int GW_HWNDLAST = 1; public const int GW_HWNDNEXT = 2; public const int GW_HWNDPREV = 3; public const int GW_OWNER = 4; public const int GW_CHILD = 5; public const int CB_SETCURSEL = 0x014E; public const int CB_SHOWDROPDOWN = 0x014F; public const int HWND_TOP = 0; public const int HWND_BOTTOM = 1; public const int HWND_TOPMOST = -1; public const int HWND_NOTOPMOST = -2; public const int SWP_SHOWWINDOW = 0x0040; public const int SWP_HIDEWINDOW = 0x0080; public const int SWP_NOACTIVATE = 0x0010; public const int MK_LBUTTON = 0x0001; public const int MK_RBUTTON = 0x0002; public const int MK_SHIFT = 0x0004; public const int MK_CONTROL = 0x0008; public const int MK_MBUTTON = 0x0010; public const int WM_NCMOUSEHOVER = 0x02A0; public const int WM_NCMOUSELEAVE = 0x02A2; public const int WM_NCHITTEST = 0x0084; public const int WM_NCPAINT = 0x0085; public const int WM_NCACTIVATE = 0x0086; public const int WM_NCMOUSEMOVE = 0x00A0; public const int WM_MOVING = 0x0216; public const int WM_ACTIVATEAPP = 0x001C; public static int SignedLOWORD(int n) { return (short)(n & 0xffff); } public static int SignedHIWORD(int n) { return (short)((n >> 0x10) & 0xffff); } public static int MAKELONG(int low, int high) { return ((high << 0x10) | (low & 0xffff)); } /// <summary> /// Create a compatible memory HDC from the given HDC.<br/> /// The memory HDC can be rendered into without effecting the original HDC.<br/> /// The returned memory HDC and <paramref name="dib"/> must be released using <see cref="ReleaseMemoryHdc"/>. /// </summary> /// <param name="hdc">the HDC to create memory HDC from</param> /// <param name="width">the width of the memory HDC to create</param> /// <param name="height">the height of the memory HDC to create</param> /// <param name="dib">returns used bitmap memory section that must be released when done with memory HDC</param> /// <returns>memory HDC</returns> public static IntPtr CreateMemoryHdc(IntPtr hdc, int width, int height, out IntPtr dib, out IntPtr ppvBits) { // Create a memory DC so we can work off-screen IntPtr memoryHdc = MyWin32.CreateCompatibleDC(hdc); MyWin32.SetBkMode(memoryHdc, 1); // Create a device-independent bitmap and select it into our DC var info = new Win32.BitMapInfo(); info.biSize = Marshal.SizeOf(info); info.biWidth = width; info.biHeight = -height; info.biPlanes = 1; info.biBitCount = 32; info.biCompression = 0; // BI_RGB dib = MyWin32.CreateDIBSection(hdc, ref info, 0, out ppvBits, IntPtr.Zero, 0); MyWin32.SelectObject(memoryHdc, dib); return memoryHdc; } /// <summary> /// Release the given memory HDC and dib section created from <see cref="CreateMemoryHdc"/>. /// </summary> /// <param name="memoryHdc">Memory HDC to release</param> /// <param name="dib">bitmap section to release</param> public static void ReleaseMemoryHdc(IntPtr memoryHdc, IntPtr dib) { MyWin32.DeleteObject(dib); MyWin32.DeleteDC(memoryHdc); } internal const int s_POINTS_PER_INCH = 72; internal static float ConvEmSizeInPointsToPixels(float emsizeInPoint, float pixels_per_inch) { return (int)(((float)emsizeInPoint / (float)s_POINTS_PER_INCH) * pixels_per_inch); } } [System.Security.SuppressUnmanagedCodeSecurity] class NativeTextWin32 { const string GDI32 = "gdi32.dll"; [DllImport(GDI32)] public static extern bool GetCharWidth32(IntPtr hdc, uint uFirstChar, uint uLastChar, ref int width); [DllImport(GDI32, CharSet = CharSet.Unicode)] public static extern bool TextOut(IntPtr hdc, int nXStart, int nYStart, [MarshalAs(UnmanagedType.LPWStr)]string charBuffer, int cbstring); [DllImport(GDI32, CharSet = CharSet.Unicode)] public static extern bool TextOut(IntPtr hdc, int nXStart, int nYStart, char[] charBuffer, int cbstring); [DllImport(GDI32, EntryPoint = "TextOutW")] public static unsafe extern bool TextOutUnsafe(IntPtr hdc, int x, int y, char* s, int len); [DllImport(GDI32)] public static unsafe extern bool ExtTextOut(IntPtr hdc, int x, int y, uint fuOptions, Rectangle* lpRect, char[] charBuffer, int cbCount, object arrayOfSpaceValues); [DllImport(GDI32, CharSet = CharSet.Unicode)] public static extern bool GetTextExtentPoint32(IntPtr hdc, char[] charBuffer, int c, out Size size); [DllImport(GDI32, EntryPoint = "GetTextExtentPoint32", CharSet = CharSet.Unicode)] public static unsafe extern bool GetTextExtentPoint32Char(IntPtr hdc, char* ch, int c, out Size size); public const int ETO_OPAQUE = 0x0002; public const int ETO_CLIPPED = 0x0004; [DllImport(GDI32, EntryPoint = "GetTextExtentPoint32W", CharSet = CharSet.Unicode)] public static extern int GetTextExtentPoint32(IntPtr hdc, [MarshalAs(UnmanagedType.LPWStr)] string str, int len, ref Size size); [DllImport(GDI32, EntryPoint = "GetTextExtentPoint32W", CharSet = CharSet.Unicode)] public static unsafe extern int UnsafeGetTextExtentPoint32( IntPtr hdc, char* str, int len, ref Size size); [DllImport(GDI32, EntryPoint = "GetTextExtentExPointW", CharSet = CharSet.Unicode)] public static extern bool GetTextExtentExPoint(IntPtr hDc, [MarshalAs(UnmanagedType.LPWStr)]string str, int nLength, int nMaxExtent, int[] lpnFit, int[] alpDx, ref Size size); [DllImport(GDI32, EntryPoint = "GetTextExtentExPointW", CharSet = CharSet.Unicode)] public static unsafe extern bool UnsafeGetTextExtentExPoint( IntPtr hDc, char* str, int len, int nMaxExtent, int[] lpnFit, int[] alpDx, ref Size size); /// <summary> /// translates a string into an array of glyph indices. The function can be used to determine whether a glyph exists in a font. /// This function attempts to identify a single-glyph representation for each character in the string pointed to by lpstr. /// While this is useful for certain low-level purposes (such as manipulating font files), higher-level applications that wish to map a string to glyphs will typically wish to use the Uniscribe functions. /// </summary> /// <param name="hdc"></param> /// <param name="text"></param> /// <param name="c">The length of both the length of the string pointed to by lpstr and the size (in WORDs) of the buffer pointed to by pgi.</param> /// <param name="buffer">This buffer must be of dimension c. On successful return, contains an array of glyph indices corresponding to the characters in the string</param> /// <param name="fl">(0 | GGI_MARK_NONEXISTING_GLYPHS) Specifies how glyphs should be handled if they are not supported. This parameter can be the following value.</param> /// <returns>If the function succeeds, it returns the number of bytes (for the ANSI function) or WORDs (for the Unicode function) converted.</returns> [DllImport(GDI32, CharSet = CharSet.Unicode)] public static extern unsafe int GetGlyphIndices(IntPtr hdc, char* text, int c, ushort* glyIndexBuffer, int fl); [DllImport(GDI32)] public static unsafe extern int GetCharABCWidths(IntPtr hdc, uint uFirstChar, uint uLastChar, void* lpabc); [DllImport(GDI32)] public static unsafe extern int GetCharABCWidthsFloat(IntPtr hdc, uint uFirstChar, uint uLastChar, void* lpabc); public const int GGI_MARK_NONEXISTING_GLYPHS = 0X0001; [StructLayout(LayoutKind.Sequential)] public struct FontABC { public int abcA; public uint abcB; public int abcC; public int Sum { get { return abcA + (int)abcB + abcC; } } } [StructLayout(LayoutKind.Sequential)] public struct ABCFloat { /// <summary>Specifies the A spacing of the character. The A spacing is the distance to add to the current /// position before drawing the character glyph.</summary> public float abcfA; /// <summary>Specifies the B spacing of the character. The B spacing is the width of the drawn portion of /// the character glyph.</summary> public float abcfB; /// <summary>Specifies the C spacing of the character. The C spacing is the distance to add to the current /// position to provide white space to the right of the character glyph.</summary> public float abcfC; } [DllImport(GDI32, CharSet = CharSet.Unicode)] public static unsafe extern int GetCharacterPlacement(IntPtr hdc, char* str, int nCount, int nMaxExtent, ref GCP_RESULTS lpResults, int dwFlags); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public unsafe struct GCP_RESULTS { public int lStructSize; public char* lpOutString; public uint* lpOrder; public int* lpDx; public int* lpCaretPos; public char* lpClass; public char* lpGlyphs; public uint nGlyphs; public int nMaxFit; } // DWORD GetCharacterPlacement( // _In_ HDC hdc, // _In_ LPCTSTR lpString, // _In_ int nCount, // _In_ int nMaxExtent, // _Inout_ LPGCP_RESULTS lpResults, // _In_ DWORD dwFlags //); // typedef struct _OUTLINETEXTMETRICW { //UINT otmSize; //TEXTMETRICW otmTextMetrics; //BYTE otmFiller; //PANOSE otmPanoseNumber; //UINT otmfsSelection; //UINT otmfsType; // int otmsCharSlopeRise; // int otmsCharSlopeRun; // int otmItalicAngle; //UINT otmEMSquare; // int otmAscent; // int otmDescent; //UINT otmLineGap; //UINT otmsCapEmHeight; //UINT otmsXHeight; //RECT otmrcFontBox; // int otmMacAscent; // int otmMacDescent; //UINT otmMacLineGap; //UINT otmusMinimumPPEM; //POINT otmptSubscriptSize; //POINT otmptSubscriptOffset; //POINT otmptSuperscriptSize; //POINT otmptSuperscriptOffset; //UINT otmsStrikeoutSize; // int otmsStrikeoutPosition; // int otmsUnderscoreSize; // int otmsUnderscorePosition; //PSTR otmpFamilyName; //PSTR otmpFaceName; //PSTR otmpStyleName; //PSTR otmpFullName; //} [StructLayout(LayoutKind.Sequential)] public struct PANOSE { byte bFamilyType; byte bSerifStyle; byte bWeight; byte bProportion; byte bContrast; byte bStrokeVariation; byte bArmStyle; byte bLetterform; byte bMidline; byte bXHeight; } [StructLayout(LayoutKind.Sequential)] public unsafe struct _OUTLINETEXTMETRICW { uint otmSize; TEXTMETRICW otmTextMetrics; byte otmFiller; PANOSE otmPanoseNumber; uint otmfsSelection; uint otmfsType; int otmsCharSlopeRise; int otmsCharSlopeRun; int otmItalicAngle; uint otmEMSquare; int otmAscent; int otmDescent; uint otmLineGap; uint otmsCapEmHeight; uint otmsXHeight; Rectangle otmrcFontBox; int otmMacAscent; int otmMacDescent; uint otmMacLineGap; uint otmusMinimumPPEM; Point otmptSubscriptSize; Point otmptSubscriptOffset; Point otmptSuperscriptSize; Point otmptSuperscriptOffset; uint otmsStrikeoutSize; int otmsStrikeoutPosition; int otmsUnderscoreSize; int otmsUnderscorePosition; char* otmpFamilyName; char* otmpFaceName; char* otmpStyleName; char* otmpFullName; } [StructLayout(LayoutKind.Sequential)] public struct TEXTMETRICW { int tmHeight; int tmAscent; int tmDescent; int tmInternalLeading; int tmExternalLeading; int tmAveCharWidth; int tmMaxCharWidth; int tmWeight; int tmOverhang; int tmDigitizedAspectX; int tmDigitizedAspectY; char tmFirstChar; char tmLastChar; char tmDefaultChar; char tmBreakChar; byte tmItalic; byte tmUnderlined; byte tmStruckOut; byte tmPitchAndFamily; byte tmCharSet; } #if DEBUG public static void dbugDrawTextOrigin(IntPtr hdc, int x, int y) { MyWin32.Rectangle(hdc, x, y, x + 20, y + 20); MyWin32.MoveToEx(hdc, x, y, 0); MyWin32.LineTo(hdc, x + 20, y + 20); MyWin32.MoveToEx(hdc, x, y + 20, 0); MyWin32.LineTo(hdc, x + 20, y); } #endif } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace BugLoggingSystem.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETSTANDARD1_3 #define SIMPLE_JSON_TYPEINFO #endif using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Reflection; namespace Dapplo.HttpExtensions.JsonSimple; [GeneratedCode("reflection-utils", "1.0.0")] #if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC public #else internal #endif static class ReflectionUtils { #if SIMPLE_JSON_NO_LINQ_EXPRESSION private static readonly object[] EmptyObjects = { }; #endif public delegate object GetDelegate(object source); public delegate void SetDelegate(object source, object value); public delegate object ConstructorDelegate(params object[] args); public delegate TValue ThreadSafeDictionaryValueFactory<in TKey, out TValue>(TKey key); #if SIMPLE_JSON_TYPEINFO public static TypeInfo GetTypeInfo(Type type) { return type.GetTypeInfo(); } #else public static Type GetTypeInfo(Type type) { return type; } #endif public static Attribute GetAttribute(MemberInfo info, Type type) { #if SIMPLE_JSON_TYPEINFO if (info is null || type is null || !info.IsDefined(type)) { return null; } return info.GetCustomAttribute(type); #else if (info is null || type is null || !Attribute.IsDefined(info, type)) return null; return Attribute.GetCustomAttribute(info, type); #endif } public static Type GetGenericListElementType(Type type) { #if SIMPLE_JSON_TYPEINFO IEnumerable<Type> interfaces = type.GetTypeInfo().ImplementedInterfaces; #else IEnumerable<Type> interfaces = type.GetInterfaces(); #endif foreach (var implementedInterface in interfaces) { if (IsTypeGeneric(implementedInterface) && implementedInterface.GetGenericTypeDefinition() == typeof(IList<>)) { return GetGenericTypeArguments(implementedInterface)[0]; } } return GetGenericTypeArguments(type)[0]; } public static Attribute GetAttribute(Type objectType, Type attributeType) { #if SIMPLE_JSON_TYPEINFO if (objectType is null || attributeType is null || !objectType.GetTypeInfo().IsDefined(attributeType)) { return null; } return objectType.GetTypeInfo().GetCustomAttribute(attributeType); #else if (objectType is null || attributeType is null || !Attribute.IsDefined(objectType, attributeType)) return null; return Attribute.GetCustomAttribute(objectType, attributeType); #endif } public static Type[] GetGenericTypeArguments(Type type) { #if SIMPLE_JSON_TYPEINFO return type.GetTypeInfo().GenericTypeArguments; #else return type.GetGenericArguments(); #endif } public static bool IsTypeGeneric(Type type) { return GetTypeInfo(type).IsGenericType; } public static bool IsTypeGenericeCollectionInterface(Type type) { if (!IsTypeGeneric(type)) { return false; } var genericDefinition = type.GetGenericTypeDefinition(); return genericDefinition == typeof(IList<>) || genericDefinition == typeof(ICollection<>) || genericDefinition == typeof(IEnumerable<>) #if SIMPLE_JSON_READONLY_COLLECTIONS || genericDefinition == typeof(IReadOnlyCollection<>) || genericDefinition == typeof(IReadOnlyList<>) #endif ; } public static bool IsAssignableFrom(Type type1, Type type2) { return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2)); } public static bool IsTypeDictionary(Type type) { #if SIMPLE_JSON_TYPEINFO if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) { return true; } #else if (typeof(IDictionary).IsAssignableFrom(type)) return true; #endif if (!GetTypeInfo(type).IsGenericType) { return false; } var genericDefinition = type.GetGenericTypeDefinition(); return genericDefinition == typeof(IDictionary<,>); } public static bool IsNullableType(Type type) { return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public static object ToNullableType(object obj, Type nullableType) { return obj is null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture); } public static bool IsValueType(Type type) { return GetTypeInfo(type).IsValueType; } public static IEnumerable<ConstructorInfo> GetConstructors(Type type) { #if SIMPLE_JSON_TYPEINFO return type.GetTypeInfo().DeclaredConstructors; #else return type.GetConstructors(); #endif } public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType) { var constructorInfos = GetConstructors(type); foreach (var constructorInfo in constructorInfos) { var parameters = constructorInfo.GetParameters(); if (argsType.Length != parameters.Length) { continue; } var i = 0; var matches = true; foreach (var parameterInfo in constructorInfo.GetParameters()) { if (parameterInfo.ParameterType != argsType[i]) { matches = false; break; } } if (matches) { return constructorInfo; } } return null; } public static IEnumerable<PropertyInfo> GetProperties(Type type) { #if SIMPLE_JSON_TYPEINFO return type.GetRuntimeProperties(); #else return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); #endif } public static IEnumerable<FieldInfo> GetFields(Type type) { #if SIMPLE_JSON_TYPEINFO return type.GetRuntimeFields(); #else return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); #endif } public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo) { #if SIMPLE_JSON_TYPEINFO return propertyInfo.GetMethod; #else return propertyInfo.GetGetMethod(true); #endif } public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo) { #if SIMPLE_JSON_TYPEINFO return propertyInfo.SetMethod; #else return propertyInfo.GetSetMethod(true); #endif } public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo) { #if SIMPLE_JSON_NO_LINQ_EXPRESSION return GetConstructorByReflection(constructorInfo); #else return GetConstructorByExpression(constructorInfo); #endif } public static ConstructorDelegate GetContructor(Type type, params Type[] argsType) { #if SIMPLE_JSON_NO_LINQ_EXPRESSION return GetConstructorByReflection(type, argsType); #else return GetConstructorByExpression(type, argsType); #endif } #if SIMPLE_JSON_NO_LINQ_EXPRESSION public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType) { ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType); return constructorInfo is null ? null : GetConstructorByReflection(constructorInfo); } public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo) { return constructorInfo.Invoke; } #else public static ConstructorDelegate GetConstructorByExpression(ConstructorInfo constructorInfo) { var paramsInfo = constructorInfo.GetParameters(); var param = Expression.Parameter(typeof(object[]), "args"); var argsExp = new Expression[paramsInfo.Length]; for (var i = 0; i < paramsInfo.Length; i++) { Expression index = Expression.Constant(i); var paramType = paramsInfo[i].ParameterType; Expression paramAccessorExp = Expression.ArrayIndex(param, index); Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType); argsExp[i] = paramCastExp; } var newExp = Expression.New(constructorInfo, argsExp); var lambda = Expression.Lambda<Func<object[], object>>(newExp, param); var compiledLambda = lambda.Compile(); return args => compiledLambda(args); } public static ConstructorDelegate GetConstructorByExpression(Type type, params Type[] argsType) { var constructorInfo = GetConstructorInfo(type, argsType); return constructorInfo is null ? null : GetConstructorByExpression(constructorInfo); } #endif public static GetDelegate GetGetMethod(PropertyInfo propertyInfo) { #if SIMPLE_JSON_NO_LINQ_EXPRESSION return GetGetMethodByReflection(propertyInfo); #else return GetGetMethodByExpression(propertyInfo); #endif } public static GetDelegate GetGetMethod(FieldInfo fieldInfo) { #if SIMPLE_JSON_NO_LINQ_EXPRESSION return GetGetMethodByReflection(fieldInfo); #else return GetGetMethodByExpression(fieldInfo); #endif } #if SIMPLE_JSON_NO_LINQ_EXPRESSION public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo) { MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo); return source => methodInfo.Invoke(source, EmptyObjects); } public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo) { return fieldInfo.GetValue; } #else public static GetDelegate GetGetMethodByExpression(PropertyInfo propertyInfo) { var getMethodInfo = GetGetterMethodInfo(propertyInfo); var instance = Expression.Parameter(typeof(object), "instance"); if (propertyInfo.DeclaringType is null) { throw new NotSupportedException($"propertyInfo for {propertyInfo.Name} doesn't have a declaring type."); } var instanceCast = !IsValueType(propertyInfo.DeclaringType) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType); var compiled = Expression.Lambda<Func<object, object>>(Expression.TypeAs(Expression.Call(instanceCast, getMethodInfo), typeof(object)), instance).Compile(); return source => compiled(source); } public static GetDelegate GetGetMethodByExpression(FieldInfo fieldInfo) { if (fieldInfo.DeclaringType is null) { throw new NotSupportedException($"fieldInfo for {fieldInfo.Name} doesn't have a declaring type."); } var instance = Expression.Parameter(typeof(object), "instance"); var unaryExpression = Expression.Convert(instance, fieldInfo.DeclaringType); var member = Expression.Field(unaryExpression, fieldInfo); var compiled = Expression.Lambda<GetDelegate>(Expression.Convert(member, typeof(object)), instance).Compile(); return source => compiled(source); } #endif public static SetDelegate GetSetMethod(PropertyInfo propertyInfo) { #if SIMPLE_JSON_NO_LINQ_EXPRESSION return GetSetMethodByReflection(propertyInfo); #else return GetSetMethodByExpression(propertyInfo); #endif } public static SetDelegate GetSetMethod(FieldInfo fieldInfo) { #if SIMPLE_JSON_NO_LINQ_EXPRESSION return GetSetMethodByReflection(fieldInfo); #else return GetSetMethodByExpression(fieldInfo); #endif } #if SIMPLE_JSON_NO_LINQ_EXPRESSION public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo) { MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo); return delegate(object source, object value) { methodInfo.Invoke(source, new object[] { value }); }; } public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo) { return fieldInfo.SetValue; } #else public static SetDelegate GetSetMethodByExpression(PropertyInfo propertyInfo) { var setMethodInfo = GetSetterMethodInfo(propertyInfo); var instance = Expression.Parameter(typeof(object), "instance"); var value = Expression.Parameter(typeof(object), "value"); var instanceCast = !IsValueType(propertyInfo.DeclaringType) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType); var valueCast = !IsValueType(propertyInfo.PropertyType) ? Expression.TypeAs(value, propertyInfo.PropertyType) : Expression.Convert(value, propertyInfo.PropertyType); var compiled = Expression.Lambda<Action<object, object>>(Expression.Call(instanceCast, setMethodInfo, valueCast), instance, value).Compile(); return delegate(object source, object val) { compiled(source, val); }; } public static SetDelegate GetSetMethodByExpression(FieldInfo fieldInfo) { var instance = Expression.Parameter(typeof(object), "instance"); var value = Expression.Parameter(typeof(object), "value"); var compiled = Expression.Lambda<Action<object, object>>( Assign(Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo), Expression.Convert(value, fieldInfo.FieldType)), instance, value).Compile(); return delegate(object source, object val) { compiled(source, val); }; } public static BinaryExpression Assign(Expression left, Expression right) { #if SIMPLE_JSON_TYPEINFO return Expression.Assign(left, right); #else var assign = typeof(Assigner<>).MakeGenericType(left.Type).GetMethod("Assign"); var assignExpr = Expression.Add(left, right, assign); return assignExpr; #endif } #if !SIMPLE_JSON_TYPEINFO private static class Assigner<T> { public static T Assign(out T left, T right) { return left = right; } } #endif #endif public sealed class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private readonly object _lock = new object(); private readonly ThreadSafeDictionaryValueFactory<TKey, TValue> _valueFactory; private Dictionary<TKey, TValue> _dictionary; public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory<TKey, TValue> valueFactory) { _valueFactory = valueFactory; } public void Add(TKey key, TValue value) { throw new NotImplementedException(); } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public ICollection<TKey> Keys => _dictionary.Keys; public bool Remove(TKey key) { throw new NotImplementedException(); } public bool TryGetValue(TKey key, out TValue value) { value = this[key]; return true; } public ICollection<TValue> Values => _dictionary.Values; public TValue this[TKey key] { get { return Get(key); } set { throw new NotImplementedException(); } } public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); } public int Count => _dictionary.Count; public bool IsReadOnly { get { throw new NotImplementedException(); } } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _dictionary.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _dictionary.GetEnumerator(); } private TValue AddValue(TKey key) { var value = _valueFactory(key); lock (_lock) { if (_dictionary is null) { _dictionary = new Dictionary<TKey, TValue> {[key] = value}; } else { if (_dictionary.TryGetValue(key, out var val)) { return val; } var dict = new Dictionary<TKey, TValue>(_dictionary) {[key] = value}; _dictionary = dict; } } return value; } private TValue Get(TKey key) { if (_dictionary is null) { return AddValue(key); } if (!_dictionary.TryGetValue(key, out var value)) { return AddValue(key); } return value; } } }
// // SqlMethods.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2008 Novell, Inc. // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace System.Data.Linq.SqlClient { public static class SqlMethods { static Exception NotSupported() { return new NotSupportedException("The method in SqlMethods type cannot be used directly. It is only for Linq to SQL trsnslation"); } [MonoTODO] public static int DateDiffDay (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffDay (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffHour (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffHour (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffMillisecond (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffMillisecond (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffMinute (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffMinute (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffMonth (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffMonth (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffSecond (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffSecond (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffYear (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffYear (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } #region .NET 3.5 SP1 (DateTimeOffset) [MonoTODO] public static int DateDiffMicrosecond (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffMicrosecond (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffNanosecond (DateTime startDate, DateTime endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffNanosecond (DateTime? startDate, DateTime? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffDay (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffDay (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffHour (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffHour (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffMicrosecond (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffMicrosecond (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffMillisecond (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffMillisecond (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffMinute (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffMinute (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffMonth (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffMonth (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffNanosecond (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffNanosecond (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffSecond (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffSecond (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } [MonoTODO] public static int DateDiffYear (DateTimeOffset startDate, DateTimeOffset endDate) { throw NotSupported(); } [MonoTODO] public static int? DateDiffYear (DateTimeOffset? startDate, DateTimeOffset? endDate) { throw NotSupported(); } #endregion [MonoTODO] public static bool Like (string matchExpression, string pattern) { throw NotSupported(); } [MonoTODO] public static bool Like (string matchExpression, string pattern, char escapeCharacter) { throw NotSupported(); } } }
using System; using System.Linq; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.VFX; namespace UnityEditor.VFX { abstract class VFXOperatorDynamicOperand : VFXOperator { /* Global rules (these function are too general, should be a separated utility) */ //output depends on all input type applying float > uint > int > bool (http://c0x.coding-guidelines.com/6.3.1.8.html) public static readonly Type[] kExpectedTypeOrdering = new[] { typeof(Vector4), typeof(Position), typeof(Vector), typeof(DirectionType), typeof(Vector3), typeof(Vector2), typeof(float), typeof(uint), typeof(int), }; public static readonly Dictionary<Type, Type[]> kTypeAffinity = new Dictionary<Type, Type[]> { { typeof(Matrix4x4), new Type[] {} }, { typeof(Vector4), new[] {typeof(Color), typeof(Vector3), typeof(Position), typeof(DirectionType), typeof(Vector2), typeof(float), typeof(int), typeof(uint)} }, { typeof(Color), new[] {typeof(Vector4), typeof(Vector3), typeof(Vector2), typeof(float), typeof(int), typeof(uint)} }, { typeof(Vector3), new[] {typeof(Position), typeof(DirectionType), typeof(Vector), typeof(Color), typeof(Vector2), typeof(float), typeof(int), typeof(uint)} }, { typeof(Position), new[] {typeof(Vector3), typeof(Vector)} }, { typeof(DirectionType), new[] {typeof(Vector3), typeof(Vector) } }, { typeof(Vector), new[] {typeof(Vector3), typeof(Position), typeof(DirectionType) } }, { typeof(Vector2), new[] {typeof(float), typeof(int), typeof(uint)} }, { typeof(float), new[] {typeof(int), typeof(uint), typeof(Vector2), typeof(Vector3), typeof(Vector4), typeof(Color)} }, { typeof(int), new[] {typeof(uint), typeof(float), typeof(Vector2), typeof(Vector3), typeof(Vector4), typeof(Color)} }, { typeof(uint), new[] {typeof(int), typeof(float), typeof(Vector2), typeof(Vector3), typeof(Vector4), typeof(Color)} }, }; public sealed override void OnEnable() { base.OnEnable(); } static public IEnumerable<Type> GetTypeAffinityList(Type type) { Type[] affinity = null; if (!kTypeAffinity.TryGetValue(type, out affinity)) { return Enumerable.Empty<Type>(); } return affinity; } public Type GetBestAffinityType(Type type) { if (validTypes.Contains(type)) { return type; } Type[] affinity = null; if (!kTypeAffinity.TryGetValue(type, out affinity)) { return null; } var bestAffinity = affinity.Where(o => validTypes.Contains(o)).FirstOrDefault(); return bestAffinity; //Can be null } public abstract IEnumerable<Type> validTypes { get; } protected abstract Type defaultValueType { get; } protected virtual object GetDefaultValueForType(Type type) { return VFXTypeExtension.GetDefaultField(type); } protected virtual object GetIdentityValueForType(Type type) { return GetDefaultValueForType(type); } } abstract class VFXOperatorNumeric : VFXOperatorDynamicOperand { protected sealed override Type defaultValueType { get { return typeof(float); } } [Flags] protected enum ValidTypeRule { allowVector4Type = 1 << 1, allowVector3Type = 1 << 2, allowVector2Type = 1 << 3, allowOneDimensionType = 1 << 4, allowSignedInteger = 1 << 5, allowUnsignedInteger = 1 << 6, allowSpaceable = 1 << 7, allowInteger = allowSignedInteger | allowUnsignedInteger, allowVectorType = allowSpaceable | allowVector4Type | allowVector3Type | allowVector2Type, allowEverything = allowVectorType | allowOneDimensionType | allowInteger, allowEverythingExceptInteger = allowEverything & ~allowInteger, allowEverythingExceptUnsignedInteger = allowEverything & ~allowUnsignedInteger, allowEverythingExceptIntegerAndVector4 = allowEverything & ~(allowInteger | allowVector4Type), allowEverythingExceptOneDimension = allowEverything & ~allowOneDimensionType }; private static readonly Type[] kSpaceableType = new Type[] { typeof(Position), typeof(DirectionType), typeof(Vector) }; private static readonly Type[] kVector4Type = new Type[] { typeof(Vector4) }; private static readonly Type[] kVector3Type = new Type[] { typeof(Vector3) }; private static readonly Type[] kVector2Type = new Type[] { typeof(Vector2) }; private static readonly Type[] kOneDimensionType = new Type[] { typeof(float), typeof(uint), typeof(int) }; private static readonly Type[] kSIntegerType = new Type[] { typeof(int) }; private static readonly Type[] kUIntegerType = new Type[] { typeof(uint) }; protected virtual ValidTypeRule typeFilter { get { return ValidTypeRule.allowEverything; } } public sealed override IEnumerable<Type> validTypes { get { IEnumerable<Type> types = kExpectedTypeOrdering; if ((typeFilter & ValidTypeRule.allowSpaceable) != ValidTypeRule.allowSpaceable) types = types.Except(kSpaceableType); if ((typeFilter & ValidTypeRule.allowVectorType) != ValidTypeRule.allowVectorType) types = types.Except(kVector4Type); if ((typeFilter & ValidTypeRule.allowVector3Type) != ValidTypeRule.allowVector3Type) types = types.Except(kVector3Type); if ((typeFilter & ValidTypeRule.allowVector2Type) != ValidTypeRule.allowVector2Type) types = types.Except(kVector2Type); if ((typeFilter & ValidTypeRule.allowOneDimensionType) != ValidTypeRule.allowOneDimensionType) types = types.Except(kOneDimensionType); if ((typeFilter & ValidTypeRule.allowSignedInteger) != ValidTypeRule.allowSignedInteger) types = types.Except(kSIntegerType); if ((typeFilter & ValidTypeRule.allowUnsignedInteger) != ValidTypeRule.allowUnsignedInteger) types = types.Except(kUIntegerType); return types; } } protected virtual Type GetExpectedOutputTypeOfOperation(IEnumerable<Type> inputTypes) { if (!inputTypes.Any()) return defaultValueType; var minIndex = inputTypes.Select(o => Array.IndexOf(kExpectedTypeOrdering, o)).Min(); if (minIndex == -1) throw new IndexOutOfRangeException("Unexpected type"); return kExpectedTypeOrdering[minIndex]; } protected virtual string operatorName { get { return string.Empty; } } public override /*sealed*/ string libraryName { get { return operatorName; } } public override /*sealed*/ string name { get { var r = operatorName; if (outputSlots.Any()) { var refSlot = outputSlots[0]; if (refSlot.spaceable) { r += string.Format(" ({0} - {1})", refSlot.property.type.UserFriendlyName(), refSlot.space); } else { r += string.Format(" ({0})", refSlot.property.type.UserFriendlyName()); } } return r; } } protected virtual string expectedOutputName { get { return string.Empty; } } protected virtual VFXPropertyAttribute[] expectedOutputAttributes { get { return null; } } protected override sealed IEnumerable<VFXPropertyWithValue> outputProperties { get { if (base.outputProperties.Any()) { //Behavior when "OutputProperties" as been declared (length, dot, square length...) foreach (var outputProperty in base.outputProperties) yield return outputProperty; } else { //Most common behavior : output of an operation depend of input type var slotType = GetExpectedOutputTypeOfOperation(inputSlots.Select(o => o.property.type)); if (slotType != null) yield return new VFXPropertyWithValue(new VFXProperty(slotType, expectedOutputName, expectedOutputAttributes)); } } } protected override sealed object GetDefaultValueForType(Type vtype) { var type = VFXExpression.GetVFXValueTypeFromType(vtype); switch (type) { case VFXValueType.Float: return defaultValueFloat; case VFXValueType.Float2: return Vector2.one * defaultValueFloat; case VFXValueType.Float3: return Vector3.one * defaultValueFloat; case VFXValueType.Float4: return Vector4.one * defaultValueFloat; case VFXValueType.Int32: return defaultValueInt; case VFXValueType.Uint32: return defaultValueUint; } return null; } protected override IEnumerable<VFXExpression> ApplyPatchInputExpression(IEnumerable<VFXExpression> inputExpression) { var minIndex = inputExpression.Select(o => Array.IndexOf(kExpectedTypeOrdering, VFXExpression.TypeToType(o.valueType))).Min(); var unifiedType = VFXExpression.GetVFXValueTypeFromType(kExpectedTypeOrdering[minIndex]); foreach (var expression in inputExpression) { if (expression.valueType == unifiedType) { yield return expression; continue; } var currentExpression = expression; if (VFXExpression.IsFloatValueType(unifiedType)) { if (VFXExpression.IsUIntValueType(expression.valueType)) { currentExpression = new VFXExpressionCastUintToFloat(currentExpression); } else if (VFXExpression.IsIntValueType(expression.valueType)) { currentExpression = new VFXExpressionCastIntToFloat(currentExpression); } currentExpression = VFXOperatorUtility.CastFloat(currentExpression, unifiedType, identityValueFloat); } else if (VFXExpression.IsIntValueType(unifiedType)) { if (VFXExpression.IsUIntValueType(currentExpression.valueType)) { currentExpression = new VFXExpressionCastUintToInt(currentExpression); } else if (VFXExpression.IsFloatValueType(currentExpression.valueType)) { currentExpression = new VFXExpressionCastFloatToInt(VFXOperatorUtility.ExtractComponents(currentExpression).First()); } } else if (VFXExpression.IsUIntValueType(unifiedType)) { if (VFXExpression.IsIntValueType(currentExpression.valueType)) { currentExpression = new VFXExpressionCastIntToUint(currentExpression); } else if (VFXExpression.IsFloatValueType(expression.valueType)) { currentExpression = new VFXExpressionCastFloatToUint(VFXOperatorUtility.ExtractComponents(expression).First()); } } yield return currentExpression; } } protected abstract double defaultValueDouble { get; } protected virtual float defaultValueFloat { get { return (float)defaultValueDouble; } } protected virtual int defaultValueInt { get { return (int)defaultValueDouble; } } protected virtual uint defaultValueUint { get { return (uint)defaultValueDouble; } } protected virtual double identityValueDouble { get { return defaultValueDouble; } } protected virtual float identityValueFloat { get { return defaultValueFloat; } } protected virtual int identityValueInt { get { return defaultValueInt; } } protected virtual uint identityValueUint { get { return defaultValueUint; } } } interface IVFXOperatorUniform { Type GetOperandType(); void SetOperandType(Type type); IEnumerable<int> staticSlotIndex { get; } } abstract class VFXOperatorNumericUniform : VFXOperatorNumeric, IVFXOperatorUniform { [VFXSetting(VFXSettingAttribute.VisibleFlags.None), SerializeField] SerializableType m_Type; protected override double defaultValueDouble //Most common case for this kind of operator (still overridable) { get { return 0.0; } } public Type GetOperandType() { return m_Type; } public void SetOperandType(Type type) { if (!validTypes.Contains(type)) throw new InvalidOperationException(); m_Type = type; Invalidate(InvalidationCause.kSettingChanged); } public IEnumerable<int> staticSlotIndex { get { return Enumerable.Empty<int>(); } } protected sealed override IEnumerable<VFXPropertyWithValue> inputProperties { get { var baseInputProperties = base.inputProperties; if (m_Type == null) // Lazy init at this stage is suitable because inputProperties access is done with SyncSlot { var typeEnumeration = baseInputProperties.Select(o => o.property.type); if (typeEnumeration.Any(o => !validTypes.Contains(o))) throw new InvalidOperationException("Forbidden type"); if (typeEnumeration.Distinct().Count() != 1) throw new InvalidOperationException("Uniform type expected"); m_Type = typeEnumeration.First(); } foreach (var property in baseInputProperties) { if (property.property.type == (Type)m_Type) yield return property; else yield return new VFXPropertyWithValue(new VFXProperty((Type)m_Type, property.property.name, property.property.attributes), GetDefaultValueForType(m_Type)); } } } } interface IVFXOperatorNumericUnified { int operandCount { get; } Type GetOperandType(int index); void SetOperandType(int index, Type type); } interface IVFXOperatorNumericUnifiedConstrained { IEnumerable<int> slotIndicesThatMustHaveSameType { get; } IEnumerable<int> slotIndicesThatCanBeScalar { get; } } abstract class VFXOperatorNumericUnified : VFXOperatorNumeric, IVFXOperatorNumericUnified { [VFXSetting(VFXSettingAttribute.VisibleFlags.None), SerializeField] SerializableType[] m_Type; protected override double defaultValueDouble //Most common case for this kind of operator (still overridable) { get { return 0.0; } } public int operandCount { get {return m_Type.Length; } } public Type GetOperandType(int index) { return m_Type[index]; } public void SetOperandType(int index, Type type) { if (!validTypes.Contains(type)) throw new InvalidOperationException(); m_Type[index] = type; Invalidate(InvalidationCause.kSettingChanged); } protected sealed override IEnumerable<VFXPropertyWithValue> inputProperties { get { var baseType = base.inputProperties; if (m_Type == null) // Lazy init at this stage is suitable because inputProperties access is done with SyncSlot { var typeArray = baseType.Select(o => o.property.type).ToArray(); if (typeArray.Any(o => !validTypes.Contains(o))) throw new InvalidOperationException("Forbidden type"); m_Type = typeArray.Select(o => new SerializableType(o)).ToArray(); } if (baseType.Count() != m_Type.Length) throw new InvalidOperationException(); var itSlot = baseType.GetEnumerator(); var itType = m_Type.Cast<SerializableType>().GetEnumerator(); while (itSlot.MoveNext() && itType.MoveNext()) { if (itSlot.Current.property.type == (Type)itType.Current) yield return itSlot.Current; else yield return new VFXPropertyWithValue(new VFXProperty((Type)itType.Current, itSlot.Current.property.name, itSlot.Current.property.attributes), GetDefaultValueForType(itType.Current)); } } } } abstract class VFXOperatorNumericCascadedUnified : VFXOperatorNumeric, IVFXOperatorNumericUnified { [Serializable] public struct Operand { public string name; public SerializableType type; } [VFXSetting(VFXSettingAttribute.VisibleFlags.None), SerializeField] Operand[] m_Operands; protected string GetDefaultName(int index) { return VFXCodeGeneratorHelper.GeneratePrefix((uint)index); } protected Operand GetDefaultOperand(int index, Type type = null) { return new Operand() { name = GetDefaultName(index), type = type != null ? type : defaultValueType }; } protected sealed override IEnumerable<VFXPropertyWithValue> inputProperties { get { if (m_Operands == null) //Lazy init at this stage is suitable because inputProperties access is done with SyncSlot { m_Operands = Enumerable.Range(0, MinimalOperandCount).Select(i => GetDefaultOperand(i)).ToArray(); } foreach (var operand in m_Operands) yield return new VFXPropertyWithValue(new VFXProperty(operand.type, operand.name), GetDefaultValueForType(operand.type)); } } public virtual int MinimalOperandCount { get { return 2; } } public void AddOperand(Type type = null) { if (type != null && !validTypes.Contains(type)) throw new InvalidOperationException("Unexpected type : " + type); int oldCount = m_Operands.Length; var infos = new Operand[oldCount + 1]; Array.Copy(m_Operands, infos, oldCount); infos[oldCount] = GetDefaultOperand(oldCount, type); m_Operands = infos; Invalidate(InvalidationCause.kSettingChanged); } public void RemoveOperand(int index) { OperandMoved(index, operandCount - 1); RemoveOperand(); } public void RemoveOperand() { if (m_Operands.Length == 0) return; int oldCount = m_Operands.Length; var infos = new Operand[oldCount - 1]; Array.Copy(m_Operands, infos, oldCount - 1); m_Operands = infos; inputSlots.Last().UnlinkAll(true); Invalidate(InvalidationCause.kSettingChanged); } public int operandCount { get { return m_Operands != null ? m_Operands.Length : 0; } } public string GetOperandName(int index) { return m_Operands[index].name; } public void SetOperandName(int index, string name) { m_Operands[index].name = name; Invalidate(InvalidationCause.kSettingChanged); } public Type GetOperandType(int index) { return m_Operands[index].type; } public void SetOperandType(int index, Type type) { if (!validTypes.Contains(type)) { Debug.LogError("Invalid type : " + type); return; } m_Operands[index].type = type; Invalidate(InvalidationCause.kSettingChanged); } public void OperandMoved(int movedIndex, int targetIndex) { if (movedIndex == targetIndex) return; var newOperands = new Operand[m_Operands.Length]; if (movedIndex < targetIndex) { Array.Copy(m_Operands, newOperands, movedIndex); Array.Copy(m_Operands, movedIndex + 1, newOperands, movedIndex, targetIndex - movedIndex); newOperands[targetIndex] = m_Operands[movedIndex]; Array.Copy(m_Operands, targetIndex + 1, newOperands, targetIndex + 1, m_Operands.Length - targetIndex - 1); } else { Array.Copy(m_Operands, newOperands, targetIndex); newOperands[targetIndex] = m_Operands[movedIndex]; Array.Copy(m_Operands, targetIndex, newOperands, targetIndex + 1, movedIndex - targetIndex); Array.Copy(m_Operands, movedIndex + 1, newOperands, movedIndex + 1, m_Operands.Length - movedIndex - 1); } m_Operands = newOperands; //Move the slots ahead of time sot that the SyncSlot does not result in links lost. MoveSlots(VFXSlot.Direction.kInput, movedIndex, targetIndex); Invalidate(InvalidationCause.kSettingChanged); } protected override VFXExpression[] BuildExpression(VFXExpression[] inputExpression) { if (inputExpression.Length == 0) { return new[] { VFXValue.Constant(defaultValueFloat) }; } //Process aggregate two by two element until result var outputExpression = new Stack<VFXExpression>(inputExpression.Reverse()); while (outputExpression.Count > 1) { var a = outputExpression.Pop(); var b = outputExpression.Pop(); var compose = ComposeExpression(a, b); outputExpression.Push(compose); } return outputExpression.ToArray(); } protected abstract VFXExpression ComposeExpression(VFXExpression a, VFXExpression b); } }
using System; using System.Data; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Collections; using System.Globalization; namespace HtmlHelp.ChmDecoding { /// <summary> /// The class <c>FullTextSearcher</c> implements a fulltext searcher for a single chm file ! /// </summary> internal sealed class FullTextEngine : IDisposable { #region Internal helper classes /// <summary> /// Internal class for decoding the header /// </summary> private sealed class FTHeader { /// <summary> /// Internal member storing the number of indexed files /// </summary> private int _numberOfIndexFiles = 0; /// <summary> /// Internal member storing the offset of the root node /// </summary> private int _rootOffset = 0; /// <summary> /// Internal member storing the index-page count /// </summary> private int _pageCount = 0; /// <summary> /// Internal member storing the depth of the tree /// </summary> private int _depth = 0; /// <summary> /// Internal member storing the scale param for document index en-/decoding /// </summary> private byte _scaleDocIdx = 0; /// <summary> /// Internal member storing the scale param for code-count en-/decoding /// </summary> private byte _scaleCodeCnt = 0; /// <summary> /// Internal member storing the scale param for location codes en-/decoding /// </summary> private byte _scaleLocCodes = 0; /// <summary> /// Internal member storing the root param for document index en-/decoding /// </summary> private byte _rootDocIdx = 0; /// <summary> /// Internal member storing the root param for code-count en-/decoding /// </summary> private byte _rootCodeCnt = 0; /// <summary> /// Internal member storing the root param for location codes en-/decoding /// </summary> private byte _rootLocCodes = 0; /// <summary> /// Internal member storing the size of the nodes in bytes /// </summary> private int _nodeSize = 0; /// <summary> /// Internal member storing the length of the longest word /// </summary> private int _lengthOfLongestWord = 0; /// <summary> /// Internal member storing the total number of words /// </summary> private int _totalNumberOfWords = 0; /// <summary> /// Internal member storing the total number of unique words /// </summary> private int _numberOfUniqueWords = 0; /// <summary> /// Internal member storing the codepage identifier /// </summary> private int _codePage = 1252; /// <summary> /// Internal member storing the language code id /// </summary> private int _lcid = 1033; /// <summary> /// Internal member storing the text encoder /// </summary> private Encoding _textEncoder = Encoding.Default; /// <summary> /// Constructor of the header /// </summary> /// <param name="binaryData">binary data from which the header will be extracted</param> public FTHeader(byte[] binaryData) { DecodeHeader(binaryData); } /// <summary> /// Internal constructor for reading from dump /// </summary> internal FTHeader() { } /// <summary> /// Decodes the binary header information and fills the members /// </summary> /// <param name="binaryData">binary data from which the header will be extracted</param> private void DecodeHeader(byte[] binaryData) { MemoryStream memStream = new MemoryStream(binaryData); BinaryReader binReader = new BinaryReader(memStream); binReader.ReadBytes(4); // 4 unknown bytes _numberOfIndexFiles = binReader.ReadInt32(); // number of indexed files binReader.ReadInt32(); // unknown binReader.ReadInt32(); // unknown _pageCount = binReader.ReadInt32(); // page-count _rootOffset = binReader.ReadInt32(); // file offset of the root node _depth = binReader.ReadInt16(); // depth of the tree binReader.ReadInt32(); // unknown _scaleDocIdx = binReader.ReadByte(); _rootDocIdx = binReader.ReadByte(); _scaleCodeCnt = binReader.ReadByte(); _rootCodeCnt = binReader.ReadByte(); _scaleLocCodes = binReader.ReadByte(); _rootLocCodes = binReader.ReadByte(); if( (_scaleDocIdx != 2) || ( _scaleCodeCnt != 2 ) || ( _scaleLocCodes != 2 ) ) { Debug.WriteLine("Unsupported scale for s/r encoding !"); throw new InvalidOperationException("Unsupported scale for s/r encoding !"); } binReader.ReadBytes(10); // unknown _nodeSize = binReader.ReadInt32(); binReader.ReadInt32(); // unknown binReader.ReadInt32(); // not important binReader.ReadInt32(); // not important _lengthOfLongestWord = binReader.ReadInt32(); _totalNumberOfWords = binReader.ReadInt32(); _numberOfUniqueWords = binReader.ReadInt32(); binReader.ReadInt32(); // not important binReader.ReadInt32(); // not important binReader.ReadInt32(); // not important binReader.ReadInt32(); // not important binReader.ReadInt32(); // not important binReader.ReadInt32(); // not important binReader.ReadBytes(24); // not important _codePage = binReader.ReadInt32(); _lcid = binReader.ReadInt32(); CultureInfo ci = new CultureInfo(_lcid); _textEncoder = Encoding.GetEncoding( ci.TextInfo.ANSICodePage ); // rest of header is not important for us } /// <summary> /// Dump the class data to a binary writer /// </summary> /// <param name="writer">writer to write the data</param> internal void Dump(ref BinaryWriter writer) { writer.Write( _numberOfIndexFiles ); writer.Write( _rootOffset ); writer.Write( _pageCount ); writer.Write( _depth ); writer.Write( _scaleDocIdx ); writer.Write( _rootDocIdx ); writer.Write( _scaleCodeCnt ); writer.Write( _rootCodeCnt ); writer.Write( _scaleLocCodes ); writer.Write( _rootLocCodes ); writer.Write( _nodeSize ); writer.Write( _lengthOfLongestWord ); writer.Write( _totalNumberOfWords ); writer.Write( _numberOfUniqueWords ); } /// <summary> /// Reads the object data from a dump store /// </summary> /// <param name="reader">reader to read the data</param> internal void ReadDump(ref BinaryReader reader) { _numberOfIndexFiles = reader.ReadInt32(); _rootOffset = reader.ReadInt32(); _pageCount = reader.ReadInt32(); _depth = reader.ReadInt32(); _scaleDocIdx = reader.ReadByte(); _rootDocIdx = reader.ReadByte(); _scaleCodeCnt = reader.ReadByte(); _rootCodeCnt = reader.ReadByte(); _scaleLocCodes = reader.ReadByte(); _rootLocCodes = reader.ReadByte(); _nodeSize = reader.ReadInt32(); _lengthOfLongestWord = reader.ReadInt32(); _totalNumberOfWords = reader.ReadInt32(); _numberOfUniqueWords = reader.ReadInt32(); } /// <summary> /// Gets the number of indexed files /// </summary> public int IndexedFileCount { get { return _numberOfIndexFiles; } } /// <summary> /// Gets the file offset of the root node /// </summary> public int RootOffset { get { return _rootOffset; } } /// <summary> /// Gets the page count /// </summary> public int PageCount { get { return _pageCount; } } /// <summary> /// Gets the index depth /// </summary> public int Depth { get { return _depth; } } /// <summary> /// Gets the scale param for document index en-/decoding /// </summary> /// <remarks>The scale and root method of integer encoding needs two parameters, /// which I'll call s (scale) and r (root size). /// The integer is encoded as two parts, p (prefix) and q (actual bits). /// p determines how many bits are stored, as well as implicitly determining /// the high-order bit of the integer. </remarks> public byte ScaleDocumentIndex { get { return _scaleDocIdx; } } /// <summary> /// Gets the root param for the document index en-/decoding /// </summary> /// <remarks>The scale and root method of integer encoding needs two parameters, /// which I'll call s (scale) and r (root size). /// The integer is encoded as two parts, p (prefix) and q (actual bits). /// p determines how many bits are stored, as well as implicitly determining /// the high-order bit of the integer. </remarks> public byte RootDocumentIndex { get { return _rootDocIdx; } } /// <summary> /// Gets the scale param for the code-count en-/decoding /// </summary> /// <remarks>The scale and root method of integer encoding needs two parameters, /// which I'll call s (scale) and r (root size). /// The integer is encoded as two parts, p (prefix) and q (actual bits). /// p determines how many bits are stored, as well as implicitly determining /// the high-order bit of the integer. </remarks> public byte ScaleCodeCount { get { return _scaleCodeCnt; } } /// <summary> /// Gets the root param for the code-count en-/decoding /// </summary> /// <remarks>The scale and root method of integer encoding needs two parameters, /// which I'll call s (scale) and r (root size). /// The integer is encoded as two parts, p (prefix) and q (actual bits). /// p determines how many bits are stored, as well as implicitly determining /// the high-order bit of the integer. </remarks> public byte RootCodeCount { get { return _rootCodeCnt; } } /// <summary> /// Gets the scale param for the location codes en-/decoding /// </summary> /// <remarks>The scale and root method of integer encoding needs two parameters, /// which I'll call s (scale) and r (root size). /// The integer is encoded as two parts, p (prefix) and q (actual bits). /// p determines how many bits are stored, as well as implicitly determining /// the high-order bit of the integer. </remarks> public byte ScaleLocationCodes { get { return _scaleLocCodes; } } /// <summary> /// Gets the root param for the location codes en-/decoding /// </summary> /// <remarks>The scale and root method of integer encoding needs two parameters, /// which I'll call s (scale) and r (root size). /// The integer is encoded as two parts, p (prefix) and q (actual bits). /// p determines how many bits are stored, as well as implicitly determining /// the high-order bit of the integer. </remarks> public byte RootLocationCodes { get { return _rootLocCodes; } } /// <summary> /// Gets the size in bytes of each index/leaf node /// </summary> public int NodeSize { get { return _nodeSize; } } /// <summary> /// Gets the length of the longest word in the index /// </summary> private int LengthOfLongestWord { get { return _lengthOfLongestWord; } } /// <summary> /// Gets the total number of words indexed (including duplicates) /// </summary> public int TotalWordCount { get { return _totalNumberOfWords; } } /// <summary> /// Gets the total number of unique words indexed (excluding duplicates) /// </summary> public int UniqueWordCount { get { return _numberOfUniqueWords; } } /// <summary> /// Gets the codepage identifier /// </summary> public int CodePage { get { return _codePage; } } /// <summary> /// Gets the language code id /// </summary> public int LCID { get { return _lcid; } } public Encoding TextEncoder { get { return _textEncoder; } } } /// <summary> /// Internal class for easier hit recording and rate-calculation /// </summary> private sealed class HitHelper : IComparable { /// <summary> /// Internal member storing the associated document index /// </summary> private int _documentIndex = 0; /// <summary> /// Internal member storing the title /// </summary> private string _title = ""; /// <summary> /// Internal member storing the locale /// </summary> private string _locale = ""; /// <summary> /// Internal member storing the location /// </summary> private string _location = ""; /// <summary> /// Internal member storing the url /// </summary> private string _url = ""; /// <summary> /// Internal member storing the rating /// </summary> private double _rating = 0; /// <summary> /// Internal member used for rating calculation /// </summary> private Hashtable _partialRating = new Hashtable(); /// <summary> /// Constructor of the class /// </summary> /// <param name="documentIndex">document index</param> /// <param name="title">title</param> /// <param name="locale">locale parameter</param> /// <param name="location">location</param> /// <param name="url">url of document</param> /// <param name="rating">rating</param> public HitHelper(int documentIndex, string title, string locale, string location, string url, double rating) { _documentIndex = documentIndex; _title = title; _locale = locale; _location = location; _url = url; _rating = rating; } /// <summary> /// Updates the rating for a found word /// </summary> /// <param name="word">word found</param> public void UpdateRating(string word) { if( _partialRating[word] == null) { _partialRating[word] = 100.0; } else { _partialRating[word] = ((double)_partialRating[word])*1.01; } _rating = 0.0; foreach(double val in _partialRating.Values) { _rating += val; } } /// <summary> /// Implements the CompareTo method of the IComparable interface. /// Allows an easy sort by the document rating /// </summary> /// <param name="obj">object to compare</param> /// <returns>0 ... equal, -1 ... this instance is less than obj, 1 ... this instance is greater than obj</returns> public int CompareTo(object obj) { if( obj is HitHelper ) { HitHelper hObj = (HitHelper)obj; return this.Rating.CompareTo( hObj.Rating ); } return -1; } /// <summary> /// Gets the internal hashtable used for counting word hits of the document /// </summary> internal Hashtable PartialRating { get { return _partialRating; } } /// <summary> /// Gets the document index of the hit helper instance /// </summary> public int DocumentIndex { get { return _documentIndex; } } /// <summary> /// Gets the title /// </summary> public string Title { get { return _title; } } /// <summary> /// Gets the locale /// </summary> public string Locale { get { return _locale; } } /// <summary> /// Gets the location /// </summary> public string Location { get { return _location; } } /// <summary> /// Gets the url /// </summary> public string URL { get { return _url; } } /// <summary> /// Gets the rating /// </summary> public double Rating { get { return _rating; } } } #endregion /// <summary> /// Regular expression getting the text between to quotes /// </summary> private string RE_Quotes = @"\""(?<innerText>.*?)\"""; /// <summary> /// Internal flag specifying if the object is going to be disposed /// </summary> private bool disposed = false; /// <summary> /// Internal member storing the binary file data /// </summary> private byte[] _binaryFileData = null; /// <summary> /// Internal datatable storing the search hits /// </summary> private DataTable _hits =null; /// <summary> /// Internal arraylist for hit management /// </summary> private ArrayList _hitsHelper = new ArrayList(); /// <summary> /// Internal member storing the header of the file /// </summary> private FTHeader _header = null; /// <summary> /// Internal member storing the associated chmfile object /// </summary> private CHMFile _associatedFile = null; /// <summary> /// Constructor of the class /// </summary> /// <param name="binaryFileData">binary file data of the $FIftiMain file</param> /// <param name="associatedFile">associated chm file</param> public FullTextEngine(byte[] binaryFileData, CHMFile associatedFile) { _binaryFileData = binaryFileData; _associatedFile = associatedFile; if(_associatedFile.SystemFile.FullTextSearch) { _header = new FTHeader(_binaryFileData); // reading header } } /// <summary> /// Standard constructor /// </summary> internal FullTextEngine() { } #region Data dumping /// <summary> /// Dump the class data to a binary writer /// </summary> /// <param name="writer">writer to write the data</param> internal void Dump(ref BinaryWriter writer) { _header.Dump(ref writer); writer.Write( _binaryFileData.Length ); writer.Write(_binaryFileData); } /// <summary> /// Reads the object data from a dump store /// </summary> /// <param name="reader">reader to read the data</param> internal void ReadDump(ref BinaryReader reader) { _header = new FTHeader(); _header.ReadDump(ref reader); int nCnt = reader.ReadInt32(); _binaryFileData = reader.ReadBytes(nCnt); } /// <summary> /// Sets the associated CHMFile instance /// </summary> /// <param name="associatedFile">instance to set</param> internal void SetCHMFile(CHMFile associatedFile) { _associatedFile = associatedFile; } #endregion /// <summary> /// Gets a flag if full-text searching is available for this chm file. /// </summary> public bool CanSearch { get { return (_associatedFile.SystemFile.FullTextSearch && (_header != null) ); } } /// <summary> /// Performs a fulltext search of a single file. /// </summary> /// <param name="search">word(s) or phrase to search</param> /// <param name="partialMatches">true if partial word should be matched also /// ( if this is true a search of 'support' will match 'supports', otherwise not )</param> /// <param name="titleOnly">true if only search in titles</param> /// <remarks>Hits are available through the <see cref="Hits">Hists property</see>.</remarks> public bool Search(string search, bool partialMatches, bool titleOnly) { return Search(search, -1, partialMatches, titleOnly); } /// <summary> /// Performs a fulltext search of a single file. /// </summary> /// <param name="search">word(s) or phrase to search</param> /// <param name="MaxHits">max hits. If this number is reached, the search will be interrupted</param> /// <param name="partialMatches">true if partial word should be matched also /// ( if this is true a search of 'support' will match 'supports', otherwise not )</param> /// <param name="titleOnly">true if only search in titles</param> /// <remarks>Hits are available through the <see cref="Hits">Hists property</see>.</remarks> public bool Search(string search, int MaxHits, bool partialMatches, bool titleOnly) { if(CanSearch) { string searchString = search; // Check if this is a quoted string bool IsQuoted = (search.IndexOf("\"")>-1); if(IsQuoted) searchString = search.Replace("\"",""); // remove the quotes during search bool bRet = true; _hitsHelper = null; _hitsHelper = new ArrayList(); _hits = null; CreateHitsTable(); string[] words = searchString.Split(new char[] {' '}); for(int i=0; i<words.Length; i++) { bRet &= SearchSingleWord(words[i], MaxHits, partialMatches, titleOnly); if(_hitsHelper.Count >= MaxHits) break; } if(bRet && IsQuoted) { FinalizeQuoted(search); } if(bRet) { _hitsHelper.Sort(); int nhCount = MaxHits; if( MaxHits < 0) { nhCount = _hitsHelper.Count; } if( nhCount > _hitsHelper.Count ) nhCount = _hitsHelper.Count; // create hits datatable for(int i=nhCount; i > 0; i--) { HitHelper curHlp = (HitHelper)(_hitsHelper[i-1]); DataRow newRow = _hits.NewRow(); newRow["Rating"] = curHlp.Rating; newRow["Title"] = curHlp.Title; newRow["Locale"] = curHlp.Locale; newRow["Location"] = curHlp.Location; newRow["URL"] = curHlp.URL; _hits.Rows.Add( newRow ); } } return bRet; } return false; } /// <summary> /// Gets rid of all search hits which doesn't match the quoted phrase /// </summary> /// <param name="search">full search string entered by the user</param> /// <remarks>Phrase search is not possible using the internal full-text index. We're just filtering all /// documents which don't contain all words of the phrase.</remarks> private void FinalizeQuoted(string search) { Regex quoteRE = new Regex(RE_Quotes, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline); int innerTextIdx = quoteRE.GroupNumberFromName("innerText"); int nIndex = 0; // get all phrases while( quoteRE.IsMatch(search, nIndex) ) { Match m = quoteRE.Match(search, nIndex); string phrase = m.Groups["innerText"].Value; string[] wordsInPhrase = phrase.Split( new char[] {' '} ); int nCnt = _hitsHelper.Count; for(int i=0; i < _hitsHelper.Count; i++) { if( ! CheckHit( ((HitHelper)(_hitsHelper[i])), wordsInPhrase) ) _hitsHelper.RemoveAt(i--); } nIndex = m.Index+m.Length; } } /// <summary> /// Eliminates all search hits where not all of the words have been found /// </summary> /// <param name="hit">hithelper instance to check</param> /// <param name="wordsInPhrase">word list</param> private bool CheckHit(HitHelper hit, string[] wordsInPhrase) { for(int i=0; i<wordsInPhrase.Length;i++) { if( (hit.PartialRating[wordsInPhrase[i]] == null) || (((double)(hit.PartialRating[wordsInPhrase[i]])) == 0.0) ) return false; } return true; } /// <summary> /// Performs a search for a single word in the index /// </summary> /// <param name="word">word to search</param> /// <param name="MaxHits">maximal hits to return</param> /// <param name="partialMatches">true if partial word should be matched also /// ( if this is true a search of 'support' will match 'supports', otherwise not )</param> /// <param name="titleOnly">true if only search in titles</param> /// <returns>Returns true if succeeded</returns> private bool SearchSingleWord(string word,int MaxHits, bool partialMatches, bool titleOnly) { string wordLower = word.ToLower(); MemoryStream memStream = new MemoryStream(_binaryFileData); BinaryReader binReader = new BinaryReader(memStream); // seek to root node binReader.BaseStream.Seek( _header.RootOffset, SeekOrigin.Begin ); if( _header.Depth > 2 ) { // unsupported index depth Debug.WriteLine("FullTextSearcher.SearchSingleWord() - Failed with message: Unsupported index depth !"); Debug.WriteLine("File: " + _associatedFile.ChmFilePath); Debug.WriteLine(" "); return false; } if( _header.Depth > 1 ) { // seek to the right leaf node ( if depth == 1, we are at the leaf node) int freeSpace = binReader.ReadInt16(); for(int i=0; i < _header.PageCount; ++i) { // exstract index entries int nWLength = (int)binReader.ReadByte(); int nCPosition = (int)binReader.ReadByte(); string sName = BinaryReaderHelp.ExtractString(ref binReader, nWLength-1, 0, true, _header.TextEncoder); int nLeafOffset = binReader.ReadInt32(); binReader.ReadInt16(); // unknown if( sName.CompareTo(wordLower) >= 0) { // store current position long curPos = binReader.BaseStream.Position; // seek to leaf offset binReader.BaseStream.Seek( nLeafOffset, SeekOrigin.Begin ); // read leafnode ReadLeafNode(ref binReader, word, MaxHits, partialMatches, titleOnly); // return to current position and continue reading index nodes binReader.BaseStream.Seek( curPos, SeekOrigin.Begin ); } } } return true; } /// <summary> /// Reads a leaf node and extracts documents which holds the searched word /// </summary> /// <param name="binReader">reference to the reader</param> /// <param name="word">word to search</param> /// <param name="MaxHits">maximal hits to return</param> /// <param name="partialMatches">true if partial word should be matched also /// ( if this is true a search of 'support' will match 'supports', otherwise not )</param> /// <param name="titleOnly">true if only search in titles</param> private void ReadLeafNode(ref BinaryReader binReader, string word, int MaxHits, bool partialMatches, bool titleOnly) { int nNextPageOffset = binReader.ReadInt32(); binReader.ReadInt16(); // unknown int lfreeSpace = binReader.ReadInt16(); string curFullWord = ""; bool bFound = false; string wordLower = word.ToLower(); for(;;) { if(binReader.BaseStream.Position >= binReader.BaseStream.Length) break; int nWLength = (int)binReader.ReadByte(); if(nWLength == 0) break; int nCPosition = (int)binReader.ReadByte(); string sName = BinaryReaderHelp.ExtractString(ref binReader, nWLength-1, 0, true, _header.TextEncoder); int Context = (int)binReader.ReadByte(); // 0...body tag, 1...title tag, others unknown long nrOfWCL = BinaryReaderHelp.ReadENCINT(ref binReader); int wclOffset = binReader.ReadInt32(); binReader.ReadInt16(); // unknown long bytesOfWCL = BinaryReaderHelp.ReadENCINT(ref binReader); if( nCPosition > 0) { curFullWord = CombineStrings(curFullWord, sName, nCPosition); } else { curFullWord = sName; } bFound = false; if(partialMatches) bFound = ( curFullWord.IndexOf(wordLower) >= 0 ); else bFound = (curFullWord == wordLower); if( bFound ) { if( (titleOnly && (Context==1)) || (!titleOnly) ) { // store actual offset long curPos = binReader.BaseStream.Position; // found the word, begin with WCL encoding binReader.BaseStream.Seek(wclOffset, SeekOrigin.Begin ); byte[] wclBytes = binReader.ReadBytes((int)bytesOfWCL); DecodeWCL(wclBytes, MaxHits, word); // back and continue reading leafnodes binReader.BaseStream.Seek(curPos, SeekOrigin.Begin ); } } } } /// <summary> /// Decodes the s/r encoded WordCodeList (=wcl) and creates hit entries /// </summary> /// <param name="wclBytes">wcl encoded byte array</param> /// <param name="MaxHits">maximal hits</param> /// <param name="word">the word to find</param> private void DecodeWCL(byte[] wclBytes,int MaxHits, string word) { byte[] wclBits = new byte[ wclBytes.Length*8 ]; int nBitIdx=0; for(int i=0; i<wclBytes.Length; i++) { for(int j=0; j<8; j++) { wclBits[nBitIdx] = ((byte)(wclBytes[i] & ((byte)( (byte)0x1 << (7-j) )))) > (byte)0 ? (byte)1 : (byte)0; nBitIdx++; } } nBitIdx = 0; int nDocIdx = 0; // delta encoded while(nBitIdx < wclBits.Length) { nDocIdx += BinaryReaderHelp.ReadSRItem(wclBits, _header.ScaleDocumentIndex, _header.RootDocumentIndex, ref nBitIdx); int nCodeCnt = BinaryReaderHelp.ReadSRItem(wclBits, _header.ScaleCodeCount, _header.RootCodeCount, ref nBitIdx); int nWordLocation = 0; // delta encoded for(int locidx=0; locidx<nCodeCnt; locidx++) { nWordLocation += BinaryReaderHelp.ReadSRItem(wclBits, _header.ScaleLocationCodes, _header.RootLocationCodes, ref nBitIdx); } // apply padding while( (nBitIdx % 8) != 0) nBitIdx++; // Record hit HitHelper hitObj = DocumentHit(nDocIdx); if(hitObj == null) { if(_hitsHelper.Count > MaxHits) return; hitObj = new HitHelper(nDocIdx, ((TopicEntry)(_associatedFile.TopicsFile.TopicTable[nDocIdx])).Title, ((TopicEntry)(_associatedFile.TopicsFile.TopicTable[nDocIdx])).Locale, _associatedFile.CompileFile, ((TopicEntry)(_associatedFile.TopicsFile.TopicTable[nDocIdx])).URL, 0.0); for(int k=0;k<nCodeCnt;k++) hitObj.UpdateRating(word); _hitsHelper.Add(hitObj); } else { for(int k=0;k<nCodeCnt;k++) hitObj.UpdateRating(word); } } } /// <summary> /// Combines a "master" word with a partial word. /// </summary> /// <param name="word">the master word</param> /// <param name="partial">the partial word</param> /// <param name="partialPosition">position to place the parial word</param> /// <returns>returns a combined string</returns> private string CombineStrings(string word, string partial, int partialPosition) { string sCombined = word; int i=0; for(i=0; i<partial.Length; i++) { if( (i+partialPosition) > (sCombined.Length-1) ) { sCombined += partial[i]; } else { StringBuilder sb = new StringBuilder(sCombined); sb.Replace( sCombined[partialPosition+i], partial[i], partialPosition+i, 1); sCombined = sb.ToString(); } } if(! ((i+partialPosition) > (sCombined.Length-1)) ) { sCombined = sCombined.Substring(0, partialPosition+partial.Length); } return sCombined; } /// <summary> /// Gets the HitHelper instance for a specific document index /// </summary> /// <param name="index">document index</param> /// <returns>The reference of the hithelper instance for this document index, otherwise null</returns> private HitHelper DocumentHit(int index) { foreach(HitHelper curObj in _hitsHelper) { if( curObj.DocumentIndex == index) return curObj; } return null; } /// <summary> /// Creates a DataTable for storing the hits /// </summary> private void CreateHitsTable() { _hits = new DataTable("FT_Search_Hits"); DataColumn ftColumn; ftColumn = new DataColumn(); ftColumn.DataType = System.Type.GetType("System.Double"); ftColumn.ColumnName = "Rating"; ftColumn.ReadOnly = false; ftColumn.Unique = false; _hits.Columns.Add(ftColumn); ftColumn = new DataColumn(); ftColumn.DataType = System.Type.GetType("System.String"); ftColumn.ColumnName = "Title"; ftColumn.ReadOnly = false; ftColumn.Unique = false; _hits.Columns.Add(ftColumn); ftColumn = new DataColumn(); ftColumn.DataType = System.Type.GetType("System.String"); ftColumn.ColumnName = "Locale"; ftColumn.ReadOnly = false; ftColumn.Unique = false; _hits.Columns.Add(ftColumn); ftColumn = new DataColumn(); ftColumn.DataType = System.Type.GetType("System.String"); ftColumn.ColumnName = "Location"; ftColumn.ReadOnly = false; ftColumn.Unique = false; _hits.Columns.Add(ftColumn); ftColumn = new DataColumn(); ftColumn.DataType = System.Type.GetType("System.String"); ftColumn.ColumnName = "URL"; ftColumn.ReadOnly = false; ftColumn.Unique = false; _hits.Columns.Add(ftColumn); } /// <summary> /// Gets an datatable containing the hits of the last search /// </summary> public DataTable Hits { get { return _hits; } } /// <summary> /// Implement IDisposable. /// </summary> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing">disposing flag</param> private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if(!this.disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if(disposing) { // Dispose managed resources. _binaryFileData = null; } } disposed = 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="FeedMappingServiceClient"/> instances.</summary> public sealed partial class FeedMappingServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FeedMappingServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FeedMappingServiceSettings"/>.</returns> public static FeedMappingServiceSettings GetDefault() => new FeedMappingServiceSettings(); /// <summary>Constructs a new <see cref="FeedMappingServiceSettings"/> object with default settings.</summary> public FeedMappingServiceSettings() { } private FeedMappingServiceSettings(FeedMappingServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetFeedMappingSettings = existing.GetFeedMappingSettings; MutateFeedMappingsSettings = existing.MutateFeedMappingsSettings; OnCopy(existing); } partial void OnCopy(FeedMappingServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedMappingServiceClient.GetFeedMapping</c> and <c>FeedMappingServiceClient.GetFeedMappingAsync</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 GetFeedMappingSettings { 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>FeedMappingServiceClient.MutateFeedMappings</c> and <c>FeedMappingServiceClient.MutateFeedMappingsAsync</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 MutateFeedMappingsSettings { 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="FeedMappingServiceSettings"/> object.</returns> public FeedMappingServiceSettings Clone() => new FeedMappingServiceSettings(this); } /// <summary> /// Builder class for <see cref="FeedMappingServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class FeedMappingServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedMappingServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FeedMappingServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FeedMappingServiceClientBuilder() { UseJwtAccessWithScopes = FeedMappingServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FeedMappingServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedMappingServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FeedMappingServiceClient Build() { FeedMappingServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FeedMappingServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FeedMappingServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FeedMappingServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FeedMappingServiceClient.Create(callInvoker, Settings); } private async stt::Task<FeedMappingServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FeedMappingServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FeedMappingServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedMappingServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FeedMappingServiceClient.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>FeedMappingService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage feed mappings. /// </remarks> public abstract partial class FeedMappingServiceClient { /// <summary> /// The default endpoint for the FeedMappingService 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 FeedMappingService scopes.</summary> /// <remarks> /// The default FeedMappingService 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="FeedMappingServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="FeedMappingServiceClientBuilder"/> /// . /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FeedMappingServiceClient"/>.</returns> public static stt::Task<FeedMappingServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FeedMappingServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FeedMappingServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="FeedMappingServiceClientBuilder"/> /// . /// </summary> /// <returns>The created <see cref="FeedMappingServiceClient"/>.</returns> public static FeedMappingServiceClient Create() => new FeedMappingServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FeedMappingServiceClient"/> 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="FeedMappingServiceSettings"/>.</param> /// <returns>The created <see cref="FeedMappingServiceClient"/>.</returns> internal static FeedMappingServiceClient Create(grpccore::CallInvoker callInvoker, FeedMappingServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FeedMappingService.FeedMappingServiceClient grpcClient = new FeedMappingService.FeedMappingServiceClient(callInvoker); return new FeedMappingServiceClientImpl(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 FeedMappingService client</summary> public virtual FeedMappingService.FeedMappingServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed mapping 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::FeedMapping GetFeedMapping(GetFeedMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed mapping 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::FeedMapping> GetFeedMappingAsync(GetFeedMappingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed mapping 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::FeedMapping> GetFeedMappingAsync(GetFeedMappingRequest request, st::CancellationToken cancellationToken) => GetFeedMappingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed mapping in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed mapping to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedMapping GetFeedMapping(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedMapping(new GetFeedMappingRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed mapping in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed mapping 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::FeedMapping> GetFeedMappingAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedMappingAsync(new GetFeedMappingRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed mapping in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed mapping 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::FeedMapping> GetFeedMappingAsync(string resourceName, st::CancellationToken cancellationToken) => GetFeedMappingAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed mapping in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed mapping to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedMapping GetFeedMapping(gagvr::FeedMappingName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedMapping(new GetFeedMappingRequest { ResourceNameAsFeedMappingName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed mapping in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed mapping 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::FeedMapping> GetFeedMappingAsync(gagvr::FeedMappingName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedMappingAsync(new GetFeedMappingRequest { ResourceNameAsFeedMappingName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed mapping in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed mapping 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::FeedMapping> GetFeedMappingAsync(gagvr::FeedMappingName resourceName, st::CancellationToken cancellationToken) => GetFeedMappingAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes feed mappings. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedMappingError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [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 MutateFeedMappingsResponse MutateFeedMappings(MutateFeedMappingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes feed mappings. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedMappingError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [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<MutateFeedMappingsResponse> MutateFeedMappingsAsync(MutateFeedMappingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes feed mappings. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedMappingError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [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<MutateFeedMappingsResponse> MutateFeedMappingsAsync(MutateFeedMappingsRequest request, st::CancellationToken cancellationToken) => MutateFeedMappingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes feed mappings. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedMappingError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed mappings are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed mappings. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedMappingsResponse MutateFeedMappings(string customerId, scg::IEnumerable<FeedMappingOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedMappings(new MutateFeedMappingsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or removes feed mappings. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedMappingError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed mappings are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed mappings. /// </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<MutateFeedMappingsResponse> MutateFeedMappingsAsync(string customerId, scg::IEnumerable<FeedMappingOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedMappingsAsync(new MutateFeedMappingsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or removes feed mappings. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedMappingError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed mappings are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed mappings. /// </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<MutateFeedMappingsResponse> MutateFeedMappingsAsync(string customerId, scg::IEnumerable<FeedMappingOperation> operations, st::CancellationToken cancellationToken) => MutateFeedMappingsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>FeedMappingService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage feed mappings. /// </remarks> public sealed partial class FeedMappingServiceClientImpl : FeedMappingServiceClient { private readonly gaxgrpc::ApiCall<GetFeedMappingRequest, gagvr::FeedMapping> _callGetFeedMapping; private readonly gaxgrpc::ApiCall<MutateFeedMappingsRequest, MutateFeedMappingsResponse> _callMutateFeedMappings; /// <summary> /// Constructs a client wrapper for the FeedMappingService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="FeedMappingServiceSettings"/> used within this client.</param> public FeedMappingServiceClientImpl(FeedMappingService.FeedMappingServiceClient grpcClient, FeedMappingServiceSettings settings) { GrpcClient = grpcClient; FeedMappingServiceSettings effectiveSettings = settings ?? FeedMappingServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetFeedMapping = clientHelper.BuildApiCall<GetFeedMappingRequest, gagvr::FeedMapping>(grpcClient.GetFeedMappingAsync, grpcClient.GetFeedMapping, effectiveSettings.GetFeedMappingSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetFeedMapping); Modify_GetFeedMappingApiCall(ref _callGetFeedMapping); _callMutateFeedMappings = clientHelper.BuildApiCall<MutateFeedMappingsRequest, MutateFeedMappingsResponse>(grpcClient.MutateFeedMappingsAsync, grpcClient.MutateFeedMappings, effectiveSettings.MutateFeedMappingsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateFeedMappings); Modify_MutateFeedMappingsApiCall(ref _callMutateFeedMappings); 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_GetFeedMappingApiCall(ref gaxgrpc::ApiCall<GetFeedMappingRequest, gagvr::FeedMapping> call); partial void Modify_MutateFeedMappingsApiCall(ref gaxgrpc::ApiCall<MutateFeedMappingsRequest, MutateFeedMappingsResponse> call); partial void OnConstruction(FeedMappingService.FeedMappingServiceClient grpcClient, FeedMappingServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FeedMappingService client</summary> public override FeedMappingService.FeedMappingServiceClient GrpcClient { get; } partial void Modify_GetFeedMappingRequest(ref GetFeedMappingRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateFeedMappingsRequest(ref MutateFeedMappingsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested feed mapping 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::FeedMapping GetFeedMapping(GetFeedMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedMappingRequest(ref request, ref callSettings); return _callGetFeedMapping.Sync(request, callSettings); } /// <summary> /// Returns the requested feed mapping 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::FeedMapping> GetFeedMappingAsync(GetFeedMappingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedMappingRequest(ref request, ref callSettings); return _callGetFeedMapping.Async(request, callSettings); } /// <summary> /// Creates or removes feed mappings. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedMappingError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [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 MutateFeedMappingsResponse MutateFeedMappings(MutateFeedMappingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedMappingsRequest(ref request, ref callSettings); return _callMutateFeedMappings.Sync(request, callSettings); } /// <summary> /// Creates or removes feed mappings. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedMappingError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [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<MutateFeedMappingsResponse> MutateFeedMappingsAsync(MutateFeedMappingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedMappingsRequest(ref request, ref callSettings); return _callMutateFeedMappings.Async(request, callSettings); } } }
/* * 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.IO.Compression; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Serialization; using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Ionic.Zlib; using GZipStream = Ionic.Zlib.GZipStream; using CompressionMode = Ionic.Zlib.CompressionMode; using OpenSim.Framework.Serialization.External; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// Prepare to write out an archive. /// </summary> public class ArchiveWriteRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The minimum major version of OAR that we can write. /// </summary> public static int MIN_MAJOR_VERSION = 0; /// <summary> /// The maximum major version of OAR that we can write. /// </summary> public static int MAX_MAJOR_VERSION = 1; /// <summary> /// Whether we're saving a multi-region archive. /// </summary> public bool MultiRegionFormat { get; set; } /// <summary> /// Determine whether this archive will save assets. Default is true. /// </summary> public bool SaveAssets { get; set; } /// <summary> /// Determines which objects will be included in the archive, according to their permissions. /// Default is null, meaning no permission checks. /// </summary> public string FilterContent { get; set; } protected Scene m_rootScene; protected Stream m_saveStream; protected TarArchiveWriter m_archiveWriter; protected Guid m_requestId; protected Dictionary<string, object> m_options; /// <summary> /// Constructor /// </summary> /// <param name="module">Calling module</param> /// <param name="savePath">The path to which to save data.</param> /// <param name="requestId">The id associated with this request</param> /// <exception cref="System.IO.IOException"> /// If there was a problem opening a stream for the file specified by the savePath /// </exception> public ArchiveWriteRequest(Scene scene, string savePath, Guid requestId) : this(scene, requestId) { try { m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.ErrorFormat("{0} {1}", e.Message, e.StackTrace); } } /// <summary> /// Constructor. /// </summary> /// <param name="scene">The root scene to archive</param> /// <param name="saveStream">The stream to which to save data.</param> /// <param name="requestId">The id associated with this request</param> public ArchiveWriteRequest(Scene scene, Stream saveStream, Guid requestId) : this(scene, requestId) { m_saveStream = saveStream; } protected ArchiveWriteRequest(Scene scene, Guid requestId) { m_rootScene = scene; m_requestId = requestId; m_archiveWriter = null; MultiRegionFormat = false; SaveAssets = true; FilterContent = null; } /// <summary> /// Archive the region requested. /// </summary> /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception> public void ArchiveRegion(Dictionary<string, object> options) { m_options = options; if (options.ContainsKey("all") && (bool)options["all"]) MultiRegionFormat = true; if (options.ContainsKey("noassets") && (bool)options["noassets"]) SaveAssets = false; Object temp; if (options.TryGetValue("checkPermissions", out temp)) FilterContent = (string)temp; // Find the regions to archive ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup(); if (MultiRegionFormat) { m_log.InfoFormat("[ARCHIVER]: Saving {0} regions", SceneManager.Instance.Scenes.Count); SceneManager.Instance.ForEachScene(delegate(Scene scene) { scenesGroup.AddScene(scene); }); } else { scenesGroup.AddScene(m_rootScene); } scenesGroup.CalcSceneLocations(); m_archiveWriter = new TarArchiveWriter(m_saveStream); try { // Write out control file. It should be first so that it will be found ASAP when loading the file. m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(scenesGroup)); m_log.InfoFormat("[ARCHIVER]: Added control file to archive."); // Archive the regions Dictionary<UUID, sbyte> assetUuids = new Dictionary<UUID, sbyte>(); scenesGroup.ForEachScene(delegate(Scene scene) { string regionDir = MultiRegionFormat ? scenesGroup.GetRegionDir(scene.RegionInfo.RegionID) : ""; ArchiveOneRegion(scene, regionDir, assetUuids); }); // Archive the assets if (SaveAssets) { m_log.DebugFormat("[ARCHIVER]: Saving {0} assets", assetUuids.Count); // Asynchronously request all the assets required to perform this archive operation AssetsRequest ar = new AssetsRequest( new AssetsArchiver(m_archiveWriter), assetUuids, m_rootScene.AssetService, m_rootScene.UserAccountService, m_rootScene.RegionInfo.ScopeID, options, ReceivedAllAssets); WorkManager.RunInThread(o => ar.Execute(), null, "Archive Assets Request"); // CloseArchive() will be called from ReceivedAllAssets() } else { m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified"); CloseArchive(string.Empty); } } catch (Exception e) { CloseArchive(e.Message); throw; } } private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary<UUID, sbyte> assetUuids) { m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.Name); EntityBase[] entities = scene.GetEntities(); List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); int numObjectsSkippedPermissions = 0; // Filter entities so that we only have scene objects. // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods // end up having to do this IPermissionsModule permissionsModule = scene.RequestModuleInterface<IPermissionsModule>(); foreach (EntityBase entity in entities) { if (entity is SceneObjectGroup) { SceneObjectGroup sceneObject = (SceneObjectGroup)entity; if (!sceneObject.IsDeleted && !sceneObject.IsAttachment) { if (!CanUserArchiveObject(scene.RegionInfo.EstateSettings.EstateOwner, sceneObject, FilterContent, permissionsModule)) { // The user isn't allowed to copy/transfer this object, so it will not be included in the OAR. ++numObjectsSkippedPermissions; } else { sceneObjects.Add(sceneObject); } } } } if (SaveAssets) { UuidGatherer assetGatherer = new UuidGatherer(scene.AssetService, assetUuids); int prevAssets = assetUuids.Count; foreach (SceneObjectGroup sceneObject in sceneObjects) assetGatherer.AddForInspection(sceneObject); assetGatherer.GatherAll(); m_log.DebugFormat( "[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets", sceneObjects.Count, assetUuids.Count - prevAssets); } if (numObjectsSkippedPermissions > 0) { m_log.DebugFormat( "[ARCHIVER]: {0} scene objects skipped due to lack of permissions", numObjectsSkippedPermissions); } // Make sure that we also request terrain texture assets RegionSettings regionSettings = scene.RegionInfo.RegionSettings; if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1) assetUuids[regionSettings.TerrainTexture1] = (sbyte)AssetType.Texture; if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2) assetUuids[regionSettings.TerrainTexture2] = (sbyte)AssetType.Texture; if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3) assetUuids[regionSettings.TerrainTexture3] = (sbyte)AssetType.Texture; if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4) assetUuids[regionSettings.TerrainTexture4] = (sbyte)AssetType.Texture; Save(scene, sceneObjects, regionDir); } /// <summary> /// Checks whether the user has permission to export an object group to an OAR. /// </summary> /// <param name="user">The user</param> /// <param name="objGroup">The object group</param> /// <param name="filterContent">Which permissions to check: "C" = Copy, "T" = Transfer</param> /// <param name="permissionsModule">The scene's permissions module</param> /// <returns>Whether the user is allowed to export the object to an OAR</returns> private bool CanUserArchiveObject(UUID user, SceneObjectGroup objGroup, string filterContent, IPermissionsModule permissionsModule) { if (filterContent == null) return true; if (permissionsModule == null) return true; // this shouldn't happen // Check whether the user is permitted to export all of the parts in the SOG. If any // part can't be exported then the entire SOG can't be exported. bool permitted = true; //int primNumber = 1; foreach (SceneObjectPart obj in objGroup.Parts) { uint perm; PermissionClass permissionClass = permissionsModule.GetPermissionClass(user, obj); switch (permissionClass) { case PermissionClass.Owner: perm = obj.BaseMask; break; case PermissionClass.Group: perm = obj.GroupMask | obj.EveryoneMask; break; case PermissionClass.Everyone: default: perm = obj.EveryoneMask; break; } bool canCopy = (perm & (uint)PermissionMask.Copy) != 0; bool canTransfer = (perm & (uint)PermissionMask.Transfer) != 0; // Special case: if Everyone can copy the object then this implies it can also be // Transferred. // However, if the user is the Owner then we don't check EveryoneMask, because it seems that the mask // always (incorrectly) includes the Copy bit set in this case. But that's a mistake: the viewer // does NOT show that the object has Everyone-Copy permissions, and doesn't allow it to be copied. if (permissionClass != PermissionClass.Owner) canTransfer |= (obj.EveryoneMask & (uint)PermissionMask.Copy) != 0; bool partPermitted = true; if (filterContent.Contains("C") && !canCopy) partPermitted = false; if (filterContent.Contains("T") && !canTransfer) partPermitted = false; // If the user is the Creator of the object then it can always be included in the OAR bool creator = (obj.CreatorID.Guid == user.Guid); if (creator) partPermitted = true; //string name = (objGroup.PrimCount == 1) ? objGroup.Name : string.Format("{0} ({1}/{2})", obj.Name, primNumber, objGroup.PrimCount); //m_log.DebugFormat("[ARCHIVER]: Object permissions: {0}: Base={1:X4}, Owner={2:X4}, Everyone={3:X4}, permissionClass={4}, checkPermissions={5}, canCopy={6}, canTransfer={7}, creator={8}, permitted={9}", // name, obj.BaseMask, obj.OwnerMask, obj.EveryoneMask, // permissionClass, checkPermissions, canCopy, canTransfer, creator, partPermitted); if (!partPermitted) { permitted = false; break; } //++primNumber; } return permitted; } /// <summary> /// Create the control file. /// </summary> /// <returns></returns> public string CreateControlFile(ArchiveScenesGroup scenesGroup) { int majorVersion; int minorVersion; if (MultiRegionFormat) { majorVersion = MAX_MAJOR_VERSION; minorVersion = 0; } else { // To support older versions of OpenSim, we continue to create single-region OARs // using the old file format. In the future this format will be discontinued. majorVersion = 0; minorVersion = 8; } // // if (m_options.ContainsKey("version")) // { // string[] parts = m_options["version"].ToString().Split('.'); // if (parts.Length >= 1) // { // majorVersion = Int32.Parse(parts[0]); // // if (parts.Length >= 2) // minorVersion = Int32.Parse(parts[1]); // } // } // // if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION) // { // throw new Exception( // string.Format( // "OAR version number for save must be between {0} and {1}", // MIN_MAJOR_VERSION, MAX_MAJOR_VERSION)); // } // else if (majorVersion == MAX_MAJOR_VERSION) // { // // Force 1.0 // minorVersion = 0; // } // else if (majorVersion == MIN_MAJOR_VERSION) // { // // Force 0.4 // minorVersion = 4; // } m_log.InfoFormat("[ARCHIVER]: Creating version {0}.{1} OAR", majorVersion, minorVersion); if (majorVersion == 1) { m_log.WarnFormat("[ARCHIVER]: Please be aware that version 1.0 OARs are not compatible with OpenSim versions prior to 0.7.4. Do not use the --all option if you want to produce a compatible OAR"); } String s; using (StringWriter sw = new StringWriter()) { using (XmlTextWriter xtw = new XmlTextWriter(sw)) { xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement("archive"); xtw.WriteAttributeString("major_version", majorVersion.ToString()); xtw.WriteAttributeString("minor_version", minorVersion.ToString()); xtw.WriteStartElement("creation_info"); DateTime now = DateTime.UtcNow; TimeSpan t = now - new DateTime(1970, 1, 1); xtw.WriteElementString("datetime", ((int)t.TotalSeconds).ToString()); if (!MultiRegionFormat) xtw.WriteElementString("id", m_rootScene.RegionInfo.RegionID.ToString()); xtw.WriteEndElement(); xtw.WriteElementString("assets_included", SaveAssets.ToString()); if (MultiRegionFormat) { WriteRegionsManifest(scenesGroup, xtw); } else { xtw.WriteStartElement("region_info"); WriteRegionInfo(m_rootScene, xtw); xtw.WriteEndElement(); } xtw.WriteEndElement(); xtw.Flush(); } s = sw.ToString(); } return s; } /// <summary> /// Writes the list of regions included in a multi-region OAR. /// </summary> private static void WriteRegionsManifest(ArchiveScenesGroup scenesGroup, XmlTextWriter xtw) { xtw.WriteStartElement("regions"); // Write the regions in order: rows from South to North, then regions from West to East. // The list of regions can have "holes"; we write empty elements in their position. for (uint y = (uint)scenesGroup.Rect.Top; y < scenesGroup.Rect.Bottom; ++y) { SortedDictionary<uint, Scene> row; if (scenesGroup.Regions.TryGetValue(y, out row)) { xtw.WriteStartElement("row"); for (uint x = (uint)scenesGroup.Rect.Left; x < scenesGroup.Rect.Right; ++x) { Scene scene; if (row.TryGetValue(x, out scene)) { xtw.WriteStartElement("region"); xtw.WriteElementString("id", scene.RegionInfo.RegionID.ToString()); xtw.WriteElementString("dir", scenesGroup.GetRegionDir(scene.RegionInfo.RegionID)); WriteRegionInfo(scene, xtw); xtw.WriteEndElement(); } else { // Write a placeholder for a missing region xtw.WriteElementString("region", ""); } } xtw.WriteEndElement(); } else { // Write a placeholder for a missing row xtw.WriteElementString("row", ""); } } xtw.WriteEndElement(); // "regions" } protected static void WriteRegionInfo(Scene scene, XmlTextWriter xtw) { bool isMegaregion; Vector2 size; IRegionCombinerModule rcMod = scene.RequestModuleInterface<IRegionCombinerModule>(); if (rcMod != null) isMegaregion = rcMod.IsRootForMegaregion(scene.RegionInfo.RegionID); else isMegaregion = false; if (isMegaregion) size = rcMod.GetSizeOfMegaregion(scene.RegionInfo.RegionID); else size = new Vector2((float)scene.RegionInfo.RegionSizeX, (float)scene.RegionInfo.RegionSizeY); xtw.WriteElementString("is_megaregion", isMegaregion.ToString()); xtw.WriteElementString("size_in_meters", string.Format("{0},{1}", size.X, size.Y)); } protected void Save(Scene scene, List<SceneObjectGroup> sceneObjects, string regionDir) { if (regionDir != string.Empty) regionDir = ArchiveConstants.REGIONS_PATH + regionDir + "/"; m_log.InfoFormat("[ARCHIVER]: Adding region settings to archive."); // Write out region settings string settingsPath = String.Format("{0}{1}{2}.xml", regionDir, ArchiveConstants.SETTINGS_PATH, scene.RegionInfo.RegionName); m_archiveWriter.WriteFile(settingsPath, RegionSettingsSerializer.Serialize(scene.RegionInfo.RegionSettings)); m_log.InfoFormat("[ARCHIVER]: Adding parcel settings to archive."); // Write out land data (aka parcel) settings List<ILandObject> landObjects = scene.LandChannel.AllParcels(); foreach (ILandObject lo in landObjects) { LandData landData = lo.LandData; string landDataPath = String.Format("{0}{1}", regionDir, ArchiveConstants.CreateOarLandDataPath(landData)); m_archiveWriter.WriteFile(landDataPath, LandDataSerializer.Serialize(landData, m_options)); } m_log.InfoFormat("[ARCHIVER]: Adding terrain information to archive."); // Write out terrain string terrainPath = String.Format("{0}{1}{2}.r32", regionDir, ArchiveConstants.TERRAINS_PATH, scene.RegionInfo.RegionName); using (MemoryStream ms = new MemoryStream()) { scene.RequestModuleInterface<ITerrainModule>().SaveToStream(terrainPath, ms); m_archiveWriter.WriteFile(terrainPath, ms.ToArray()); } m_log.InfoFormat("[ARCHIVER]: Adding scene objects to archive."); // Write out scene object metadata IRegionSerialiserModule serializer = scene.RequestModuleInterface<IRegionSerialiserModule>(); foreach (SceneObjectGroup sceneObject in sceneObjects) { //m_log.DebugFormat("[ARCHIVER]: Saving {0} {1}, {2}", entity.Name, entity.UUID, entity.GetType()); string serializedObject = serializer.SerializeGroupToXml2(sceneObject, m_options); string objectPath = string.Format("{0}{1}", regionDir, ArchiveHelpers.CreateObjectPath(sceneObject)); m_archiveWriter.WriteFile(objectPath, serializedObject); } } protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut) { string errorMessage; if (timedOut) { errorMessage = "Loading assets timed out"; } else { foreach (UUID uuid in assetsNotFoundUuids) { m_log.DebugFormat("[ARCHIVER]: Could not find asset {0}", uuid); } // m_log.InfoFormat( // "[ARCHIVER]: Received {0} of {1} assets requested", // assetsFoundUuids.Count, assetsFoundUuids.Count + assetsNotFoundUuids.Count); errorMessage = String.Empty; } CloseArchive(errorMessage); } /// <summary> /// Closes the archive and notifies that we're done. /// </summary> /// <param name="errorMessage">The error that occurred, or empty for success</param> protected void CloseArchive(string errorMessage) { try { if (m_archiveWriter != null) m_archiveWriter.Close(); m_saveStream.Close(); } catch (Exception e) { m_log.Error(string.Format("[ARCHIVER]: Error closing archive: {0} ", e.Message), e); if (errorMessage == string.Empty) errorMessage = e.Message; } m_log.InfoFormat("[ARCHIVER]: Finished writing out OAR for {0}", m_rootScene.RegionInfo.RegionName); m_rootScene.EventManager.TriggerOarFileSaved(m_requestId, errorMessage); } } }
// 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.Immutable; using System.Diagnostics; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata.Decoding { /// <summary> /// Decodes signature blobs. /// See Metadata Specification section II.23.2: Blobs and signatures. /// </summary> public struct SignatureDecoder<TType> { private readonly ISignatureTypeProvider<TType> _provider; private readonly MetadataReader _metadataReaderOpt; private readonly SignatureDecoderOptions _options; /// <summary> /// Creates a new SignatureDecoder. /// </summary> /// <param name="provider">The provider used to obtain type symbols as the signature is decoded.</param> /// <param name="metadataReader"> /// The metadata reader from which the signature was obtained. It may be null if the given provider allows it. /// However, if <see cref="SignatureDecoderOptions.DifferentiateClassAndValueTypes"/> is specified, it should /// be non-null to evaluate WinRT projections from class to value type or vice-versa correctly. /// </param> /// <param name="options">Set of optional decoder features to enable.</param> public SignatureDecoder( ISignatureTypeProvider<TType> provider, MetadataReader metadataReader = null, SignatureDecoderOptions options = SignatureDecoderOptions.None) { if (provider == null) { throw new ArgumentNullException("provider"); } _metadataReaderOpt = metadataReader; _provider = provider; _options = options; } /// <summary> /// Decodes a type embedded in a signature and advances the reader past the type. /// </summary> /// <param name="blobReader">The blob reader positioned at the leading SignatureTypeCode</param> /// <param name="allowTypeSpecifications">Allow a <see cref="TypeSpecificationHandle"/> to follow a (CLASS | VALUETYPE) in the signature. /// At present, the only context where that would be valid is in a LocalConstantSig as defined by the Portable PDB specification. /// </param> /// <returns>The decoded type.</returns> /// <exception cref="System.BadImageFormatException">The reader was not positioned at a valid signature type.</exception> public TType DecodeType(ref BlobReader blobReader, bool allowTypeSpecifications = false) { return DecodeType(ref blobReader, allowTypeSpecifications, blobReader.ReadCompressedInteger()); } private TType DecodeType(ref BlobReader blobReader, bool allowTypeSpecifications, int typeCode) { TType elementType; int index; switch (typeCode) { case (int)SignatureTypeCode.Boolean: case (int)SignatureTypeCode.Char: case (int)SignatureTypeCode.SByte: case (int)SignatureTypeCode.Byte: case (int)SignatureTypeCode.Int16: case (int)SignatureTypeCode.UInt16: case (int)SignatureTypeCode.Int32: case (int)SignatureTypeCode.UInt32: case (int)SignatureTypeCode.Int64: case (int)SignatureTypeCode.UInt64: case (int)SignatureTypeCode.Single: case (int)SignatureTypeCode.Double: case (int)SignatureTypeCode.IntPtr: case (int)SignatureTypeCode.UIntPtr: case (int)SignatureTypeCode.Object: case (int)SignatureTypeCode.String: case (int)SignatureTypeCode.Void: case (int)SignatureTypeCode.TypedReference: return _provider.GetPrimitiveType((PrimitiveTypeCode)typeCode); case (int)SignatureTypeCode.Pointer: elementType = DecodeType(ref blobReader); return _provider.GetPointerType(elementType); case (int)SignatureTypeCode.ByReference: elementType = DecodeType(ref blobReader); return _provider.GetByReferenceType(elementType); case (int)SignatureTypeCode.Pinned: elementType = DecodeType(ref blobReader); return _provider.GetPinnedType(elementType); case (int)SignatureTypeCode.SZArray: elementType = DecodeType(ref blobReader); return _provider.GetSZArrayType(elementType); case (int)SignatureTypeCode.FunctionPointer: MethodSignature<TType> methodSignature = DecodeMethodSignature(ref blobReader); return _provider.GetFunctionPointerType(methodSignature); case (int)SignatureTypeCode.Array: return DecodeArrayType(ref blobReader); case (int)SignatureTypeCode.RequiredModifier: return DecodeModifiedType(ref blobReader, isRequired: true); case (int)SignatureTypeCode.OptionalModifier: return DecodeModifiedType(ref blobReader, isRequired: false); case (int)SignatureTypeCode.GenericTypeInstance: return DecodeGenericTypeInstance(ref blobReader); case (int)SignatureTypeCode.GenericTypeParameter: index = blobReader.ReadCompressedInteger(); return _provider.GetGenericTypeParameter(index); case (int)SignatureTypeCode.GenericMethodParameter: index = blobReader.ReadCompressedInteger(); return _provider.GetGenericMethodParameter(index); case (int)SignatureTypeHandleCode.Class: case (int)SignatureTypeHandleCode.ValueType: return DecodeTypeDefOrRef(ref blobReader, (SignatureTypeHandleCode)typeCode); default: throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureTypeCode, typeCode)); } } /// <summary> /// Decodes a list of types, with at least one instance that is preceded by its count as a compressed integer. /// </summary> private ImmutableArray<TType> DecodeTypeSequence(ref BlobReader blobReader) { int count = blobReader.ReadCompressedInteger(); if (count == 0) { // This method is used for Local signatures and method specs, neither of which can have // 0 elements. Parameter sequences can have 0 elements, but they are handled separately // to deal with the sentinel/varargs case. throw new BadImageFormatException(SR.SignatureTypeSequenceMustHaveAtLeastOneElement); } var types = ImmutableArray.CreateBuilder<TType>(count); for (int i = 0; i < count; i++) { types.Add(DecodeType(ref blobReader)); } return types.MoveToImmutable(); } /// <summary> /// Decodes a method (definition, reference, or standalone) or property signature blob. /// </summary> /// <param name="blobReader">BlobReader positioned at a method signature.</param> /// <returns>The decoded method signature.</returns> /// <exception cref="System.BadImageFormatException">The method signature is invalid.</exception> public MethodSignature<TType> DecodeMethodSignature(ref BlobReader blobReader) { SignatureHeader header = blobReader.ReadSignatureHeader(); CheckMethodOrPropertyHeader(header); int genericParameterCount = 0; if (header.IsGeneric) { genericParameterCount = blobReader.ReadCompressedInteger(); } int parameterCount = blobReader.ReadCompressedInteger(); TType returnType = DecodeType(ref blobReader); ImmutableArray<TType> parameterTypes; int requiredParameterCount; if (parameterCount == 0) { requiredParameterCount = 0; parameterTypes = ImmutableArray<TType>.Empty; } else { var parameterBuilder = ImmutableArray.CreateBuilder<TType>(parameterCount); int parameterIndex; for (parameterIndex = 0; parameterIndex < parameterCount; parameterIndex++) { int typeCode = blobReader.ReadCompressedInteger(); if (typeCode == (int)SignatureTypeCode.Sentinel) { break; } parameterBuilder.Add(DecodeType(ref blobReader, allowTypeSpecifications: false, typeCode: typeCode)); } requiredParameterCount = parameterIndex; for (; parameterIndex < parameterCount; parameterIndex++) { parameterBuilder.Add(DecodeType(ref blobReader)); } parameterTypes = parameterBuilder.MoveToImmutable(); } return new MethodSignature<TType>(header, returnType, requiredParameterCount, genericParameterCount, parameterTypes); } /// <summary> /// Decodes a method specification signature blob and advances the reader past the signature. /// </summary> /// <param name="blobReader">A BlobReader positioned at a valid method specification signature.</param> /// <returns>The types used to instantiate a generic method via the method specification.</returns> public ImmutableArray<TType> DecodeMethodSpecificationSignature(ref BlobReader blobReader) { SignatureHeader header = blobReader.ReadSignatureHeader(); CheckHeader(header, SignatureKind.MethodSpecification); return DecodeTypeSequence(ref blobReader); } /// <summary> /// Decodes a local variable signature blob and advances the reader past the signature. /// </summary> /// <param name="blobReader">The blob reader positioned at a local variable signature.</param> /// <returns>The local variable types.</returns> /// <exception cref="System.BadImageFormatException">The local variable signature is invalid.</exception> public ImmutableArray<TType> DecodeLocalSignature(ref BlobReader blobReader) { SignatureHeader header = blobReader.ReadSignatureHeader(); CheckHeader(header, SignatureKind.LocalVariables); return DecodeTypeSequence(ref blobReader); } /// <summary> /// Decodes a field signature blob and advances the reader past the signature. /// </summary> /// <param name="blobReader">The blob reader positioned at a field signature.</param> /// <returns>The decoded field type.</returns> public TType DecodeFieldSignature(ref BlobReader blobReader) { SignatureHeader header = blobReader.ReadSignatureHeader(); CheckHeader(header, SignatureKind.Field); return DecodeType(ref blobReader); } private TType DecodeArrayType(ref BlobReader blobReader) { // PERF_TODO: Cache/reuse common case of small number of all-zero lower-bounds. TType elementType = DecodeType(ref blobReader); int rank = blobReader.ReadCompressedInteger(); var sizes = ImmutableArray<int>.Empty; var lowerBounds = ImmutableArray<int>.Empty; int sizesCount = blobReader.ReadCompressedInteger(); if (sizesCount > 0) { var builder = ImmutableArray.CreateBuilder<int>(sizesCount); for (int i = 0; i < sizesCount; i++) { builder.Add(blobReader.ReadCompressedInteger()); } sizes = builder.MoveToImmutable(); } int lowerBoundsCount = blobReader.ReadCompressedInteger(); if (lowerBoundsCount > 0) { var builder = ImmutableArray.CreateBuilder<int>(lowerBoundsCount); for (int i = 0; i < lowerBoundsCount; i++) { builder.Add(blobReader.ReadCompressedSignedInteger()); } lowerBounds = builder.MoveToImmutable(); } var arrayShape = new ArrayShape(rank, sizes, lowerBounds); return _provider.GetArrayType(elementType, arrayShape); } private TType DecodeGenericTypeInstance(ref BlobReader blobReader) { TType genericType = DecodeType(ref blobReader); ImmutableArray<TType> types = DecodeTypeSequence(ref blobReader); return _provider.GetGenericInstance(genericType, types); } private TType DecodeModifiedType(ref BlobReader blobReader, bool isRequired) { TType modifier = DecodeTypeDefOrRefOrSpec(ref blobReader, SignatureTypeHandleCode.Unresolved); TType unmodifiedType = DecodeType(ref blobReader); return _provider.GetModifiedType(_metadataReaderOpt, isRequired, modifier, unmodifiedType); } private TType DecodeTypeDefOrRef(ref BlobReader blobReader, SignatureTypeHandleCode code) { return DecodeTypeHandle(ref blobReader, code, alllowTypeSpecifications: false); } private TType DecodeTypeDefOrRefOrSpec(ref BlobReader blobReader, SignatureTypeHandleCode code) { return DecodeTypeHandle(ref blobReader, code, alllowTypeSpecifications: true); } private TType DecodeTypeHandle(ref BlobReader blobReader, SignatureTypeHandleCode code, bool alllowTypeSpecifications) { // Force no differentiation of class vs. value type unless the option is enabled. // Avoids cost of WinRT projection. if ((_options & SignatureDecoderOptions.DifferentiateClassAndValueTypes) == 0) { code = SignatureTypeHandleCode.Unresolved; } EntityHandle handle = blobReader.ReadTypeHandle(); if (!handle.IsNil) { switch (handle.Kind) { case HandleKind.TypeDefinition: var typeDef = (TypeDefinitionHandle)handle; return _provider.GetTypeFromDefinition(_metadataReaderOpt, typeDef, code); case HandleKind.TypeReference: var typeRef = (TypeReferenceHandle)handle; if (code != SignatureTypeHandleCode.Unresolved) { ProjectClassOrValueType(typeRef, ref code); } return _provider.GetTypeFromReference(_metadataReaderOpt, typeRef, code); case HandleKind.TypeSpecification: if (!alllowTypeSpecifications) { // To prevent cycles, the token following (CLASS | VALUETYPE) must not be a type spec. // https://github.com/dotnet/coreclr/blob/8ff2389204d7c41b17eff0e9536267aea8d6496f/src/md/compiler/mdvalidator.cpp#L6154-L6160 throw new BadImageFormatException(SR.NotTypeDefOrRefHandle); } if (code != SignatureTypeHandleCode.Unresolved) { // TODO: We need more work here in differentiating case because instantiations can project class // to value type as in IReference<T> -> Nullable<T>. Unblocking Roslyn work where the differentiation // feature is not used. Note that the use-case of custom-mods will not hit this because there is no // CLASS | VALUETYPE before the modifier token and so it always comes in unresolved. code = SignatureTypeHandleCode.Unresolved; // never lie in the meantime. } var typeSpec = (TypeSpecificationHandle)handle; return _provider.GetTypeFromSpecification(_metadataReaderOpt, typeSpec, SignatureTypeHandleCode.Unresolved); default: // indicates an error returned from ReadTypeHandle, otherwise unreachable. Debug.Assert(handle.IsNil); // will fall through to throw in release. break; } } throw new BadImageFormatException(SR.NotTypeDefOrRefOrSpecHandle); } private void ProjectClassOrValueType(TypeReferenceHandle handle, ref SignatureTypeHandleCode code) { Debug.Assert(code != SignatureTypeHandleCode.Unresolved); Debug.Assert((_options & SignatureDecoderOptions.DifferentiateClassAndValueTypes) != 0); if (_metadataReaderOpt == null) { // If we're asked to differentiate value types without a reader, then // return the designation unprojected as it occurs in the signature blob. return; } TypeReference typeRef = _metadataReaderOpt.GetTypeReference(handle); switch (typeRef.SignatureTreatment) { case TypeRefSignatureTreatment.ProjectedToClass: code = SignatureTypeHandleCode.Class; break; case TypeRefSignatureTreatment.ProjectedToValueType: code = SignatureTypeHandleCode.ValueType; break; } } private void CheckHeader(SignatureHeader header, SignatureKind expectedKind) { if (header.Kind != expectedKind) { throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader, expectedKind, header.Kind, header.RawValue)); } } private void CheckMethodOrPropertyHeader(SignatureHeader header) { SignatureKind kind = header.Kind; if (kind != SignatureKind.Method && kind != SignatureKind.Property) { throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader2, SignatureKind.Property, SignatureKind.Method, header.Kind, header.RawValue)); } } } }