context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using CAPNet.Models; namespace CAPNet { /// <summary> /// Class that converts an alert to its XML representation /// </summary> public static class XmlCreator { /// <summary> /// The xml namespace for CAP 1.1 /// </summary> public static readonly XNamespace CAP11Namespace = "urn:oasis:names:tc:emergency:cap:1.1"; /// <summary> /// The xml namespace for CAP 1.2 /// </summary> public static readonly XNamespace CAP12Namespace = "urn:oasis:names:tc:emergency:cap:1.2"; /// <summary> /// /// </summary> /// <param name="alerts"></param> /// <returns></returns> public static IEnumerable<XElement> Create(IEnumerable<Alert> alerts) { return from alert in alerts select Create(alert); } /// <summary> /// /// </summary> /// <param name="alert"></param> /// <returns></returns> public static XElement Create(Alert alert) { var alertElement = new XElement(CAP12Namespace + "alert"); AddElementIfHasContent(alertElement, "identifier", alert.Identifier); AddElementIfHasContent(alertElement, "sender", alert.Sender); // set milliseconds to 0 AddElementIfHasContent(alertElement, "sent", StripMiliseconds(alert.Sent)); AddElementIfHasContent(alertElement, "status", alert.Status); AddElementIfHasContent(alertElement, "msgType", alert.MessageType); AddElementIfHasContent(alertElement, "source", alert.Source); AddElementIfHasContent(alertElement, "scope", alert.Scope); AddElementIfHasContent(alertElement, "restriction", alert.Restriction); string addressesContent = alert.Addresses.ElementsDelimitedBySpace(); AddElementIfHasContent(alertElement, "addresses", addressesContent); AddElementIfHasContent(alertElement, "code", alert.Code); AddElementIfHasContent(alertElement, "note", alert.Note); string referencesContent = alert.References.ElementsDelimitedBySpace(); AddElementIfHasContent(alertElement, "references", referencesContent); string incidentsContent = alert.Incidents.ElementsDelimitedBySpace(); AddElementIfHasContent(alertElement, "incidents", incidentsContent); AddElements(alertElement, Create(alert.Info)); return alertElement; } private static DateTimeOffset? StripMiliseconds(DateTimeOffset? date) { if(date!=null) return date.Value.AddMilliseconds(-date.Value.Millisecond); return null; } private static IEnumerable<XElement> Create(IEnumerable<Info> infos) { var infoElements = from info in infos select Create(info); return infoElements; } private static XElement Create(Info info) { var infoElement = new XElement(CAP12Namespace + "info"); if (!info.Language.Equals(info.DefaultLanguage)) infoElement.Add(new XElement(CAP12Namespace + "language", info.Language)); infoElement.Add(info.Categories.Select(cat => new XElement(CAP12Namespace + "category", cat))); AddElementIfHasContent(infoElement, "event", info.Event); infoElement.Add(info.ResponseTypes.Select(res => new XElement(CAP12Namespace + "responseType", res))); AddElementIfHasContent(infoElement, "urgency", info.Urgency); AddElementIfHasContent(infoElement, "severity", info.Severity); AddElementIfHasContent(infoElement, "certainty", info.Certainty); AddElementIfHasContent(infoElement, "audience", info.Audience); AddElements(infoElement, Create(info.EventCodes)); AddElementIfHasContent(infoElement, "effective", StripMiliseconds(info.Effective)); AddElementIfHasContent(infoElement, "onset", info.Onset); AddElementIfHasContent(infoElement, "expires", info.Expires); AddElementIfHasContent(infoElement, "senderName", info.SenderName); AddElementIfHasContent(infoElement, "headline", info.Headline); AddElementIfHasContent(infoElement, "description", info.Description); AddElementIfHasContent(infoElement, "instruction", info.Instruction); AddElementIfHasContent(infoElement, "web", info.Web); AddElementIfHasContent(infoElement, "contact", info.Contact); AddElements(infoElement, Create(info.Parameters)); AddElements(infoElement, Create(info.Resources)); AddElements(infoElement, Create(info.Areas)); return infoElement; } private static IEnumerable<XElement> Create(IEnumerable<EventCode> codes) { var eventCodesElements = from e in codes select new XElement( CAP12Namespace + "eventCode", new XElement(CAP12Namespace + "valueName", e.ValueName), new XElement(CAP12Namespace + "value", e.Value)); return eventCodesElements; } private static IEnumerable<XElement> Create(IEnumerable<Parameter> parameters) { var parameterElements = from parameter in parameters select new XElement( CAP12Namespace + "parameter", new XElement(CAP12Namespace + "valueName", parameter.ValueName), new XElement(CAP12Namespace + "value", parameter.Value)); return parameterElements; } private static IEnumerable<XElement> Create(IEnumerable<Resource> resources) { var resourceElements = from resource in resources select Create(resource); return resourceElements; } private static XElement Create(Resource resource) { var resourceElement = new XElement(CAP12Namespace + "resource"); AddElementIfHasContent(resourceElement, "resourceDesc", resource.Description); AddElementIfHasContent(resourceElement, "mimeType", resource.MimeType); AddElementIfHasContent(resourceElement, "size", resource.Size); AddElementIfHasContent(resourceElement, "uri", resource.Uri); AddElementIfHasContent(resourceElement, "derefUri", resource.DereferencedUri); AddElementIfHasContent(resourceElement, "digest", resource.Digest); return resourceElement; } private static IEnumerable<XElement> Create(IEnumerable<GeoCode> geoCodes) { var geoCodeElements = from geoCode in geoCodes select new XElement( CAP12Namespace + "geocode", new XElement(CAP12Namespace + "valueName", geoCode.ValueName), new XElement(CAP12Namespace + "value", geoCode.Value)); return geoCodeElements; } private static IEnumerable<XElement> Create(IEnumerable<Area> areas) { var areaElements = from area in areas select Create(area); return areaElements; } private static XElement Create(Area area) { var areaElement = new XElement(CAP12Namespace + "area"); AddElementIfHasContent(areaElement, "areaDesc", area.Description); var polygons = Create(area.Polygons); AddElements(areaElement, polygons); var circles = Create(area.Circles); AddElements(areaElement, circles); var geoCodes = Create(area.GeoCodes); AddElements(areaElement, geoCodes); AddElementIfHasContent(areaElement, "altitude", area.Altitude); AddElementIfHasContent(areaElement, "ceiling", area.Ceiling); return areaElement; } private static IEnumerable<XElement> Create(IEnumerable<Polygon> polygons) { return from polygon in polygons select new XElement( CAP12Namespace + "polygon", polygon); } private static IEnumerable<XElement> Create(IEnumerable<Circle> circles) { return from circle in circles select new XElement( CAP12Namespace + "circle", circle); } private static void AddElementIfHasContent(XElement parent, string name, byte[] content) { if (content != null) { string base64DerefUri = Convert.ToBase64String(content); parent.Add(new XElement(CAP12Namespace + name, base64DerefUri)); } } private static void AddElementIfHasContent<T>(XElement element, string name, T content) { if (content != null) element.Add(new XElement(CAP12Namespace + name, content)); } private static void AddElements(XElement parent, IEnumerable<XElement> elements) { foreach (XElement element in elements) parent.Add(element); } private static void AddElementIfHasContent(XElement parent, string name, string content) { if (!string.IsNullOrEmpty(content)) parent.Add(new XElement(CAP12Namespace + name, content)); } } }
using System; using System.Globalization; /// <summary> /// Convert.ToString(System.Double,System.IFormatProvider) /// </summary> public class ConvertToString12 { public static int Main() { ConvertToString12 testObj = new ConvertToString12(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Double,System.IFormatProvider)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify value is a random Double and IFormatProvider is a null reference... "; string c_TEST_ID = "P001"; Double doubleValue = TestLibrary.Generator.GetDouble(-55); IFormatProvider provider = null; String actualValue = doubleValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify value is a random negative Double and IFormatProvider is en-US CultureInfo... "; string c_TEST_ID = "P002"; Double doubleValue = TestLibrary.Generator.GetDouble(-55); doubleValue = -doubleValue; IFormatProvider provider = new CultureInfo("en-US"); String actualValue = doubleValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify value is a random Double and IFormatProvider is fr_FR CultureInfo... "; string c_TEST_ID = "P003"; Double doubleValue = TestLibrary.Generator.GetDouble(-55); IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = doubleValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string c_TEST_DESC = "PosTest4: Verify value is -61680.3855 and IFormatProvider is user-defined NumberFormatInfo... "; string c_TEST_ID = "P004"; Double doubleValue = -61680.3855; NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); numberFormatInfo.NegativeSign = "minus "; numberFormatInfo.NumberDecimalSeparator = " point "; String actualValue = "minus 61680 point 3855"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue,numberFormatInfo); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string c_TEST_DESC = "PosTest5: Verify value is Double.Epsilon and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P005"; Double doubleValue = Double.Epsilon; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = "4,94065645841247E-324"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; string c_TEST_DESC = "PosTest6: Verify value is 0 and IFormatProvider is IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P006"; Double doubleValue = 0.00; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = doubleValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; string c_TEST_DESC = "PosTest7: Verify value is Double.NaN and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P007"; Double doubleValue = Double.NaN; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = doubleValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; string c_TEST_DESC = "PosTest8: Verify value is Double.NegativeInfinity and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P008"; Double doubleValue = Double.NegativeInfinity; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = doubleValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion }
/* **************************************************************************** * * 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.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; using System.Numerics; #else using Microsoft.Scripting.Ast; using Microsoft.Scripting.Math; #endif using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Dynamic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Operations; using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; namespace IronPython.Runtime.Types { [PythonType("instance")] [Serializable] [DebuggerTypeProxy(typeof(OldInstance.OldInstanceDebugView)), DebuggerDisplay("old-style instance of {ClassName}")] public sealed partial class OldInstance : ICodeFormattable, #if CLR2 IValueEquality, #endif #if FEATURE_CUSTOM_TYPE_DESCRIPTOR ICustomTypeDescriptor, #endif ISerializable, IWeakReferenceable, IDynamicMetaObjectProvider, IPythonMembersList, Binding.IFastGettable { private PythonDictionary _dict; internal OldClass _class; private WeakRefTracker _weakRef; // initialized if user defines finalizer on class or instance private static PythonDictionary MakeDictionary(OldClass oldClass) { return new PythonDictionary(new CustomInstanceDictionaryStorage(oldClass.OptimizedInstanceNames, oldClass.OptimizedInstanceNamesVersion)); } public OldInstance(CodeContext/*!*/ context, OldClass @class) { _class = @class; _dict = MakeDictionary(@class); if (_class.HasFinalizer) { // class defines finalizer, we get it automatically. AddFinalizer(context); } } public OldInstance(CodeContext/*!*/ context, OldClass @class, PythonDictionary dict) { _class = @class; _dict = dict ?? PythonDictionary.MakeSymbolDictionary(); if (_class.HasFinalizer) { // class defines finalizer, we get it automatically. AddFinalizer(context); } } #if FEATURE_SERIALIZATION private OldInstance(SerializationInfo info, StreamingContext context) { _class = (OldClass)info.GetValue("__class__", typeof(OldClass)); _dict = MakeDictionary(_class); List<object> keys = (List<object>)info.GetValue("keys", typeof(List<object>)); List<object> values = (List<object>)info.GetValue("values", typeof(List<object>)); for (int i = 0; i < keys.Count; i++) { _dict[keys[i]] = values[i]; } } #pragma warning disable 169 // unused method - called via reflection from serialization [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] private void GetObjectData(SerializationInfo info, StreamingContext context) { ContractUtils.RequiresNotNull(info, "info"); info.AddValue("__class__", _class); List<object> keys = new List<object>(); List<object> values = new List<object>(); foreach (object o in _dict.keys()) { keys.Add(o); object value; bool res = _dict.TryGetValue(o, out value); Debug.Assert(res); values.Add(value); } info.AddValue("keys", keys); info.AddValue("values", values); } #pragma warning restore 169 #endif /// <summary> /// Returns the dictionary used to store state for this object /// </summary> internal PythonDictionary Dictionary { get { return _dict; } } internal string ClassName { get { return _class.Name; } } public static bool operator true(OldInstance self) { return (bool)self.__nonzero__(DefaultContext.Default); } public static bool operator false(OldInstance self) { return !(bool)self.__nonzero__(DefaultContext.Default); } #region Object overrides public override string ToString() { object ret = InvokeOne(this, "__str__"); if (ret != NotImplementedType.Value) { string strRet; if (Converter.TryConvertToString(ret, out strRet) && strRet != null) { return strRet; } throw PythonOps.TypeError("__str__ returned non-string type ({0})", PythonTypeOps.GetName(ret)); } return __repr__(DefaultContext.Default); } #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { object ret = InvokeOne(this, "__repr__"); if(ret != NotImplementedType.Value) { string strRet; if (Converter.TryConvertToString(ret, out strRet) && strRet != null) { return strRet; } throw PythonOps.TypeError("__repr__ returned non-string type ({0})", PythonTypeOps.GetName(ret)); } return string.Format("<{0} instance at {1}>", _class.FullName, PythonOps.HexId(this)); } #endregion [return: MaybeNotImplemented] public object __divmod__(CodeContext context, object divmod) { object value; if (TryGetBoundCustomMember(context, "__divmod__", out value)) { return PythonCalls.Call(context, value, divmod); } return NotImplementedType.Value; } [return: MaybeNotImplemented] public static object __rdivmod__(CodeContext context, object divmod, [NotNull]OldInstance self) { object value; if (self.TryGetBoundCustomMember(context, "__rdivmod__", out value)) { return PythonCalls.Call(context, value, divmod); } return NotImplementedType.Value; } public object __coerce__(CodeContext context, object other) { object value; if (TryGetBoundCustomMember(context, "__coerce__", out value)) { return PythonCalls.Call(context, value, other); } return NotImplementedType.Value; } public object __len__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__len__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__len__"); } public object __pos__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__pos__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__pos__"); } [SpecialName] public object GetItem(CodeContext context, object item) { return PythonOps.Invoke(context, this, "__getitem__", item); } [SpecialName] public void SetItem(CodeContext context, object item, object value) { PythonOps.Invoke(context, this, "__setitem__", item, value); } [SpecialName] public object DeleteItem(CodeContext context, object item) { object value; if (TryGetBoundCustomMember(context, "__delitem__", out value)) { return PythonCalls.Call(context, value, item); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__delitem__"); } public object __getslice__(CodeContext context, int i, int j) { object callable; if (TryRawGetAttr(context, "__getslice__", out callable)) { return PythonCalls.Call(context, callable, i, j); } else if (TryRawGetAttr(context, "__getitem__", out callable)) { return PythonCalls.Call(context, callable, new Slice(i, j)); } throw PythonOps.TypeError("instance {0} does not have __getslice__ or __getitem__", _class.Name); } public void __setslice__(CodeContext context, int i, int j, object value) { object callable; if (TryRawGetAttr(context, "__setslice__", out callable)) { PythonCalls.Call(context, callable, i, j, value); return; } else if (TryRawGetAttr(context, "__setitem__", out callable)) { PythonCalls.Call(context, callable, new Slice(i, j), value); return; } throw PythonOps.TypeError("instance {0} does not have __setslice__ or __setitem__", _class.Name); } public object __delslice__(CodeContext context, int i, int j) { object callable; if (TryRawGetAttr(context, "__delslice__", out callable)) { return PythonCalls.Call(context, callable, i, j); } else if (TryRawGetAttr(context, "__delitem__", out callable)) { return PythonCalls.Call(context, callable, new Slice(i, j)); } throw PythonOps.TypeError("instance {0} does not have __delslice__ or __delitem__", _class.Name); } public object __index__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__int__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.TypeError("object cannot be converted to an index"); } public object __neg__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__neg__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__neg__"); } public object __abs__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__abs__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__abs__"); } public object __invert__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__invert__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__invert__"); } public object __contains__(CodeContext context, object index) { object value; if (TryGetBoundCustomMember(context, "__contains__", out value)) { return PythonCalls.Call(context, value, index); } IEnumerator ie = PythonOps.GetEnumerator(this); while (ie.MoveNext()) { if (PythonOps.EqualRetBool(context, ie.Current, index)) return ScriptingRuntimeHelpers.True; } return ScriptingRuntimeHelpers.False; } [SpecialName] public object Call(CodeContext context) { return Call(context, ArrayUtils.EmptyObjects); } [SpecialName] public object Call(CodeContext context, object args) { try { PythonOps.FunctionPushFrame(PythonContext.GetContext(context)); object value; if (TryGetBoundCustomMember(context, "__call__", out value)) { return PythonOps.CallWithContext(context, value, args); } } finally { PythonOps.FunctionPopFrame(); } throw PythonOps.AttributeError("{0} instance has no __call__ method", _class.Name); } [SpecialName] public object Call(CodeContext context, params object[] args) { try { PythonOps.FunctionPushFrame(PythonContext.GetContext(context)); object value; if (TryGetBoundCustomMember(context, "__call__", out value)) { return PythonOps.CallWithContext(context, value, args); } } finally { PythonOps.FunctionPopFrame(); } throw PythonOps.AttributeError("{0} instance has no __call__ method", _class.Name); } [SpecialName] public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) { try { PythonOps.FunctionPushFrame(PythonContext.GetContext(context)); object value; if (TryGetBoundCustomMember(context, "__call__", out value)) { return context.LanguageContext.CallWithKeywords(value, args, dict); } } finally { PythonOps.FunctionPopFrame(); } throw PythonOps.AttributeError("{0} instance has no __call__ method", _class.Name); } public object __nonzero__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__nonzero__", out value)) { return PythonOps.CallWithContext(context, value); } if (TryGetBoundCustomMember(context, "__len__", out value)) { value = PythonOps.CallWithContext(context, value); // Convert resulting object to the desired type if (value is Int32 || value is BigInteger) { return ScriptingRuntimeHelpers.BooleanToObject(Converter.ConvertToBoolean(value)); } throw PythonOps.TypeError("an integer is required, got {0}", PythonTypeOps.GetName(value)); } return ScriptingRuntimeHelpers.True; } public object __hex__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__hex__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__hex__"); } public object __oct__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__oct__", out value)) { return PythonOps.CallWithContext(context, value); } throw PythonOps.AttributeErrorForOldInstanceMissingAttribute(_class.Name, "__oct__"); } public object __int__(CodeContext context) { object value; if (PythonOps.TryGetBoundAttr(context, this, "__int__", out value)) { return PythonOps.CallWithContext(context, value); } return NotImplementedType.Value; } public object __long__(CodeContext context) { object value; if (PythonOps.TryGetBoundAttr(context, this, "__long__", out value)) { return PythonOps.CallWithContext(context, value); } return NotImplementedType.Value; } public object __float__(CodeContext context) { object value; if (PythonOps.TryGetBoundAttr(context, this, "__float__", out value)) { return PythonOps.CallWithContext(context, value); } return NotImplementedType.Value; } public object __complex__(CodeContext context) { object value; if (TryGetBoundCustomMember(context, "__complex__", out value)) { return PythonOps.CallWithContext(context, value); } return NotImplementedType.Value; } public object __getattribute__(CodeContext context, string name) { object res; if (TryGetBoundCustomMember(context, name, out res)) { return res; } throw PythonOps.AttributeError("{0} instance has no attribute '{1}'", _class._name, name); } internal object GetBoundMember(CodeContext context, string name) { object ret; if (TryGetBoundCustomMember(context, name, out ret)) { return ret; } throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'", PythonTypeOps.GetName(this), name); } #region ICustomMembers Members internal bool TryGetBoundCustomMember(CodeContext context, string name, out object value) { if (name == "__dict__") { //!!! user code can modify __del__ property of __dict__ behind our back value = _dict; return true; } else if (name == "__class__") { value = _class; return true; } if (TryRawGetAttr(context, name, out value)) return true; if (name != "__getattr__") { object getattr; if (TryRawGetAttr(context, "__getattr__", out getattr)) { try { value = PythonCalls.Call(context, getattr, name); return true; } catch (MissingMemberException) { // __getattr__ raised AttributeError, return false. } } } return false; } internal void SetCustomMember(CodeContext context, string name, object value) { object setFunc; if (name == "__class__") { SetClass(value); } else if (name == "__dict__") { SetDict(context, value); } else if (_class.HasSetAttr && _class.TryLookupSlot("__setattr__", out setFunc)) { PythonCalls.Call(context, _class.GetOldStyleDescriptor(context, setFunc, this, _class), name.ToString(), value); } else if (name == "__del__") { SetFinalizer(context, name, value); } else { _dict[name] = value; } } private void SetFinalizer(CodeContext/*!*/ context, string name, object value) { if (!HasFinalizer()) { // user is defining __del__ late bound for the 1st time AddFinalizer(context); } _dict[name] = value; } private void SetDict(CodeContext/*!*/ context, object value) { PythonDictionary dict = value as PythonDictionary; if (dict == null) { throw PythonOps.TypeError("__dict__ must be set to a dictionary"); } if (HasFinalizer() && !_class.HasFinalizer) { if (!dict.ContainsKey("__del__")) { ClearFinalizer(); } } else if (dict.ContainsKey("__del__")) { AddFinalizer(context); } _dict = dict; } private void SetClass(object value) { OldClass oc = value as OldClass; if (oc == null) { throw PythonOps.TypeError("__class__ must be set to class"); } _class = oc; } internal bool DeleteCustomMember(CodeContext context, string name) { if (name == "__class__") throw PythonOps.TypeError("__class__ must be set to class"); if (name == "__dict__") throw PythonOps.TypeError("__dict__ must be set to a dictionary"); object delFunc; if (_class.HasDelAttr && _class.TryLookupSlot("__delattr__", out delFunc)) { PythonCalls.Call(context, _class.GetOldStyleDescriptor(context, delFunc, this, _class), name.ToString()); return true; } if (name == "__del__") { // removing finalizer if (HasFinalizer() && !_class.HasFinalizer) { ClearFinalizer(); } } if (!_dict.Remove(name)) { throw PythonOps.AttributeError("{0} is not a valid attribute", name); } return true; } #endregion #region IMembersList Members IList<string> IMembersList.GetMemberNames() { return PythonOps.GetStringMemberList(this); } IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { PythonDictionary attrs = new PythonDictionary(_dict); OldClass.RecurseAttrHierarchy(this._class, attrs); return PythonOps.MakeListFromSequence(attrs); } #endregion [return: MaybeNotImplemented] public object __cmp__(CodeContext context, object other) { OldInstance oiOther = other as OldInstance; // CPython raises this if called directly, but not via cmp(os,ns) which still calls the user __cmp__ //if(!(oiOther is OldInstance)) // throw Ops.TypeError("instance.cmp(x,y) -> y must be an instance, got {0}", Ops.StringRepr(DynamicHelpers.GetPythonType(other))); object res = InternalCompare("__cmp__", other); if (res != NotImplementedType.Value) return res; if (oiOther != null) { res = oiOther.InternalCompare("__cmp__", this); if (res != NotImplementedType.Value) return ((int)res) * -1; } return NotImplementedType.Value; } private object CompareForwardReverse(object other, string forward, string reverse) { object res = InternalCompare(forward, other); if (res != NotImplementedType.Value) return res; OldInstance oi = other as OldInstance; if (oi != null) { // comparison operators are reflexive return oi.InternalCompare(reverse, this); } return NotImplementedType.Value; } [return: MaybeNotImplemented] public static object operator >([NotNull]OldInstance self, object other) { return self.CompareForwardReverse(other, "__gt__", "__lt__"); } [return: MaybeNotImplemented] public static object operator <([NotNull]OldInstance self, object other) { return self.CompareForwardReverse(other, "__lt__", "__gt__"); } [return: MaybeNotImplemented] public static object operator >=([NotNull]OldInstance self, object other) { return self.CompareForwardReverse(other, "__ge__", "__le__"); } [return: MaybeNotImplemented] public static object operator <=([NotNull]OldInstance self, object other) { return self.CompareForwardReverse(other, "__le__", "__ge__"); } private object InternalCompare(string cmp, object other) { return InvokeOne(this, other, cmp); } #region ICustomTypeDescriptor Members #if FEATURE_CUSTOM_TYPE_DESCRIPTOR AttributeCollection ICustomTypeDescriptor.GetAttributes() { return CustomTypeDescHelpers.GetAttributes(this); } string ICustomTypeDescriptor.GetClassName() { return CustomTypeDescHelpers.GetClassName(this); } string ICustomTypeDescriptor.GetComponentName() { return CustomTypeDescHelpers.GetComponentName(this); } TypeConverter ICustomTypeDescriptor.GetConverter() { return CustomTypeDescHelpers.GetConverter(this); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return CustomTypeDescHelpers.GetDefaultEvent(this); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return CustomTypeDescHelpers.GetDefaultProperty(this); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return CustomTypeDescHelpers.GetEditor(this, editorBaseType); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return CustomTypeDescHelpers.GetEvents(this, attributes); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return CustomTypeDescHelpers.GetEvents(this); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { return CustomTypeDescHelpers.GetProperties(this, attributes); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return CustomTypeDescHelpers.GetProperties(this); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return CustomTypeDescHelpers.GetPropertyOwner(this, pd); } #endif #endregion #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { return _weakRef; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { _weakRef = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { ((IWeakReferenceable)this).SetWeakRef(value); } #endregion #region Rich Equality // Specific rich equality support for when the user calls directly from oldinstance type. public int __hash__(CodeContext/*!*/ context) { object func; object ret = InvokeOne(this, "__hash__"); if (ret != NotImplementedType.Value) { if (ret is BigInteger) { return BigIntegerOps.__hash__((BigInteger)ret); } else if (!(ret is int)) throw PythonOps.TypeError("expected int from __hash__, got {0}", PythonTypeOps.GetName(ret)); return (int)ret; } if (TryGetBoundCustomMember(context, "__cmp__", out func) || TryGetBoundCustomMember(context, "__eq__", out func)) { throw PythonOps.TypeError("unhashable instance"); } return base.GetHashCode(); } public override int GetHashCode() { object ret; try { ret = InvokeOne(this, "__hash__"); } catch { return base.GetHashCode(); } if (ret != NotImplementedType.Value) { if (ret is int) { return (int)ret; } if (ret is BigInteger) { return BigIntegerOps.__hash__((BigInteger)ret); } } return base.GetHashCode(); } [return: MaybeNotImplemented] public object __eq__(object other) { object res = InvokeBoth(other, "__eq__"); if (res != NotImplementedType.Value) { return res; } return NotImplementedType.Value; } private object InvokeBoth(object other, string si) { object res = InvokeOne(this, other, si); if (res != NotImplementedType.Value) { return res; } OldInstance oi = other as OldInstance; if (oi != null) { res = InvokeOne(oi, this, si); if (res != NotImplementedType.Value) { return res; } } return NotImplementedType.Value; } private static object InvokeOne(OldInstance self, object other, string si) { object func; try { if (!self.TryGetBoundCustomMember(DefaultContext.Default, si, out func)) { return NotImplementedType.Value; } } catch (MissingMemberException) { return NotImplementedType.Value; } return PythonOps.CallWithContext(DefaultContext.Default, func, other); } private static object InvokeOne(OldInstance self, object other, object other2, string si) { object func; try { if (!self.TryGetBoundCustomMember(DefaultContext.Default, si, out func)) { return NotImplementedType.Value; } } catch (MissingMemberException) { return NotImplementedType.Value; } return PythonOps.CallWithContext(DefaultContext.Default, func, other, other2); } private static object InvokeOne(OldInstance self, string si) { object func; try { if (!self.TryGetBoundCustomMember(DefaultContext.Default, si, out func)) { return NotImplementedType.Value; } } catch (MissingMemberException) { return NotImplementedType.Value; } return PythonOps.CallWithContext(DefaultContext.Default, func); } [return: MaybeNotImplemented] public object __ne__(object other) { object res = InvokeBoth(other, "__ne__"); if (res != NotImplementedType.Value) { return res; } return NotImplementedType.Value; } [return: MaybeNotImplemented] [SpecialName] public static object Power([NotNull]OldInstance self, object other, object mod) { object res = InvokeOne(self, other, mod, "__pow__"); if (res != NotImplementedType.Value) return res; return NotImplementedType.Value; } #endregion #region ISerializable Members #if FEATURE_SERIALIZATION void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("__class__", _class); info.AddValue("__dict__", _dict); } #endif #endregion #region Private Implementation Details private void RecurseAttrHierarchyInt(OldClass oc, IDictionary<string, object> attrs) { foreach (KeyValuePair<object, object> kvp in oc._dict._storage.GetItems()) { string strKey = kvp.Key as string; if (strKey != null) { if (!attrs.ContainsKey(strKey)) { attrs.Add(strKey, strKey); } } } // recursively get attrs in parent hierarchy if (oc.BaseClasses.Count != 0) { foreach (OldClass parent in oc.BaseClasses) { RecurseAttrHierarchyInt(parent, attrs); } } } private void AddFinalizer(CodeContext/*!*/ context) { InstanceFinalizer oif = new InstanceFinalizer(context, this); _weakRef = new WeakRefTracker(oif, oif); } private void ClearFinalizer() { if (_weakRef == null) return; WeakRefTracker wrt = _weakRef; if (wrt != null) { // find our handler and remove it (other users could have created weak refs to us) for (int i = 0; i < wrt.HandlerCount; i++) { if (wrt.GetHandlerCallback(i) is InstanceFinalizer) { wrt.RemoveHandlerAt(i); break; } } // we removed the last handler if (wrt.HandlerCount == 0) { GC.SuppressFinalize(wrt); _weakRef = null; } } } private bool HasFinalizer() { if (_weakRef != null) { WeakRefTracker wrt = _weakRef; if (wrt != null) { for (int i = 0; i < wrt.HandlerCount; i++) { if (wrt.GetHandlerCallback(i) is InstanceFinalizer) { return true; } } } } return false; } private bool TryRawGetAttr(CodeContext context, string name, out object ret) { if (_dict._storage.TryGetValue(name, out ret)) { return true; } if (_class.TryLookupSlot(name, out ret)) { ret = _class.GetOldStyleDescriptor(context, ret, this, _class); return true; } return false; } #endregion #region IValueEquality Members #if CLR2 int IValueEquality.GetValueHashCode() { return GetHashCode(); } bool IValueEquality.ValueEquals(object other) { return Equals(other); } #endif #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Expression/*!*/ parameter) { return new Binding.MetaOldInstance(parameter, BindingRestrictions.Empty, this); } #endregion internal class OldInstanceDebugView { private readonly OldInstance _userObject; public OldInstanceDebugView(OldInstance userObject) { _userObject = userObject; } public OldClass __class__ { get { return _userObject._class; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal List<ObjectDebugView> Members { get { var res = new List<ObjectDebugView>(); if (_userObject._dict != null) { foreach (var v in _userObject._dict) { res.Add(new ObjectDebugView(v.Key, v.Value)); } } return res; } } } class FastOldInstanceGet { private readonly string _name; public FastOldInstanceGet(string name) { _name = name; } public object Target(CallSite site, object instance, CodeContext context) { OldInstance oi = instance as OldInstance; if (oi != null) { object res; if (oi.TryGetBoundCustomMember(context, _name, out res)) { return res; } throw PythonOps.AttributeError("{0} instance has no attribute '{1}'", oi._class.Name, _name); } return ((CallSite<Func<CallSite, object, CodeContext, object>>)site).Update(site, instance, context); } public object LightThrowTarget(CallSite site, object instance, CodeContext context) { OldInstance oi = instance as OldInstance; if (oi != null) { object res; if (oi.TryGetBoundCustomMember(context, _name, out res)) { return res; } return LightExceptions.Throw(PythonOps.AttributeError("{0} instance has no attribute '{1}'", oi._class.Name, _name)); } return ((CallSite<Func<CallSite, object, CodeContext, object>>)site).Update(site, instance, context); } public object NoThrowTarget(CallSite site, object instance, CodeContext context) { OldInstance oi = instance as OldInstance; if (oi != null) { object res; if (oi.TryGetBoundCustomMember(context, _name, out res)) { return res; } return OperationFailed.Value; } return ((CallSite<Func<CallSite, object, CodeContext, object>>)site).Update(site, instance, context); } } #region IFastGettable Members T Binding.IFastGettable.MakeGetBinding<T>(System.Runtime.CompilerServices.CallSite<T> site, Binding.PythonGetMemberBinder binder, CodeContext state, string name) { if (binder.IsNoThrow) { return (T)(object)new Func<CallSite, object, CodeContext, object>(new FastOldInstanceGet(name).NoThrowTarget); } else if (binder.SupportsLightThrow) { return (T)(object)new Func<CallSite, object, CodeContext, object>(new FastOldInstanceGet(name).LightThrowTarget); } else { return (T)(object)new Func<CallSite, object, CodeContext, object>(new FastOldInstanceGet(name).Target); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; namespace System.Runtime.Caching { internal struct ExpiresEntryRef { static internal readonly ExpiresEntryRef INVALID = new ExpiresEntryRef(0, 0); private const uint ENTRY_MASK = 0x000000ffu; private const uint PAGE_MASK = 0xffffff00u; private const int PAGE_SHIFT = 8; private uint _ref; internal ExpiresEntryRef(int pageIndex, int entryIndex) { Dbg.Assert((pageIndex & 0x00ffffff) == pageIndex, "(pageIndex & 0x00ffffff) == pageIndex"); Dbg.Assert((entryIndex & ENTRY_MASK) == entryIndex, "(entryIndex & ENTRY_MASK) == entryIndex"); Dbg.Assert(entryIndex != 0 || pageIndex == 0, "entryIndex != 0 || pageIndex == 0"); _ref = ((((uint)pageIndex) << PAGE_SHIFT) | (((uint)(entryIndex)) & ENTRY_MASK)); } public override bool Equals(object value) { if (value is ExpiresEntryRef) { return _ref == ((ExpiresEntryRef)value)._ref; } return false; } public static bool operator !=(ExpiresEntryRef r1, ExpiresEntryRef r2) { return r1._ref != r2._ref; } public static bool operator ==(ExpiresEntryRef r1, ExpiresEntryRef r2) { return r1._ref == r2._ref; } public override int GetHashCode() { return (int)_ref; } internal int PageIndex { get { int result = (int)(_ref >> PAGE_SHIFT); return result; } } internal int Index { get { int result = (int)(_ref & ENTRY_MASK); return result; } } internal bool IsInvalid { get { return _ref == 0; } } } [SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", Justification = "Grandfathered suppression from original caching code checkin")] [StructLayout(LayoutKind.Explicit)] internal struct ExpiresEntry { [FieldOffset(0)] internal DateTime _utcExpires; [FieldOffset(0)] internal ExpiresEntryRef _next; [FieldOffset(4)] internal int _cFree; [FieldOffset(8)] internal MemoryCacheEntry _cacheEntry; } internal struct ExpiresPage { internal ExpiresEntry[] _entries; internal int _pageNext; internal int _pagePrev; } internal struct ExpiresPageList { internal int _head; internal int _tail; } internal sealed class ExpiresBucket { private const int NUM_ENTRIES = 127; private const int LENGTH_ENTRIES = 128; private const int MIN_PAGES_INCREMENT = 10; private const int MAX_PAGES_INCREMENT = 340; private const double MIN_LOAD_FACTOR = 0.5; private const int COUNTS_LENGTH = 4; private static readonly TimeSpan s_COUNT_INTERVAL = new TimeSpan(CacheExpires._tsPerBucket.Ticks / COUNTS_LENGTH); private readonly CacheExpires _cacheExpires; private readonly byte _bucket; private ExpiresPage[] _pages; private int _cEntriesInUse; private int _cPagesInUse; private int _cEntriesInFlush; private int _minEntriesInUse; private ExpiresPageList _freePageList; private ExpiresPageList _freeEntryList; private bool _blockReduce; private DateTime _utcMinExpires; private int[] _counts; private DateTime _utcLastCountReset; internal ExpiresBucket(CacheExpires cacheExpires, byte bucket, DateTime utcNow) { _cacheExpires = cacheExpires; _bucket = bucket; _counts = new int[COUNTS_LENGTH]; ResetCounts(utcNow); InitZeroPages(); Dbg.Validate("CacheValidateExpires", this); } private void InitZeroPages() { Dbg.Assert(_cPagesInUse == 0, "_cPagesInUse == 0"); Dbg.Assert(_cEntriesInUse == 0, "_cEntriesInUse == 0"); Dbg.Assert(_cEntriesInFlush == 0, "_cEntriesInFlush == 0"); _pages = null; _minEntriesInUse = -1; _freePageList._head = -1; _freePageList._tail = -1; _freeEntryList._head = -1; _freeEntryList._tail = -1; } private void ResetCounts(DateTime utcNow) { _utcLastCountReset = utcNow; _utcMinExpires = DateTime.MaxValue; for (int i = 0; i < _counts.Length; i++) { _counts[i] = 0; } } private int GetCountIndex(DateTime utcExpires) { return Math.Max(0, (int)((utcExpires - _utcLastCountReset).Ticks / s_COUNT_INTERVAL.Ticks)); } private void AddCount(DateTime utcExpires) { int ci = GetCountIndex(utcExpires); for (int i = _counts.Length - 1; i >= ci; i--) { _counts[i]++; } if (utcExpires < _utcMinExpires) { _utcMinExpires = utcExpires; } } private void RemoveCount(DateTime utcExpires) { int ci = GetCountIndex(utcExpires); for (int i = _counts.Length - 1; i >= ci; i--) { _counts[i]--; } } private int GetExpiresCount(DateTime utcExpires) { if (utcExpires < _utcMinExpires) return 0; int ci = GetCountIndex(utcExpires); if (ci >= _counts.Length) return _cEntriesInUse; return _counts[ci]; } private void AddToListHead(int pageIndex, ref ExpiresPageList list) { Dbg.Assert((list._head == -1) == (list._tail == -1), "(list._head == -1) == (list._tail == -1)"); (_pages[(pageIndex)]._pagePrev) = -1; (_pages[(pageIndex)]._pageNext) = list._head; if (list._head != -1) { Dbg.Assert((_pages[(list._head)]._pagePrev) == -1, "PagePrev(list._head) == -1"); (_pages[(list._head)]._pagePrev) = pageIndex; } else { list._tail = pageIndex; } list._head = pageIndex; } private void AddToListTail(int pageIndex, ref ExpiresPageList list) { Dbg.Assert((list._head == -1) == (list._tail == -1), "(list._head == -1) == (list._tail == -1)"); (_pages[(pageIndex)]._pageNext) = -1; (_pages[(pageIndex)]._pagePrev) = list._tail; if (list._tail != -1) { Dbg.Assert((_pages[(list._tail)]._pageNext) == -1, "PageNext(list._tail) == -1"); (_pages[(list._tail)]._pageNext) = pageIndex; } else { list._head = pageIndex; } list._tail = pageIndex; } private int RemoveFromListHead(ref ExpiresPageList list) { Dbg.Assert(list._head != -1, "list._head != -1"); int oldHead = list._head; RemoveFromList(oldHead, ref list); return oldHead; } private void RemoveFromList(int pageIndex, ref ExpiresPageList list) { Dbg.Assert((list._head == -1) == (list._tail == -1), "(list._head == -1) == (list._tail == -1)"); if ((_pages[(pageIndex)]._pagePrev) != -1) { Dbg.Assert((_pages[((_pages[(pageIndex)]._pagePrev))]._pageNext) == pageIndex, "PageNext(PagePrev(pageIndex)) == pageIndex"); (_pages[((_pages[(pageIndex)]._pagePrev))]._pageNext) = (_pages[(pageIndex)]._pageNext); } else { Dbg.Assert(list._head == pageIndex, "list._head == pageIndex"); list._head = (_pages[(pageIndex)]._pageNext); } if ((_pages[(pageIndex)]._pageNext) != -1) { Dbg.Assert((_pages[((_pages[(pageIndex)]._pageNext))]._pagePrev) == pageIndex, "PagePrev(PageNext(pageIndex)) == pageIndex"); (_pages[((_pages[(pageIndex)]._pageNext))]._pagePrev) = (_pages[(pageIndex)]._pagePrev); } else { Dbg.Assert(list._tail == pageIndex, "list._tail == pageIndex"); list._tail = (_pages[(pageIndex)]._pagePrev); } (_pages[(pageIndex)]._pagePrev) = -1; (_pages[(pageIndex)]._pageNext) = -1; } private void MoveToListHead(int pageIndex, ref ExpiresPageList list) { Dbg.Assert(list._head != -1, "list._head != -1"); Dbg.Assert(list._tail != -1, "list._tail != -1"); if (list._head == pageIndex) return; RemoveFromList(pageIndex, ref list); AddToListHead(pageIndex, ref list); } private void MoveToListTail(int pageIndex, ref ExpiresPageList list) { Dbg.Assert(list._head != -1, "list._head != -1"); Dbg.Assert(list._tail != -1, "list._tail != -1"); if (list._tail == pageIndex) { return; } RemoveFromList(pageIndex, ref list); AddToListTail(pageIndex, ref list); } private void UpdateMinEntries() { if (_cPagesInUse <= 1) { _minEntriesInUse = -1; } else { int capacity = _cPagesInUse * NUM_ENTRIES; Dbg.Assert(capacity > 0, "capacity > 0"); Dbg.Assert(MIN_LOAD_FACTOR < 1.0, "MIN_LOAD_FACTOR < 1.0"); _minEntriesInUse = (int)(capacity * MIN_LOAD_FACTOR); if ((_minEntriesInUse - 1) > ((_cPagesInUse - 1) * NUM_ENTRIES)) { _minEntriesInUse = -1; } } } private void RemovePage(int pageIndex) { Dbg.Assert((((_pages[(pageIndex)]._entries))[0]._cFree) == NUM_ENTRIES, "FreeEntryCount(EntriesI(pageIndex)) == NUM_ENTRIES"); RemoveFromList(pageIndex, ref _freeEntryList); AddToListHead(pageIndex, ref _freePageList); Dbg.Assert((_pages[(pageIndex)]._entries) != null, "EntriesI(pageIndex) != null"); (_pages[(pageIndex)]._entries) = null; _cPagesInUse--; if (_cPagesInUse == 0) { InitZeroPages(); } else { UpdateMinEntries(); } } private ExpiresEntryRef GetFreeExpiresEntry() { Dbg.Assert(_freeEntryList._head >= 0, "_freeEntryList._head >= 0"); int pageIndex = _freeEntryList._head; ExpiresEntry[] entries = (_pages[(pageIndex)]._entries); int entryIndex = ((entries)[0]._next).Index; ((entries)[0]._next) = entries[entryIndex]._next; ((entries)[0]._cFree)--; if (((entries)[0]._cFree) == 0) { Dbg.Assert(((entries)[0]._next).IsInvalid, "FreeEntryHead(entries).IsInvalid"); RemoveFromList(pageIndex, ref _freeEntryList); } return new ExpiresEntryRef(pageIndex, entryIndex); } private void AddExpiresEntryToFreeList(ExpiresEntryRef entryRef) { ExpiresEntry[] entries = (_pages[(entryRef.PageIndex)]._entries); int entryIndex = entryRef.Index; Dbg.Assert(entries[entryIndex]._cacheEntry == null, "entries[entryIndex]._cacheEntry == null"); entries[entryIndex]._cFree = 0; entries[entryIndex]._next = ((entries)[0]._next); ((entries)[0]._next) = entryRef; _cEntriesInUse--; int pageIndex = entryRef.PageIndex; ((entries)[0]._cFree)++; if (((entries)[0]._cFree) == 1) { AddToListHead(pageIndex, ref _freeEntryList); } else if (((entries)[0]._cFree) == NUM_ENTRIES) { RemovePage(pageIndex); } } private void Expand() { Dbg.Assert(_cPagesInUse * NUM_ENTRIES == _cEntriesInUse, "_cPagesInUse * NUM_ENTRIES == _cEntriesInUse"); Dbg.Assert(_freeEntryList._head == -1, "_freeEntryList._head == -1"); Dbg.Assert(_freeEntryList._tail == -1, "_freeEntryList._tail == -1"); if (_freePageList._head == -1) { int oldLength; if (_pages == null) { oldLength = 0; } else { oldLength = _pages.Length; } Dbg.Assert(_cPagesInUse == oldLength, "_cPagesInUse == oldLength"); Dbg.Assert(_cEntriesInUse == oldLength * NUM_ENTRIES, "_cEntriesInUse == oldLength * ExpiresEntryRef.NUM_ENTRIES"); int newLength = oldLength * 2; newLength = Math.Max(oldLength + MIN_PAGES_INCREMENT, newLength); newLength = Math.Min(newLength, oldLength + MAX_PAGES_INCREMENT); Dbg.Assert(newLength > oldLength, "newLength > oldLength"); ExpiresPage[] newPages = new ExpiresPage[newLength]; for (int i = 0; i < oldLength; i++) { newPages[i] = _pages[i]; } for (int i = oldLength; i < newPages.Length; i++) { newPages[i]._pagePrev = i - 1; newPages[i]._pageNext = i + 1; } newPages[oldLength]._pagePrev = -1; newPages[newPages.Length - 1]._pageNext = -1; _freePageList._head = oldLength; _freePageList._tail = newPages.Length - 1; _pages = newPages; } int pageIndex = RemoveFromListHead(ref _freePageList); AddToListHead(pageIndex, ref _freeEntryList); ExpiresEntry[] entries = new ExpiresEntry[LENGTH_ENTRIES]; ((entries)[0]._cFree) = NUM_ENTRIES; for (int i = 0; i < entries.Length - 1; i++) { entries[i]._next = new ExpiresEntryRef(pageIndex, i + 1); } entries[entries.Length - 1]._next = ExpiresEntryRef.INVALID; (_pages[(pageIndex)]._entries) = entries; _cPagesInUse++; UpdateMinEntries(); } private void Reduce() { if (_cEntriesInUse >= _minEntriesInUse || _blockReduce) return; Dbg.Assert(_freeEntryList._head != -1, "_freeEntryList._head != -1"); Dbg.Assert(_freeEntryList._tail != -1, "_freeEntryList._tail != -1"); Dbg.Assert(_freeEntryList._head != _freeEntryList._tail, "_freeEntryList._head != _freeEntryList._tail"); int meanFree = (int)(NUM_ENTRIES - (NUM_ENTRIES * MIN_LOAD_FACTOR)); int pageIndexLast = _freeEntryList._tail; int pageIndexCurrent = _freeEntryList._head; int pageIndexNext; ExpiresEntry[] entries; for (; ;) { pageIndexNext = (_pages[(pageIndexCurrent)]._pageNext); if ((((_pages[(pageIndexCurrent)]._entries))[0]._cFree) > meanFree) { MoveToListTail(pageIndexCurrent, ref _freeEntryList); } else { MoveToListHead(pageIndexCurrent, ref _freeEntryList); } if (pageIndexCurrent == pageIndexLast) { break; } pageIndexCurrent = pageIndexNext; } for (; ;) { if (_freeEntryList._tail == -1) break; entries = (_pages[(_freeEntryList._tail)]._entries); Dbg.Assert(((entries)[0]._cFree) > 0, "FreeEntryCount(entries) > 0"); int availableFreeEntries = (_cPagesInUse * NUM_ENTRIES) - ((entries)[0]._cFree) - _cEntriesInUse; if (availableFreeEntries < (NUM_ENTRIES - ((entries)[0]._cFree))) break; for (int i = 1; i < entries.Length; i++) { if (entries[i]._cacheEntry == null) continue; Dbg.Assert(_freeEntryList._head != _freeEntryList._tail, "_freeEntryList._head != _freeEntryList._tail"); ExpiresEntryRef newRef = GetFreeExpiresEntry(); Dbg.Assert(newRef.PageIndex != _freeEntryList._tail, "newRef.PageIndex != _freeEntryList._tail"); MemoryCacheEntry cacheEntry = entries[i]._cacheEntry; cacheEntry.ExpiresEntryRef = newRef; ExpiresEntry[] newEntries = (_pages[(newRef.PageIndex)]._entries); newEntries[newRef.Index] = entries[i]; ((entries)[0]._cFree)++; } RemovePage(_freeEntryList._tail); Dbg.Validate("CacheValidateExpires", this); } } internal void AddCacheEntry(MemoryCacheEntry cacheEntry) { lock (this) { if ((cacheEntry.State & (EntryState.AddedToCache | EntryState.AddingToCache)) == 0) return; ExpiresEntryRef entryRef = cacheEntry.ExpiresEntryRef; Dbg.Assert((cacheEntry.ExpiresBucket == 0xff) == entryRef.IsInvalid, "(cacheEntry.ExpiresBucket == 0xff) == entryRef.IsInvalid"); if (cacheEntry.ExpiresBucket != 0xff || !entryRef.IsInvalid) return; if (_freeEntryList._head == -1) { Expand(); } ExpiresEntryRef freeRef = GetFreeExpiresEntry(); Dbg.Assert(cacheEntry.ExpiresBucket == 0xff, "cacheEntry.ExpiresBucket == 0xff"); Dbg.Assert(cacheEntry.ExpiresEntryRef.IsInvalid, "cacheEntry.ExpiresEntryRef.IsInvalid"); cacheEntry.ExpiresBucket = _bucket; cacheEntry.ExpiresEntryRef = freeRef; ExpiresEntry[] entries = (_pages[(freeRef.PageIndex)]._entries); int entryIndex = freeRef.Index; entries[entryIndex]._cacheEntry = cacheEntry; entries[entryIndex]._utcExpires = cacheEntry.UtcAbsExp; AddCount(cacheEntry.UtcAbsExp); _cEntriesInUse++; if ((cacheEntry.State & (EntryState.AddedToCache | EntryState.AddingToCache)) == 0) { RemoveCacheEntryNoLock(cacheEntry); } } } private void RemoveCacheEntryNoLock(MemoryCacheEntry cacheEntry) { ExpiresEntryRef entryRef = cacheEntry.ExpiresEntryRef; if (cacheEntry.ExpiresBucket != _bucket || entryRef.IsInvalid) return; ExpiresEntry[] entries = (_pages[(entryRef.PageIndex)]._entries); int entryIndex = entryRef.Index; RemoveCount(entries[entryIndex]._utcExpires); cacheEntry.ExpiresBucket = 0xff; cacheEntry.ExpiresEntryRef = ExpiresEntryRef.INVALID; entries[entryIndex]._cacheEntry = null; AddExpiresEntryToFreeList(entryRef); if (_cEntriesInUse == 0) { ResetCounts(DateTime.UtcNow); } Reduce(); Dbg.Trace("CacheExpiresRemove", "Removed item=" + cacheEntry.Key + ",_bucket=" + _bucket + ",ref=" + entryRef + ",now=" + Dbg.FormatLocalDate(DateTime.Now) + ",expires=" + cacheEntry.UtcAbsExp.ToLocalTime()); Dbg.Validate("CacheValidateExpires", this); Dbg.Dump("CacheExpiresRemove", this); } internal void RemoveCacheEntry(MemoryCacheEntry cacheEntry) { lock (this) { RemoveCacheEntryNoLock(cacheEntry); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")] internal void UtcUpdateCacheEntry(MemoryCacheEntry cacheEntry, DateTime utcExpires) { lock (this) { ExpiresEntryRef entryRef = cacheEntry.ExpiresEntryRef; if (cacheEntry.ExpiresBucket != _bucket || entryRef.IsInvalid) return; ExpiresEntry[] entries = (_pages[(entryRef.PageIndex)]._entries); int entryIndex = entryRef.Index; Dbg.Assert(cacheEntry == entries[entryIndex]._cacheEntry); RemoveCount(entries[entryIndex]._utcExpires); AddCount(utcExpires); entries[entryIndex]._utcExpires = utcExpires; cacheEntry.UtcAbsExp = utcExpires; Dbg.Validate("CacheValidateExpires", this); Dbg.Trace("CacheExpiresUpdate", "Updated item " + cacheEntry.Key + " in bucket " + _bucket); } } internal int FlushExpiredItems(DateTime utcNow, bool useInsertBlock) { if (_cEntriesInUse == 0 || GetExpiresCount(utcNow) == 0) return 0; Dbg.Assert(_cEntriesInFlush == 0, "_cEntriesInFlush == 0"); ExpiresEntryRef inFlushHead = ExpiresEntryRef.INVALID; ExpiresEntry[] entries; int entryIndex; MemoryCacheEntry cacheEntry; int flushed = 0; try { if (useInsertBlock) { _cacheExpires.MemoryCacheStore.BlockInsert(); } lock (this) { Dbg.Assert(_blockReduce == false, "_blockReduce == false"); if (_cEntriesInUse == 0 || GetExpiresCount(utcNow) == 0) return 0; ResetCounts(utcNow); int cPages = _cPagesInUse; for (int i = 0; i < _pages.Length; i++) { entries = _pages[i]._entries; if (entries != null) { int cEntries = NUM_ENTRIES - ((entries)[0]._cFree); for (int j = 1; j < entries.Length; j++) { cacheEntry = entries[j]._cacheEntry; if (cacheEntry != null) { if (entries[j]._utcExpires > utcNow) { AddCount(entries[j]._utcExpires); } else { cacheEntry.ExpiresBucket = 0xff; cacheEntry.ExpiresEntryRef = ExpiresEntryRef.INVALID; entries[j]._cFree = 1; entries[j]._next = inFlushHead; inFlushHead = new ExpiresEntryRef(i, j); flushed++; _cEntriesInFlush++; } cEntries--; if (cEntries == 0) break; } } cPages--; if (cPages == 0) break; } } if (flushed == 0) { Dbg.Trace("CacheExpiresFlushTotal", "FlushExpiredItems flushed " + flushed + " expired items, bucket=" + _bucket + "; Time=" + Dbg.FormatLocalDate(DateTime.Now)); return 0; } _blockReduce = true; } } finally { if (useInsertBlock) { _cacheExpires.MemoryCacheStore.UnblockInsert(); } } Dbg.Assert(!inFlushHead.IsInvalid, "!inFlushHead.IsInvalid"); MemoryCacheStore cacheStore = _cacheExpires.MemoryCacheStore; ExpiresEntryRef current = inFlushHead; ExpiresEntryRef next; while (!current.IsInvalid) { entries = (_pages[(current.PageIndex)]._entries); entryIndex = current.Index; next = entries[entryIndex]._next; cacheEntry = entries[entryIndex]._cacheEntry; entries[entryIndex]._cacheEntry = null; Dbg.Assert(cacheEntry.ExpiresEntryRef.IsInvalid, "cacheEntry.ExpiresEntryRef.IsInvalid"); cacheStore.Remove(cacheEntry, cacheEntry, CacheEntryRemovedReason.Expired); current = next; } try { if (useInsertBlock) { _cacheExpires.MemoryCacheStore.BlockInsert(); } lock (this) { current = inFlushHead; while (!current.IsInvalid) { entries = (_pages[(current.PageIndex)]._entries); entryIndex = current.Index; next = entries[entryIndex]._next; _cEntriesInFlush--; AddExpiresEntryToFreeList(current); current = next; } Dbg.Assert(_cEntriesInFlush == 0, "_cEntriesInFlush == 0"); _blockReduce = false; Reduce(); Dbg.Trace("CacheExpiresFlushTotal", "FlushExpiredItems flushed " + flushed + " expired items, bucket=" + _bucket + "; Time=" + Dbg.FormatLocalDate(DateTime.Now)); Dbg.Validate("CacheValidateExpires", this); Dbg.Dump("CacheExpiresFlush", this); } } finally { if (useInsertBlock) { _cacheExpires.MemoryCacheStore.UnblockInsert(); } } return flushed; } } internal sealed class CacheExpires { internal static readonly TimeSpan MIN_UPDATE_DELTA = new TimeSpan(0, 0, 1); internal static readonly TimeSpan MIN_FLUSH_INTERVAL = new TimeSpan(0, 0, 1); internal static readonly TimeSpan _tsPerBucket = new TimeSpan(0, 0, 20); private const int NUMBUCKETS = 30; private static readonly TimeSpan s_tsPerCycle = new TimeSpan(NUMBUCKETS * _tsPerBucket.Ticks); private readonly MemoryCacheStore _cacheStore; private readonly ExpiresBucket[] _buckets; private GCHandleRef<Timer> _timerHandleRef; private DateTime _utcLastFlush; private int _inFlush; internal CacheExpires(MemoryCacheStore cacheStore) { Dbg.Assert(NUMBUCKETS < Byte.MaxValue); DateTime utcNow = DateTime.UtcNow; _cacheStore = cacheStore; _buckets = new ExpiresBucket[NUMBUCKETS]; for (byte b = 0; b < _buckets.Length; b++) { _buckets[b] = new ExpiresBucket(this, b, utcNow); } } private int UtcCalcExpiresBucket(DateTime utcDate) { long ticksFromCycleStart = utcDate.Ticks % s_tsPerCycle.Ticks; int bucket = (int)(((ticksFromCycleStart / _tsPerBucket.Ticks) + 1) % NUMBUCKETS); return bucket; } private int FlushExpiredItems(bool checkDelta, bool useInsertBlock) { int flushed = 0; if (Interlocked.Exchange(ref _inFlush, 1) == 0) { try { if (_timerHandleRef == null) { return 0; } DateTime utcNow = DateTime.UtcNow; if (!checkDelta || utcNow - _utcLastFlush >= MIN_FLUSH_INTERVAL || utcNow < _utcLastFlush) { _utcLastFlush = utcNow; foreach (ExpiresBucket bucket in _buckets) { flushed += bucket.FlushExpiredItems(utcNow, useInsertBlock); } Dbg.Trace("CacheExpiresFlushTotal", "FlushExpiredItems flushed a total of " + flushed + " items; Time=" + Dbg.FormatLocalDate(DateTime.Now)); Dbg.Dump("CacheExpiresFlush", this); } } finally { Interlocked.Exchange(ref _inFlush, 0); } } return flushed; } internal int FlushExpiredItems(bool useInsertBlock) { return FlushExpiredItems(true, useInsertBlock); } private void TimerCallback(object state) { FlushExpiredItems(false, false); } internal void EnableExpirationTimer(bool enable) { if (enable) { if (_timerHandleRef == null) { DateTime utcNow = DateTime.UtcNow; TimeSpan due = _tsPerBucket - (new TimeSpan(utcNow.Ticks % _tsPerBucket.Ticks)); Timer timer = new Timer(new TimerCallback(this.TimerCallback), null, due.Ticks / TimeSpan.TicksPerMillisecond, _tsPerBucket.Ticks / TimeSpan.TicksPerMillisecond); _timerHandleRef = new GCHandleRef<Timer>(timer); Dbg.Trace("Cache", "Cache expiration timer created."); } } else { GCHandleRef<Timer> timerHandleRef = _timerHandleRef; if (timerHandleRef != null && Interlocked.CompareExchange(ref _timerHandleRef, null, timerHandleRef) == timerHandleRef) { timerHandleRef.Dispose(); Dbg.Trace("Cache", "Cache expiration timer disposed."); while (_inFlush != 0) { Thread.Sleep(100); } } } } internal MemoryCacheStore MemoryCacheStore { get { return _cacheStore; } } internal void Add(MemoryCacheEntry cacheEntry) { DateTime utcNow = DateTime.UtcNow; if (utcNow > cacheEntry.UtcAbsExp) { cacheEntry.UtcAbsExp = utcNow; } int bucket = UtcCalcExpiresBucket(cacheEntry.UtcAbsExp); _buckets[bucket].AddCacheEntry(cacheEntry); } internal void Remove(MemoryCacheEntry cacheEntry) { byte bucket = cacheEntry.ExpiresBucket; if (bucket != 0xff) { _buckets[bucket].RemoveCacheEntry(cacheEntry); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")] internal void UtcUpdate(MemoryCacheEntry cacheEntry, DateTime utcNewExpires) { int oldBucket = cacheEntry.ExpiresBucket; int newBucket = UtcCalcExpiresBucket(utcNewExpires); if (oldBucket != newBucket) { Dbg.Trace("CacheExpiresUpdate", "Updating item " + cacheEntry.Key + " from bucket " + oldBucket + " to new bucket " + newBucket); if (oldBucket != 0xff) { _buckets[oldBucket].RemoveCacheEntry(cacheEntry); cacheEntry.UtcAbsExp = utcNewExpires; _buckets[newBucket].AddCacheEntry(cacheEntry); } } else { if (oldBucket != 0xff) { _buckets[oldBucket].UtcUpdateCacheEntry(cacheEntry, utcNewExpires); } } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Diagnostics.CodeAnalysis; using System.Linq; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell { /// <summary> /// /// Executor wraps a Pipeline instance, and provides helper methods for executing commands in that pipeline. It is used to /// provide bookkeeping and structure to the use of pipeline in such a way that they can be interrupted and cancelled by a /// break event handler, and track nesting of pipelines (which happens with interrupted input loops (aka subshells) and use /// of tab-completion in prompts. The bookkeeping is necessary because the break handler is static and global, and there is /// no means for tying a break handler to an instance of an object. /// /// The class' instance methods manage a single pipeline. The class' static methods track the outstanding instances to /// ensure that only one instance is 'active' (and therefore cancellable) at a time. /// /// </summary> internal class Executor { [Flags] internal enum ExecutionOptions { None = 0x0, AddOutputter = 0x01, AddToHistory = 0x02, ReadInputObjects = 0x04 } /// <summary> /// /// Constructs a new instance /// /// </summary> /// <param name="parent"> /// /// A reference to the parent ConsoleHost that created this instance. /// /// </param> /// <param name="useNestedPipelines"> /// /// true if the executor is supposed to use nested pipelines; false if not. /// /// </param> /// <param name="isPromptFunctionExecutor"> /// /// True if the instance will be used to execute the prompt function, which will delay stopping the pipeline by some /// milliseconds. This we prevent us from stopping the pipeline so quickly that when the user leans on the ctrl-c key /// that the prompt "stops working" (because it is being stopped faster than it can run to completion). /// /// </param> internal Executor(ConsoleHost parent, bool useNestedPipelines, bool isPromptFunctionExecutor) { Dbg.Assert(parent != null, "parent should not be null"); _parent = parent; this.useNestedPipelines = useNestedPipelines; _isPromptFunctionExecutor = isPromptFunctionExecutor; Reset(); } #region async // called on the pipeline thread private void OutputObjectStreamHandler(object sender, EventArgs e) { // e is just an empty instance of EventArgs, so we ignore it. sender is the PipelineReader that raised it's // DataReady event that calls this handler, which is the PipelineReader for the Output object stream. PipelineReader<PSObject> reader = (PipelineReader<PSObject>)sender; // we use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be // inconsistent for this method to be called when there are no objects, since it will be called synchronously on // the pipeline thread, blocking in this call until an object is streamed would deadlock the pipeline. So we // prefer to take no chance of blocking. Collection<PSObject> objects = reader.NonBlockingRead(); foreach (PSObject obj in objects) { _parent.OutputSerializer.Serialize(obj); } } // called on the pipeline thread private void ErrorObjectStreamHandler(object sender, EventArgs e) { // e is just an empty instance of EventArgs, so we ignore it. sender is the PipelineReader that raised it's // DataReady event that calls this handler, which is the PipelineReader for the Error object stream. PipelineReader<object> reader = (PipelineReader<object>)sender; // we use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be // inconsistent for this method to be called when there are no objects, since it will be called synchronously on // the pipeline thread, blocking in this call until an object is streamed would deadlock the pipeline. So we // prefer to take no chance of blocking. Collection<object> objects = reader.NonBlockingRead(); foreach (object obj in objects) { _parent.ErrorSerializer.Serialize(obj); } } /// <summary> /// This method handles the failure in excecuting pipeline asynchronously /// </summary> /// <param name="ex"></param> private void AsyncPipelineFailureHandler(Exception ex) { ErrorRecord er = null; IContainsErrorRecord cer = ex as IContainsErrorRecord; if (cer != null) { er = cer.ErrorRecord; //Exception inside the error record is ParentContainsErrorRecordException which //doesn't have stack trace. Replace it with top level exception. er = new ErrorRecord(er, ex); } if (er == null) { er = new ErrorRecord(ex, "ConsoleHostAsyncPipelineFailure", ErrorCategory.NotSpecified, null); } _parent.ErrorSerializer.Serialize(er); } private class PipelineFinishedWaitHandle { internal PipelineFinishedWaitHandle(Pipeline p) { p.StateChanged += new EventHandler<PipelineStateEventArgs>(PipelineStateChangedHandler); } internal void Wait() { _eventHandle.WaitOne(); } private void PipelineStateChangedHandler(object sender, PipelineStateEventArgs e) { if ( e.PipelineStateInfo.State == PipelineState.Completed || e.PipelineStateInfo.State == PipelineState.Failed || e.PipelineStateInfo.State == PipelineState.Stopped) { _eventHandle.Set(); } } private System.Threading.ManualResetEvent _eventHandle = new System.Threading.ManualResetEvent(false); } internal void ExecuteCommandAsync(string command, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(!useNestedPipelines, "can't async invoke a nested pipeline"); Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); bool addToHistory = (options & ExecutionOptions.AddToHistory) > 0; Pipeline tempPipeline = _parent.RunspaceRef.CreatePipeline(command, addToHistory, false); ExecuteCommandAsyncHelper(tempPipeline, out exceptionThrown, options); } internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(!_isPromptFunctionExecutor, "should not async invoke the prompt"); exceptionThrown = null; Executor oldCurrent = CurrentExecutor; CurrentExecutor = this; lock (_instanceStateLock) { Dbg.Assert(_pipeline == null, "no other pipeline should exist"); _pipeline = tempPipeline; } try { if ((options & ExecutionOptions.AddOutputter) > 0 && _parent.OutputFormat == Serialization.DataFormat.Text) { // Tell the script command to merge it's output and error streams if (tempPipeline.Commands.Count == 1) { tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } // then add out-default to the pipeline to render everything... Command outDefault = new Command("Out-Default", /* isScript */false, /* useLocalScope */ true); tempPipeline.Commands.Add(outDefault); } tempPipeline.Output.DataReady += new EventHandler(OutputObjectStreamHandler); tempPipeline.Error.DataReady += new EventHandler(ErrorObjectStreamHandler); PipelineFinishedWaitHandle waiterThereIsAFlyInMySoup = new PipelineFinishedWaitHandle(tempPipeline); tempPipeline.InvokeAsync(); if ((options & ExecutionOptions.ReadInputObjects) > 0 && Console.IsInputRedirected) { // read input objects from stdin WrappedDeserializer des = new WrappedDeserializer(_parent.InputFormat, "Input", Console.In); while (!des.AtEnd) { object o = des.Deserialize(); if (o == null) { break; } try { tempPipeline.Input.Write(o); } catch (PipelineClosedException) { //This exception can occurs when input is closed. This can happen //for various reasons. For ex:Command in the pipeline is invalid and //command discovery throws excecption which closes the pipeline and //hence the Input pipe. break; } }; des.End(); } tempPipeline.Input.Close(); waiterThereIsAFlyInMySoup.Wait(); //report error if pipeline failed if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason != null) { if (_parent.OutputFormat == Serialization.DataFormat.Text) { //Report the exception using normal error reporting exceptionThrown = tempPipeline.PipelineStateInfo.Reason; } else { //serialize the error record AsyncPipelineFailureHandler(tempPipeline.PipelineStateInfo.Reason); } } } catch (Exception e) { ConsoleHost.CheckForSevereException(e); exceptionThrown = e; } finally { // Once we have the results, or an exception is thrown, we throw away the pipeline. _parent.ui.ResetProgress(); CurrentExecutor = oldCurrent; Reset(); } } #endregion async internal Pipeline CreatePipeline() { if (useNestedPipelines) { return _parent.RunspaceRef.CreateNestedPipeline(); } else { return _parent.RunspaceRef.CreatePipeline(); } } internal Pipeline CreatePipeline(string command, bool addToHistory) { Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); return _parent.RunspaceRef.CreatePipeline(command, addToHistory, useNestedPipelines); } /// <summary> /// /// All calls to the Runspace to execute a command line must be done with this function, which properly synchronizes /// access to the running pipeline between the main thread and the break handler thread. This synchronization is /// necessary so that executions can be aborted with Ctrl-C (including evaluation of the prompt and collection of /// command-completion candidates. /// /// On any given Executor instance, ExecuteCommand should be called at most once at a time by any one thread. It is NOT /// reentrant. /// /// </summary> /// <param name="command"> /// /// The command line to be executed. Must be non-null. /// /// </param> /// <param name="exceptionThrown"> /// /// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null. /// Can be tested to see if the execution was successful or not. /// /// </param> /// <param name="options"> /// /// options to govern the execution /// /// </param> /// <returns> /// /// the object stream resulting from the execution. May be null. /// /// </returns> internal Collection<PSObject> ExecuteCommand(string command, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); Pipeline tempPipeline = CreatePipeline(command, (options & ExecutionOptions.AddToHistory) > 0); return ExecuteCommandHelper(tempPipeline, out exceptionThrown, options); } private Command GetOutDefaultCommand(bool endOfStatement) { return new Command(command: "Out-Default", isScript: false, useLocalScope: true, mergeUnclaimedPreviousErrorResults: true) { IsEndOfStatement = endOfStatement }; } internal Collection<PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(tempPipeline != null, "command should have a value"); exceptionThrown = null; Collection<PSObject> results = null; if ((options & ExecutionOptions.AddOutputter) > 0) { if (tempPipeline.Commands.Count < 2) { if (tempPipeline.Commands.Count == 1) { // Tell the script command to merge it's output and error streams. tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } // Add Out-Default to the pipeline to render. tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false)); } else { // For multiple commands/scripts we need to insert Out-Default at the end of each statement. CommandCollection executeCommands = new CommandCollection(); foreach (var cmd in tempPipeline.Commands) { executeCommands.Add(cmd); if (cmd.IsEndOfStatement) { // End of statement needs to pipe to Out-Default. cmd.IsEndOfStatement = false; executeCommands.Add(GetOutDefaultCommand(endOfStatement: true)); } } var lastCmd = executeCommands.Last(); if (!((lastCmd.CommandText != null) && (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase))) ) { // Ensure pipeline output goes to Out-Default. executeCommands.Add(GetOutDefaultCommand(endOfStatement: false)); } tempPipeline.Commands.Clear(); foreach (var cmd in executeCommands) { tempPipeline.Commands.Add(cmd); } } } Executor oldCurrent = CurrentExecutor; CurrentExecutor = this; lock (_instanceStateLock) { Dbg.Assert(_pipeline == null, "no other pipeline should exist"); _pipeline = tempPipeline; } try { // blocks until all results are retrieved. results = tempPipeline.Invoke(); } catch (Exception e) { ConsoleHost.CheckForSevereException(e); exceptionThrown = e; } finally { // Once we have the results, or an exception is thrown, we throw away the pipeline. _parent.ui.ResetProgress(); CurrentExecutor = oldCurrent; Reset(); } return results; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Needed by ProfileTests as mentioned in bug 140572")] internal Collection<PSObject> ExecuteCommand(string command) { Collection<PSObject> result = null; Exception e = null; do { result = ExecuteCommand(command, out e, ExecutionOptions.None); if (e != null) { break; } if (result == null) { break; } } while (false); return result; } /// <summary> /// /// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a string. Any Exception /// thrown in the course of execution is returned thru the exceptionThrown parameter. /// /// </summary> /// <param name="command"> /// /// The command to execute. May be any valid monad command. /// /// </param> /// <param name="exceptionThrown"> /// /// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null. /// Can be tested to see if the execution was successful or not. /// /// </param> /// <returns> /// /// The string representation of the first result object returned, or null if an exception was thrown or no objects were /// returned by the command. /// /// </returns> internal string ExecuteCommandAndGetResultAsString(string command, out Exception exceptionThrown) { exceptionThrown = null; string result = null; do { Collection<PSObject> streamResults = ExecuteCommand(command, out exceptionThrown, ExecutionOptions.None); if (exceptionThrown != null) { break; } if (streamResults == null || streamResults.Count == 0) { break; } // we got back one or more objects. Pick off the first result. if (streamResults[0] == null) return String.Empty; // And convert the base object into a string. We can't use the proxied // ToString() on the PSObject because there is no default runspace // available. PSObject msho = streamResults[0] as PSObject; if (msho != null) result = msho.BaseObject.ToString(); else result = streamResults[0].ToString(); } while (false); return result; } /// <summary> /// /// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a bool. Any Exception /// thrown in the course of execution is caught and ignored. /// /// </summary> /// <param name="command"> /// /// The command to execute. May be any valid monad command. /// /// </param> /// <returns> /// /// The Nullable`bool representation of the first result object returned, or null if an exception was thrown or no /// objects were returned by the command. /// /// </returns> internal Nullable<bool> ExecuteCommandAndGetResultAsBool(string command) { Exception unused = null; Nullable<bool> result = ExecuteCommandAndGetResultAsBool(command, out unused); return result; } /// <summary> /// /// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a bool. Any Exception /// thrown in the course of execution is returned thru the exceptionThrown parameter. /// /// </summary> /// <param name="command"> /// /// The command to execute. May be any valid monad command. /// /// </param> /// <param name="exceptionThrown"> /// /// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null. /// Can be tested to see if the execution was successful or not. /// /// </param> /// <returns> /// /// The Nullable`bool representation of the first result object returned, or null if an exception was thrown or no /// objects were returned by the command. /// /// </returns> internal Nullable<bool> ExecuteCommandAndGetResultAsBool(string command, out Exception exceptionThrown) { exceptionThrown = null; Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); Nullable<bool> result = null; do { Collection<PSObject> streamResults = ExecuteCommand(command, out exceptionThrown, ExecutionOptions.None); if (exceptionThrown != null) { break; } if (streamResults == null || streamResults.Count == 0) { break; } // we got back one or more objects. result = (streamResults.Count > 1) || (LanguagePrimitives.IsTrue(streamResults[0])); } while (false); return result; } /// <summary> /// /// Cancels execution of the current instance. If the current instance is not running, then does nothing. Called in /// response to a break handler, by the static Executor.Cancel method. /// /// </summary> private void Cancel() { // if there's a pipeline running, stop it. lock (_instanceStateLock) { if (_pipeline != null && !_cancelled) { _cancelled = true; if (_isPromptFunctionExecutor) { System.Threading.Thread.Sleep(100); } _pipeline.Stop(); } } } internal void BlockCommandOutput() { RemotePipeline remotePipeline = _pipeline as RemotePipeline; if (remotePipeline != null) { // Waits until queued data is handled. remotePipeline.DrainIncomingData(); // Blocks any new data. remotePipeline.SuspendIncomingData(); } } internal void ResumeCommandOutput() { RemotePipeline remotePipeline = _pipeline as RemotePipeline; if (remotePipeline != null) { // Resumes data flow. remotePipeline.ResumeIncomingData(); } } /// <summary> /// /// Resets the instance to its post-ctor state. Does not cancel execution. /// /// </summary> private void Reset() { lock (_instanceStateLock) { _pipeline = null; _cancelled = false; } } /// <summary> /// /// Makes the given instance the "current" instance, that is, the instance that will receive a Cancel call if the break /// handler is triggered and calls the static Cancel method. /// /// </summary> /// <value> /// /// The instance to make current. Null is allowed. /// /// </value> /// <remarks> /// /// Here are some state-transition cases to illustrate the use of CurrentExecutor /// /// null is current /// p1.ExecuteCommand /// set p1 as current /// promptforparams /// tab complete /// p2.ExecuteCommand /// set p2 as current /// p2.Execute completes /// restore old current to p1 /// p1.Execute completes /// restore null as current /// /// Here's another case: /// null is current /// p1.ExecuteCommand /// set p1 as current /// ShouldProcess - suspend /// EnterNestedPrompt /// set null as current so that break does not exit the subshell /// evaluate prompt /// p2.ExecuteCommand /// set p2 as current /// Execute completes /// restore null as current /// nested loop exit /// restore p1 as current /// /// Summary: /// ExecuteCommand always saves/sets/restores CurrentExector /// Host.EnterNestedPrompt always saves/clears/restores CurrentExecutor /// /// </remarks> internal static Executor CurrentExecutor { get { Executor result = null; lock (s_staticStateLock) { result = s_currentExecutor; } return result; } set { lock (s_staticStateLock) { // null is acceptable. s_currentExecutor = value; } } } /// <summary> /// /// Cancels the execution of the current instance (the instance last passed to PushCurrentExecutor), if any. If no /// instance is Current, then does nothing. /// /// </summary> internal static void CancelCurrentExecutor() { Executor temp = null; lock (s_staticStateLock) { temp = s_currentExecutor; } if (temp != null) { temp.Cancel(); } } // These statics are threadsafe, as there can be only one instance of ConsoleHost in a process at a time, and access // to currentExecutor is guarded by staticStateLock, and static initializers are run by the CLR at program init time. private static Executor s_currentExecutor; private static object s_staticStateLock = new object(); private ConsoleHost _parent; private Pipeline _pipeline; private bool _cancelled; internal bool useNestedPipelines; private object _instanceStateLock = new object(); private bool _isPromptFunctionExecutor; } } // namespace
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation hybrid runbook worker group. (see /// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations /// for more information) /// </summary> internal partial class HybridRunbookWorkerGroupOperations : IServiceOperations<AutomationManagementClient>, IHybridRunbookWorkerGroupOperations { /// <summary> /// Initializes a new instance of the /// HybridRunbookWorkerGroupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal HybridRunbookWorkerGroupOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Delete a hybrid runbook worker group. (see /// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. Automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// Required. The hybrid runbook worker group name /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (hybridRunbookWorkerGroupName == null) { throw new ArgumentNullException("hybridRunbookWorkerGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("hybridRunbookWorkerGroupName", hybridRunbookWorkerGroupName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/hybridRunbookWorkerGroups/"; url = url + Uri.EscapeDataString(hybridRunbookWorkerGroupName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve a hybrid runbook worker group. (see /// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// Required. The hybrid runbook worker group name /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get hybrid runbook worker group /// operation. /// </returns> public async Task<HybridRunbookWorkerGroupGetResponse> GetAsync(string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (hybridRunbookWorkerGroupName == null) { throw new ArgumentNullException("hybridRunbookWorkerGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("hybridRunbookWorkerGroupName", hybridRunbookWorkerGroupName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/hybridRunbookWorkerGroups/"; url = url + Uri.EscapeDataString(hybridRunbookWorkerGroupName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result HybridRunbookWorkerGroupGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new HybridRunbookWorkerGroupGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { HybridRunbookWorkerGroup hybridRunbookWorkerGroupInstance = new HybridRunbookWorkerGroup(); result.HybridRunbookWorkerGroup = hybridRunbookWorkerGroupInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); hybridRunbookWorkerGroupInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); hybridRunbookWorkerGroupInstance.Name = nameInstance; } JToken hybridRunbookWorkersArray = responseDoc["hybridRunbookWorkers"]; if (hybridRunbookWorkersArray != null && hybridRunbookWorkersArray.Type != JTokenType.Null) { foreach (JToken hybridRunbookWorkersValue in ((JArray)hybridRunbookWorkersArray)) { HybridRunbookWorker hybridRunbookWorkerInstance = new HybridRunbookWorker(); hybridRunbookWorkerGroupInstance.HybridRunbookWorkers.Add(hybridRunbookWorkerInstance); JToken nameValue2 = hybridRunbookWorkersValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); hybridRunbookWorkerInstance.Name = nameInstance2; } JToken ipAddressValue = hybridRunbookWorkersValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); hybridRunbookWorkerInstance.IpAddress = ipAddressInstance; } JToken lastSeenDateTimeValue = hybridRunbookWorkersValue["lastSeenDateTime"]; if (lastSeenDateTimeValue != null && lastSeenDateTimeValue.Type != JTokenType.Null) { DateTimeOffset lastSeenDateTimeInstance = ((DateTimeOffset)lastSeenDateTimeValue); hybridRunbookWorkerInstance.LastSeenDateTime = lastSeenDateTimeInstance; } JToken registrationTimeValue = hybridRunbookWorkersValue["registrationTime"]; if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null) { DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue); hybridRunbookWorkerInstance.RegistrationDateTime = registrationTimeInstance; } } } JToken credentialValue = responseDoc["credential"]; if (credentialValue != null && credentialValue.Type != JTokenType.Null) { RunAsCredentialAssociationProperty credentialInstance = new RunAsCredentialAssociationProperty(); hybridRunbookWorkerGroupInstance.Credential = credentialInstance; JToken nameValue3 = credentialValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); credentialInstance.Name = nameInstance3; } } JToken groupTypeValue = responseDoc["groupType"]; if (groupTypeValue != null && groupTypeValue.Type != JTokenType.Null) { string groupTypeInstance = ((string)groupTypeValue); hybridRunbookWorkerGroupInstance.GroupType = groupTypeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve a list of hybrid runbook worker groups. (see /// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list job stream's stream /// items operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list hybrid runbook worker groups. /// </returns> public async Task<HybridRunbookWorkerGroupsListResponse> ListAsync(string resourceGroupName, string automationAccount, HybridRunbookWorkerGroupListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/hybridRunbookWorkerGroups"; List<string> queryParameters = new List<string>(); List<string> odataFilter = new List<string>(); if (parameters != null && parameters.GroupType != null) { odataFilter.Add("groupType eq '" + Uri.EscapeDataString(parameters.GroupType) + "'"); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result HybridRunbookWorkerGroupsListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new HybridRunbookWorkerGroupsListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { HybridRunbookWorkerGroup hybridRunbookWorkerGroupInstance = new HybridRunbookWorkerGroup(); result.HybridRunbookWorkerGroups.Add(hybridRunbookWorkerGroupInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); hybridRunbookWorkerGroupInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); hybridRunbookWorkerGroupInstance.Name = nameInstance; } JToken hybridRunbookWorkersArray = valueValue["hybridRunbookWorkers"]; if (hybridRunbookWorkersArray != null && hybridRunbookWorkersArray.Type != JTokenType.Null) { foreach (JToken hybridRunbookWorkersValue in ((JArray)hybridRunbookWorkersArray)) { HybridRunbookWorker hybridRunbookWorkerInstance = new HybridRunbookWorker(); hybridRunbookWorkerGroupInstance.HybridRunbookWorkers.Add(hybridRunbookWorkerInstance); JToken nameValue2 = hybridRunbookWorkersValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); hybridRunbookWorkerInstance.Name = nameInstance2; } JToken ipAddressValue = hybridRunbookWorkersValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); hybridRunbookWorkerInstance.IpAddress = ipAddressInstance; } JToken lastSeenDateTimeValue = hybridRunbookWorkersValue["lastSeenDateTime"]; if (lastSeenDateTimeValue != null && lastSeenDateTimeValue.Type != JTokenType.Null) { DateTimeOffset lastSeenDateTimeInstance = ((DateTimeOffset)lastSeenDateTimeValue); hybridRunbookWorkerInstance.LastSeenDateTime = lastSeenDateTimeInstance; } JToken registrationTimeValue = hybridRunbookWorkersValue["registrationTime"]; if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null) { DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue); hybridRunbookWorkerInstance.RegistrationDateTime = registrationTimeInstance; } } } JToken credentialValue = valueValue["credential"]; if (credentialValue != null && credentialValue.Type != JTokenType.Null) { RunAsCredentialAssociationProperty credentialInstance = new RunAsCredentialAssociationProperty(); hybridRunbookWorkerGroupInstance.Credential = credentialInstance; JToken nameValue3 = credentialValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); credentialInstance.Name = nameInstance3; } } JToken groupTypeValue = valueValue["groupType"]; if (groupTypeValue != null && groupTypeValue.Type != JTokenType.Null) { string groupTypeInstance = ((string)groupTypeValue); hybridRunbookWorkerGroupInstance.GroupType = groupTypeInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of hybrid runbook worker groups. (see /// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations /// for more information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list hybrid runbook worker groups. /// </returns> public async Task<HybridRunbookWorkerGroupsListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result HybridRunbookWorkerGroupsListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new HybridRunbookWorkerGroupsListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { HybridRunbookWorkerGroup hybridRunbookWorkerGroupInstance = new HybridRunbookWorkerGroup(); result.HybridRunbookWorkerGroups.Add(hybridRunbookWorkerGroupInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); hybridRunbookWorkerGroupInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); hybridRunbookWorkerGroupInstance.Name = nameInstance; } JToken hybridRunbookWorkersArray = valueValue["hybridRunbookWorkers"]; if (hybridRunbookWorkersArray != null && hybridRunbookWorkersArray.Type != JTokenType.Null) { foreach (JToken hybridRunbookWorkersValue in ((JArray)hybridRunbookWorkersArray)) { HybridRunbookWorker hybridRunbookWorkerInstance = new HybridRunbookWorker(); hybridRunbookWorkerGroupInstance.HybridRunbookWorkers.Add(hybridRunbookWorkerInstance); JToken nameValue2 = hybridRunbookWorkersValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); hybridRunbookWorkerInstance.Name = nameInstance2; } JToken ipAddressValue = hybridRunbookWorkersValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); hybridRunbookWorkerInstance.IpAddress = ipAddressInstance; } JToken lastSeenDateTimeValue = hybridRunbookWorkersValue["lastSeenDateTime"]; if (lastSeenDateTimeValue != null && lastSeenDateTimeValue.Type != JTokenType.Null) { DateTimeOffset lastSeenDateTimeInstance = ((DateTimeOffset)lastSeenDateTimeValue); hybridRunbookWorkerInstance.LastSeenDateTime = lastSeenDateTimeInstance; } JToken registrationTimeValue = hybridRunbookWorkersValue["registrationTime"]; if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null) { DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue); hybridRunbookWorkerInstance.RegistrationDateTime = registrationTimeInstance; } } } JToken credentialValue = valueValue["credential"]; if (credentialValue != null && credentialValue.Type != JTokenType.Null) { RunAsCredentialAssociationProperty credentialInstance = new RunAsCredentialAssociationProperty(); hybridRunbookWorkerGroupInstance.Credential = credentialInstance; JToken nameValue3 = credentialValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); credentialInstance.Name = nameInstance3; } } JToken groupTypeValue = valueValue["groupType"]; if (groupTypeValue != null && groupTypeValue.Type != JTokenType.Null) { string groupTypeInstance = ((string)groupTypeValue); hybridRunbookWorkerGroupInstance.GroupType = groupTypeInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a hybrid runbook worker group. (see /// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// Required. The hybrid runbook worker group name /// </param> /// <param name='parameters'> /// Required. The hybrid runbook worker group /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the patch hybrid runbook worker group /// operation. /// </returns> public async Task<HybridRunbookWorkerGroupPatchResponse> PatchAsync(string resourceGroupName, string automationAccount, string hybridRunbookWorkerGroupName, HybridRunbookWorkerGroupPatchParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (hybridRunbookWorkerGroupName == null) { throw new ArgumentNullException("hybridRunbookWorkerGroupName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("hybridRunbookWorkerGroupName", hybridRunbookWorkerGroupName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/hybridRunbookWorkerGroups/"; url = url + Uri.EscapeDataString(hybridRunbookWorkerGroupName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject hybridRunbookWorkerGroupPatchParametersValue = new JObject(); requestDoc = hybridRunbookWorkerGroupPatchParametersValue; if (parameters.Credential != null) { JObject credentialValue = new JObject(); hybridRunbookWorkerGroupPatchParametersValue["credential"] = credentialValue; if (parameters.Credential.Name != null) { credentialValue["name"] = parameters.Credential.Name; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result HybridRunbookWorkerGroupPatchResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new HybridRunbookWorkerGroupPatchResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { HybridRunbookWorkerGroup hybridRunbookWorkerGroupInstance = new HybridRunbookWorkerGroup(); result.HybridRunbookWorkerGroup = hybridRunbookWorkerGroupInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); hybridRunbookWorkerGroupInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); hybridRunbookWorkerGroupInstance.Name = nameInstance; } JToken hybridRunbookWorkersArray = responseDoc["hybridRunbookWorkers"]; if (hybridRunbookWorkersArray != null && hybridRunbookWorkersArray.Type != JTokenType.Null) { foreach (JToken hybridRunbookWorkersValue in ((JArray)hybridRunbookWorkersArray)) { HybridRunbookWorker hybridRunbookWorkerInstance = new HybridRunbookWorker(); hybridRunbookWorkerGroupInstance.HybridRunbookWorkers.Add(hybridRunbookWorkerInstance); JToken nameValue2 = hybridRunbookWorkersValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); hybridRunbookWorkerInstance.Name = nameInstance2; } JToken ipAddressValue = hybridRunbookWorkersValue["ipAddress"]; if (ipAddressValue != null && ipAddressValue.Type != JTokenType.Null) { string ipAddressInstance = ((string)ipAddressValue); hybridRunbookWorkerInstance.IpAddress = ipAddressInstance; } JToken lastSeenDateTimeValue = hybridRunbookWorkersValue["lastSeenDateTime"]; if (lastSeenDateTimeValue != null && lastSeenDateTimeValue.Type != JTokenType.Null) { DateTimeOffset lastSeenDateTimeInstance = ((DateTimeOffset)lastSeenDateTimeValue); hybridRunbookWorkerInstance.LastSeenDateTime = lastSeenDateTimeInstance; } JToken registrationTimeValue = hybridRunbookWorkersValue["registrationTime"]; if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null) { DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue); hybridRunbookWorkerInstance.RegistrationDateTime = registrationTimeInstance; } } } JToken credentialValue2 = responseDoc["credential"]; if (credentialValue2 != null && credentialValue2.Type != JTokenType.Null) { RunAsCredentialAssociationProperty credentialInstance = new RunAsCredentialAssociationProperty(); hybridRunbookWorkerGroupInstance.Credential = credentialInstance; JToken nameValue3 = credentialValue2["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); credentialInstance.Name = nameInstance3; } } JToken groupTypeValue = responseDoc["groupType"]; if (groupTypeValue != null && groupTypeValue.Type != JTokenType.Null) { string groupTypeInstance = ((string)groupTypeValue); hybridRunbookWorkerGroupInstance.GroupType = groupTypeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using Orleans.Concurrency; using Orleans.MultiCluster; using Orleans.LogConsistency; using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Core; using Orleans.Runtime; using Orleans.Storage; namespace Orleans.EventSourcing { /// <summary> /// A base class for log-consistent grains using standard event-sourcing terminology. /// All operations are reentrancy-safe. /// <typeparam name="TGrainState">The type for the grain state, i.e. the aggregate view of the event log.</typeparam> /// </summary> public abstract class JournaledGrain<TGrainState> : JournaledGrain<TGrainState, object> where TGrainState : class, new() { protected JournaledGrain() { } /// <summary> /// This constructor is particularly useful for unit testing where test code can create a Grain and replace /// the IGrainIdentity, IGrainRuntime and State with test doubles (mocks/stubs). /// </summary> protected JournaledGrain(IGrainIdentity identity, IGrainRuntime runtime) : base(identity, runtime) { } } /// <summary> /// A base class for log-consistent grains using standard event-sourcing terminology. /// All operations are reentrancy-safe. /// <typeparam name="TGrainState">The type for the grain state, i.e. the aggregate view of the event log.</typeparam> /// <typeparam name="TEventBase">The common base class for the events</typeparam> /// </summary> public abstract class JournaledGrain<TGrainState,TEventBase> : LogConsistentGrain<TGrainState>, ILogConsistencyProtocolParticipant, ILogViewAdaptorHost<TGrainState, TEventBase> where TGrainState : class, new() where TEventBase: class { protected JournaledGrain() { } /// <summary> /// This constructor is particularly useful for unit testing where test code can create a Grain and replace /// the IGrainIdentity, IGrainRuntime and State with test doubles (mocks/stubs). /// </summary> protected JournaledGrain(IGrainIdentity identity, IGrainRuntime runtime) : base(identity, runtime) { } /// <summary> /// Raise an event. /// </summary> /// <param name="event">Event to raise</param> /// <returns></returns> protected virtual void RaiseEvent<TEvent>(TEvent @event) where TEvent : TEventBase { if (@event == null) throw new ArgumentNullException("event"); LogViewAdaptor.Submit(@event); } /// <summary> /// Raise multiple events, as an atomic sequence. /// </summary> /// <param name="events">Events to raise</param> /// <returns></returns> protected virtual void RaiseEvents<TEvent>(IEnumerable<TEvent> events) where TEvent : TEventBase { if (events == null) throw new ArgumentNullException("events"); LogViewAdaptor.SubmitRange((IEnumerable<TEventBase>) events); } /// <summary> /// Raise an event conditionally. /// Succeeds only if there are no conflicts, that is, no other events were raised in the meantime. /// </summary> /// <param name="event">Event to raise</param> /// <returns>true if successful, false if there was a conflict.</returns> protected virtual Task<bool> RaiseConditionalEvent<TEvent>(TEvent @event) where TEvent : TEventBase { if (@event == null) throw new ArgumentNullException("event"); return LogViewAdaptor.TryAppend(@event); } /// <summary> /// Raise multiple events, as an atomic sequence, conditionally. /// Succeeds only if there are no conflicts, that is, no other events were raised in the meantime. /// </summary> /// <param name="events">Events to raise</param> /// <returns>true if successful, false if there was a conflict.</returns> protected virtual Task<bool> RaiseConditionalEvents<TEvent>(IEnumerable<TEvent> events) where TEvent : TEventBase { if (events == null) throw new ArgumentNullException("events"); return LogViewAdaptor.TryAppendRange((IEnumerable<TEventBase>) events); } /// <summary> /// The current confirmed state. /// Includes only confirmed events. /// </summary> protected TGrainState State { get { return this.LogViewAdaptor.ConfirmedView; } } /// <summary> /// The version of the current confirmed state. /// Equals the total number of confirmed events. /// </summary> protected int Version { get { return this.LogViewAdaptor.ConfirmedVersion; } } /// <summary> /// Called whenever the tentative state may have changed due to local or remote events. /// <para>Override this to react to changes of the state.</para> /// </summary> protected virtual void OnTentativeStateChanged() { } /// <summary> /// The current tentative state. /// Includes both confirmed and unconfirmed events. /// </summary> protected TGrainState TentativeState { get { return this.LogViewAdaptor.TentativeView; } } /// <summary> /// Called after the confirmed state may have changed (i.e. the confirmed version number is larger). /// <para>Override this to react to changes of the confirmed state.</para> /// </summary> protected virtual void OnStateChanged() { // overridden by journaled grains that want to react to state changes } /// <summary> /// Waits until all previously raised events have been confirmed. /// <para>await this after raising one or more events, to ensure events are persisted before proceeding, or to guarantee strong consistency (linearizability) even if there are multiple instances of this grain</para> /// </summary> /// <returns>a task that completes once the events have been confirmed.</returns> protected Task ConfirmEvents() { return LogViewAdaptor.ConfirmSubmittedEntries(); } /// <summary> /// Retrieves the latest state now, and confirms all previously raised events. /// Effectively, this enforces synchronization with the global state. /// <para>Await this before reading the state to ensure strong consistency (linearizability) even if there are multiple instances of this grain</para> /// </summary> /// <returns>a task that completes once the log has been refreshed and the events have been confirmed.</returns> protected Task RefreshNow() { return LogViewAdaptor.Synchronize(); } /// <summary> /// Returns the current queue of unconfirmed events. /// </summary> public IEnumerable<TEventBase> UnconfirmedEvents { get { return LogViewAdaptor.UnconfirmedSuffix; } } /// <summary> /// By default, upon activation, the journaled grain waits until it has loaded the latest /// view from storage. Subclasses can override this behavior, /// and skip the wait if desired. /// </summary> public override Task OnActivateAsync() { return LogViewAdaptor.Synchronize(); } /// <summary> /// Retrieves a segment of the confirmed event sequence, possibly from storage. /// Throws <see cref="NotSupportedException"/> if the events are not available to read. /// Whether events are available, and for how long, depends on the providers used and how they are configured. /// </summary> /// <param name="fromVersion">the position of the event sequence from which to start</param> /// <param name="toVersion">the position of the event sequence on which to end</param> /// <returns>a task which returns the sequence of events between the two versions</returns> protected Task<IReadOnlyList<TEventBase>> RetrieveConfirmedEvents(int fromVersion, int toVersion) { if (fromVersion < 0) throw new ArgumentException("invalid range", nameof(fromVersion)); if (toVersion < fromVersion || toVersion > LogViewAdaptor.ConfirmedVersion) throw new ArgumentException("invalid range", nameof(toVersion)); return LogViewAdaptor.RetrieveLogSegment(fromVersion, toVersion); } /// <summary> /// Called when the underlying persistence or replication protocol is running into some sort of connection trouble. /// <para>Override this to monitor the health of the log-consistency protocol and/or /// to customize retry delays. /// Any exceptions thrown are caught and logged by the <see cref="ILogConsistencyProvider"/>.</para> /// </summary> /// <returns>The time to wait before retrying</returns> protected virtual void OnConnectionIssue(ConnectionIssue issue) { } /// <summary> /// Called when a previously reported connection issue has been resolved. /// <para>Override this to monitor the health of the log-consistency protocol. /// Any exceptions thrown are caught and logged by the <see cref="ILogConsistencyProvider"/>.</para> /// </summary> protected virtual void OnConnectionIssueResolved(ConnectionIssue issue) { } /// <inheritdoc /> protected IEnumerable<ConnectionIssue> UnresolvedConnectionIssues { get { return LogViewAdaptor.UnresolvedConnectionIssues; } } /// <inheritdoc /> protected void EnableStatsCollection() { LogViewAdaptor.EnableStatsCollection(); } /// <inheritdoc /> protected void DisableStatsCollection() { LogViewAdaptor.DisableStatsCollection(); } /// <inheritdoc /> protected LogConsistencyStatistics GetStats() { return LogViewAdaptor.GetStats(); } /// <summary> /// Defines how to apply events to the state. Unless it is overridden in the subclass, it calls /// a dynamic "Apply" function on the state, with the event as a parameter. /// All exceptions thrown by this method are caught and logged by the log view provider. /// <para>Override this to customize how to transition the state for a given event.</para> /// </summary> /// <param name="state"></param> /// <param name="event"></param> protected virtual void TransitionState(TGrainState state, TEventBase @event) { dynamic s = state; dynamic e = @event; s.Apply(e); } #region internal plumbing /// <summary> /// Adaptor for log consistency protocol. /// Is installed by the log-consistency provider. /// </summary> internal ILogViewAdaptor<TGrainState, TEventBase> LogViewAdaptor { get; private set; } /// <summary> /// Called right after grain is constructed, to install the adaptor. /// The log-consistency provider contains a factory method that constructs the adaptor with chosen types for this grain /// </summary> protected override void InstallAdaptor(ILogViewAdaptorFactory factory, object initialState, string graintypename, IGrainStorage grainStorage, ILogConsistencyProtocolServices services) { // call the log consistency provider to construct the adaptor, passing the type argument LogViewAdaptor = factory.MakeLogViewAdaptor<TGrainState, TEventBase>(this, (TGrainState)initialState, graintypename, grainStorage, services); } /// <summary> /// If there is no log-consistency provider specified, store versioned state using default storage provider /// </summary> protected override ILogViewAdaptorFactory DefaultAdaptorFactory { get { return new StateStorage.DefaultAdaptorFactory(); } } /// <summary> /// called by adaptor to update the view when entries are appended. /// </summary> /// <param name="view">log view</param> /// <param name="entry">log entry</param> void ILogViewAdaptorHost<TGrainState, TEventBase>.UpdateView(TGrainState view, TEventBase entry) { TransitionState(view, entry); } /// <summary> /// Notify log view adaptor of activation (called before user-level OnActivate) /// </summary> async Task ILogConsistencyProtocolParticipant.PreActivateProtocolParticipant() { await LogViewAdaptor.PreOnActivate(); } /// <summary> /// Notify log view adaptor of activation (called after user-level OnActivate) /// </summary> async Task ILogConsistencyProtocolParticipant.PostActivateProtocolParticipant() { await LogViewAdaptor.PostOnActivate(); } /// <summary> /// Notify log view adaptor of deactivation /// </summary> Task ILogConsistencyProtocolParticipant.DeactivateProtocolParticipant() { return LogViewAdaptor.PostOnDeactivate(); } /// <summary> /// Receive a protocol message from other clusters, passed on to log view adaptor. /// </summary> [AlwaysInterleave] Task<ILogConsistencyProtocolMessage> ILogConsistencyProtocolParticipant.OnProtocolMessageReceived(ILogConsistencyProtocolMessage payload) { return LogViewAdaptor.OnProtocolMessageReceived(payload); } /// <summary> /// Receive a configuration change, pass on to log view adaptor. /// </summary> [AlwaysInterleave] Task ILogConsistencyProtocolParticipant.OnMultiClusterConfigurationChange(MultiCluster.MultiClusterConfiguration next) { return LogViewAdaptor.OnMultiClusterConfigurationChange(next); } /// <summary> /// called by adaptor on state change. /// </summary> void ILogViewAdaptorHost<TGrainState, TEventBase>.OnViewChanged(bool tentative, bool confirmed) { if (tentative) OnTentativeStateChanged(); if (confirmed) OnStateChanged(); } /// <summary> /// called by adaptor on connection issues. /// </summary> void IConnectionIssueListener.OnConnectionIssue(ConnectionIssue connectionIssue) { OnConnectionIssue(connectionIssue); } /// <summary> /// called by adaptor when a connection issue is resolved. /// </summary> void IConnectionIssueListener.OnConnectionIssueResolved(ConnectionIssue connectionIssue) { OnConnectionIssueResolved(connectionIssue); } #endregion } }
using J2N.Threading; using Lucene.Net.Documents; using NUnit.Framework; using System; using System.IO; using System.Threading; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using TextField = TextField; [TestFixture] public class TestIndexWriterNRTIsCurrent : LuceneTestCase { public class ReaderHolder { internal volatile DirectoryReader reader; internal volatile bool stop = false; } [Test] public virtual void TestIsCurrentWithThreads() { Directory dir = NewDirectory(); IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); IndexWriter writer = new IndexWriter(dir, conf); ReaderHolder holder = new ReaderHolder(); ReaderThread[] threads = new ReaderThread[AtLeast(3)]; CountdownEvent latch = new CountdownEvent(1); WriterThread writerThread = new WriterThread(holder, writer, AtLeast(500), Random, latch); for (int i = 0; i < threads.Length; i++) { threads[i] = new ReaderThread(holder, latch); threads[i].Start(); } writerThread.Start(); writerThread.Join(); bool failed = writerThread.failed != null; if (failed) { Console.WriteLine(writerThread.failed.ToString()); Console.Write(writerThread.failed.StackTrace); } for (int i = 0; i < threads.Length; i++) { threads[i].Join(); if (threads[i].failed != null) { Console.WriteLine(threads[i].failed.ToString()); Console.Write(threads[i].failed.StackTrace); failed = true; } } Assert.IsFalse(failed); writer.Dispose(); dir.Dispose(); } public class WriterThread : ThreadJob { internal readonly ReaderHolder holder; internal readonly IndexWriter writer; internal readonly int numOps; internal bool countdown = true; internal readonly CountdownEvent latch; internal Exception failed; internal WriterThread(ReaderHolder holder, IndexWriter writer, int numOps, Random random, CountdownEvent latch) : base() { this.holder = holder; this.writer = writer; this.numOps = numOps; this.latch = latch; } public override void Run() { DirectoryReader currentReader = null; Random random = LuceneTestCase.Random; try { Document doc = new Document(); doc.Add(new TextField("id", "1", Field.Store.NO)); writer.AddDocument(doc); holder.reader = currentReader = writer.GetReader(true); Term term = new Term("id"); for (int i = 0; i < numOps && !holder.stop; i++) { float nextOp = (float)random.NextDouble(); if (nextOp < 0.3) { term.Set("id", new BytesRef("1")); writer.UpdateDocument(term, doc); } else if (nextOp < 0.5) { writer.AddDocument(doc); } else { term.Set("id", new BytesRef("1")); writer.DeleteDocuments(term); } if (holder.reader != currentReader) { holder.reader = currentReader; if (countdown) { countdown = false; latch.Signal(); } } if (random.NextBoolean()) { writer.Commit(); DirectoryReader newReader = DirectoryReader.OpenIfChanged(currentReader); if (newReader != null) { currentReader.DecRef(); currentReader = newReader; } if (currentReader.NumDocs == 0) { writer.AddDocument(doc); } } } } catch (Exception e) { failed = e; } finally { holder.reader = null; if (countdown) { latch.Signal(); } if (currentReader != null) { try { currentReader.DecRef(); } #pragma warning disable 168 catch (IOException e) #pragma warning restore 168 { } } } if (Verbose) { Console.WriteLine("writer stopped - forced by reader: " + holder.stop); } } } public sealed class ReaderThread : ThreadJob { internal readonly ReaderHolder holder; internal readonly CountdownEvent latch; internal Exception failed; internal ReaderThread(ReaderHolder holder, CountdownEvent latch) : base() { this.holder = holder; this.latch = latch; } public override void Run() { #if FEATURE_THREAD_INTERRUPT try { #endif latch.Wait(); #if FEATURE_THREAD_INTERRUPT } catch (ThreadInterruptedException e) { failed = e; return; } #endif DirectoryReader reader; while ((reader = holder.reader) != null) { if (reader.TryIncRef()) { try { bool current = reader.IsCurrent(); if (Verbose) { Console.WriteLine("Thread: " + Thread.CurrentThread + " Reader: " + reader + " isCurrent:" + current); } Assert.IsFalse(current); } catch (Exception e) { if (Verbose) { Console.WriteLine("FAILED Thread: " + Thread.CurrentThread + " Reader: " + reader + " isCurrent: false"); } failed = e; holder.stop = true; return; } finally { try { reader.DecRef(); } catch (IOException e) { if (failed == null) { failed = e; } } } return; } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Security { internal class SslState { private static int s_uniqueNameInteger = 123; private static AsyncProtocolCallback s_partialFrameCallback = new AsyncProtocolCallback(PartialFrameCallback); private static AsyncProtocolCallback s_readFrameCallback = new AsyncProtocolCallback(ReadFrameCallback); private static AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback); private SslAuthenticationOptions _sslAuthenticationOptions; private Stream _innerStream; private SslStreamInternal _secureStream; private int _nestedAuth; private SecureChannel _context; private bool _handshakeCompleted; private bool _shutdown; private SecurityStatusPal _securityStatus; private ExceptionDispatchInfo _exception; private enum CachedSessionStatus : byte { Unknown = 0, IsNotCached = 1, IsCached = 2, Renegotiated = 3 } private CachedSessionStatus _CachedSession; // This block is used by re-handshake code to buffer data decrypted with the old key. private byte[] _queuedReadData; private int _queuedReadCount; private bool _pendingReHandshake; private const int MaxQueuedReadBytes = 1024 * 128; // // This block is used to rule the >>re-handshakes<< that are concurrent with read/write I/O requests. // private const int LockNone = 0; private const int LockWrite = 1; private const int LockHandshake = 2; private const int LockPendingWrite = 3; private const int LockRead = 4; private const int LockPendingRead = 6; private int _lockWriteState; private object _queuedWriteStateRequest; private int _lockReadState; private object _queuedReadStateRequest; // // The public Client and Server classes enforce the parameters rules before // calling into this .ctor. // internal SslState(Stream innerStream) { _innerStream = innerStream; } internal void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthenticationOptions) { if (_exception != null) { _exception.Throw(); } if (Context != null && Context.IsValidContext) { throw new InvalidOperationException(SR.net_auth_reauth); } if (Context != null && IsServer) { throw new InvalidOperationException(SR.net_auth_client_server); } if (sslClientAuthenticationOptions.TargetHost == null) { throw new ArgumentNullException(nameof(sslClientAuthenticationOptions.TargetHost)); } if (sslClientAuthenticationOptions.TargetHost.Length == 0) { sslClientAuthenticationOptions.TargetHost = "?" + Interlocked.Increment(ref s_uniqueNameInteger).ToString(NumberFormatInfo.InvariantInfo); } _exception = null; try { _sslAuthenticationOptions = new SslAuthenticationOptions(sslClientAuthenticationOptions); _context = new SecureChannel(_sslAuthenticationOptions); } catch (Win32Exception e) { throw new AuthenticationException(SR.net_auth_SSPI, e); } } internal void ValidateCreateContext(SslServerAuthenticationOptions sslServerAuthenticationOptions) { if (_exception != null) { _exception.Throw(); } if (Context != null && Context.IsValidContext) { throw new InvalidOperationException(SR.net_auth_reauth); } if (Context != null && !IsServer) { throw new InvalidOperationException(SR.net_auth_client_server); } if (sslServerAuthenticationOptions.ServerCertificate == null) { throw new ArgumentNullException(nameof(sslServerAuthenticationOptions.ServerCertificate)); } _exception = null; try { _sslAuthenticationOptions = new SslAuthenticationOptions(sslServerAuthenticationOptions); _context = new SecureChannel(_sslAuthenticationOptions); } catch (Win32Exception e) { throw new AuthenticationException(SR.net_auth_SSPI, e); } } internal SslApplicationProtocol NegotiatedApplicationProtocol { get { if (Context == null) return default; return Context.NegotiatedApplicationProtocol; } } internal bool IsAuthenticated { get { return _context != null && _context.IsValidContext && _exception == null && HandshakeCompleted; } } internal bool IsMutuallyAuthenticated { get { return IsAuthenticated && (Context.IsServer ? Context.LocalServerCertificate : Context.LocalClientCertificate) != null && Context.IsRemoteCertificateAvailable; /* does not work: Context.IsMutualAuthFlag;*/ } } internal bool RemoteCertRequired { get { return Context == null || Context.RemoteCertRequired; } } internal bool IsServer { get { return Context != null && Context.IsServer; } } // // This will return selected local cert for both client/server streams // internal X509Certificate LocalCertificate { get { CheckThrow(true); return InternalLocalCertificate; } } private X509Certificate InternalLocalCertificate { get { return Context.IsServer ? Context.LocalServerCertificate : Context.LocalClientCertificate; } } internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) { return (Context == null) ? null : Context.GetChannelBinding(kind); } internal bool CheckCertRevocationStatus { get { return Context != null && Context.CheckCertRevocationStatus != X509RevocationMode.NoCheck; } } internal bool IsShutdown { get { return _shutdown; } } internal CipherAlgorithmType CipherAlgorithm { get { CheckThrow(true); SslConnectionInfo info = Context.ConnectionInfo; if (info == null) { return CipherAlgorithmType.None; } return (CipherAlgorithmType)info.DataCipherAlg; } } internal int CipherStrength { get { CheckThrow(true); SslConnectionInfo info = Context.ConnectionInfo; if (info == null) { return 0; } return info.DataKeySize; } } internal HashAlgorithmType HashAlgorithm { get { CheckThrow(true); SslConnectionInfo info = Context.ConnectionInfo; if (info == null) { return (HashAlgorithmType)0; } return (HashAlgorithmType)info.DataHashAlg; } } internal int HashStrength { get { CheckThrow(true); SslConnectionInfo info = Context.ConnectionInfo; if (info == null) { return 0; } return info.DataHashKeySize; } } internal ExchangeAlgorithmType KeyExchangeAlgorithm { get { CheckThrow(true); SslConnectionInfo info = Context.ConnectionInfo; if (info == null) { return (ExchangeAlgorithmType)0; } return (ExchangeAlgorithmType)info.KeyExchangeAlg; } } internal int KeyExchangeStrength { get { CheckThrow(true); SslConnectionInfo info = Context.ConnectionInfo; if (info == null) { return 0; } return info.KeyExchKeySize; } } internal SslProtocols SslProtocol { get { CheckThrow(true); SslConnectionInfo info = Context.ConnectionInfo; if (info == null) { return SslProtocols.None; } SslProtocols proto = (SslProtocols)info.Protocol; SslProtocols ret = SslProtocols.None; #pragma warning disable 0618 // Ssl2, Ssl3 are deprecated. // Restore client/server bits so the result maps exactly on published constants. if ((proto & SslProtocols.Ssl2) != 0) { ret |= SslProtocols.Ssl2; } if ((proto & SslProtocols.Ssl3) != 0) { ret |= SslProtocols.Ssl3; } #pragma warning restore if ((proto & SslProtocols.Tls) != 0) { ret |= SslProtocols.Tls; } if ((proto & SslProtocols.Tls11) != 0) { ret |= SslProtocols.Tls11; } if ((proto & SslProtocols.Tls12) != 0) { ret |= SslProtocols.Tls12; } return ret; } } internal Stream InnerStream { get { return _innerStream; } } internal SslStreamInternal SecureStream { get { CheckThrow(true); if (_secureStream == null) { Interlocked.CompareExchange<SslStreamInternal>(ref _secureStream, new SslStreamInternal(this), null); } return _secureStream; } } internal int MaxDataSize { get { return Context.MaxDataSize; } } private ExceptionDispatchInfo SetException(Exception e) { Debug.Assert(e != null, $"Expected non-null Exception to be passed to {nameof(SetException)}"); if (_exception == null) { _exception = ExceptionDispatchInfo.Capture(e); } if (_exception != null && Context != null) { Context.Close(); } return _exception; } private bool HandshakeCompleted { get { return _handshakeCompleted; } } private SecureChannel Context { get { return _context; } } internal void CheckThrow(bool authSuccessCheck, bool shutdownCheck = false) { if (_exception != null) { _exception.Throw(); } if (authSuccessCheck && !IsAuthenticated) { throw new InvalidOperationException(SR.net_auth_noauth); } if (shutdownCheck && _shutdown) { throw new InvalidOperationException(SR.net_ssl_io_already_shutdown); } } internal void Flush() { InnerStream.Flush(); } internal Task FlushAsync(CancellationToken cancellationToken) { return InnerStream.FlushAsync(cancellationToken); } // // This is to not depend on GC&SafeHandle class if the context is not needed anymore. // internal void Close() { _exception = ExceptionDispatchInfo.Capture(new ObjectDisposedException("SslStream")); if (Context != null) { Context.Close(); } } internal SecurityStatusPal EncryptData(ReadOnlyMemory<byte> buffer, ref byte[] outBuffer, out int outSize) { CheckThrow(true); return Context.Encrypt(buffer, ref outBuffer, out outSize); } internal SecurityStatusPal DecryptData(byte[] buffer, ref int offset, ref int count) { CheckThrow(true); return PrivateDecryptData(buffer, ref offset, ref count); } private SecurityStatusPal PrivateDecryptData(byte[] buffer, ref int offset, ref int count) { return Context.Decrypt(buffer, ref offset, ref count); } // // Called by re-handshake if found data decrypted with the old key // private Exception EnqueueOldKeyDecryptedData(byte[] buffer, int offset, int count) { lock (this) { if (_queuedReadCount + count > MaxQueuedReadBytes) { return new IOException(SR.Format(SR.net_auth_ignored_reauth, MaxQueuedReadBytes.ToString(NumberFormatInfo.CurrentInfo))); } if (count != 0) { // This is inefficient yet simple and that should be a rare case of receiving data encrypted with "old" key. _queuedReadData = EnsureBufferSize(_queuedReadData, _queuedReadCount, _queuedReadCount + count); Buffer.BlockCopy(buffer, offset, _queuedReadData, _queuedReadCount, count); _queuedReadCount += count; FinishHandshakeRead(LockHandshake); } } return null; } // // When re-handshaking the "old" key decrypted data are queued until the handshake is done. // When stream calls for decryption we will feed it queued data left from "old" encryption key. // // Must be called under the lock in case concurrent handshake is going. // internal int CheckOldKeyDecryptedData(byte[] buffer, int offset, int count) { CheckThrow(true); if (_queuedReadData != null) { // This is inefficient yet simple and should be a REALLY rare case. int toCopy = Math.Min(_queuedReadCount, count); Buffer.BlockCopy(_queuedReadData, 0, buffer, offset, toCopy); _queuedReadCount -= toCopy; if (_queuedReadCount == 0) { _queuedReadData = null; } else { Buffer.BlockCopy(_queuedReadData, toCopy, _queuedReadData, 0, _queuedReadCount); } return toCopy; } return -1; } // // This method assumes that a SSPI context is already in a good shape. // For example it is either a fresh context or already authenticated context that needs renegotiation. // internal void ProcessAuthentication(LazyAsyncResult lazyResult) { if (Interlocked.Exchange(ref _nestedAuth, 1) == 1) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, lazyResult == null ? "BeginAuthenticate" : "Authenticate", "authenticate")); } try { CheckThrow(false); AsyncProtocolRequest asyncRequest = null; if (lazyResult != null) { asyncRequest = new AsyncProtocolRequest(lazyResult); asyncRequest.Buffer = null; #if DEBUG lazyResult._debugAsyncChain = asyncRequest; #endif } // A trick to discover and avoid cached sessions. _CachedSession = CachedSessionStatus.Unknown; ForceAuthentication(Context.IsServer, null, asyncRequest); // Not aync so the connection is completed at this point. if (lazyResult == null && NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Log.SspiSelectedCipherSuite(nameof(ProcessAuthentication), SslProtocol, CipherAlgorithm, CipherStrength, HashAlgorithm, HashStrength, KeyExchangeAlgorithm, KeyExchangeStrength); } } catch (Exception) { // If an exception emerges synchronously, the asynchronous operation was not // initiated, so no operation is in progress. _nestedAuth = 0; throw; } finally { // For synchronous operations, the operation has completed. if (lazyResult == null) { _nestedAuth = 0; } } } // // This is used to reply on re-handshake when received SEC_I_RENEGOTIATE on Read(). // internal void ReplyOnReAuthentication(byte[] buffer) { lock (this) { // Note we are already inside the read, so checking for already going concurrent handshake. _lockReadState = LockHandshake; if (_pendingReHandshake) { // A concurrent handshake is pending, resume. FinishRead(buffer); return; } } // Start rehandshake from here. // Forcing async mode. The caller will queue another Read as soon as we return using its preferred // calling convention, which will be woken up when the handshake completes. The callback is just // to capture any SocketErrors that happen during the handshake so they can be surfaced from the Read. AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(new LazyAsyncResult(this, null, new AsyncCallback(RehandshakeCompleteCallback))); // Buffer contains a result from DecryptMessage that will be passed to ISC/ASC asyncRequest.Buffer = buffer; ForceAuthentication(false, buffer, asyncRequest); } // // This method attempts to start authentication. // Incoming buffer is either null or is the result of "renegotiate" decrypted message // If write is in progress the method will either wait or be put on hold // private void ForceAuthentication(bool receiveFirst, byte[] buffer, AsyncProtocolRequest asyncRequest) { if (CheckEnqueueHandshake(buffer, asyncRequest)) { // Async handshake is enqueued and will resume later. return; } // Either Sync handshake is ready to go or async handshake won the race over write. // This will tell that we don't know the framing yet (what SSL version is) _Framing = Framing.Unknown; try { if (receiveFirst) { // Listen for a client blob. StartReceiveBlob(buffer, asyncRequest); } else { // We start with the first blob. StartSendBlob(buffer, (buffer == null ? 0 : buffer.Length), asyncRequest); } } catch (Exception e) { // Failed auth, reset the framing if any. _Framing = Framing.Unknown; _handshakeCompleted = false; if (SetException(e).SourceException == e) { throw; } else { _exception.Throw(); } } finally { if (_exception != null) { // This a failed handshake. Release waiting IO if any. FinishHandshake(null, null); } } } internal void EndProcessAuthentication(IAsyncResult result) { if (result == null) { throw new ArgumentNullException("asyncResult"); } LazyAsyncResult lazyResult = result as LazyAsyncResult; if (lazyResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult"); } if (Interlocked.Exchange(ref _nestedAuth, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate")); } InternalEndProcessAuthentication(lazyResult); // Connection is completed at this point. if (NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Log.SspiSelectedCipherSuite(nameof(EndProcessAuthentication), SslProtocol, CipherAlgorithm, CipherStrength, HashAlgorithm, HashStrength, KeyExchangeAlgorithm, KeyExchangeStrength); } } internal void InternalEndProcessAuthentication(LazyAsyncResult lazyResult) { // No "artificial" timeouts implemented so far, InnerStream controls that. lazyResult.InternalWaitForCompletion(); Exception e = lazyResult.Result as Exception; if (e != null) { // Failed auth, reset the framing if any. _Framing = Framing.Unknown; _handshakeCompleted = false; SetException(e).Throw(); } } // // Client side starts here, but server also loops through this method. // private void StartSendBlob(byte[] incoming, int count, AsyncProtocolRequest asyncRequest) { ProtocolToken message = Context.NextMessage(incoming, 0, count); _securityStatus = message.Status; if (message.Size != 0) { if (Context.IsServer && _CachedSession == CachedSessionStatus.Unknown) { // //[Schannel] If the first call to ASC returns a token less than 200 bytes, // then it's a reconnect (a handshake based on a cache entry). // _CachedSession = message.Size < 200 ? CachedSessionStatus.IsCached : CachedSessionStatus.IsNotCached; } if (_Framing == Framing.Unified) { _Framing = DetectFraming(message.Payload, message.Payload.Length); } if (asyncRequest == null) { InnerStream.Write(message.Payload, 0, message.Size); } else { asyncRequest.AsyncState = message; Task t = InnerStream.WriteAsync(message.Payload, 0, message.Size); if (t.IsCompleted) { t.GetAwaiter().GetResult(); } else { IAsyncResult ar = TaskToApm.Begin(t, s_writeCallback, asyncRequest); if (!ar.CompletedSynchronously) { #if DEBUG asyncRequest._DebugAsyncChain = ar; #endif return; } TaskToApm.End(ar); } } } CheckCompletionBeforeNextReceive(message, asyncRequest); } // // This will check and logically complete / fail the auth handshake. // private void CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) { if (message.Failed) { StartSendAuthResetSignal(null, asyncRequest, ExceptionDispatchInfo.Capture(new AuthenticationException(SR.net_auth_SSPI, message.GetException()))); return; } else if (message.Done && !_pendingReHandshake) { ProtocolToken alertToken = null; if (!CompleteHandshake(ref alertToken)) { StartSendAuthResetSignal(alertToken, asyncRequest, ExceptionDispatchInfo.Capture(new AuthenticationException(SR.net_ssl_io_cert_validation, null))); return; } // Release waiting IO if any. Presumably it should not throw. // Otherwise application may get not expected type of the exception. FinishHandshake(null, asyncRequest); return; } StartReceiveBlob(message.Payload, asyncRequest); } // // Server side starts here, but client also loops through this method. // private void StartReceiveBlob(byte[] buffer, AsyncProtocolRequest asyncRequest) { if (_pendingReHandshake) { if (CheckEnqueueHandshakeRead(ref buffer, asyncRequest)) { return; } if (!_pendingReHandshake) { // Renegotiate: proceed to the next step. ProcessReceivedBlob(buffer, buffer.Length, asyncRequest); return; } } //This is first server read. buffer = EnsureBufferSize(buffer, 0, SecureChannel.ReadHeaderSize); int readBytes = 0; if (asyncRequest == null) { readBytes = FixedSizeReader.ReadPacket(_innerStream, buffer, 0, SecureChannel.ReadHeaderSize); } else { asyncRequest.SetNextRequest(buffer, 0, SecureChannel.ReadHeaderSize, s_partialFrameCallback); FixedSizeReader.ReadPacketAsync(_innerStream, asyncRequest); if (!asyncRequest.MustCompleteSynchronously) { return; } readBytes = asyncRequest.Result; } StartReadFrame(buffer, readBytes, asyncRequest); } // private void StartReadFrame(byte[] buffer, int readBytes, AsyncProtocolRequest asyncRequest) { if (readBytes == 0) { // EOF received throw new IOException(SR.net_auth_eof); } if (_Framing == Framing.Unknown) { _Framing = DetectFraming(buffer, readBytes); } int restBytes = GetRemainingFrameSize(buffer, 0, readBytes); if (restBytes < 0) { throw new IOException(SR.net_ssl_io_frame); } if (restBytes == 0) { // EOF received throw new AuthenticationException(SR.net_auth_eof, null); } buffer = EnsureBufferSize(buffer, readBytes, readBytes + restBytes); if (asyncRequest == null) { restBytes = FixedSizeReader.ReadPacket(_innerStream, buffer, readBytes, restBytes); } else { asyncRequest.SetNextRequest(buffer, readBytes, restBytes, s_readFrameCallback); FixedSizeReader.ReadPacketAsync(_innerStream, asyncRequest); if (!asyncRequest.MustCompleteSynchronously) { return; } restBytes = asyncRequest.Result; if (restBytes == 0) { //EOF received: fail. readBytes = 0; } } ProcessReceivedBlob(buffer, readBytes + restBytes, asyncRequest); } private void ProcessReceivedBlob(byte[] buffer, int count, AsyncProtocolRequest asyncRequest) { if (count == 0) { // EOF received. throw new AuthenticationException(SR.net_auth_eof, null); } if (_pendingReHandshake) { int offset = 0; SecurityStatusPal status = PrivateDecryptData(buffer, ref offset, ref count); if (status.ErrorCode == SecurityStatusPalErrorCode.OK) { Exception e = EnqueueOldKeyDecryptedData(buffer, offset, count); if (e != null) { StartSendAuthResetSignal(null, asyncRequest, ExceptionDispatchInfo.Capture(e)); return; } _Framing = Framing.Unknown; StartReceiveBlob(buffer, asyncRequest); return; } else if (status.ErrorCode != SecurityStatusPalErrorCode.Renegotiate) { // Fail re-handshake. ProtocolToken message = new ProtocolToken(null, status); StartSendAuthResetSignal(null, asyncRequest, ExceptionDispatchInfo.Capture(new AuthenticationException(SR.net_auth_SSPI, message.GetException()))); return; } // We expect only handshake messages from now. _pendingReHandshake = false; if (offset != 0) { Buffer.BlockCopy(buffer, offset, buffer, 0, count); } } StartSendBlob(buffer, count, asyncRequest); } // // This is to reset auth state on remote side. // If this write succeeds we will allow auth retrying. // private void StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception) { if (message == null || message.Size == 0) { // // We don't have an alert to send so cannot retry and fail prematurely. // exception.Throw(); } if (asyncRequest == null) { InnerStream.Write(message.Payload, 0, message.Size); } else { asyncRequest.AsyncState = exception; Task t = InnerStream.WriteAsync(message.Payload, 0, message.Size); if (t.IsCompleted) { t.GetAwaiter().GetResult(); } else { IAsyncResult ar = TaskToApm.Begin(t, s_writeCallback, asyncRequest); if (!ar.CompletedSynchronously) { return; } TaskToApm.End(ar); } } exception.Throw(); } // - Loads the channel parameters // - Optionally verifies the Remote Certificate // - Sets HandshakeCompleted flag // - Sets the guarding event if other thread is waiting for // handshake completion // // - Returns false if failed to verify the Remote Cert // private bool CompleteHandshake(ref ProtocolToken alertToken) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); Context.ProcessHandshakeSuccess(); if (!Context.VerifyRemoteCertificate(_sslAuthenticationOptions.CertValidationDelegate, ref alertToken)) { _handshakeCompleted = false; if (NetEventSource.IsEnabled) NetEventSource.Exit(this, false); return false; } _handshakeCompleted = true; if (NetEventSource.IsEnabled) NetEventSource.Exit(this, true); return true; } private static void WriteCallback(IAsyncResult transportResult) { if (transportResult.CompletedSynchronously) { return; } AsyncProtocolRequest asyncRequest; SslState sslState; #if DEBUG try { #endif asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState; sslState = (SslState)asyncRequest.AsyncObject; #if DEBUG } catch (Exception exception) when (!ExceptionCheck.IsFatal(exception)) { NetEventSource.Fail(null, $"Exception while decoding context: {exception}"); throw; } #endif // Async completion. try { TaskToApm.End(transportResult); // Special case for an error notification. object asyncState = asyncRequest.AsyncState; ExceptionDispatchInfo exception = asyncState as ExceptionDispatchInfo; if (exception != null) { exception.Throw(); } sslState.CheckCompletionBeforeNextReceive((ProtocolToken)asyncState, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } sslState.FinishHandshake(e, asyncRequest); } } private static void PartialFrameCallback(AsyncProtocolRequest asyncRequest) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null); // Async ONLY completion. SslState sslState = (SslState)asyncRequest.AsyncObject; try { sslState.StartReadFrame(asyncRequest.Buffer, asyncRequest.Result, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } sslState.FinishHandshake(e, asyncRequest); } } // // private static void ReadFrameCallback(AsyncProtocolRequest asyncRequest) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null); // Async ONLY completion. SslState sslState = (SslState)asyncRequest.AsyncObject; try { if (asyncRequest.Result == 0) { //EOF received: will fail. asyncRequest.Offset = 0; } sslState.ProcessReceivedBlob(asyncRequest.Buffer, asyncRequest.Offset + asyncRequest.Result, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } sslState.FinishHandshake(e, asyncRequest); } } private bool CheckEnqueueHandshakeRead(ref byte[] buffer, AsyncProtocolRequest request) { LazyAsyncResult lazyResult = null; lock (this) { if (_lockReadState == LockPendingRead) { return false; } int lockState = Interlocked.Exchange(ref _lockReadState, LockHandshake); if (lockState != LockRead) { return false; } if (request != null) { _queuedReadStateRequest = request; return true; } lazyResult = new LazyAsyncResult(null, null, /*must be */ null); _queuedReadStateRequest = lazyResult; } // Need to exit from lock before waiting. lazyResult.InternalWaitForCompletion(); buffer = (byte[])lazyResult.Result; return false; } private void FinishHandshakeRead(int newState) { lock (this) { // Lock is redundant here. Included for clarity. int lockState = Interlocked.Exchange(ref _lockReadState, newState); if (lockState != LockPendingRead) { return; } _lockReadState = LockRead; object obj = _queuedReadStateRequest; if (obj == null) { // Other thread did not get under the lock yet. return; } _queuedReadStateRequest = null; if (obj is LazyAsyncResult) { ((LazyAsyncResult)obj).InvokeCallback(); } else { ThreadPool.QueueUserWorkItem(new WaitCallback(CompleteRequestWaitCallback), obj); } } } // Returns: // -1 - proceed // 0 - queued // X - some bytes are ready, no need for IO internal int CheckEnqueueRead(byte[] buffer, int offset, int count, AsyncProtocolRequest request) { int lockState = Interlocked.CompareExchange(ref _lockReadState, LockRead, LockNone); if (lockState != LockHandshake) { // Proceed, no concurrent handshake is ongoing so no need for a lock. return CheckOldKeyDecryptedData(buffer, offset, count); } LazyAsyncResult lazyResult = null; lock (this) { int result = CheckOldKeyDecryptedData(buffer, offset, count); if (result != -1) { return result; } // Check again under lock. if (_lockReadState != LockHandshake) { // The other thread has finished before we grabbed the lock. _lockReadState = LockRead; return -1; } _lockReadState = LockPendingRead; if (request != null) { // Request queued. _queuedReadStateRequest = request; return 0; } lazyResult = new LazyAsyncResult(null, null, /*must be */ null); _queuedReadStateRequest = lazyResult; } // Need to exit from lock before waiting. lazyResult.InternalWaitForCompletion(); lock (this) { return CheckOldKeyDecryptedData(buffer, offset, count); } } internal void FinishRead(byte[] renegotiateBuffer) { int lockState = Interlocked.CompareExchange(ref _lockReadState, LockNone, LockRead); if (lockState != LockHandshake) { return; } lock (this) { LazyAsyncResult ar = _queuedReadStateRequest as LazyAsyncResult; if (ar != null) { _queuedReadStateRequest = null; ar.InvokeCallback(renegotiateBuffer); } else { AsyncProtocolRequest request = (AsyncProtocolRequest)_queuedReadStateRequest; request.Buffer = renegotiateBuffer; _queuedReadStateRequest = null; ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncResumeHandshakeRead), request); } } } internal Task CheckEnqueueWriteAsync() { // Clear previous request. int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockWrite, LockNone); if (lockState != LockHandshake) { return Task.CompletedTask; } lock (this) { if (_lockWriteState != LockHandshake) { CheckThrow(authSuccessCheck: true); return Task.CompletedTask; } _lockWriteState = LockPendingWrite; TaskCompletionSource<int> completionSource = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); _queuedWriteStateRequest = completionSource; return completionSource.Task; } } internal void CheckEnqueueWrite() { // Clear previous request. _queuedWriteStateRequest = null; int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockWrite, LockNone); if (lockState != LockHandshake) { // Proceed with write. return; } LazyAsyncResult lazyResult = null; lock (this) { if (_lockWriteState != LockHandshake) { // Handshake has completed before we grabbed the lock. CheckThrow(authSuccessCheck: true); return; } _lockWriteState = LockPendingWrite; lazyResult = new LazyAsyncResult(null, null, /*must be */null); _queuedWriteStateRequest = lazyResult; } // Need to exit from lock before waiting. lazyResult.InternalWaitForCompletion(); CheckThrow(authSuccessCheck: true); return; } internal void FinishWrite() { int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockNone, LockWrite); if (lockState != LockHandshake) { return; } lock (this) { HandleWriteCallback(); } } private void HandleWriteCallback() { object obj = _queuedWriteStateRequest; _queuedWriteStateRequest = null; switch (obj) { case null: break; case LazyAsyncResult lazy: lazy.InvokeCallback(); break; case TaskCompletionSource<int> tsc: tsc.SetResult(0); break; default: ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncResumeHandshake), obj); break; } } // Returns: // true - operation queued // false - operation can proceed private bool CheckEnqueueHandshake(byte[] buffer, AsyncProtocolRequest asyncRequest) { LazyAsyncResult lazyResult = null; lock (this) { if (_lockWriteState == LockPendingWrite) { return false; } int lockState = Interlocked.Exchange(ref _lockWriteState, LockHandshake); if (lockState != LockWrite) { // Proceed with handshake. return false; } if (asyncRequest != null) { asyncRequest.Buffer = buffer; _queuedWriteStateRequest = asyncRequest; return true; } lazyResult = new LazyAsyncResult(null, null, /*must be*/null); _queuedWriteStateRequest = lazyResult; } lazyResult.InternalWaitForCompletion(); return false; } private void FinishHandshake(Exception e, AsyncProtocolRequest asyncRequest) { try { lock (this) { if (e != null) { SetException(e); } // Release read if any. FinishHandshakeRead(LockNone); // If there is a pending write we want to keep it's lock state. int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockNone, LockHandshake); if (lockState != LockPendingWrite) { return; } _lockWriteState = LockWrite; HandleWriteCallback(); } } finally { if (asyncRequest != null) { if (e != null) { asyncRequest.CompleteUserWithError(e); } else { asyncRequest.CompleteUser(); } } } } private static byte[] EnsureBufferSize(byte[] buffer, int copyCount, int size) { if (buffer == null || buffer.Length < size) { byte[] saved = buffer; buffer = new byte[size]; if (saved != null && copyCount != 0) { Buffer.BlockCopy(saved, 0, buffer, 0, copyCount); } } return buffer; } private enum Framing { Unknown = 0, BeforeSSL3, SinceSSL3, Unified, Invalid } // This is set on the first packet to figure out the framing style. private Framing _Framing = Framing.Unknown; // SSL3/TLS protocol frames definitions. private enum FrameType : byte { ChangeCipherSpec = 20, Alert = 21, Handshake = 22, AppData = 23 } // We need at least 5 bytes to determine what we have. private Framing DetectFraming(byte[] bytes, int length) { /* PCTv1.0 Hello starts with * RECORD_LENGTH_MSB (ignore) * RECORD_LENGTH_LSB (ignore) * PCT1_CLIENT_HELLO (must be equal) * PCT1_CLIENT_VERSION_MSB (if version greater than PCTv1) * PCT1_CLIENT_VERSION_LSB (if version greater than PCTv1) * * ... PCT hello ... */ /* Microsoft Unihello starts with * RECORD_LENGTH_MSB (ignore) * RECORD_LENGTH_LSB (ignore) * SSL2_CLIENT_HELLO (must be equal) * SSL2_CLIENT_VERSION_MSB (if version greater than SSLv2) ( or v3) * SSL2_CLIENT_VERSION_LSB (if version greater than SSLv2) ( or v3) * * ... SSLv2 Compatible Hello ... */ /* SSLv2 CLIENT_HELLO starts with * RECORD_LENGTH_MSB (ignore) * RECORD_LENGTH_LSB (ignore) * SSL2_CLIENT_HELLO (must be equal) * SSL2_CLIENT_VERSION_MSB (if version greater than SSLv2) ( or v3) * SSL2_CLIENT_VERSION_LSB (if version greater than SSLv2) ( or v3) * * ... SSLv2 CLIENT_HELLO ... */ /* SSLv2 SERVER_HELLO starts with * RECORD_LENGTH_MSB (ignore) * RECORD_LENGTH_LSB (ignore) * SSL2_SERVER_HELLO (must be equal) * SSL2_SESSION_ID_HIT (ignore) * SSL2_CERTIFICATE_TYPE (ignore) * SSL2_CLIENT_VERSION_MSB (if version greater than SSLv2) ( or v3) * SSL2_CLIENT_VERSION_LSB (if version greater than SSLv2) ( or v3) * * ... SSLv2 SERVER_HELLO ... */ /* SSLv3 Type 2 Hello starts with * RECORD_LENGTH_MSB (ignore) * RECORD_LENGTH_LSB (ignore) * SSL2_CLIENT_HELLO (must be equal) * SSL2_CLIENT_VERSION_MSB (if version greater than SSLv3) * SSL2_CLIENT_VERSION_LSB (if version greater than SSLv3) * * ... SSLv2 Compatible Hello ... */ /* SSLv3 Type 3 Hello starts with * 22 (HANDSHAKE MESSAGE) * VERSION MSB * VERSION LSB * RECORD_LENGTH_MSB (ignore) * RECORD_LENGTH_LSB (ignore) * HS TYPE (CLIENT_HELLO) * 3 bytes HS record length * HS Version * HS Version */ /* SSLv2 message codes * SSL_MT_ERROR 0 * SSL_MT_CLIENT_HELLO 1 * SSL_MT_CLIENT_MASTER_KEY 2 * SSL_MT_CLIENT_FINISHED 3 * SSL_MT_SERVER_HELLO 4 * SSL_MT_SERVER_VERIFY 5 * SSL_MT_SERVER_FINISHED 6 * SSL_MT_REQUEST_CERTIFICATE 7 * SSL_MT_CLIENT_CERTIFICATE 8 */ int version = -1; if ((bytes == null || bytes.Length <= 0)) { NetEventSource.Fail(this, "Header buffer is not allocated."); } // If the first byte is SSL3 HandShake, then check if we have a SSLv3 Type3 client hello. if (bytes[0] == (byte)FrameType.Handshake || bytes[0] == (byte)FrameType.AppData || bytes[0] == (byte)FrameType.Alert) { if (length < 3) { return Framing.Invalid; } #if TRACE_VERBOSE if (bytes[1] != 3 && NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"WARNING: SslState::DetectFraming() SSL protocol is > 3, trying SSL3 framing in retail = {bytes[i]:x}"); } #endif version = (bytes[1] << 8) | bytes[2]; if (version < 0x300 || version >= 0x500) { return Framing.Invalid; } // // This is an SSL3 Framing // return Framing.SinceSSL3; } #if TRACE_VERBOSE if ((bytes[0] & 0x80) == 0 && NetEventSource.IsEnabled) { // We have a three-byte header format if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"WARNING: SslState::DetectFraming() SSL v <=2 HELLO has no high bit set for 3 bytes header, we are broken, received byte = {bytes[0]:x}"); } #endif if (length < 3) { return Framing.Invalid; } if (bytes[2] > 8) { return Framing.Invalid; } if (bytes[2] == 0x1) // SSL_MT_CLIENT_HELLO { if (length >= 5) { version = (bytes[3] << 8) | bytes[4]; } } else if (bytes[2] == 0x4) // SSL_MT_SERVER_HELLO { if (length >= 7) { version = (bytes[5] << 8) | bytes[6]; } } if (version != -1) { // If this is the first packet, the client may start with an SSL2 packet // but stating that the version is 3.x, so check the full range. // For the subsequent packets we assume that an SSL2 packet should have a 2.x version. if (_Framing == Framing.Unknown) { if (version != 0x0002 && (version < 0x200 || version >= 0x500)) { return Framing.Invalid; } } else { if (version != 0x0002) { return Framing.Invalid; } } } // When server has replied the framing is already fixed depending on the prior client packet if (!Context.IsServer || _Framing == Framing.Unified) { return Framing.BeforeSSL3; } return Framing.Unified; // Will use Ssl2 just for this frame. } // // This is called from SslStream class too. internal int GetRemainingFrameSize(byte[] buffer, int offset, int dataSize) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, buffer, offset, dataSize); int payloadSize = -1; switch (_Framing) { case Framing.Unified: case Framing.BeforeSSL3: if (dataSize < 2) { throw new System.IO.IOException(SR.net_ssl_io_frame); } // Note: Cannot detect version mismatch for <= SSL2 if ((buffer[offset] & 0x80) != 0) { // Two bytes payloadSize = (((buffer[offset] & 0x7f) << 8) | buffer[offset + 1]) + 2; payloadSize -= dataSize; } else { // Three bytes payloadSize = (((buffer[offset] & 0x3f) << 8) | buffer[offset + 1]) + 3; payloadSize -= dataSize; } break; case Framing.SinceSSL3: if (dataSize < 5) { throw new System.IO.IOException(SR.net_ssl_io_frame); } payloadSize = ((buffer[offset + 3] << 8) | buffer[offset + 4]) + 5; payloadSize -= dataSize; break; default: break; } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, payloadSize); return payloadSize; } // // Called with no user stack. // private void AsyncResumeHandshake(object state) { AsyncProtocolRequest request = state as AsyncProtocolRequest; Debug.Assert(request != null, "Expected an AsyncProtocolRequest reference."); try { ForceAuthentication(Context.IsServer, request.Buffer, request); } catch (Exception e) { request.CompleteUserWithError(e); } } // // Called with no user stack. // private void AsyncResumeHandshakeRead(object state) { AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)state; try { if (_pendingReHandshake) { // Resume as read a blob. StartReceiveBlob(asyncRequest.Buffer, asyncRequest); } else { // Resume as process the blob. ProcessReceivedBlob(asyncRequest.Buffer, asyncRequest.Buffer == null ? 0 : asyncRequest.Buffer.Length, asyncRequest); } } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } FinishHandshake(e, asyncRequest); } } // // Called with no user stack. // private void CompleteRequestWaitCallback(object state) { AsyncProtocolRequest request = (AsyncProtocolRequest)state; // Force async completion. if (request.MustCompleteSynchronously) { throw new InternalException(); } request.CompleteRequest(0); } private void RehandshakeCompleteCallback(IAsyncResult result) { LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)result; if (lazyAsyncResult == null) { NetEventSource.Fail(this, "result is null!"); } if (!lazyAsyncResult.InternalPeekCompleted) { NetEventSource.Fail(this, "result is not completed!"); } // If the rehandshake succeeded, FinishHandshake has already been called; if there was a SocketException // during the handshake, this gets called directly from FixedSizeReader, and we need to call // FinishHandshake to wake up the Read that triggered this rehandshake so the error gets back to the caller Exception exception = lazyAsyncResult.InternalWaitForCompletion() as Exception; if (exception != null) { // We may be calling FinishHandshake reentrantly, as FinishHandshake can call // asyncRequest.CompleteWithError, which will result in this method being called. // This is not a problem because: // // 1. We pass null as the asyncRequest parameter, so this second call to FinishHandshake won't loop // back here. // // 2. _QueuedWriteStateRequest and _QueuedReadStateRequest are set to null after the first call, // so, we won't invoke their callbacks again. // // 3. SetException won't overwrite an already-set _Exception. // // 4. There are three possibilities for _LockReadState and _LockWriteState: // // a. They were set back to None by the first call to FinishHandshake, and this will set them to // None again: a no-op. // // b. They were set to None by the first call to FinishHandshake, but as soon as the lock was given // up, another thread took a read/write lock. Calling FinishHandshake again will set them back // to None, but that's fine because that thread will be throwing _Exception before it actually // does any reading or writing and setting them back to None in a catch block anyways. // // c. If there is a Read/Write going on another thread, and the second FinishHandshake clears its // read/write lock, it's fine because no other Read/Write can look at the lock until the current // one gives up _SslStream._NestedRead/Write, and no handshake will look at the lock because // handshakes are only triggered in response to successful reads (which won't happen once // _Exception is set). FinishHandshake(exception, null); } } internal IAsyncResult BeginShutdown(AsyncCallback asyncCallback, object asyncState) { CheckThrow(authSuccessCheck: true, shutdownCheck: true); ProtocolToken message = Context.CreateShutdownToken(); return TaskToApm.Begin(InnerStream.WriteAsync(message.Payload, 0, message.Payload.Length), asyncCallback, asyncState); } internal void EndShutdown(IAsyncResult result) { CheckThrow(authSuccessCheck: true, shutdownCheck: true); TaskToApm.End(result); _shutdown = true; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Directives.cs" company="Solidsoft Reply Ltd."> // Copyright (c) 2015 Solidsoft Reply Limited. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace SolidsoftReply.Esb.Libraries.Resolution { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using SolidsoftReply.Esb.Libraries.Resolution.ResolutionService; /// <summary> /// Class containing the result of the resolution /// </summary> [Serializable] public class Directives : IEnumerable<Directive> { /// <summary> /// The resolver directive items. /// </summary> private readonly List<Directive> items = new List<Directive>(); /// <summary> /// Initializes a new instance of the <see cref="Directives"/> class. /// </summary> public Directives() { } /// <summary> /// Initializes a new instance of the <see cref="Directives"/> class. /// </summary> /// <param name="interchange"> /// The resolution service interchange object. /// </param> public Directives(Interchange interchange) { if (interchange == null) { return; } if (interchange.Directives == null) { return; } foreach (var rd in interchange.Directives.Select(di => new Directive(di.Value.Directive))) { this.items.Add(rd); } } /// <summary> /// Gets a value indicating whether any of the directives define a service windows. /// Returns true if the current time is in any of those service windows. Otherwise /// returns false. If no service windows are defined, always returns true. /// </summary> public bool InAnyServiceWindow { get { // return 'true' by default for scenarios where no // service window is defined by any directive. var result = true; var anyInWindow = false; var anyOutsideWindow = false; foreach (var directive in this.items) { if (!directive.ServiceWindowStartTimeSpecified || !directive.ServiceWindowStopTimeSpecified) { continue; } // Take a snapshot of the current time var timeNow = DateTime.Now.TimeOfDay; // This directive has a defined service window if (directive.ServiceWindowStartTime.TimeOfDay > timeNow && directive.ServiceWindowStopTime.TimeOfDay <= timeNow) { anyOutsideWindow = true; } else { anyInWindow = true; } } if (anyOutsideWindow && !anyInWindow) { result = false; } return result; } } /// <summary> /// Gets a TimeSpan for the time of day at which the next service window opens. /// If no service window later than now is defined, returns TimeSpan.MaxValue. /// </summary> public TimeSpan NextWindowOpen { get { // Take a snapshot of the current time var timeNow = DateTime.Now.TimeOfDay; TimeSpan[] earliestNext = { TimeSpan.MaxValue }; foreach (var directive in this.items.Where(directive => directive.ServiceWindowStartTimeSpecified && directive.ServiceWindowStopTimeSpecified).Where(directive => directive.ServiceWindowStartTime.TimeOfDay > timeNow && directive.ServiceWindowStartTime.TimeOfDay < earliestNext[0])) { earliestNext[0] = directive.ServiceWindowStartTime.TimeOfDay; } return earliestNext[0]; } } /// <summary> /// Gets a TimeSpan for the time of day at which the current service window closes. /// If no service window later than now is defined, returns TimeSpan.MaxValue. /// </summary> public TimeSpan CurrentWindowClose { get { // Take a snapshot of the current time var timeNow = DateTime.Now.TimeOfDay; TimeSpan[] earliestNext = { TimeSpan.MaxValue }; foreach (var directive in this.items.Where(directive => directive.ServiceWindowStartTimeSpecified && directive.ServiceWindowStopTimeSpecified).Where(directive => directive.ServiceWindowStopTime.TimeOfDay > timeNow && directive.ServiceWindowStopTime.TimeOfDay < earliestNext[0])) { earliestNext[0] = directive.ServiceWindowStopTime.TimeOfDay; } return earliestNext[0]; } } /// <summary> /// Gets the number of directives. /// </summary> public int Count { get { return this.items.Count; } } /// <summary> /// Gets a directive by index. /// </summary> /// <param name="index">The directive index.</param> /// <returns>The indexed resolver directive.</returns> public Directive this[int index] { get { return this.GetDirective(index); } } /// <summary> /// Gets a directive by name. /// </summary> /// <param name="name">The directive name.</param> /// <returns>The named resolver directive.</returns> public Directive this[string name] { get { return this.GetDirective(name); } } /// <summary> /// Returns the indexed directive. /// </summary> /// <param name="index">The directive index.</param> /// <returns>A named resolver directive.</returns> public Directive GetDirective(int index) { if (index > this.items.Count) { throw new EsbResolutionException(Properties.Resources.ExceptionElementNotOnList); } return this.items[index]; } /// <summary> /// Returns the named directive. /// </summary> /// <param name="name">The directive name.</param> /// <returns>A named resolver directive.</returns> public Directive GetDirective(string name) { return this.items.FirstOrDefault(directive => directive.Name == name) ?? new Directive(); } /// <summary> /// Returns the first directive. If no directive exists, returns null. /// </summary> /// <returns>The first directive, or null.</returns> public Directive FirstOrDefault() { return this.items.Count == 0 ? default(Directive) : this.items[0]; } /// <summary> /// Performs all BAM actions for configured BAM steps in all the directives. /// </summary> /// <param name="data">The BAM step data.</param> public void OnStep(BamStepData data) { this.OnStep(data, MultiStepControl.AllSteps, false); } /// <summary> /// Performs all BAM actions for configured BAM steps in all the directives. This method /// can optionally handle step processing after application of a map. /// </summary> /// <param name="data">The BAM step data.</param> /// <param name="afterMap">Indicates if the step is after the application of a map.</param> public void OnStep(BamStepData data, bool afterMap) { this.OnStep(data, MultiStepControl.AllSteps, afterMap); } /// <summary> /// Performs all BAM actions for configured BAM steps in either the first or /// all the directives. Optionally perform BAM actions for all step extensions. /// </summary> /// <param name="data">The BAM step data.</param> /// <param name="depth"> /// Specify the depth of BAM processing; first or all steps and, optionally, /// each step extension. /// </param> public void OnStep(BamStepData data, MultiStepControl depth) { this.OnStep(data, depth, false); } /// <summary> /// Performs all BAM actions for configured BAM steps in either the first or all /// the directives. Optionally perform BAM actions for all step extensions. /// This method can optionally handle step processing after application of a map. /// </summary> /// <param name="data">The BAM step data.</param> /// <param name="depth"> /// Specify the depth of BAM processing; first or all steps and, optionally, /// each step extension. /// </param> /// <param name="afterMap">Indicates if the step is after the application of a map.</param> public void OnStep(BamStepData data, MultiStepControl depth, bool afterMap) { switch (depth) { case MultiStepControl.AllSteps: foreach (var bamDirective in this.items) { bamDirective.OnStep(data, afterMap); } break; case MultiStepControl.AllStepsWithExtensions: foreach (var bamDirective in this.items) { bamDirective.OnStep(data, afterMap); foreach (var extension in bamDirective.BamStepExtensions) { var eventStream = new TrackpointDirectiveEventStream(bamDirective, data); eventStream.SelectBamStepExtension(extension, afterMap); bamDirective.EventStream = eventStream; bamDirective.OnStep(data, afterMap); } } break; case MultiStepControl.FirstStepOnly: this.OnFirstStep(data, afterMap); break; case MultiStepControl.FirstStepWithExtensions: var firstBamDirective = this.items.FirstOrDefault(item => !string.IsNullOrWhiteSpace(item.BamStepName)) ?? this.items.FirstOrDefault(item => !string.IsNullOrWhiteSpace(item.BamAfterMapStepName)); if (firstBamDirective != null) { firstBamDirective.OnStep(data, afterMap); foreach (var extension in firstBamDirective.BamStepExtensions) { var eventStream = new TrackpointDirectiveEventStream(firstBamDirective, data); eventStream.SelectBamStepExtension(extension, afterMap); firstBamDirective.EventStream = eventStream; firstBamDirective.OnStep(data, afterMap); } } break; } } /// <summary> /// Performs all BAM actions for a BAM steps in a specified directive. /// </summary> /// <param name="directiveName">The name of the directive that defines the BAM step.</param> /// <param name="data">The BAM step data.</param> public void OnStep(string directiveName, BamStepData data) { this.OnStep(directiveName, data, false); } /// <summary> /// Performs all BAM actions for a BAM steps in a specified directive. This method can /// optionally handle step processing after application of a map. /// </summary> /// <param name="directiveName">The name of the directive that defines the BAM step.</param> /// <param name="data">The BAM step data.</param> /// <param name="afterMap">Indicates if the step is after the application of a map.</param> public void OnStep(string directiveName, BamStepData data, bool afterMap) { var firstBamDirective = this.items.FirstOrDefault(directive => directive.Name == directiveName); if (firstBamDirective != null) { firstBamDirective.OnStep(data, afterMap); } } /// <summary> /// Return the item enumerator /// </summary> /// <returns>An IEnumerator interface</returns> IEnumerator<Directive> IEnumerable<Directive>.GetEnumerator() { return this.items.GetEnumerator(); } /// <summary> /// Return the item enumerator /// </summary> /// <returns>An IEnumerator interface</returns> public IEnumerator GetEnumerator() { return this.items.GetEnumerator(); } /// <summary> /// Retrieves data for a particular step of a BAM activity for the first directive found that /// defines a step. Call this method on every step in which some data may be needed for BAM /// - e.g., at the point a service is called, or at the point of resolution. /// </summary> /// <param name="data">The BAM step data.</param> /// <param name="afterMap">Indicates if the step is after the application of a map.</param> private void OnFirstStep(BamStepData data, bool afterMap) { var firstBamDirective = this.items.FirstOrDefault(item => !string.IsNullOrWhiteSpace(item.BamStepName)) ?? this.items.FirstOrDefault(item => !string.IsNullOrWhiteSpace(item.BamAfterMapStepName)); if (firstBamDirective != null) { firstBamDirective.OnStep(data, afterMap); } } } }
#region License /* * 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. */ #endregion using System; using System.Reflection; using System.Text; using AopAlliance.Intercept; using Common.Logging; namespace Spring.Aspects.Logging { /// <summary> /// Configurable advice for logging. /// </summary> /// <remarks> /// /// </remarks> /// <author>Mark Pollack</author> [Serializable] public class SimpleLoggingAdvice : AbstractLoggingAdvice { #region Fields /// <summary> /// Flag to indicate if unique identifier should be in the log message. /// </summary> private bool logUniqueIdentifier; /// <summary> /// Flag to indicate if the execution time should be in the log message. /// </summary> private bool logExecutionTime; /// <summary> /// Flag to indicate if the method arguments should be in the log message. /// </summary> private bool logMethodArguments; /// <summary> /// Flag to indicate if the return value should be in the log message. /// </summary> private bool logReturnValue; /// <summary> /// The separator string to use for delmiting log message fields. /// </summary> private string separator = ", "; /// <summary> /// The log level to use for logging the entry, exit, exception messages. /// </summary> private LogLevel logLevel = LogLevel.Trace; #endregion #region Constructor(s) /// <summary> /// Initializes a new instance of the <see cref="SimpleLoggingAdvice"/> class. /// </summary> public SimpleLoggingAdvice() { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLoggingAdvice"/> class. /// </summary> /// <param name="useDynamicLogger">if set to <c>true</c> to use dynamic logger, if /// <c>false</c> use static logger.</param> public SimpleLoggingAdvice(bool useDynamicLogger) { UseDynamicLogger = useDynamicLogger; } /// <summary> /// Initializes a new instance of the <see cref="SimpleLoggingAdvice"/> class. /// </summary> /// <param name="defaultLogger">the default logger to use</param> public SimpleLoggingAdvice(ILog defaultLogger) : base(defaultLogger) {} #endregion #region Properties /// <summary> /// Gets or sets a value indicating whether to log a unique identifier with the log message. /// </summary> /// <value><c>true</c> if [log unique identifier]; otherwise, <c>false</c>.</value> public bool LogUniqueIdentifier { get { return logUniqueIdentifier; } set { logUniqueIdentifier = value; } } /// <summary> /// Gets or sets a value indicating whether to log execution time. /// </summary> /// <value><c>true</c> if log execution time; otherwise, <c>false</c>.</value> public bool LogExecutionTime { get { return logExecutionTime; } set { logExecutionTime = value; } } /// <summary> /// Gets or sets a value indicating whether log method arguments. /// </summary> /// <value><c>true</c> if log method arguments]; otherwise, <c>false</c>.</value> public bool LogMethodArguments { get { return logMethodArguments; } set { logMethodArguments = value; } } /// <summary> /// Gets or sets a value indicating whether log return value. /// </summary> /// <value><c>true</c> if log return value; otherwise, <c>false</c>.</value> public bool LogReturnValue { get { return logReturnValue; } set { logReturnValue = value; } } /// <summary> /// Gets or sets the seperator string to use for delmiting log message fields. /// </summary> /// <value>The seperator.</value> public string Separator { get { return separator; } set { separator = value; } } /// <summary> /// Gets or sets the entry log level. /// </summary> /// <value>The entry log level.</value> public LogLevel LogLevel { get { return logLevel; } set { logLevel = value; } } #endregion #region Protected Methods /// <summary> /// Subclasses must override this method to perform any tracing around the supplied /// IMethodInvocation. /// </summary> /// <param name="invocation">The method invocation to log</param> /// <param name="log">The log to write messages to</param> /// <returns> /// The result of the call to IMethodInvocation.Proceed() /// </returns> /// <remarks> /// Subclasses are resonsible for ensuring that the IMethodInvocation actually executes /// by calling IMethodInvocation.Proceed(). /// <para> /// By default, the passed-in ILog instance will have log level /// "trace" enabled. Subclasses do not have to check for this again, unless /// they overwrite the IsInterceptorEnabled method to modify /// the default behavior. /// </para> /// </remarks> /// <exception cref="System.Exception"> /// If any of the interceptors in the chain or the target object itself /// throws an exception. /// </exception> protected override object InvokeUnderLog(IMethodInvocation invocation, ILog log) { object returnValue = null; bool exitThroughException = false; DateTime startTime = DateTime.Now; string uniqueIdentifier = null; if (LogUniqueIdentifier) { uniqueIdentifier = CreateUniqueIdentifier(); } try { WriteToLog(LogLevel, log, GetEntryMessage(invocation, uniqueIdentifier), null); returnValue = invocation.Proceed(); return returnValue; } catch (Exception e) { TimeSpan executionTimeSpan = DateTime.Now - startTime; WriteToLog(LogLevel, log, GetExceptionMessage(invocation, e, executionTimeSpan, uniqueIdentifier), e); exitThroughException = true; throw; } finally { if (!exitThroughException) { TimeSpan executionTimeSpan = DateTime.Now - startTime; WriteToLog(LogLevel, log, GetExitMessage(invocation, returnValue, executionTimeSpan, uniqueIdentifier), null); } } } /// <summary> /// Determines whether the given log is enabled. /// </summary> /// <param name="log">The log instance to check.</param> /// <returns> /// <c>true</c> if log is for a given log level; otherwise, <c>false</c>. /// </returns> /// <remarks> /// Default is true when the trace level is enabled. Subclasses may override this /// to change the level at which logging occurs, or return true to ignore level /// checks.</remarks> protected override bool IsLogEnabled(ILog log) { switch (LogLevel) { case LogLevel.All: case LogLevel.Trace: if (log.IsTraceEnabled) { return true; } break; case LogLevel.Debug: if (log.IsDebugEnabled) { return true; } break; case LogLevel.Error: if (log.IsErrorEnabled) { return true; } break; case LogLevel.Fatal: if (log.IsFatalEnabled) { return true; } break; case LogLevel.Info: if (log.IsInfoEnabled) { return true; } break; case LogLevel.Warn: if (log.IsWarnEnabled) { return true; } break; case LogLevel.Off: default: break; } return false; } /// <summary> /// Creates a unique identifier. /// </summary> /// <remarks> /// Default implementation uses Guid.NewGuid(). Subclasses may override to provide an alternative /// ID generation implementation. /// </remarks> /// <returns>A unique identifier</returns> protected virtual string CreateUniqueIdentifier() { return Guid.NewGuid().ToString(); } /// <summary> /// Gets the entry message to log /// </summary> /// <param name="invocation">The invocation.</param> /// <param name="idString">The id string.</param> /// <returns>The entry log message</returns> protected virtual string GetEntryMessage(IMethodInvocation invocation, string idString) { StringBuilder sb = new StringBuilder(128); sb.Append("Entering "); AppendCommonInformation(sb, invocation, idString); if (logMethodArguments) { sb.Append(GetMethodArgumentAsString(invocation)); } return RemoveLastSeparator(sb.ToString(), Separator); } /// <summary> /// Gets the exception message. /// </summary> /// <param name="invocation">The method invocation.</param> /// <param name="e">The thown exception.</param> /// <param name="executionTimeSpan">The execution time span.</param> /// <param name="idString">The id string.</param> /// <returns>The exception log message.</returns> protected virtual string GetExceptionMessage(IMethodInvocation invocation, Exception e, TimeSpan executionTimeSpan, string idString) { StringBuilder sb = new StringBuilder(128); sb.Append("Exception thrown in "); sb.Append(invocation.Method.Name).Append(Separator); AppendCommonInformation(sb, invocation, idString); if (LogExecutionTime) { sb.Append(executionTimeSpan.TotalMilliseconds).Append(" ms"); } return RemoveLastSeparator(sb.ToString(), Separator); } /// <summary> /// Gets the exit log message. /// </summary> /// <param name="invocation">The method invocation.</param> /// <param name="returnValue">The return value.</param> /// <param name="executionTimeSpan">The execution time span.</param> /// <param name="idString">The id string.</param> /// <returns>the exit log message</returns> protected virtual string GetExitMessage(IMethodInvocation invocation, object returnValue, TimeSpan executionTimeSpan, string idString) { StringBuilder sb = new StringBuilder(128); sb.Append("Exiting "); AppendCommonInformation(sb, invocation, idString); if (LogReturnValue && invocation.Method.ReturnType != typeof(void)) { sb.Append("return=").Append(returnValue).Append(Separator); } if (LogExecutionTime) { sb.Append(executionTimeSpan.TotalMilliseconds).Append(" ms"); } return RemoveLastSeparator(sb.ToString(), Separator); } /// <summary> /// Appends common information across entry,exit, exception logging /// </summary> /// <remarks>Add method name and unique identifier if required.</remarks> /// <param name="sb">The string buffer building logging message.</param> /// <param name="invocation">The method invocation.</param> /// <param name="idString">The unique identifier string.</param> protected virtual void AppendCommonInformation(StringBuilder sb, IMethodInvocation invocation, string idString) { sb.Append(invocation.Method.Name); if (LogUniqueIdentifier) { sb.Append(Separator).Append(idString); } sb.Append(Separator); } /// <summary> /// Gets the method argument as argumen name/value pairs. /// </summary> /// <param name="invocation">The method invocation.</param> /// <returns>string for logging method argument name and values.</returns> protected virtual string GetMethodArgumentAsString(IMethodInvocation invocation) { StringBuilder sb = new StringBuilder(128); ParameterInfo[] parameterInfos = invocation.Method.GetParameters(); object[] argValues = invocation.Arguments; for (int i=0; i< parameterInfos.Length; i++) { sb.Append(parameterInfos[i].Name).Append("=").Append(argValues[i]); if (i != parameterInfos.Length) sb.Append("; "); } return RemoveLastSeparator(sb.ToString(), "; "); } #endregion #region Private Methods private string RemoveLastSeparator(string str, string separator) { if (str.EndsWith(separator)) { return str.Substring(0, str.Length - separator.Length); } else { return str; } } private void WriteToLog(LogLevel logLevel, ILog log, string text, Exception e) { switch (logLevel) { case LogLevel.All: case LogLevel.Trace: if (log.IsTraceEnabled) { if (e == null) log.Trace(text); else log.Trace(text, e); } break; case LogLevel.Debug: if (log.IsDebugEnabled) { if (e == null) log.Debug(text); else log.Debug(text, e); } break; case LogLevel.Error: if (log.IsErrorEnabled) { if (e == null) log.Error(text); else log.Error(text, e); } break; case LogLevel.Fatal: if (log.IsFatalEnabled) { if (e == null) log.Fatal(text); else log.Fatal(text, e); } break; case LogLevel.Info: if (log.IsInfoEnabled) { if (e == null) log.Info(text); else log.Info(text, e); } break; case LogLevel.Warn: if (log.IsWarnEnabled) { if (e == null) log.Warn(text); else log.Warn(text, e); } break; case LogLevel.Off: default: break; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// Provides support for EventSource activities by marking the start and /// end of a particular operation. /// </summary> internal sealed class EventSourceActivity : IDisposable { /// <summary> /// Initializes a new instance of the EventSourceActivity class that /// is attached to the specified event source. The new activity will /// not be attached to any related (parent) activity. /// The activity is created in the Initialized state. /// </summary> /// <param name="eventSource"> /// The event source to which the activity information is written. /// </param> public EventSourceActivity(EventSource eventSource) { if (eventSource == null) throw new ArgumentNullException("eventSource"); Contract.EndContractBlock(); this.eventSource = eventSource; } /// <summary> /// You can make an activity out of just an EventSource. /// </summary> public static implicit operator EventSourceActivity(EventSource eventSource) { return new EventSourceActivity(eventSource); } /* Properties */ /// <summary> /// Gets the event source to which this activity writes events. /// </summary> public EventSource EventSource { get { return this.eventSource; } } /// <summary> /// Gets this activity's unique identifier, or the default Guid if the /// event source was disabled when the activity was initialized. /// </summary> public Guid Id { get { return this.activityId; } } #if false // don't expose RelatedActivityId unless there is a need. /// <summary> /// Gets the unique identifier of this activity's related (parent) /// activity. /// </summary> public Guid RelatedId { get { return this.relatedActivityId; } } #endif /// <summary> /// Writes a Start event with the specified name and data. If the start event is not active (because the provider /// is not on or keyword-level indiates the event is off, then the returned activity is simply the 'this' poitner /// and it is effectively like the Start d /// /// A new activityID GUID is generated and the returned /// EventSourceActivity remembers this activity and will mark every event (including the start stop and any writes) /// with this activityID. In addition the Start activity will log a 'relatedActivityID' that was the activity /// ID before the start event. This way event processors can form a linked list of all the activities that /// caused this one (directly or indirectly). /// </summary> /// <param name="eventName"> /// The name to use for the event. It is strongly suggested that this name end in 'Start' (e.g. DownloadStart). /// If you do this, then the Stop() method will automatically replace the 'Start' suffix with a 'Stop' suffix. /// </param> /// <param name="options">Allow options (keywords, level) to be set for the write associated with this start /// These will also be used for the stop event.</param> /// <param name="data">The data to include in the event.</param> public EventSourceActivity Start<T>(string eventName, EventSourceOptions options, T data) { return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords /// and level==Info) Data payload is empty. /// </summary> public EventSourceActivity Start(string eventName) { var options = new EventSourceOptions(); var data = new EmptyStruct(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data). Data payload is empty. /// </summary> public EventSourceActivity Start(string eventName, EventSourceOptions options) { var data = new EmptyStruct(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords /// and level==Info) /// </summary> public EventSourceActivity Start<T>(string eventName, T data) { var options = new EventSourceOptions(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Writes a Stop event with the specified data, and sets the activity /// to the Stopped state. The name is determined by the eventName used in Start. /// If that Start event name is suffixed with 'Start' that is removed, and regardless /// 'Stop' is appended to the result to form the Stop event name. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="data">The data to include in the event.</param> public void Stop<T>(T data) { this.Stop(null, ref data); } /// <summary> /// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop') /// This can be useful to indicate unusual ways of stoping (but it is still STRONGLY recommeded that /// you start with the same prefix used for the start event and you end with the 'Stop' suffix. /// </summary> public void Stop<T>(string eventName) { var data = new EmptyStruct(); this.Stop(eventName, ref data); } /// <summary> /// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop') /// This can be useful to indicate unusual ways of stoping (but it is still STRONGLY recommeded that /// you start with the same prefix used for the start event and you end with the 'Stop' suffix. /// </summary> public void Stop<T>(string eventName, T data) { this.Stop(eventName, ref data); } /// <summary> /// Writes an event associated with this activity to the eventSource associted with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. If null, the name is determined from /// data's type. /// </param> /// <param name="options"> /// The options to use for the event. /// </param> /// <param name="data">The data to include in the event.</param> public void Write<T>(string eventName, EventSourceOptions options, T data) { this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes an event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. If null, the name is determined from /// data's type. /// </param> /// <param name="data">The data to include in the event.</param> public void Write<T>(string eventName, T data) { var options = new EventSourceOptions(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes a trivial event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. Must not be null. /// </param> /// <param name="options"> /// The options to use for the event. /// </param> public void Write(string eventName, EventSourceOptions options) { var data = new EmptyStruct(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes a trivial event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. Must not be null. /// </param> public void Write(string eventName) { var options = new EventSourceOptions(); var data = new EmptyStruct(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes an event to a arbitrary eventSource stamped with the activity ID of this activity. /// </summary> public void Write<T>(EventSource source, string eventName, EventSourceOptions options, T data) { this.Write(source, eventName, ref options, ref data); } /// <summary> /// Releases any unmanaged resources associated with this object. /// If the activity is in the Started state, calls Stop(). /// </summary> public void Dispose() { if (this.state == State.Started) { var data = new EmptyStruct(); this.Stop(null, ref data); } } #region private private EventSourceActivity Start<T>(string eventName, ref EventSourceOptions options, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // If the source is not on at all, then we don't need to do anything and we can simply return ourselves. if (!this.eventSource.IsEnabled()) return this; var newActivity = new EventSourceActivity(eventSource); if (!this.eventSource.IsEnabled(options.Level, options.Keywords)) { // newActivity.relatedActivityId = this.Id; Guid relatedActivityId = this.Id; newActivity.activityId = Guid.NewGuid(); newActivity.startStopOptions = options; newActivity.eventName = eventName; newActivity.startStopOptions.Opcode = EventOpcode.Start; this.eventSource.Write(eventName, ref newActivity.startStopOptions, ref newActivity.activityId, ref relatedActivityId, ref data); } else { // If we are not active, we don't set the eventName, which basically also turns off the Stop event as well. newActivity.activityId = this.Id; } return newActivity; } private void Write<T>(EventSource eventSource, string eventName, ref EventSourceOptions options, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // Write after stop. if (eventName == null) throw new ArgumentNullException(); eventSource.Write(eventName, ref options, ref this.activityId, ref s_empty, ref data); } private void Stop<T>(string eventName, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // If start was not fired, then stop isn't as well. if (!StartEventWasFired) return; this.state = State.Stopped; if (eventName == null) { eventName = this.eventName; if (eventName.EndsWith("Start")) eventName = eventName.Substring(0, eventName.Length - 5); eventName = eventName + "Stop"; } this.startStopOptions.Opcode = EventOpcode.Stop; this.eventSource.Write(eventName, ref this.startStopOptions, ref this.activityId, ref s_empty, ref data); } private enum State { Started, Stopped } /// <summary> /// If eventName is non-null then we logged a start event /// </summary> private bool StartEventWasFired { get { return eventName != null; }} private readonly EventSource eventSource; private EventSourceOptions startStopOptions; internal Guid activityId; // internal Guid relatedActivityId; private State state; private string eventName; static internal Guid s_empty; #endregion } }
/* * 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.Linq; using System.Net; using System.Reflection; using System.Text; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Monitoring; using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.PhysicsModules.SharedBase; using OpenSim.Server.Base; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using OpenSim.Services.UserAccountService; namespace OpenSim { /// <summary> /// Common OpenSimulator simulator code /// </summary> public class OpenSimBase : RegionApplicationBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // These are the names of the plugin-points extended by this // class during system startup. // private const string PLUGIN_ASSET_CACHE = "/OpenSim/AssetCache"; private const string PLUGIN_ASSET_SERVER_CLIENT = "/OpenSim/AssetClient"; // OpenSim.ini Section name for ESTATES Settings public const string ESTATE_SECTION_NAME = "Estates"; /// <summary> /// Allow all plugin loading to be disabled for tests/debug. /// </summary> /// <remarks> /// true by default /// </remarks> public bool EnableInitialPluginLoad { get; set; } /// <summary> /// Control whether we attempt to load an estate data service. /// </summary> /// <remarks>For tests/debugging</remarks> public bool LoadEstateDataService { get; set; } protected string proxyUrl; protected int proxyOffset = 0; public string userStatsURI = String.Empty; public string managedStatsURI = String.Empty; public string managedStatsPassword = String.Empty; protected bool m_autoCreateClientStack = true; /// <value> /// The file used to load and save prim backup xml if no filename has been specified /// </value> protected const string DEFAULT_PRIM_BACKUP_FILENAME = "prim-backup.xml"; public ConfigSettings ConfigurationSettings { get { return m_configSettings; } set { m_configSettings = value; } } protected ConfigSettings m_configSettings; protected ConfigurationLoader m_configLoader; public ConsoleCommand CreateAccount = null; public List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>(); private List<string> m_permsModules; private bool m_securePermissionsLoading = true; /// <value> /// The config information passed into the OpenSimulator region server. /// </value> public OpenSimConfigSource ConfigSource { get; private set; } protected EnvConfigSource m_EnvConfigSource = new EnvConfigSource(); public EnvConfigSource envConfigSource { get { return m_EnvConfigSource; } } public uint HttpServerPort { get { return m_httpServerPort; } } protected IRegistryCore m_applicationRegistry = new RegistryCore(); public IRegistryCore ApplicationRegistry { get { return m_applicationRegistry; } } /// <summary> /// Constructor. /// </summary> /// <param name="configSource"></param> public OpenSimBase(IConfigSource configSource) : base() { EnableInitialPluginLoad = true; LoadEstateDataService = true; LoadConfigSettings(configSource); } protected virtual void LoadConfigSettings(IConfigSource configSource) { m_configLoader = new ConfigurationLoader(); ConfigSource = m_configLoader.LoadConfigSettings(configSource, envConfigSource, out m_configSettings, out m_networkServersInfo); Config = ConfigSource.Source; ReadExtraConfigSettings(); } protected virtual void ReadExtraConfigSettings() { IConfig networkConfig = Config.Configs["Network"]; if (networkConfig != null) { proxyUrl = networkConfig.GetString("proxy_url", ""); proxyOffset = Int32.Parse(networkConfig.GetString("proxy_offset", "0")); } IConfig startupConfig = Config.Configs["Startup"]; if (startupConfig != null) { Util.LogOverloads = startupConfig.GetBoolean("LogOverloads", true); } } protected virtual void LoadPlugins() { IConfig startupConfig = Config.Configs["Startup"]; string registryLocation = (startupConfig != null) ? startupConfig.GetString("RegistryLocation", String.Empty) : String.Empty; // The location can also be specified in the environment. If there // is no location in the configuration, we must call the constructor // without a location parameter to allow that to happen. if (registryLocation == String.Empty) { using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this))) { loader.Load("/OpenSim/Startup"); m_plugins = loader.Plugins; } } else { using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this), registryLocation)) { loader.Load("/OpenSim/Startup"); m_plugins = loader.Plugins; } } } protected override List<string> GetHelpTopics() { List<string> topics = base.GetHelpTopics(); Scene s = SceneManager.CurrentOrFirstScene; if (s != null && s.GetCommanders() != null) topics.AddRange(s.GetCommanders().Keys); return topics; } /// <summary> /// Performs startup specific to the region server, including initialization of the scene /// such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { IConfig startupConfig = Config.Configs["Startup"]; if (startupConfig != null) { // refuse to run MegaRegions if(startupConfig.GetBoolean("CombineContiguousRegions", false)) { m_log.Fatal("CombineContiguousRegions (MegaRegions) option is no longer suported. Use a older version to save region contents as OAR, then import into a fresh install of this new version"); throw new Exception("CombineContiguousRegions not suported"); } string pidFile = startupConfig.GetString("PIDFile", String.Empty); if (pidFile != String.Empty) CreatePIDFile(pidFile); userStatsURI = startupConfig.GetString("Stats_URI", String.Empty); m_securePermissionsLoading = startupConfig.GetBoolean("SecurePermissionsLoading", true); string permissionModules = Util.GetConfigVarFromSections<string>(Config, "permissionmodules", new string[] { "Startup", "Permissions" }, "DefaultPermissionsModule"); m_permsModules = new List<string>(permissionModules.Split(',').Select(m => m.Trim())); managedStatsURI = startupConfig.GetString("ManagedStatsRemoteFetchURI", String.Empty); managedStatsPassword = startupConfig.GetString("ManagedStatsRemoteFetchPassword", String.Empty); } // Load the simulation data service IConfig simDataConfig = Config.Configs["SimulationDataStore"]; if (simDataConfig == null) throw new Exception("Configuration file is missing the [SimulationDataStore] section. Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?"); string module = simDataConfig.GetString("LocalServiceModule", String.Empty); if (String.IsNullOrEmpty(module)) throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [SimulationDataStore] section."); m_simulationDataService = ServerUtils.LoadPlugin<ISimulationDataService>(module, new object[] { Config }); if (m_simulationDataService == null) throw new Exception( string.Format( "Could not load an ISimulationDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [SimulationDataStore] config section.", module)); // Load the estate data service module = Util.GetConfigVarFromSections<string>(Config, "LocalServiceModule", new string[]{"EstateDataStore", "EstateService"}, String.Empty); if (String.IsNullOrEmpty(module)) throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [EstateDataStore] or [EstateService] section"); if (LoadEstateDataService) { m_estateDataService = ServerUtils.LoadPlugin<IEstateDataService>(module, new object[] { Config }); if (m_estateDataService == null) throw new Exception( string.Format( "Could not load an IEstateDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [EstateDataStore] config section.", module)); } base.StartupSpecific(); if (EnableInitialPluginLoad) LoadPlugins(); // We still want to post initalize any plugins even if loading has been disabled since a test may have // inserted them manually. foreach (IApplicationPlugin plugin in m_plugins) plugin.PostInitialise(); if (m_console != null) AddPluginCommands(m_console); } protected virtual void AddPluginCommands(ICommandConsole console) { List<string> topics = GetHelpTopics(); foreach (string topic in topics) { string capitalizedTopic = char.ToUpper(topic[0]) + topic.Substring(1); // This is a hack to allow the user to enter the help command in upper or lowercase. This will go // away at some point. console.Commands.AddCommand(capitalizedTopic, false, "help " + topic, "help " + capitalizedTopic, "Get help on plugin command '" + topic + "'", HandleCommanderHelp); console.Commands.AddCommand(capitalizedTopic, false, "help " + capitalizedTopic, "help " + capitalizedTopic, "Get help on plugin command '" + topic + "'", HandleCommanderHelp); ICommander commander = null; Scene s = SceneManager.CurrentOrFirstScene; if (s != null && s.GetCommanders() != null) { if (s.GetCommanders().ContainsKey(topic)) commander = s.GetCommanders()[topic]; } if (commander == null) continue; foreach (string command in commander.Commands.Keys) { console.Commands.AddCommand(capitalizedTopic, false, topic + " " + command, topic + " " + commander.Commands[command].ShortHelp(), String.Empty, HandleCommanderCommand); } } } private void HandleCommanderCommand(string module, string[] cmd) { SceneManager.SendCommandToPluginModules(cmd); } private void HandleCommanderHelp(string module, string[] cmd) { // Only safe for the interactive console, since it won't // let us come here unless both scene and commander exist // ICommander moduleCommander = SceneManager.CurrentOrFirstScene.GetCommander(cmd[1].ToLower()); if (moduleCommander != null) m_console.Output(moduleCommander.Help); } protected override void Initialize() { // Called from base.StartUp() IConfig startupConfig = Config.Configs["Startup"]; if (startupConfig == null || startupConfig.GetBoolean("JobEngineEnabled", true)) WorkManager.JobEngine.Start(); m_httpServerPort = m_networkServersInfo.HttpListenerPort; SceneManager.OnRestartSim += HandleRestartRegion; // Only enable the watchdogs when all regions are ready. Otherwise we get false positives when cpu is // heavily used during initial startup. // // FIXME: It's also possible that region ready status should be flipped during an OAR load since this // also makes heavy use of the CPU. SceneManager.OnRegionsReadyStatusChange += sm => { MemoryWatchdog.Enabled = sm.AllRegionsReady; Watchdog.Enabled = sm.AllRegionsReady; }; } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <param name="portadd_flag"></param> /// <returns></returns> public void CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene) { CreateRegion(regionInfo, portadd_flag, false, out scene); } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <returns></returns> public void CreateRegion(RegionInfo regionInfo, out IScene scene) { CreateRegion(regionInfo, false, true, out scene); } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <param name="portadd_flag"></param> /// <param name="do_post_init"></param> /// <returns></returns> public void CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene) { int port = regionInfo.InternalEndPoint.Port; // set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims) // Commented this out because otherwise regions can't register with // the grid as there is already another region with the same UUID // at those coordinates. This is required for the load balancer to work. // --Mike, 2009.02.25 //regionInfo.originRegionID = regionInfo.RegionID; // set initial ServerURI regionInfo.HttpPort = m_httpServerPort; regionInfo.ServerURI = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort.ToString() + "/"; regionInfo.osSecret = m_osSecret; if ((proxyUrl.Length > 0) && (portadd_flag)) { // set proxy url to RegionInfo regionInfo.proxyUrl = proxyUrl; regionInfo.ProxyOffset = proxyOffset; Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName); } Scene scene = SetupScene(regionInfo, proxyOffset, Config); m_log.Info("[MODULES]: Loading Region's modules (old style)"); // Use this in the future, the line above will be deprecated soon m_log.Info("[REGIONMODULES]: Loading Region's modules (new style)"); IRegionModulesController controller; if (ApplicationRegistry.TryGet(out controller)) { controller.AddRegionToModules(scene); } else m_log.Error("[REGIONMODULES]: The new RegionModulesController is missing..."); if (m_securePermissionsLoading) { foreach (string s in m_permsModules) { if (!scene.RegionModules.ContainsKey(s)) { m_log.Fatal("[MODULES]: Required module " + s + " not found."); Environment.Exit(0); } } m_log.InfoFormat("[SCENE]: Secure permissions loading enabled, modules loaded: {0}", String.Join(" ", m_permsModules.ToArray())); } scene.SetModuleInterfaces(); // First Step of bootreport sequence if (scene.SnmpService != null) { scene.SnmpService.ColdStart(1,scene); scene.SnmpService.LinkDown(scene); } if (scene.SnmpService != null) { scene.SnmpService.BootInfo("Loading prins", scene); } while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null) SetUpEstateOwner(scene); scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID); // Prims have to be loaded after module configuration since some modules may be invoked during the load scene.LoadPrimsFromStorage(regionInfo.originRegionID); // TODO : Try setting resource for region xstats here on scene MainServer.Instance.AddStreamHandler(new RegionStatsHandler(regionInfo)); if (scene.SnmpService != null) { scene.SnmpService.BootInfo("Grid Registration in progress", scene); } try { scene.RegisterRegionWithGrid(); } catch (Exception e) { m_log.ErrorFormat( "[STARTUP]: Registration of region with grid failed, aborting startup due to {0} {1}", e.Message, e.StackTrace); if (scene.SnmpService != null) { scene.SnmpService.Critical("Grid registration failed. Startup aborted.", scene); } // Carrying on now causes a lot of confusion down the // line - we need to get the user's attention Environment.Exit(1); } if (scene.SnmpService != null) { scene.SnmpService.BootInfo("Grid Registration done", scene); } // We need to do this after we've initialized the // scripting engines. scene.CreateScriptInstances(); if (scene.SnmpService != null) { scene.SnmpService.BootInfo("ScriptEngine started", scene); } SceneManager.Add(scene); //if (m_autoCreateClientStack) //{ // foreach (IClientNetworkServer clientserver in clientServers) // { // m_clientServers.Add(clientserver); // clientserver.Start(); // } //} if (scene.SnmpService != null) { scene.SnmpService.BootInfo("Initializing region modules", scene); } scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); }; mscene = scene; if (scene.SnmpService != null) { scene.SnmpService.BootInfo("The region is operational", scene); scene.SnmpService.LinkUp(scene); } //return clientServers; } /// <summary> /// Try to set up the estate owner for the given scene. /// </summary> /// <remarks> /// The involves asking the user for information about the user on the console. If the user does not already /// exist then it is created. /// </remarks> /// <param name="scene"></param> private void SetUpEstateOwner(Scene scene) { RegionInfo regionInfo = scene.RegionInfo; string estateOwnerFirstName = null; string estateOwnerLastName = null; string estateOwnerEMail = null; string estateOwnerPassword = null; string rawEstateOwnerUuid = null; if (Config.Configs[ESTATE_SECTION_NAME] != null) { string defaultEstateOwnerName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerName", "").Trim(); string[] ownerNames = defaultEstateOwnerName.Split(' '); if (ownerNames.Length >= 2) { estateOwnerFirstName = ownerNames[0]; estateOwnerLastName = ownerNames[1]; } // Info to be used only on Standalone Mode rawEstateOwnerUuid = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerUUID", null); estateOwnerEMail = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerEMail", null); estateOwnerPassword = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerPassword", null); } MainConsole.Instance.OutputFormat("Estate {0} has no owner set.", regionInfo.EstateSettings.EstateName); List<char> excluded = new List<char>(new char[1]{' '}); if (estateOwnerFirstName == null || estateOwnerLastName == null) { estateOwnerFirstName = MainConsole.Instance.CmdPrompt("Estate owner first name", "Test", excluded); estateOwnerLastName = MainConsole.Instance.CmdPrompt("Estate owner last name", "User", excluded); } UserAccount account = scene.UserAccountService.GetUserAccount(regionInfo.ScopeID, estateOwnerFirstName, estateOwnerLastName); if (account == null) { // XXX: The LocalUserAccountServicesConnector is currently registering its inner service rather than // itself! // if (scene.UserAccountService is LocalUserAccountServicesConnector) // { // IUserAccountService innerUas // = ((LocalUserAccountServicesConnector)scene.UserAccountService).UserAccountService; // // m_log.DebugFormat("B {0}", innerUas.GetType()); // // if (innerUas is UserAccountService) // { if (scene.UserAccountService is UserAccountService) { if (estateOwnerPassword == null) estateOwnerPassword = MainConsole.Instance.PasswdPrompt("Password"); if (estateOwnerEMail == null) estateOwnerEMail = MainConsole.Instance.CmdPrompt("Email"); if (rawEstateOwnerUuid == null) rawEstateOwnerUuid = MainConsole.Instance.CmdPrompt("User ID", UUID.Random().ToString()); UUID estateOwnerUuid = UUID.Zero; if (!UUID.TryParse(rawEstateOwnerUuid, out estateOwnerUuid)) { m_log.ErrorFormat("[OPENSIM]: ID {0} is not a valid UUID", rawEstateOwnerUuid); return; } // If we've been given a zero uuid then this signals that we should use a random user id if (estateOwnerUuid == UUID.Zero) estateOwnerUuid = UUID.Random(); account = ((UserAccountService)scene.UserAccountService).CreateUser( regionInfo.ScopeID, estateOwnerUuid, estateOwnerFirstName, estateOwnerLastName, estateOwnerPassword, estateOwnerEMail); } } if (account == null) { m_log.ErrorFormat( "[OPENSIM]: Unable to store account. If this simulator is connected to a grid, you must create the estate owner account first at the grid level."); } else { regionInfo.EstateSettings.EstateOwner = account.PrincipalID; m_estateDataService.StoreEstateSettings(regionInfo.EstateSettings); } } private void ShutdownRegion(Scene scene) { m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName); if (scene.SnmpService != null) { scene.SnmpService.BootInfo("The region is shutting down", scene); scene.SnmpService.LinkDown(scene); } IRegionModulesController controller; if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller)) { controller.RemoveRegionFromModules(scene); } } public void RemoveRegion(Scene scene, bool cleanup) { // only need to check this if we are not at the // root level if ((SceneManager.CurrentScene != null) && (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID)) { SceneManager.TrySetCurrentScene(".."); } scene.DeleteAllSceneObjects(); SceneManager.CloseScene(scene); //ShutdownClientServer(scene.RegionInfo); if (!cleanup) return; if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile)) { if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".xml")) { File.Delete(scene.RegionInfo.RegionFile); m_log.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile); } if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".ini")) { try { IniConfigSource source = new IniConfigSource(scene.RegionInfo.RegionFile); if (source.Configs[scene.RegionInfo.RegionName] != null) { source.Configs.Remove(scene.RegionInfo.RegionName); if (source.Configs.Count == 0) { File.Delete(scene.RegionInfo.RegionFile); } else { source.Save(scene.RegionInfo.RegionFile); } } } catch (Exception) { } } } } public void RemoveRegion(string name, bool cleanUp) { Scene target; if (SceneManager.TryGetScene(name, out target)) RemoveRegion(target, cleanUp); } /// <summary> /// Remove a region from the simulator without deleting it permanently. /// </summary> /// <param name="scene"></param> /// <returns></returns> public void CloseRegion(Scene scene) { // only need to check this if we are not at the // root level if ((SceneManager.CurrentScene != null) && (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID)) { SceneManager.TrySetCurrentScene(".."); } SceneManager.CloseScene(scene); //ShutdownClientServer(scene.RegionInfo); } /// <summary> /// Remove a region from the simulator without deleting it permanently. /// </summary> /// <param name="name"></param> /// <returns></returns> public void CloseRegion(string name) { Scene target; if (SceneManager.TryGetScene(name, out target)) CloseRegion(target); } /// <summary> /// Create a scene and its initial base structures. /// </summary> /// <param name="regionInfo"></param> /// <param name="clientServer"> </param> /// <returns></returns> protected Scene SetupScene(RegionInfo regionInfo) { return SetupScene(regionInfo, 0, null); } /// <summary> /// Create a scene and its initial base structures. /// </summary> /// <param name="regionInfo"></param> /// <param name="proxyOffset"></param> /// <param name="configSource"></param> /// <param name="clientServer"> </param> /// <returns></returns> protected Scene SetupScene(RegionInfo regionInfo, int proxyOffset, IConfigSource configSource) { //List<IClientNetworkServer> clientNetworkServers = null; AgentCircuitManager circuitManager = new AgentCircuitManager(); Scene scene = CreateScene(regionInfo, m_simulationDataService, m_estateDataService, circuitManager); scene.LoadWorldMap(); return scene; } protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService, IEstateDataService estateDataService, AgentCircuitManager circuitManager) { return new Scene( regionInfo, circuitManager, simDataService, estateDataService, Config, m_version); } protected virtual void HandleRestartRegion(RegionInfo whichRegion) { m_log.InfoFormat( "[OPENSIM]: Got restart signal from SceneManager for region {0} ({1},{2})", whichRegion.RegionName, whichRegion.RegionLocX, whichRegion.RegionLocY); //ShutdownClientServer(whichRegion); IScene scene; CreateRegion(whichRegion, true, out scene); scene.Start(); } # region Setup methods /// <summary> /// Handler to supply the current status of this sim /// </summary> /// <remarks> /// Currently this is always OK if the simulator is still listening for connections on its HTTP service /// </remarks> public class SimStatusHandler : BaseStreamHandler { public SimStatusHandler() : base("GET", "/simstatus", "SimStatus", "Simulator Status") {} protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return Util.UTF8.GetBytes("OK"); } public override string ContentType { get { return "text/plain"; } } } /// <summary> /// Handler to supply the current extended status of this sim /// Sends the statistical data in a json serialization /// </summary> public class XSimStatusHandler : BaseStreamHandler { OpenSimBase m_opensim; public XSimStatusHandler(OpenSimBase sim) : base("GET", "/" + Util.SHA1Hash(sim.osSecret), "XSimStatus", "Simulator XStatus") { m_opensim = sim; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); } public override string ContentType { get { return "text/plain"; } } } /// <summary> /// Handler to supply the current extended status of this sim to a user configured URI /// Sends the statistical data in a json serialization /// If the request contains a key, "callback" the response will be wrappend in the /// associated value for jsonp used with ajax/javascript /// </summary> protected class UXSimStatusHandler : BaseStreamHandler { OpenSimBase m_opensim; public UXSimStatusHandler(OpenSimBase sim) : base("GET", "/" + sim.userStatsURI, "UXSimStatus", "Simulator UXStatus") { m_opensim = sim; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); } public override string ContentType { get { return "text/plain"; } } } /// <summary> /// handler to supply serving http://domainname:port/robots.txt /// </summary> public class SimRobotsHandler : BaseStreamHandler { public SimRobotsHandler() : base("GET", "/robots.txt", "SimRobots.txt", "Simulator Robots.txt") {} protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string robots = "# go away\nUser-agent: *\nDisallow: /\n"; return Util.UTF8.GetBytes(robots); } public override string ContentType { get { return "text/plain"; } } } #endregion /// <summary> /// Performs any last-minute sanity checking and shuts down the region server /// </summary> protected override void ShutdownSpecific() { if (proxyUrl.Length > 0) { Util.XmlRpcCommand(proxyUrl, "Stop"); } m_log.Info("[SHUTDOWN]: Closing all threads"); m_log.Info("[SHUTDOWN]: Killing listener thread"); m_log.Info("[SHUTDOWN]: Killing clients"); m_log.Info("[SHUTDOWN]: Closing console and terminating"); try { SceneManager.Close(); foreach (IApplicationPlugin plugin in m_plugins) plugin.Dispose(); } catch (Exception e) { m_log.Error("[SHUTDOWN]: Ignoring failure during shutdown - ", e); } base.ShutdownSpecific(); } /// <summary> /// Get the start time and up time of Region server /// </summary> /// <param name="starttime">The first out parameter describing when the Region server started</param> /// <param name="uptime">The second out parameter describing how long the Region server has run</param> public void GetRunTime(out string starttime, out string uptime) { starttime = m_startuptime.ToString(); uptime = (DateTime.Now - m_startuptime).ToString(); } /// <summary> /// Get the number of the avatars in the Region server /// </summary> /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param> public void GetAvatarNumber(out int usernum) { usernum = SceneManager.GetCurrentSceneAvatars().Count; } /// <summary> /// Get the number of regions /// </summary> /// <param name="regionnum">The first out parameter describing the number of regions</param> public void GetRegionNumber(out int regionnum) { regionnum = SceneManager.Scenes.Count; } /// <summary> /// Create an estate with an initial region. /// </summary> /// <remarks> /// This method doesn't allow an estate to be created with the same name as existing estates. /// </remarks> /// <param name="regInfo"></param> /// <param name="estatesByName">A list of estate names that already exist.</param> /// <param name="estateName">Estate name to create if already known</param> /// <returns>true if the estate was created, false otherwise</returns> public bool CreateEstate(RegionInfo regInfo, Dictionary<string, EstateSettings> estatesByName, string estateName) { // Create a new estate regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true); string newName; if (!string.IsNullOrEmpty(estateName)) newName = estateName; else newName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName); if (estatesByName.ContainsKey(newName)) { MainConsole.Instance.OutputFormat("An estate named {0} already exists. Please try again.", newName); return false; } regInfo.EstateSettings.EstateName = newName; // FIXME: Later on, the scene constructor will reload the estate settings no matter what. // Therefore, we need to do an initial save here otherwise the new estate name will be reset // back to the default. The reloading of estate settings by scene could be eliminated if it // knows that the passed in settings in RegionInfo are already valid. Also, it might be // possible to eliminate some additional later saves made by callers of this method. EstateDataService.StoreEstateSettings(regInfo.EstateSettings); return true; } /// <summary> /// Load the estate information for the provided RegionInfo object. /// </summary> /// <param name="regInfo"></param> public bool PopulateRegionEstateInfo(RegionInfo regInfo) { if (EstateDataService != null) regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false); if (regInfo.EstateSettings.EstateID != 0) return false; // estate info in the database did not change m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName); List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll(); Dictionary<string, EstateSettings> estatesByName = new Dictionary<string, EstateSettings>(); foreach (EstateSettings estate in estates) estatesByName[estate.EstateName] = estate; string defaultEstateName = null; if (Config.Configs[ESTATE_SECTION_NAME] != null) { defaultEstateName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateName", null); if (defaultEstateName != null) { EstateSettings defaultEstate; bool defaultEstateJoined = false; if (estatesByName.ContainsKey(defaultEstateName)) { defaultEstate = estatesByName[defaultEstateName]; if (EstateDataService.LinkRegion(regInfo.RegionID, (int)defaultEstate.EstateID)) defaultEstateJoined = true; } else { if (CreateEstate(regInfo, estatesByName, defaultEstateName)) defaultEstateJoined = true; } if (defaultEstateJoined) return true; // need to update the database else m_log.ErrorFormat( "[OPENSIM BASE]: Joining default estate {0} failed", defaultEstateName); } } // If we have no default estate or creation of the default estate failed then ask the user. while (true) { if (estates.Count == 0) { m_log.Info("[ESTATE]: No existing estates found. You must create a new one."); if (CreateEstate(regInfo, estatesByName, null)) break; else continue; } else { string response = MainConsole.Instance.CmdPrompt( string.Format( "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName), "yes", new List<string>() { "yes", "no" }); if (response == "no") { if (CreateEstate(regInfo, estatesByName, null)) break; else continue; } else { string[] estateNames = estatesByName.Keys.ToArray(); response = MainConsole.Instance.CmdPrompt( string.Format( "Name of estate to join. Existing estate names are ({0})", string.Join(", ", estateNames)), estateNames[0]); List<int> estateIDs = EstateDataService.GetEstates(response); if (estateIDs.Count < 1) { MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again."); continue; } int estateID = estateIDs[0]; regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID); if (EstateDataService.LinkRegion(regInfo.RegionID, estateID)) break; MainConsole.Instance.Output("Joining the estate failed. Please try again."); } } } return true; // need to update the database } } public class OpenSimConfigSource { public IConfigSource Source; } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Utilities; using NuGet.Versioning; namespace Microsoft.DotNet.ProjectModel.Resolution { public class LibraryManager { private readonly IList<LibraryDescription> _libraries; private readonly IList<DiagnosticMessage> _diagnostics; private readonly string _projectPath; public LibraryManager(IList<LibraryDescription> libraries, IList<DiagnosticMessage> diagnostics, string projectPath) { _libraries = libraries; _diagnostics = diagnostics; _projectPath = projectPath; } public IList<LibraryDescription> GetLibraries() { return _libraries; } public IList<DiagnosticMessage> GetAllDiagnostics() { var messages = new List<DiagnosticMessage>(); if (_diagnostics != null) { messages.AddRange(_diagnostics); } var dependencies = new Dictionary<string, List<DependencyItem>>(); var topLevel = new List<LibraryItem>(); var platformLibraries = new List<LibraryDescription>(); foreach (var library in GetLibraries()) { if (!library.Resolved) { string message; string errorCode; if (library.Compatible) { foreach (var range in library.RequestedRanges) { errorCode = ErrorCodes.NU1001; message = $"The dependency {FormatLibraryRange(range)} could not be resolved."; AddDiagnostics(messages, library, message, DiagnosticMessageSeverity.Error, errorCode); } } else { errorCode = ErrorCodes.NU1002; message = $"The dependency {library.Identity} does not support framework {library.Framework}."; AddDiagnostics(messages, library, message, DiagnosticMessageSeverity.Error, errorCode); } } else { var isPlatform = library.RequestedRanges.Any(r => r.Type.Equals(LibraryDependencyType.Platform)); if (isPlatform) { platformLibraries.Add(library); } // Store dependency -> library for later // J.N -> [(R1, P1), (R2, P2)] foreach (var dependency in library.Dependencies) { List<DependencyItem> items; if (!dependencies.TryGetValue(dependency.Name, out items)) { items = new List<DependencyItem>(); dependencies[dependency.Name] = items; } items.Add(new DependencyItem(dependency, library)); } foreach (var range in library.RequestedRanges) { // Skip libraries that aren't specified in a project.json // Only report problems for this project if (string.IsNullOrEmpty(range.SourceFilePath)) { continue; } // We only care about things requested in this project if (!string.Equals(_projectPath, range.SourceFilePath)) { continue; } if (range.VersionRange == null) { // TODO: Show errors/warnings for things without versions continue; } topLevel.Add(new LibraryItem(range, library)); // If we ended up with a declared version that isn't what was asked for directly // then report a warning // Case 1: Non floating version and the minimum doesn't match what was specified // Case 2: Floating version that fell outside of the range if ((!range.VersionRange.IsFloating && range.VersionRange.MinVersion != library.Identity.Version) || (range.VersionRange.IsFloating && !range.VersionRange.Float.Satisfies(library.Identity.Version))) { var message = $"Dependency specified was {FormatLibraryRange(range)} but ended up with {library.Identity}."; messages.Add( new DiagnosticMessage( ErrorCodes.NU1007, message, range.SourceFilePath, DiagnosticMessageSeverity.Warning, range.SourceLine, range.SourceColumn, library)); } } } } if (platformLibraries.Count > 1) { foreach (var platformLibrary in platformLibraries) { AddDiagnostics( messages, platformLibrary, "The following dependencies are marked with type 'platform', however only one dependency can have this type: " + string.Join(", ", platformLibraries.Select(l => l.Identity.Name).ToArray()), DiagnosticMessageSeverity.Error, ErrorCodes.DOTNET1013); } } // Version conflicts foreach (var libraryItem in topLevel) { var library = libraryItem.Library; if (library.Identity.Type != LibraryType.Package) { continue; } List<DependencyItem> items; if (dependencies.TryGetValue(library.Identity.Name, out items)) { foreach (var item in items) { var versionRange = item.Dependency.VersionRange; if (versionRange == null) { continue; } if (item.Library != library && !versionRange.Satisfies(library.Identity.Version)) { var message = $"Dependency conflict. {item.Library.Identity} expected {FormatLibraryRange(item.Dependency)} but got {library.Identity.Version}"; messages.Add( new DiagnosticMessage( ErrorCodes.NU1012, message, libraryItem.RequestedRange.SourceFilePath, DiagnosticMessageSeverity.Warning, libraryItem.RequestedRange.SourceLine, libraryItem.RequestedRange.SourceColumn, library)); } } } } return messages; } private static string FormatLibraryRange(LibraryRange range) { if (range.VersionRange == null) { return range.Name; } return range.Name + " " + VersionUtility.RenderVersion(range.VersionRange); } private void AddDiagnostics(List<DiagnosticMessage> messages, LibraryDescription library, string message, DiagnosticMessageSeverity severity, string errorCode) { // A (in project.json) -> B (unresolved) (not in project.json) foreach (var source in GetRangesWithSourceLocations(library).Distinct()) { // We only care about things requested in this project if (!string.Equals(_projectPath, source.SourceFilePath)) { continue; } messages.Add( new DiagnosticMessage( errorCode, message, source.SourceFilePath, severity, source.SourceLine, source.SourceColumn, library)); } } private IEnumerable<LibraryRange> GetRangesWithSourceLocations(LibraryDescription library) { foreach (var range in library.RequestedRanges) { if (!string.IsNullOrEmpty(range.SourceFilePath)) { yield return range; } } foreach (var parent in library.Parents) { foreach (var relevantPath in GetRangesWithSourceLocations(parent)) { yield return relevantPath; } } } private struct DependencyItem { public LibraryRange Dependency { get; private set; } public LibraryDescription Library { get; private set; } public DependencyItem(LibraryRange dependency, LibraryDescription library) { Dependency = dependency; Library = library; } } private struct LibraryItem { public LibraryRange RequestedRange { get; private set; } public LibraryDescription Library { get; private set; } public LibraryItem(LibraryRange requestedRange, LibraryDescription library) { RequestedRange = requestedRange; Library = library; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Platform; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osu.Game.Tournament.Screens.Ladder.Components; using osuTK; namespace osu.Game.Tournament.Screens.TeamIntro { public class SeedingScreen : TournamentMatchScreen, IProvideVideo { private Container mainContainer; private readonly Bindable<TournamentTeam> currentTeam = new Bindable<TournamentTeam>(); [BackgroundDependencyLoader] private void load(Storage storage) { RelativeSizeAxes = Axes.Both; InternalChildren = new Drawable[] { new TourneyVideo("seeding") { RelativeSizeAxes = Axes.Both, Loop = true, }, mainContainer = new Container { RelativeSizeAxes = Axes.Both, }, new ControlPanel { Children = new Drawable[] { new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Show first team", Action = () => currentTeam.Value = CurrentMatch.Value.Team1.Value, }, new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Show second team", Action = () => currentTeam.Value = CurrentMatch.Value.Team2.Value, }, new SettingsTeamDropdown(LadderInfo.Teams) { LabelText = "Show specific team", Current = currentTeam, } } } }; currentTeam.BindValueChanged(teamChanged, true); } private void teamChanged(ValueChangedEvent<TournamentTeam> team) { if (team.NewValue == null) { mainContainer.Clear(); return; } showTeam(team.NewValue); } protected override void CurrentMatchChanged(ValueChangedEvent<TournamentMatch> match) { base.CurrentMatchChanged(match); if (match.NewValue == null) return; currentTeam.Value = match.NewValue.Team1.Value; } private void showTeam(TournamentTeam team) { mainContainer.Children = new Drawable[] { new LeftInfo(team) { Position = new Vector2(55, 150), }, new RightInfo(team) { Position = new Vector2(500, 150), }, }; } private class RightInfo : CompositeDrawable { public RightInfo(TournamentTeam team) { FillFlowContainer fill; Width = 400; InternalChildren = new Drawable[] { fill = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, }, }; foreach (var seeding in team.SeedingResults) { fill.Add(new ModRow(seeding.Mod.Value, seeding.Seed.Value)); foreach (var beatmap in seeding.Beatmaps) fill.Add(new BeatmapScoreRow(beatmap)); } } private class BeatmapScoreRow : CompositeDrawable { public BeatmapScoreRow(SeedingBeatmap beatmap) { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChildren = new Drawable[] { new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Horizontal, Spacing = new Vector2(5), Children = new Drawable[] { new TournamentSpriteText { Text = beatmap.Beatmap.Metadata.Title, Colour = TournamentGame.TEXT_COLOUR, }, new TournamentSpriteText { Text = "by", Colour = TournamentGame.TEXT_COLOUR, Font = OsuFont.Torus.With(weight: FontWeight.Regular) }, new TournamentSpriteText { Text = beatmap.Beatmap.Metadata.Artist, Colour = TournamentGame.TEXT_COLOUR, Font = OsuFont.Torus.With(weight: FontWeight.Regular) }, } }, new FillFlowContainer { AutoSizeAxes = Axes.Y, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Direction = FillDirection.Horizontal, Spacing = new Vector2(40), Children = new Drawable[] { new TournamentSpriteText { Text = beatmap.Score.ToString("#,0"), Colour = TournamentGame.TEXT_COLOUR, Width = 80 }, new TournamentSpriteText { Text = "#" + beatmap.Seed.Value.ToString("#,0"), Colour = TournamentGame.TEXT_COLOUR, Font = OsuFont.Torus.With(weight: FontWeight.Regular) }, } }, }; } } private class ModRow : CompositeDrawable { private readonly string mods; private readonly int seeding; public ModRow(string mods, int seeding) { this.mods = mods; this.seeding = seeding; Padding = new MarginPadding { Vertical = 10 }; AutoSizeAxes = Axes.Y; } [BackgroundDependencyLoader] private void load(TextureStore textures) { FillFlowContainer row; InternalChildren = new Drawable[] { row = new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(5), }, }; if (!string.IsNullOrEmpty(mods)) { row.Add(new Sprite { Texture = textures.Get($"mods/{mods.ToLower()}"), Scale = new Vector2(0.5f) }); } row.Add(new Container { Size = new Vector2(50, 16), CornerRadius = 10, Masking = true, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = TournamentGame.ELEMENT_BACKGROUND_COLOUR, }, new TournamentSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, Text = seeding.ToString("#,0"), Colour = TournamentGame.ELEMENT_FOREGROUND_COLOUR }, } }); } } } private class LeftInfo : CompositeDrawable { public LeftInfo(TournamentTeam team) { FillFlowContainer fill; Width = 200; if (team == null) return; InternalChildren = new Drawable[] { fill = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { new TeamDisplay(team) { Margin = new MarginPadding { Bottom = 30 } }, new RowDisplay("Average Rank:", $"#{team.AverageRank:#,0}"), new RowDisplay("Seed:", team.Seed.Value), new RowDisplay("Last year's placing:", team.LastYearPlacing.Value > 0 ? $"#{team.LastYearPlacing:#,0}" : "0"), new Container { Margin = new MarginPadding { Bottom = 30 } }, } }, }; foreach (var p in team.Players) fill.Add(new RowDisplay(p.Username, p.Statistics?.GlobalRank?.ToString("\\##,0") ?? "-")); } internal class RowDisplay : CompositeDrawable { public RowDisplay(string left, string right) { AutoSizeAxes = Axes.Y; RelativeSizeAxes = Axes.X; InternalChildren = new Drawable[] { new TournamentSpriteText { Text = left, Colour = TournamentGame.TEXT_COLOUR, Font = OsuFont.Torus.With(size: 22, weight: FontWeight.SemiBold), }, new TournamentSpriteText { Text = right, Colour = TournamentGame.TEXT_COLOUR, Anchor = Anchor.TopRight, Origin = Anchor.TopLeft, Font = OsuFont.Torus.With(size: 22, weight: FontWeight.Regular), }, }; } } private class TeamDisplay : DrawableTournamentTeam { public TeamDisplay(TournamentTeam team) : base(team) { AutoSizeAxes = Axes.Both; Flag.RelativeSizeAxes = Axes.None; Flag.Scale = new Vector2(1.2f); InternalChild = new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 5), Children = new Drawable[] { Flag, new OsuSpriteText { Text = team?.FullName.Value ?? "???", Font = OsuFont.Torus.With(size: 32, weight: FontWeight.SemiBold), Colour = TournamentGame.TEXT_COLOUR, }, } }; } } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:41:10 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** #pragma warning disable 1591 namespace DotSpatial.Projections.ProjectedCategories { /// <summary> /// KrugerZian1980 /// </summary> public class KrugerXian1980 : CoordinateSystemCategory { #region Private Variables public readonly ProjectionInfo Xian19803DegreeGKCM102E; public readonly ProjectionInfo Xian19803DegreeGKCM105E; public readonly ProjectionInfo Xian19803DegreeGKCM108E; public readonly ProjectionInfo Xian19803DegreeGKCM111E; public readonly ProjectionInfo Xian19803DegreeGKCM114E; public readonly ProjectionInfo Xian19803DegreeGKCM117E; public readonly ProjectionInfo Xian19803DegreeGKCM120E; public readonly ProjectionInfo Xian19803DegreeGKCM123E; public readonly ProjectionInfo Xian19803DegreeGKCM126E; public readonly ProjectionInfo Xian19803DegreeGKCM129E; public readonly ProjectionInfo Xian19803DegreeGKCM132E; public readonly ProjectionInfo Xian19803DegreeGKCM135E; public readonly ProjectionInfo Xian19803DegreeGKCM75E; public readonly ProjectionInfo Xian19803DegreeGKCM78E; public readonly ProjectionInfo Xian19803DegreeGKCM81E; public readonly ProjectionInfo Xian19803DegreeGKCM84E; public readonly ProjectionInfo Xian19803DegreeGKCM87E; public readonly ProjectionInfo Xian19803DegreeGKCM90E; public readonly ProjectionInfo Xian19803DegreeGKCM93E; public readonly ProjectionInfo Xian19803DegreeGKCM96E; public readonly ProjectionInfo Xian19803DegreeGKCM99E; public readonly ProjectionInfo Xian19803DegreeGKZone25; public readonly ProjectionInfo Xian19803DegreeGKZone26; public readonly ProjectionInfo Xian19803DegreeGKZone27; public readonly ProjectionInfo Xian19803DegreeGKZone28; public readonly ProjectionInfo Xian19803DegreeGKZone29; public readonly ProjectionInfo Xian19803DegreeGKZone30; public readonly ProjectionInfo Xian19803DegreeGKZone31; public readonly ProjectionInfo Xian19803DegreeGKZone32; public readonly ProjectionInfo Xian19803DegreeGKZone33; public readonly ProjectionInfo Xian19803DegreeGKZone34; public readonly ProjectionInfo Xian19803DegreeGKZone35; public readonly ProjectionInfo Xian19803DegreeGKZone36; public readonly ProjectionInfo Xian19803DegreeGKZone37; public readonly ProjectionInfo Xian19803DegreeGKZone38; public readonly ProjectionInfo Xian19803DegreeGKZone39; public readonly ProjectionInfo Xian19803DegreeGKZone40; public readonly ProjectionInfo Xian19803DegreeGKZone41; public readonly ProjectionInfo Xian19803DegreeGKZone42; public readonly ProjectionInfo Xian19803DegreeGKZone43; public readonly ProjectionInfo Xian19803DegreeGKZone44; public readonly ProjectionInfo Xian19803DegreeGKZone45; public readonly ProjectionInfo Xian1980GKCM105E; public readonly ProjectionInfo Xian1980GKCM111E; public readonly ProjectionInfo Xian1980GKCM117E; public readonly ProjectionInfo Xian1980GKCM123E; public readonly ProjectionInfo Xian1980GKCM129E; public readonly ProjectionInfo Xian1980GKCM135E; public readonly ProjectionInfo Xian1980GKCM75E; public readonly ProjectionInfo Xian1980GKCM81E; public readonly ProjectionInfo Xian1980GKCM87E; public readonly ProjectionInfo Xian1980GKCM93E; public readonly ProjectionInfo Xian1980GKCM99E; public readonly ProjectionInfo Xian1980GKZone13; public readonly ProjectionInfo Xian1980GKZone14; public readonly ProjectionInfo Xian1980GKZone15; public readonly ProjectionInfo Xian1980GKZone16; public readonly ProjectionInfo Xian1980GKZone17; public readonly ProjectionInfo Xian1980GKZone18; public readonly ProjectionInfo Xian1980GKZone19; public readonly ProjectionInfo Xian1980GKZone20; public readonly ProjectionInfo Xian1980GKZone21; public readonly ProjectionInfo Xian1980GKZone22; public readonly ProjectionInfo Xian1980GKZone23; #endregion #region Constructors /// <summary> /// Creates a new instance of KrugerZian1980 /// </summary> public KrugerXian1980() { Xian19803DegreeGKCM102E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=102 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM105E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM108E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=108 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM111E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM114E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=114 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM117E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM120E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=120 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM123E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM126E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=126 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM129E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM132E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=132 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM135E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM75E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM78E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=78 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM81E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM84E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=84 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM87E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM90E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=90 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM93E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM96E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=96 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM99E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone25 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=25500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone26 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=78 +k=1.000000 +x_0=26500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone27 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=27500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone28 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=84 +k=1.000000 +x_0=28500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone29 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=29500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone30 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=90 +k=1.000000 +x_0=30500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone31 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=31500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone32 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=96 +k=1.000000 +x_0=32500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone33 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=33500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone34 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=102 +k=1.000000 +x_0=34500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone35 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=35500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone36 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=108 +k=1.000000 +x_0=36500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone37 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=37500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone38 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=114 +k=1.000000 +x_0=38500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone39 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=39500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone40 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=120 +k=1.000000 +x_0=40500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone41 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=41500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone42 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=126 +k=1.000000 +x_0=42500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone43 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=43500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone44 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=132 +k=1.000000 +x_0=44500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKZone45 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=45500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM105E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM111E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM117E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM123E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM129E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM135E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM75E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM81E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM87E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM93E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKCM99E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone13 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=13500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone14 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=14500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone15 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=15500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone16 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=16500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone17 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=17500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone18 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=18500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone19 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=19500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone20 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=20500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone21 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=21500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone22 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=22500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian1980GKZone23 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=23500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs "); Xian19803DegreeGKCM102E.Name = "Xian_1980_3_Degree_GK_CM_102E"; Xian19803DegreeGKCM105E.Name = "Xian_1980_3_Degree_GK_CM_105E"; Xian19803DegreeGKCM108E.Name = "Xian_1980_3_Degree_GK_CM_108E"; Xian19803DegreeGKCM111E.Name = "Xian_1980_3_Degree_GK_CM_111E"; Xian19803DegreeGKCM114E.Name = "Xian_1980_3_Degree_GK_CM_114E"; Xian19803DegreeGKCM117E.Name = "Xian_1980_3_Degree_GK_CM_117E"; Xian19803DegreeGKCM120E.Name = "Xian_1980_3_Degree_GK_CM_120E"; Xian19803DegreeGKCM123E.Name = "Xian_1980_3_Degree_GK_CM_123E"; Xian19803DegreeGKCM126E.Name = "Xian_1980_3_Degree_GK_CM_126E"; Xian19803DegreeGKCM129E.Name = "Xian_1980_3_Degree_GK_CM_129E"; Xian19803DegreeGKCM132E.Name = "Xian_1980_3_Degree_GK_CM_132E"; Xian19803DegreeGKCM135E.Name = "Xian_1980_3_Degree_GK_CM_135E"; Xian19803DegreeGKCM75E.Name = "Xian_1980_3_Degree_GK_CM_75E"; Xian19803DegreeGKCM78E.Name = "Xian_1980_3_Degree_GK_CM_78E"; Xian19803DegreeGKCM81E.Name = "Xian_1980_3_Degree_GK_CM_81E"; Xian19803DegreeGKCM84E.Name = "Xian_1980_3_Degree_GK_CM_84E"; Xian19803DegreeGKCM87E.Name = "Xian_1980_3_Degree_GK_CM_87E"; Xian19803DegreeGKCM90E.Name = "Xian_1980_3_Degree_GK_CM_90E"; Xian19803DegreeGKCM93E.Name = "Xian_1980_3_Degree_GK_CM_93E"; Xian19803DegreeGKCM96E.Name = "Xian_1980_3_Degree_GK_CM_96E"; Xian19803DegreeGKCM99E.Name = "Xian_1980_3_Degree_GK_CM_99E"; Xian19803DegreeGKZone25.Name = "Xian_1980_3_Degree_GK_Zone_25"; Xian19803DegreeGKZone26.Name = "Xian_1980_3_Degree_GK_Zone_26"; Xian19803DegreeGKZone27.Name = "Xian_1980_3_Degree_GK_Zone_27"; Xian19803DegreeGKZone28.Name = "Xian_1980_3_Degree_GK_Zone_28"; Xian19803DegreeGKZone29.Name = "Xian_1980_3_Degree_GK_Zone_29"; Xian19803DegreeGKZone30.Name = "Xian_1980_3_Degree_GK_Zone_30"; Xian19803DegreeGKZone31.Name = "Xian_1980_3_Degree_GK_Zone_31"; Xian19803DegreeGKZone32.Name = "Xian_1980_3_Degree_GK_Zone_32"; Xian19803DegreeGKZone33.Name = "Xian_1980_3_Degree_GK_Zone_33"; Xian19803DegreeGKZone34.Name = "Xian_1980_3_Degree_GK_Zone_34"; Xian19803DegreeGKZone35.Name = "Xian_1980_3_Degree_GK_Zone_35"; Xian19803DegreeGKZone36.Name = "Xian_1980_3_Degree_GK_Zone_36"; Xian19803DegreeGKZone37.Name = "Xian_1980_3_Degree_GK_Zone_37"; Xian19803DegreeGKZone38.Name = "Xian_1980_3_Degree_GK_Zone_38"; Xian19803DegreeGKZone39.Name = "Xian_1980_3_Degree_GK_Zone_39"; Xian19803DegreeGKZone40.Name = "Xian_1980_3_Degree_GK_Zone_40"; Xian19803DegreeGKZone41.Name = "Xian_1980_3_Degree_GK_Zone_41"; Xian19803DegreeGKZone42.Name = "Xian_1980_3_Degree_GK_Zone_42"; Xian19803DegreeGKZone43.Name = "Xian_1980_3_Degree_GK_Zone_43"; Xian19803DegreeGKZone44.Name = "Xian_1980_3_Degree_GK_Zone_44"; Xian19803DegreeGKZone45.Name = "Xian_1980_3_Degree_GK_Zone_45"; Xian1980GKCM105E.Name = "Xian_1980_GK_CM_105E"; Xian1980GKCM111E.Name = "Xian_1980_GK_CM_111E"; Xian1980GKCM117E.Name = "Xian_1980_GK_CM_117E"; Xian1980GKCM123E.Name = "Xian_1980_GK_CM_123E"; Xian1980GKCM129E.Name = "Xian_1980_GK_CM_129E"; Xian1980GKCM135E.Name = "Xian_1980_GK_CM_135E"; Xian1980GKCM75E.Name = "Xian_1980_GK_CM_75E"; Xian1980GKCM81E.Name = "Xian_1980_GK_CM_81E"; Xian1980GKCM87E.Name = "Xian_1980_GK_CM_87E"; Xian1980GKCM93E.Name = "Xian_1980_GK_CM_93E"; Xian1980GKCM99E.Name = "Xian_1980_GK_CM_99E"; Xian1980GKZone13.Name = "Xian_1980_GK_Zone_13"; Xian1980GKZone14.Name = "Xian_1980_GK_Zone_14"; Xian1980GKZone15.Name = "Xian_1980_GK_Zone_15"; Xian1980GKZone16.Name = "Xian_1980_GK_Zone_16"; Xian1980GKZone17.Name = "Xian_1980_GK_Zone_17"; Xian1980GKZone18.Name = "Xian_1980_GK_Zone_18"; Xian1980GKZone19.Name = "Xian_1980_GK_Zone_19"; Xian1980GKZone20.Name = "Xian_1980_GK_Zone_20"; Xian1980GKZone21.Name = "Xian_1980_GK_Zone_21"; Xian1980GKZone22.Name = "Xian_1980_GK_Zone_22"; Xian1980GKZone23.Name = "Xian_1980_GK_Zone_23"; Xian19803DegreeGKCM102E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM105E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM108E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM111E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM114E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM117E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM120E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM123E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM126E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM129E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM132E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM135E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM75E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM78E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM81E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM84E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM87E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM90E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM93E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM96E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM99E.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone25.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone26.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone27.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone28.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone29.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone30.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone31.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone32.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone33.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone34.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone35.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone36.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone37.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone38.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone39.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone40.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone41.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone42.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone43.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone44.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKZone45.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM105E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM111E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM117E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM123E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM129E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM135E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM75E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM81E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM87E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM93E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKCM99E.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone13.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone14.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone15.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone16.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone17.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone18.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone19.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone20.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone21.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone22.GeographicInfo.Name = "GCS_Xian_1980"; Xian1980GKZone23.GeographicInfo.Name = "GCS_Xian_1980"; Xian19803DegreeGKCM102E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM105E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM108E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM111E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM114E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM117E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM120E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM123E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM126E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM129E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM132E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM135E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM75E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM78E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM81E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM84E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM87E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM90E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM93E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM96E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKCM99E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone25.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone26.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone27.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone28.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone29.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone30.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone31.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone32.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone33.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone34.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone35.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone36.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone37.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone38.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone39.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone40.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone41.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone42.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone43.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone44.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian19803DegreeGKZone45.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM105E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM111E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM117E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM123E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM129E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM135E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM75E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM81E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM87E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM93E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKCM99E.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone13.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone14.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone15.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone16.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone17.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone18.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone19.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone20.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone21.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone22.GeographicInfo.Datum.Name = "D_Xian_1980"; Xian1980GKZone23.GeographicInfo.Datum.Name = "D_Xian_1980"; } #endregion } } #pragma warning restore 1591
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace OpenApiLib { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class ModelMessages { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_ProtoLongRange__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::OpenApiLib.ProtoLongRange, global::OpenApiLib.ProtoLongRange.Builder> internal__static_ProtoLongRange__FieldAccessorTable; internal static pbd::MessageDescriptor internal__static_ProtoDoubleRange__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::OpenApiLib.ProtoDoubleRange, global::OpenApiLib.ProtoDoubleRange.Builder> internal__static_ProtoDoubleRange__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static ModelMessages() { byte[] descriptorData = global::System.Convert.FromBase64String( "ChNNb2RlbE1lc3NhZ2VzLnByb3RvIioKDlByb3RvTG9uZ1JhbmdlEgwKBGZy" + "b20YASABKAMSCgoCdG8YAiABKAMiLAoQUHJvdG9Eb3VibGVSYW5nZRIMCgRm" + "cm9tGAEgASgBEgoKAnRvGAIgASgBKmUKEFByb3RvUGF5bG9hZFR5cGUSEQoN" + "UFJPVE9fTUVTU0FHRRAFEg0KCUVSUk9SX1JFUxAyEhMKD0hFQVJUQkVBVF9F" + "VkVOVBAzEgwKCFBJTkdfUkVREDQSDAoIUElOR19SRVMQNSrqAQoOUHJvdG9F" + "cnJvckNvZGUSEQoNVU5LTk9XTl9FUlJPUhABEhcKE1VOU1VQUE9SVEVEX01F" + "U1NBR0UQAhITCg9JTlZBTElEX1JFUVVFU1QQAxISCg5XUk9OR19QQVNTV09S" + "RBAEEhEKDVRJTUVPVVRfRVJST1IQBRIUChBFTlRJVFlfTk9UX0ZPVU5EEAYS" + "FgoSQ0FOVF9ST1VURV9SRVFVRVNUEAcSEgoORlJBTUVfVE9PX0xPTkcQCBIR" + "Cg1NQVJLRVRfQ0xPU0VEEAkSGwoXQ09OQ1VSUkVOVF9NT0RJRklDQVRJT04Q" + "CkJHCihjb20ueHRyYWRlci5wcm90b2NvbC5wcm90by5jb21tb25zLm1vZGVs" + "QhZDb250YWluZXJNb2RlbE1lc3NhZ2VzUAGgAQE="); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_ProtoLongRange__Descriptor = Descriptor.MessageTypes[0]; internal__static_ProtoLongRange__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::OpenApiLib.ProtoLongRange, global::OpenApiLib.ProtoLongRange.Builder>(internal__static_ProtoLongRange__Descriptor, new string[] { "From", "To", }); internal__static_ProtoDoubleRange__Descriptor = Descriptor.MessageTypes[1]; internal__static_ProtoDoubleRange__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::OpenApiLib.ProtoDoubleRange, global::OpenApiLib.ProtoDoubleRange.Builder>(internal__static_ProtoDoubleRange__Descriptor, new string[] { "From", "To", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } #region Enums public enum ProtoPayloadType { PROTO_MESSAGE = 5, ERROR_RES = 50, HEARTBEAT_EVENT = 51, PING_REQ = 52, PING_RES = 53, } public enum ProtoErrorCode { UNKNOWN_ERROR = 1, UNSUPPORTED_MESSAGE = 2, INVALID_REQUEST = 3, WRONG_PASSWORD = 4, TIMEOUT_ERROR = 5, ENTITY_NOT_FOUND = 6, CANT_ROUTE_REQUEST = 7, FRAME_TOO_LONG = 8, MARKET_CLOSED = 9, CONCURRENT_MODIFICATION = 10, } #endregion #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ProtoLongRange : pb::GeneratedMessage<ProtoLongRange, ProtoLongRange.Builder> { private ProtoLongRange() { } private static readonly ProtoLongRange defaultInstance = new ProtoLongRange().MakeReadOnly(); private static readonly string[] _protoLongRangeFieldNames = new string[] { "from", "to" }; private static readonly uint[] _protoLongRangeFieldTags = new uint[] { 8, 16 }; public static ProtoLongRange DefaultInstance { get { return defaultInstance; } } public override ProtoLongRange DefaultInstanceForType { get { return DefaultInstance; } } protected override ProtoLongRange ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::OpenApiLib.ModelMessages.internal__static_ProtoLongRange__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<ProtoLongRange, ProtoLongRange.Builder> InternalFieldAccessors { get { return global::OpenApiLib.ModelMessages.internal__static_ProtoLongRange__FieldAccessorTable; } } public const int FromFieldNumber = 1; private bool hasFrom; private long from_; public bool HasFrom { get { return hasFrom; } } public long From { get { return from_; } } public const int ToFieldNumber = 2; private bool hasTo; private long to_; public bool HasTo { get { return hasTo; } } public long To { get { return to_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _protoLongRangeFieldNames; if (hasFrom) { output.WriteInt64(1, field_names[0], From); } if (hasTo) { output.WriteInt64(2, field_names[1], To); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasFrom) { size += pb::CodedOutputStream.ComputeInt64Size(1, From); } if (hasTo) { size += pb::CodedOutputStream.ComputeInt64Size(2, To); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public static ProtoLongRange ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ProtoLongRange ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ProtoLongRange ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ProtoLongRange ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ProtoLongRange ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ProtoLongRange ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static ProtoLongRange ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static ProtoLongRange ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static ProtoLongRange ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ProtoLongRange ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private ProtoLongRange MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(ProtoLongRange prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<ProtoLongRange, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(ProtoLongRange cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private ProtoLongRange result; private ProtoLongRange PrepareBuilder() { if (resultIsReadOnly) { ProtoLongRange original = result; result = new ProtoLongRange(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override ProtoLongRange MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::OpenApiLib.ProtoLongRange.Descriptor; } } public override ProtoLongRange DefaultInstanceForType { get { return global::OpenApiLib.ProtoLongRange.DefaultInstance; } } public override ProtoLongRange BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is ProtoLongRange) { return MergeFrom((ProtoLongRange) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(ProtoLongRange other) { if (other == global::OpenApiLib.ProtoLongRange.DefaultInstance) return this; PrepareBuilder(); if (other.HasFrom) { From = other.From; } if (other.HasTo) { To = other.To; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_protoLongRangeFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _protoLongRangeFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 8: { result.hasFrom = input.ReadInt64(ref result.from_); break; } case 16: { result.hasTo = input.ReadInt64(ref result.to_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasFrom { get { return result.hasFrom; } } public long From { get { return result.From; } set { SetFrom(value); } } public Builder SetFrom(long value) { PrepareBuilder(); result.hasFrom = true; result.from_ = value; return this; } public Builder ClearFrom() { PrepareBuilder(); result.hasFrom = false; result.from_ = 0L; return this; } public bool HasTo { get { return result.hasTo; } } public long To { get { return result.To; } set { SetTo(value); } } public Builder SetTo(long value) { PrepareBuilder(); result.hasTo = true; result.to_ = value; return this; } public Builder ClearTo() { PrepareBuilder(); result.hasTo = false; result.to_ = 0L; return this; } } static ProtoLongRange() { object.ReferenceEquals(global::OpenApiLib.ModelMessages.Descriptor, null); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ProtoDoubleRange : pb::GeneratedMessage<ProtoDoubleRange, ProtoDoubleRange.Builder> { private ProtoDoubleRange() { } private static readonly ProtoDoubleRange defaultInstance = new ProtoDoubleRange().MakeReadOnly(); private static readonly string[] _protoDoubleRangeFieldNames = new string[] { "from", "to" }; private static readonly uint[] _protoDoubleRangeFieldTags = new uint[] { 9, 17 }; public static ProtoDoubleRange DefaultInstance { get { return defaultInstance; } } public override ProtoDoubleRange DefaultInstanceForType { get { return DefaultInstance; } } protected override ProtoDoubleRange ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::OpenApiLib.ModelMessages.internal__static_ProtoDoubleRange__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<ProtoDoubleRange, ProtoDoubleRange.Builder> InternalFieldAccessors { get { return global::OpenApiLib.ModelMessages.internal__static_ProtoDoubleRange__FieldAccessorTable; } } public const int FromFieldNumber = 1; private bool hasFrom; private double from_; public bool HasFrom { get { return hasFrom; } } public double From { get { return from_; } } public const int ToFieldNumber = 2; private bool hasTo; private double to_; public bool HasTo { get { return hasTo; } } public double To { get { return to_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _protoDoubleRangeFieldNames; if (hasFrom) { output.WriteDouble(1, field_names[0], From); } if (hasTo) { output.WriteDouble(2, field_names[1], To); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasFrom) { size += pb::CodedOutputStream.ComputeDoubleSize(1, From); } if (hasTo) { size += pb::CodedOutputStream.ComputeDoubleSize(2, To); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public static ProtoDoubleRange ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ProtoDoubleRange ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ProtoDoubleRange ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ProtoDoubleRange ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ProtoDoubleRange ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ProtoDoubleRange ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static ProtoDoubleRange ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static ProtoDoubleRange ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static ProtoDoubleRange ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ProtoDoubleRange ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private ProtoDoubleRange MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(ProtoDoubleRange prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<ProtoDoubleRange, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(ProtoDoubleRange cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private ProtoDoubleRange result; private ProtoDoubleRange PrepareBuilder() { if (resultIsReadOnly) { ProtoDoubleRange original = result; result = new ProtoDoubleRange(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override ProtoDoubleRange MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::OpenApiLib.ProtoDoubleRange.Descriptor; } } public override ProtoDoubleRange DefaultInstanceForType { get { return global::OpenApiLib.ProtoDoubleRange.DefaultInstance; } } public override ProtoDoubleRange BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is ProtoDoubleRange) { return MergeFrom((ProtoDoubleRange) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(ProtoDoubleRange other) { if (other == global::OpenApiLib.ProtoDoubleRange.DefaultInstance) return this; PrepareBuilder(); if (other.HasFrom) { From = other.From; } if (other.HasTo) { To = other.To; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_protoDoubleRangeFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _protoDoubleRangeFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 9: { result.hasFrom = input.ReadDouble(ref result.from_); break; } case 17: { result.hasTo = input.ReadDouble(ref result.to_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasFrom { get { return result.hasFrom; } } public double From { get { return result.From; } set { SetFrom(value); } } public Builder SetFrom(double value) { PrepareBuilder(); result.hasFrom = true; result.from_ = value; return this; } public Builder ClearFrom() { PrepareBuilder(); result.hasFrom = false; result.from_ = 0D; return this; } public bool HasTo { get { return result.hasTo; } } public double To { get { return result.To; } set { SetTo(value); } } public Builder SetTo(double value) { PrepareBuilder(); result.hasTo = true; result.to_ = value; return this; } public Builder ClearTo() { PrepareBuilder(); result.hasTo = false; result.to_ = 0D; return this; } } static ProtoDoubleRange() { object.ReferenceEquals(global::OpenApiLib.ModelMessages.Descriptor, null); } } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; using Xunit; namespace Microsoft.Build.UnitTests { public class ScannerTest { private MockElementLocation _elementLocation = MockElementLocation.Instance; /// <summary> /// Tests that we give a useful error position (not 0 for example) /// </summary> [Fact] public void ErrorPosition() { string[,] tests = { { "1==1.1.", "7", "AllowAll"}, // Position of second '.' { "1==0xFG", "7", "AllowAll"}, // Position of G { "1==-0xF", "6", "AllowAll"}, // Position of x { "1234=5678", "6", "AllowAll"}, // Position of '5' { " ", "2", "AllowAll"}, // Position of End of Input { " (", "3", "AllowAll"}, // Position of End of Input { " false or ", "12", "AllowAll"}, // Position of End of Input { " \"foo", "2", "AllowAll"}, // Position of open quote { " @(foo", "2", "AllowAll"}, // Position of @ { " @(", "2", "AllowAll"}, // Position of @ { " $", "2", "AllowAll"}, // Position of $ { " $(foo", "2", "AllowAll"}, // Position of $ { " $(", "2", "AllowAll"}, // Position of $ { " $", "2", "AllowAll"}, // Position of $ { " @(foo)", "2", "AllowProperties"}, // Position of @ { " '@(foo)'", "3", "AllowProperties"}, // Position of @ /* test escaped chars: message shows them escaped so count should include them */ { "'%24%28x' == '%24(x''", "21", "AllowAll"} // Position of extra quote }; // Some errors are caught by the Parser, not merely by the Lexer/Scanner. So we have to do a full Parse, // rather than just calling AdvanceToScannerError(). (The error location is still supplied by the Scanner.) for (int i = 0; i < tests.GetLength(0); i++) { Parser parser = null; try { parser = new Parser(); ParserOptions options = (ParserOptions)Enum.Parse(typeof(ParserOptions), tests[i, 2], true /* case-insensitive */); parser.Parse(tests[i, 0], options, _elementLocation); } catch (InvalidProjectFileException ex) { Console.WriteLine(ex.Message); Assert.Equal(Convert.ToInt32(tests[i, 1]), parser.errorPosition); } } } /// <summary> /// Advance to the point of the lexer error. If the error is only caught by the parser, this isn't useful. /// </summary> /// <param name="lexer"></param> private void AdvanceToScannerError(Scanner lexer) { while (true) { if (!lexer.Advance()) break; if (lexer.IsNext(Token.TokenType.EndOfInput)) break; } } /// <summary> /// Tests the special error for "=". /// </summary> [Fact] public void SingleEquals() { Scanner lexer = new Scanner("a=b", ParserOptions.AllowProperties); AdvanceToScannerError(lexer); Assert.Equal("IllFormedEqualsInCondition", lexer.GetErrorResource()); Assert.Equal("b", lexer.UnexpectedlyFound); } /// <summary> /// Tests the special errors for "$(" and "$x" and similar cases /// </summary> [Fact] public void IllFormedProperty() { Scanner lexer = new Scanner("$(", ParserOptions.AllowProperties); AdvanceToScannerError(lexer); Assert.Equal("IllFormedPropertyCloseParenthesisInCondition", lexer.GetErrorResource()); lexer = new Scanner("$x", ParserOptions.AllowProperties); AdvanceToScannerError(lexer); Assert.Equal("IllFormedPropertyOpenParenthesisInCondition", lexer.GetErrorResource()); } /// <summary> /// Tests the special errors for "@(" and "@x" and similar cases. /// </summary> [Fact] public void IllFormedItemList() { Scanner lexer = new Scanner("@(", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assert.Equal("IllFormedItemListCloseParenthesisInCondition", lexer.GetErrorResource()); Assert.Null(lexer.UnexpectedlyFound); lexer = new Scanner("@x", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assert.Equal("IllFormedItemListOpenParenthesisInCondition", lexer.GetErrorResource()); Assert.Null(lexer.UnexpectedlyFound); lexer = new Scanner("@(x", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assert.Equal("IllFormedItemListCloseParenthesisInCondition", lexer.GetErrorResource()); Assert.Null(lexer.UnexpectedlyFound); lexer = new Scanner("@(x->'%(y)", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assert.Equal("IllFormedItemListQuoteInCondition", lexer.GetErrorResource()); Assert.Null(lexer.UnexpectedlyFound); lexer = new Scanner("@(x->'%(y)', 'x", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assert.Equal("IllFormedItemListQuoteInCondition", lexer.GetErrorResource()); Assert.Null(lexer.UnexpectedlyFound); lexer = new Scanner("@(x->'%(y)', 'x'", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assert.Equal("IllFormedItemListCloseParenthesisInCondition", lexer.GetErrorResource()); Assert.Null(lexer.UnexpectedlyFound); } /// <summary> /// Tests the special error for unterminated quotes. /// Note, scanner only understands single quotes. /// </summary> [Fact] public void IllFormedQuotedString() { Scanner lexer = new Scanner("false or 'abc", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assert.Equal("IllFormedQuotedStringInCondition", lexer.GetErrorResource()); Assert.Null(lexer.UnexpectedlyFound); lexer = new Scanner("\'", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assert.Equal("IllFormedQuotedStringInCondition", lexer.GetErrorResource()); Assert.Null(lexer.UnexpectedlyFound); } /// <summary> /// </summary> [Fact] public void NumericSingleTokenTests() { Scanner lexer = new Scanner("1234", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare("1234", lexer.IsNextString())); lexer = new Scanner("-1234", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare("-1234", lexer.IsNextString())); lexer = new Scanner("+1234", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare("+1234", lexer.IsNextString())); lexer = new Scanner("1234.1234", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare("1234.1234", lexer.IsNextString())); lexer = new Scanner(".1234", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare(".1234", lexer.IsNextString())); lexer = new Scanner("1234.", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare("1234.", lexer.IsNextString())); lexer = new Scanner("0x1234", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare("0x1234", lexer.IsNextString())); lexer = new Scanner("0X1234abcd", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare("0X1234abcd", lexer.IsNextString())); lexer = new Scanner("0x1234ABCD", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); Assert.Equal(0, String.Compare("0x1234ABCD", lexer.IsNextString())); } /// <summary> /// </summary> [Fact] public void PropsStringsAndBooleanSingleTokenTests() { Scanner lexer = new Scanner("$(foo)", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Property)); lexer = new Scanner("@(foo)", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.ItemList)); lexer = new Scanner("abcde", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.String)); Assert.Equal(0, String.Compare("abcde", lexer.IsNextString())); lexer = new Scanner("'abc-efg'", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.String)); Assert.Equal(0, String.Compare("abc-efg", lexer.IsNextString())); lexer = new Scanner("and", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.And)); Assert.Equal(0, String.Compare("and", lexer.IsNextString())); lexer = new Scanner("or", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Or)); Assert.Equal(0, String.Compare("or", lexer.IsNextString())); lexer = new Scanner("AnD", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.And)); Assert.Equal(0, String.Compare(Token.And.String, lexer.IsNextString())); lexer = new Scanner("Or", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Or)); Assert.Equal(0, String.Compare(Token.Or.String, lexer.IsNextString())); } /// <summary> /// </summary> [Fact] public void SimpleSingleTokenTests() { Scanner lexer = new Scanner("(", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.LeftParenthesis)); lexer = new Scanner(")", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner(",", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Comma)); lexer = new Scanner("==", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.EqualTo)); lexer = new Scanner("!=", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.NotEqualTo)); lexer = new Scanner("<", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.LessThan)); lexer = new Scanner(">", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.GreaterThan)); lexer = new Scanner("<=", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.LessThanOrEqualTo)); lexer = new Scanner(">=", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo)); lexer = new Scanner("!", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Not)); } /// <summary> /// </summary> [Fact] public void StringEdgeTests() { Scanner lexer = new Scanner("@(Foo, ' ')", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner("'@(Foo, ' ')'", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner("'%40(( '", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner("'@(Complex_ItemType-123, ';')' == ''", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); } /// <summary> /// </summary> [Fact] public void FunctionTests() { Scanner lexer = new Scanner("Foo()", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foo( 1 )", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foo( $(Property) )", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foo( @(ItemList) )", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foo( simplestring )", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foo( 'Not a Simple String' )", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foo( 'Not a Simple String', 1234 )", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foo( $(Property), 'Not a Simple String', 1234 )", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foo( @(ItemList), $(Property), simplestring, 'Not a Simple String', 1234 )", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assert.Equal(0, String.Compare("Foo", lexer.IsNextString())); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); } /// <summary> /// </summary> [Fact] public void ComplexTests1() { Scanner lexer = new Scanner("'String with a $(Property) inside'", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.Equal(0, String.Compare("String with a $(Property) inside", lexer.IsNextString())); lexer = new Scanner("'String with an embedded \\' in it'", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); // Assert.AreEqual(String.Compare("String with an embedded ' in it", lexer.IsNextString()), 0); lexer = new Scanner("'String with a $(Property) inside'", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.Equal(0, String.Compare("String with a $(Property) inside", lexer.IsNextString())); lexer = new Scanner("@(list, ' ')", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assert.Equal(0, String.Compare("@(list, ' ')", lexer.IsNextString())); lexer = new Scanner("@(files->'%(Filename)')", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assert.Equal(0, String.Compare("@(files->'%(Filename)')", lexer.IsNextString())); } /// <summary> /// </summary> [Fact] public void ComplexTests2() { Scanner lexer = new Scanner("1234", ParserOptions.AllowAll); Assert.True(lexer.Advance()); lexer = new Scanner("'abc-efg'==$(foo)", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.String)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.EqualTo)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.Property)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner("$(debug)!=true", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Property)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.NotEqualTo)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.String)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner("$(VERSION)<5", ParserOptions.AllowAll); Assert.True(lexer.Advance()); Assert.True(lexer.IsNext(Token.TokenType.Property)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.LessThan)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.Numeric)); lexer.Advance(); Assert.True(lexer.IsNext(Token.TokenType.EndOfInput)); } /// <summary> /// Tests all tokens with no whitespace and whitespace. /// </summary> [Fact] public void WhitespaceTests() { Scanner lexer; Console.WriteLine("here"); lexer = new Scanner("$(DEBUG) and $(FOO)", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.And)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); lexer = new Scanner("1234$(DEBUG)0xabcd@(foo)asdf<>'foo'<=false>=true==1234!=", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThan)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThan)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThanOrEqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.NotEqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner(" 1234 $(DEBUG) 0xabcd \n@(foo) \nasdf \n< \n> \n'foo' \n<= \nfalse \n>= \ntrue \n== \n 1234 \n!= ", ParserOptions.AllowAll); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThan)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThan)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThanOrEqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.NotEqualTo)); Assert.True(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); } /// <summary> /// Tests the parsing of item lists. /// </summary> [Fact] public void ItemListTests() { Scanner lexer = new Scanner("@(foo)", ParserOptions.AllowProperties); Assert.False(lexer.Advance()); Assert.Equal(0, String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional")); lexer = new Scanner("1234 '@(foo)'", ParserOptions.AllowProperties); Assert.True(lexer.Advance()); Assert.False(lexer.Advance()); Assert.Equal(0, String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional")); lexer = new Scanner("'1234 @(foo)'", ParserOptions.AllowProperties); Assert.False(lexer.Advance()); Assert.Equal(0, String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional")); } /// <summary> /// Tests that shouldn't work. /// </summary> [Fact] public void NegativeTests() { Scanner lexer = new Scanner("'$(DEBUG) == true", ParserOptions.AllowAll); Assert.False(lexer.Advance()); } } }
namespace EverlastingStudent.Data.Migrations { using System; using System.Data.Entity.Migrations; using System.Linq; using EverlastingStudent.Common.Models; using EverlastingStudent.Models; using EverlastingStudent.Models.FreelanceProjects; internal sealed class DefaultMigrationConfiguration : DbMigrationsConfiguration<EverlastingStudentDbContext> { public DefaultMigrationConfiguration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(EverlastingStudentDbContext context) { if (!context.Homeworks.Any()) { this.SeedHomeworks(context); } if (!context.BaseFreelanceProjects.Any()) { this.SeedBaseFreelanceProjects(context); } if (!context.Courses.Any()) { this.SeedCourses(context); } } private void SeedHomeworks(EverlastingStudentDbContext context) { context.Homeworks.Add(new Homework { Title = "JavaScript Syntax (If statemants, operations, variables...)", Type = TypeOfDifficulty.Easy }); context.Homeworks.Add(new Homework { Title = "Java Syntax (If statemants, operations, variables...)", Type = TypeOfDifficulty.Easy }); context.Homeworks.Add(new Homework { Title = "PHP Syntax (If statemants, operations, variables...)", Type = TypeOfDifficulty.Medium }); context.Homeworks.Add(new Homework { Title = "C# Syntax (If statemants, operations, variables...)", Type = TypeOfDifficulty.Hard }); context.Homeworks.Add(new Homework { Title = "JavaScript Loops (for, forin, while...)", Type = TypeOfDifficulty.Easy }); context.Homeworks.Add(new Homework { Title = "JavaScript OOP (classical, prototype)", Type = TypeOfDifficulty.Medium }); context.Homeworks.Add(new Homework { Title = "JavaScript Functions", Type = TypeOfDifficulty.Hard }); context.Homeworks.Add(new Homework { Title = "HTML Talbes", Type = TypeOfDifficulty.Easy }); context.Homeworks.Add(new Homework { Title = "Responsive Design", Type = TypeOfDifficulty.Hard }); context.Homeworks.Add(new Homework { Title = "SASS, LESS, Jekyll...", Type = TypeOfDifficulty.Medium }); context.Homeworks.Add(new Homework { Title = "CSS Selectors", Type = TypeOfDifficulty.Medium }); context.Homeworks.Add(new Homework { Title = "Regular Expressions (build in functions)", Type = TypeOfDifficulty.Medium }); context.Homeworks.Add(new Homework { Title = "PHP - Apache (server setup, XAMPP, LAMPP, MAMPP)", Type = TypeOfDifficulty.Easy }); context.Homeworks.Add(new Homework { Title = "Java Object Oriented Programming", Type = TypeOfDifficulty.Hard }); context.Homeworks.Add(new Homework { Title = "DataBases - SQL (Structured Query Language)", Type = TypeOfDifficulty.Easy }); context.Homeworks.Add(new Homework { Title = "Database (SELECT, UPDATE, INSERT, DELETE)", Type = TypeOfDifficulty.Medium }); context.Homeworks.Add(new Homework { Title = "High Quality code - Design Patterns", Type = TypeOfDifficulty.Hard }); context.Homeworks.Add(new Homework { Title = "High Quality code - SOLID", Type = TypeOfDifficulty.Hard }); context.SaveChanges(); } private void SeedBaseFreelanceProjects(EverlastingStudentDbContext context) { context.BaseFreelanceProjects.Add(new BaseFreelanceProject() { Title = "Create new Office.", Content = "Bla-bla-bla", RequireExperience = 0, EnergyCost = 10, MoneyGain = 3, ExperienceGain = 2, SolveDurabationInHours = 6, IsActive = true, OpenForTakenDatetime = new DateTime(1999, 1, 1), CloseForTakenDatetime = new DateTime(2020, 1, 1), IsDeleted = false, DeletedOn = null }); context.BaseFreelanceProjects.Add(new BaseFreelanceProject() { Title = "Create new Autocad.", Content = "Open Source", RequireExperience = 0, EnergyCost = 22, MoneyGain = 33, ExperienceGain = 5, SolveDurabationInHours = 2, IsActive = true, OpenForTakenDatetime = new DateTime(2002, 3, 3), CloseForTakenDatetime = new DateTime(2016, 2, 2), IsDeleted = false, DeletedOn = null }); context.BaseFreelanceProjects.Add(new BaseFreelanceProject() { Title = "Create new Php version", Content = "ahahhx", RequireExperience = 999, EnergyCost = 12, MoneyGain = 323, ExperienceGain = 65, SolveDurabationInHours = 22, IsActive = true, OpenForTakenDatetime = new DateTime(2012, 7, 8), CloseForTakenDatetime = new DateTime(2017, 2, 2), IsDeleted = false, DeletedOn = null }); context.SaveChanges(); } private void SeedCourses(EverlastingStudentDbContext context) { context.Courses.Add(new Course() { Title = "Programming Basics", Lectures = { new Lecture() { Title = "Introduction to C#", DurationInMinutes = 1, CoefficientKnowledgeGain = 0.01 }, new Lecture(){ Title = "Console Input and Output", DurationInMinutes = 1, CoefficientKnowledgeGain = 0.01 }, new Lecture(){ Title = "Conditional Statements", DurationInMinutes = 1, CoefficientKnowledgeGain = 0.01 } }, Exam = new Exam { ExamDurationInMinutes = 30, RequireExpForExam = 100 } }); context.Courses.Add(new Course() { Title = "Java Basics", Lectures = { new Lecture() { Title = "Introduction to Java", DurationInMinutes = 10, CoefficientKnowledgeGain = 0.015 }, new Lecture(){ Title = "Loops", DurationInMinutes = 10, CoefficientKnowledgeGain = 0.015 }, new Lecture(){ Title = "Strings", DurationInMinutes = 10, CoefficientKnowledgeGain = 0.015 }, new Lecture(){ Title = "Arrays", DurationInMinutes = 10, CoefficientKnowledgeGain = 0.015 } }, Exam = new Exam { ExamDurationInMinutes = 45, RequireExpForExam = 200 } }); context.Courses.Add(new Course() { Title = "Object-Oriented Programming", Lectures = { new Lecture() { Title = "Introduction to OOP", DurationInMinutes = 15, CoefficientKnowledgeGain = 0.02 }, new Lecture(){ Title = "Defining Classes", DurationInMinutes = 15, CoefficientKnowledgeGain = 0.02 }, new Lecture(){ Title = "Inheritance and Encapsulation", DurationInMinutes = 25, CoefficientKnowledgeGain = 0.02 }, new Lecture(){ Title = "Abstraction and Polymorphism", DurationInMinutes = 25, CoefficientKnowledgeGain = 0.02 } }, Exam = new Exam { ExamDurationInMinutes = 60, RequireExpForExam = 400 } }); context.Courses.Add(new Course() { Title = "High-Quality Code", Lectures = { new Lecture() { Title = "Quality Identifiers and Methods", DurationInMinutes = 15, CoefficientKnowledgeGain = 0.02 }, new Lecture(){ Title = "Code Refacturing", DurationInMinutes = 15, CoefficientKnowledgeGain = 0.02 }, new Lecture(){ Title = "Unit Testing and Mocking", DurationInMinutes = 25, CoefficientKnowledgeGain = 0.02 }, new Lecture(){ Title = "Design Patterns", DurationInMinutes = 25, CoefficientKnowledgeGain = 0.02 } }, Exam = new Exam { ExamDurationInMinutes = 75, RequireExpForExam = 600 } }); context.Courses.Add(new Course() { Title = "HTML Basics" }); context.Courses.Add(new Course() { Title = "CSS Basics" }); context.Courses.Add(new Course() { Title = "PHP Basics" }); context.Courses.Add(new Course() { Title = "JavaScript Basics" }); context.Courses.Add(new Course() { Title = "Advanced JavaScript" }); context.Courses.Add(new Course() { Title = "JavaScript Applications" }); context.Courses.Add(new Course() { Title = "AngularJS" }); context.SaveChanges(); var count = context.Courses.Count(); for (int i = 1; i < count; i++) { var course = context.Courses.Where(c => c.Id == i).First(); var nextCourse = context.Courses.Where(c => c.Id == i+1).First(); course.NextCourse = nextCourse; } context.SaveChanges(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Validation; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableArrayTest : SimpleElementImmutablesTestBase { private static readonly ImmutableArray<int> emptyDefault; private static readonly ImmutableArray<int> empty = ImmutableArray.Create<int>(); private static readonly ImmutableArray<int> oneElement = ImmutableArray.Create(1); private static readonly ImmutableArray<int> manyElements = ImmutableArray.Create(1, 2, 3); private static readonly ImmutableArray<GenericParameterHelper> oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1)); private static readonly ImmutableArray<string> twoElementRefTypeWithNull = ImmutableArray.Create("1", null); [Fact] public void CreateEmpty() { Assert.Equal(ImmutableArray.Create<int>(), ImmutableArray<int>.Empty); } [Fact] public void CreateFromEnumerable() { Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange((IEnumerable<int>)null)); IEnumerable<int> source = new[] { 1, 2, 3 }; var array = ImmutableArray.CreateRange(source); Assert.Equal(3, array.Length); } [Fact] public void CreateFromEmptyEnumerableReturnsSingleton() { IEnumerable<int> emptySource1 = new int[0]; var immutable = ImmutableArray.CreateRange(emptySource1); // This equality check returns true if the underlying arrays are the same instance. Assert.Equal(empty, immutable); } [Fact] public void CreateRangeFromImmutableArrayWithSelector() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, i => i + 0.5); Assert.Equal(new[] { 4.5, 5.5, 6.5, 7.5 }, copy1); var copy2 = ImmutableArray.CreateRange(array, i => i + 1); Assert.Equal(new[] { 5, 6, 7, 8 }, copy2); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(empty, i => i)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, (Func<int, int>)null)); } [Fact] public void CreateRangeFromImmutableArrayWithSelectorAndArgument() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, (i, j) => i + j, 0.5); Assert.Equal(new[] { 4.5, 5.5, 6.5, 7.5 }, copy1); var copy2 = ImmutableArray.CreateRange(array, (i, j) => i + j, 1); Assert.Equal(new[] { 5, 6, 7, 8 }, copy2); var copy3 = ImmutableArray.CreateRange(array, (int i, object j) => i, null); Assert.Equal(new[] { 4, 5, 6, 7 }, copy3); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(empty, (i, j) => i + j, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, (Func<int, int, int>)null, 0)); } [Fact] public void CreateRangeSliceFromImmutableArrayWithSelector() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, 0, 0, i => i + 0.5); Assert.Equal(new double[] { }, copy1); var copy2 = ImmutableArray.CreateRange(array, 0, 0, i => i); Assert.Equal(new int[] { }, copy2); var copy3 = ImmutableArray.CreateRange(array, 0, 1, i => i * 2); Assert.Equal(new int[] { 8 }, copy3); var copy4 = ImmutableArray.CreateRange(array, 0, 2, i => i + 1); Assert.Equal(new int[] { 5, 6 }, copy4); var copy5 = ImmutableArray.CreateRange(array, 0, 4, i => i); Assert.Equal(new int[] { 4, 5, 6, 7 }, copy5); var copy6 = ImmutableArray.CreateRange(array, 3, 1, i => i); Assert.Equal(new int[] { 7 }, copy6); var copy7 = ImmutableArray.CreateRange(array, 3, 0, i => i); Assert.Equal(new int[] { }, copy7); var copy8 = ImmutableArray.CreateRange(array, 4, 0, i => i); Assert.Equal(new int[] { }, copy8); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(empty, 0, 0, (Func<int, int>)null)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, (Func<int, int>)null)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 0, 5, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 4, 1, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 3, 2, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 1, -1, i => i)); } [Fact] public void CreateRangeSliceFromImmutableArrayWithSelectorAndArgument() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, 0, 0, (i, j) => i + j, 0.5); Assert.Equal(new double[] { }, copy1); var copy2 = ImmutableArray.CreateRange(array, 0, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy2); var copy3 = ImmutableArray.CreateRange(array, 0, 1, (i, j) => i * j, 2); Assert.Equal(new int[] { 8 }, copy3); var copy4 = ImmutableArray.CreateRange(array, 0, 2, (i, j) => i + j, 1); Assert.Equal(new int[] { 5, 6 }, copy4); var copy5 = ImmutableArray.CreateRange(array, 0, 4, (i, j) => i + j, 0); Assert.Equal(new int[] { 4, 5, 6, 7 }, copy5); var copy6 = ImmutableArray.CreateRange(array, 3, 1, (i, j) => i + j, 0); Assert.Equal(new int[] { 7 }, copy6); var copy7 = ImmutableArray.CreateRange(array, 3, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy7); var copy8 = ImmutableArray.CreateRange(array, 4, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy8); var copy9 = ImmutableArray.CreateRange(array, 0, 1, (int i, object j) => i, null); Assert.Equal(new int[] { 4 }, copy9); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(empty, 0, 0, (i, j) => i + j, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(empty, 0, 0, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(empty, -1, 1, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 0, 5, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 4, 1, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 3, 2, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 1, -1, (i, j) => i + j, 0)); } [Fact] public void CreateFromSliceOfImmutableArray() { var array = ImmutableArray.Create(4, 5, 6, 7); Assert.Equal(new[] { 4, 5 }, ImmutableArray.Create(array, 0, 2)); Assert.Equal(new[] { 5, 6 }, ImmutableArray.Create(array, 1, 2)); Assert.Equal(new[] { 6, 7 }, ImmutableArray.Create(array, 2, 2)); Assert.Equal(new[] { 7 }, ImmutableArray.Create(array, 3, 1)); Assert.Equal(new int[0], ImmutableArray.Create(array, 4, 0)); Assert.Equal(new int[] { }, ImmutableArray.Create(empty, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(empty, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, array.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 1, array.Length)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, array.Length + 1, 0)); } [Fact] public void CreateFromSliceOfImmutableArrayOptimizations() { var array = ImmutableArray.Create(4, 5, 6, 7); var slice = ImmutableArray.Create(array, 0, array.Length); Assert.Equal(array, slice); // array instance actually shared between the two } [Fact] public void CreateFromSliceOfImmutableArrayEmptyReturnsSingleton() { var array = ImmutableArray.Create(4, 5, 6, 7); var slice = ImmutableArray.Create(array, 1, 0); Assert.Equal(empty, slice); } [Fact] public void CreateFromSliceOfArray() { var array = new int[] { 4, 5, 6, 7 }; Assert.Equal(new[] { 4, 5 }, ImmutableArray.Create(array, 0, 2)); Assert.Equal(new[] { 5, 6 }, ImmutableArray.Create(array, 1, 2)); Assert.Equal(new[] { 6, 7 }, ImmutableArray.Create(array, 2, 2)); Assert.Equal(new[] { 7 }, ImmutableArray.Create(array, 3, 1)); Assert.Equal(new int[0], ImmutableArray.Create(array, 4, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, array.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 1, array.Length)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, array.Length + 1, 0)); } [Fact] public void CreateFromSliceOfArrayEmptyReturnsSingleton() { var array = new int[] { 4, 5, 6, 7 }; var slice = ImmutableArray.Create(array, 1, 0); Assert.Equal(empty, slice); slice = ImmutableArray.Create(array, array.Length, 0); Assert.Equal(empty, slice); } [Fact] public void CreateFromArray() { var source = new[] { 1, 2, 3 }; var immutable = ImmutableArray.Create(source); Assert.Equal(source, immutable); } [Fact] public void CreateFromNullArray() { int[] nullArray = null; ImmutableArray<int> immutable = ImmutableArray.Create(nullArray); Assert.False(immutable.IsDefault); Assert.Equal(0, immutable.Length); } [Fact] public void Covariance() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = derivedImmutable.As<object>(); Assert.False(baseImmutable.IsDefault); Assert.Equal(derivedImmutable, baseImmutable); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.False(derivedImmutable2.IsDefault); Assert.Equal(derivedImmutable, derivedImmutable2); // Try a cast that would fail. Assert.True(baseImmutable.As<Encoder>().IsDefault); } [Fact] public void DowncastOfDefaultStructs() { ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>); ImmutableArray<object> baseImmutable = derivedImmutable.As<object>(); Assert.True(baseImmutable.IsDefault); Assert.True(derivedImmutable.IsDefault); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.True(derivedImmutable2.IsDefault); Assert.True(derivedImmutable == derivedImmutable2); } /// <summary> /// Verifies that using an ordinary Create factory method is smart enough to reuse /// an underlying array when possible. /// </summary> [Fact] public void CovarianceImplicit() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = ImmutableArray.CreateRange<object>(derivedImmutable); Assert.Equal(derivedImmutable, baseImmutable); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.Equal(derivedImmutable, derivedImmutable2); } [Fact] public void CreateByCovariantStaticCast() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = ImmutableArray.Create<object, string>(derivedImmutable); Assert.Equal(derivedImmutable, baseImmutable); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.Equal(derivedImmutable, derivedImmutable2); } [Fact] public void CreateByCovariantStaticCastDefault() { ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>); ImmutableArray<object> baseImmutable = ImmutableArray.Create<object, string>(derivedImmutable); Assert.True(baseImmutable.IsDefault); Assert.True(derivedImmutable.IsDefault); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.True(derivedImmutable2.IsDefault); Assert.True(derivedImmutable == derivedImmutable2); } [Fact] public void ToImmutableArray() { IEnumerable<int> source = new[] { 1, 2, 3 }; ImmutableArray<int> immutable = source.ToImmutableArray(); Assert.Equal(source, immutable); ImmutableArray<int> immutable2 = immutable.ToImmutableArray(); Assert.Equal(immutable, immutable2); // this will compare array reference equality. } [Fact] public void Count() { Assert.Throws<NullReferenceException>(() => emptyDefault.Length); Assert.Throws<InvalidOperationException>(() => ((ICollection)emptyDefault).Count); Assert.Throws<InvalidOperationException>(() => ((ICollection<int>)emptyDefault).Count); Assert.Throws<InvalidOperationException>(() => ((IReadOnlyCollection<int>)emptyDefault).Count); Assert.Equal(0, empty.Length); Assert.Equal(0, ((ICollection)empty).Count); Assert.Equal(0, ((ICollection<int>)empty).Count); Assert.Equal(0, ((IReadOnlyCollection<int>)empty).Count); Assert.Equal(1, oneElement.Length); Assert.Equal(1, ((ICollection)oneElement).Count); Assert.Equal(1, ((ICollection<int>)oneElement).Count); Assert.Equal(1, ((IReadOnlyCollection<int>)oneElement).Count); } [Fact] public void IsEmpty() { Assert.Throws<NullReferenceException>(() => emptyDefault.IsEmpty); Assert.True(empty.IsEmpty); Assert.False(oneElement.IsEmpty); } [Fact] public void IndexOfDefault() { Assert.Throws<NullReferenceException>(() => emptyDefault.IndexOf(5)); Assert.Throws<NullReferenceException>(() => emptyDefault.IndexOf(5, 0)); Assert.Throws<NullReferenceException>(() => emptyDefault.IndexOf(5, 0, 0)); } [Fact] public void LastIndexOfDefault() { Assert.Throws<NullReferenceException>(() => emptyDefault.LastIndexOf(5)); Assert.Throws<NullReferenceException>(() => emptyDefault.LastIndexOf(5, 0)); Assert.Throws<NullReferenceException>(() => emptyDefault.LastIndexOf(5, 0, 0)); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => ImmutableArray.CreateRange(seq), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => ImmutableArray.CreateRange(seq), (b, v) => b.LastIndexOf(v), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void Contains() { Assert.Throws<NullReferenceException>(() => emptyDefault.Contains(0)); Assert.False(empty.Contains(0)); Assert.True(oneElement.Contains(1)); Assert.False(oneElement.Contains(2)); Assert.True(manyElements.Contains(3)); Assert.False(oneElementRefType.Contains(null)); Assert.True(twoElementRefTypeWithNull.Contains(null)); } [Fact] public void ContainsEqualityComparer() { var array = ImmutableArray.Create("a", "B"); Assert.False(array.Contains("A", StringComparer.Ordinal)); Assert.True(array.Contains("A", StringComparer.OrdinalIgnoreCase)); Assert.False(array.Contains("b", StringComparer.Ordinal)); Assert.True(array.Contains("b", StringComparer.OrdinalIgnoreCase)); } [Fact] public void Enumerator() { Assert.Throws<NullReferenceException>(() => emptyDefault.GetEnumerator()); ImmutableArray<int>.Enumerator enumerator = default(ImmutableArray<int>.Enumerator); Assert.Throws<NullReferenceException>(() => enumerator.Current); Assert.Throws<NullReferenceException>(() => enumerator.MoveNext()); enumerator = empty.GetEnumerator(); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator = manyElements.GetEnumerator(); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); } [Fact] public void ObjectEnumerator() { Assert.Throws<InvalidOperationException>(() => ((IEnumerable<int>)emptyDefault).GetEnumerator()); IEnumerator<int> enumerator = ((IEnumerable<int>)empty).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator = ((IEnumerable<int>)manyElements).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public void EnumeratorWithNullValues() { var enumerationResult = System.Linq.Enumerable.ToArray(twoElementRefTypeWithNull); Assert.Equal("1", enumerationResult[0]); Assert.Null(enumerationResult[1]); } [Fact] public void EqualityCheckComparesInternalArrayByReference() { var immutable1 = ImmutableArray.Create(1); var immutable2 = ImmutableArray.Create(1); Assert.NotEqual(immutable1, immutable2); Assert.True(immutable1.Equals(immutable1)); Assert.True(immutable1.Equals((object)immutable1)); } [Fact] public void EqualsObjectNull() { Assert.False(empty.Equals((object)null)); } [Fact] public void OperatorsAndEquality() { Assert.True(empty.Equals(empty)); var emptySame = empty; Assert.True(empty == emptySame); Assert.False(empty != emptySame); // empty and default should not be seen as equal Assert.False(empty.Equals(emptyDefault)); Assert.False(empty == emptyDefault); Assert.True(empty != emptyDefault); Assert.False(emptyDefault == empty); Assert.True(emptyDefault != empty); Assert.False(empty.Equals(oneElement)); Assert.False(empty == oneElement); Assert.True(empty != oneElement); Assert.False(oneElement == empty); Assert.True(oneElement != empty); } [Fact] public void NullableOperators() { ImmutableArray<int>? nullArray = null; ImmutableArray<int>? nonNullDefault = emptyDefault; ImmutableArray<int>? nonNullEmpty = empty; Assert.True(nullArray == nonNullDefault); Assert.False(nullArray != nonNullDefault); Assert.True(nonNullDefault == nullArray); Assert.False(nonNullDefault != nullArray); Assert.False(nullArray == nonNullEmpty); Assert.True(nullArray != nonNullEmpty); Assert.False(nonNullEmpty == nullArray); Assert.True(nonNullEmpty != nullArray); } [Fact] public void GetHashCodeTest() { Assert.Equal(0, emptyDefault.GetHashCode()); Assert.NotEqual(0, empty.GetHashCode()); Assert.NotEqual(0, oneElement.GetHashCode()); } [Fact] public void Add() { var source = new[] { 1, 2 }; var array1 = ImmutableArray.Create(source); var array2 = array1.Add(3); Assert.Equal(source, array1); Assert.Equal(new[] { 1, 2, 3 }, array2); Assert.Equal(new[] { 1 }, empty.Add(1)); } [Fact] public void AddRange() { var nothingToEmpty = empty.AddRange(Enumerable.Empty<int>()); Assert.False(nothingToEmpty.IsDefault); Assert.True(nothingToEmpty.IsEmpty); Assert.Equal(new[] { 1, 2 }, empty.AddRange(Enumerable.Range(1, 2))); Assert.Equal(new[] { 1, 2 }, empty.AddRange(new[] { 1, 2 })); Assert.Equal(new[] { 1, 2, 3, 4 }, manyElements.AddRange(new[] { 4 })); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, manyElements.AddRange(new[] { 4, 5 })); } [Fact] public void AddRangeDefaultEnumerable() { Assert.Throws<NullReferenceException>(() => emptyDefault.AddRange(Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => emptyDefault.AddRange(Enumerable.Range(1, 2))); Assert.Throws<NullReferenceException>(() => emptyDefault.AddRange(new[] { 1, 2 })); } [Fact] public void AddRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => emptyDefault.AddRange(empty)); Assert.Throws<NullReferenceException>(() => empty.AddRange(emptyDefault)); Assert.Throws<NullReferenceException>(() => emptyDefault.AddRange(oneElement)); Assert.Throws<NullReferenceException>(() => oneElement.AddRange(emptyDefault)); IEnumerable<int> emptyBoxed = empty; IEnumerable<int> emptyDefaultBoxed = emptyDefault; IEnumerable<int> oneElementBoxed = oneElement; Assert.Throws<NullReferenceException>(() => emptyDefault.AddRange(emptyBoxed)); Assert.Throws<InvalidOperationException>(() => empty.AddRange(emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => emptyDefault.AddRange(oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => oneElement.AddRange(emptyDefaultBoxed)); } [Fact] public void AddRangeNoOpIdentity() { Assert.Equal(empty, empty.AddRange(empty)); Assert.Equal(oneElement, empty.AddRange(oneElement)); // struct overload Assert.Equal(oneElement, empty.AddRange((IEnumerable<int>)oneElement)); // enumerable overload Assert.Equal(oneElement, oneElement.AddRange(empty)); } [Fact] public void Insert() { var array1 = ImmutableArray.Create<char>(); Assert.Throws<ArgumentOutOfRangeException>(() => array1.Insert(-1, 'a')); Assert.Throws<ArgumentOutOfRangeException>(() => array1.Insert(1, 'a')); var insertFirst = array1.Insert(0, 'c'); Assert.Equal(new[] { 'c' }, insertFirst); var insertLeft = insertFirst.Insert(0, 'a'); Assert.Equal(new[] { 'a', 'c' }, insertLeft); var insertRight = insertFirst.Insert(1, 'e'); Assert.Equal(new[] { 'c', 'e' }, insertRight); var insertBetween = insertLeft.Insert(1, 'b'); Assert.Equal(new[] { 'a', 'b', 'c' }, insertBetween); } [Fact] public void InsertDefault() { Assert.Throws<NullReferenceException>(() => emptyDefault.Insert(-1, 10)); Assert.Throws<NullReferenceException>(() => emptyDefault.Insert(1, 10)); Assert.Throws<NullReferenceException>(() => emptyDefault.Insert(0, 10)); } [Fact] public void InsertRangeNoOpIdentity() { Assert.Equal(empty, empty.InsertRange(0, empty)); Assert.Equal(oneElement, empty.InsertRange(0, oneElement)); // struct overload Assert.Equal(oneElement, empty.InsertRange(0, (IEnumerable<int>)oneElement)); // enumerable overload Assert.Equal(oneElement, oneElement.InsertRange(0, empty)); } [Fact] public void InsertRangeEmpty() { Assert.Throws<NullReferenceException>(() => emptyDefault.Insert(-1, 10)); Assert.Throws<NullReferenceException>(() => emptyDefault.Insert(1, 10)); Assert.Equal(new int[0], empty.InsertRange(0, Enumerable.Empty<int>())); Assert.Equal(empty, empty.InsertRange(0, Enumerable.Empty<int>())); Assert.Equal(new[] { 1 }, empty.InsertRange(0, new[] { 1 })); Assert.Equal(new[] { 2, 3, 4 }, empty.InsertRange(0, new[] { 2, 3, 4 })); Assert.Equal(new[] { 2, 3, 4 }, empty.InsertRange(0, Enumerable.Range(2, 3))); Assert.Equal(manyElements, manyElements.InsertRange(0, Enumerable.Empty<int>())); Assert.Throws<ArgumentOutOfRangeException>(() => empty.InsertRange(1, oneElement)); Assert.Throws<ArgumentOutOfRangeException>(() => empty.InsertRange(-1, oneElement)); } [Fact] public void InsertRangeDefault() { Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(1, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(-1, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(0, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(0, new[] { 1 })); Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(0, new[] { 2, 3, 4 })); Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(0, Enumerable.Range(2, 3))); } /// <summary> /// Validates that a fixed bug in the inappropriate adding of the /// Empty singleton enumerator to the reusable instances bag does not regress. /// </summary> [Fact] public void EmptyEnumeratorReuseRegressionTest() { IEnumerable<int> oneElementBoxed = oneElement; IEnumerable<int> emptyBoxed = empty; IEnumerable<int> emptyDefaultBoxed = emptyDefault; Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveRange(emptyBoxed)); Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveRange(emptyDefaultBoxed)); Assert.Throws<InvalidOperationException>(() => empty.RemoveRange(emptyDefaultBoxed)); Assert.Equal(oneElementBoxed, oneElementBoxed); } [Fact] public void InsertRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(0, empty)); Assert.Throws<NullReferenceException>(() => empty.InsertRange(0, emptyDefault)); Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(0, oneElement)); Assert.Throws<NullReferenceException>(() => oneElement.InsertRange(0, emptyDefault)); IEnumerable<int> emptyBoxed = empty; IEnumerable<int> emptyDefaultBoxed = emptyDefault; IEnumerable<int> oneElementBoxed = oneElement; Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(0, emptyBoxed)); Assert.Throws<InvalidOperationException>(() => empty.InsertRange(0, emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => emptyDefault.InsertRange(0, oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => oneElement.InsertRange(0, emptyDefaultBoxed)); } [Fact] public void InsertRangeLeft() { Assert.Equal(new[] { 7, 1, 2, 3 }, manyElements.InsertRange(0, new[] { 7 })); Assert.Equal(new[] { 7, 8, 1, 2, 3 }, manyElements.InsertRange(0, new[] { 7, 8 })); } [Fact] public void InsertRangeMid() { Assert.Equal(new[] { 1, 7, 2, 3 }, manyElements.InsertRange(1, new[] { 7 })); Assert.Equal(new[] { 1, 7, 8, 2, 3 }, manyElements.InsertRange(1, new[] { 7, 8 })); } [Fact] public void InsertRangeRight() { Assert.Equal(new[] { 1, 2, 3, 7 }, manyElements.InsertRange(3, new[] { 7 })); Assert.Equal(new[] { 1, 2, 3, 7, 8 }, manyElements.InsertRange(3, new[] { 7, 8 })); } [Fact] public void RemoveAt() { Assert.Throws<ArgumentOutOfRangeException>(() => empty.RemoveAt(0)); Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => oneElement.RemoveAt(1)); Assert.Throws<ArgumentOutOfRangeException>(() => empty.RemoveAt(-1)); Assert.Equal(new int[0], oneElement.RemoveAt(0)); Assert.Equal(new[] { 2, 3 }, manyElements.RemoveAt(0)); Assert.Equal(new[] { 1, 3 }, manyElements.RemoveAt(1)); Assert.Equal(new[] { 1, 2 }, manyElements.RemoveAt(2)); } [Fact] public void Remove() { Assert.Throws<NullReferenceException>(() => emptyDefault.Remove(5)); Assert.False(empty.Remove(5).IsDefault); Assert.True(oneElement.Remove(1).IsEmpty); Assert.Equal(new[] { 2, 3 }, manyElements.Remove(1)); Assert.Equal(new[] { 1, 3 }, manyElements.Remove(2)); Assert.Equal(new[] { 1, 2 }, manyElements.Remove(3)); } [Fact] public void RemoveRange() { Assert.Throws<ArgumentOutOfRangeException>(() => empty.RemoveRange(0, 0)); Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveRange(0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => oneElement.RemoveRange(1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => empty.RemoveRange(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => oneElement.RemoveRange(0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => oneElement.RemoveRange(0, -1)); var fourElements = ImmutableArray.Create(1, 2, 3, 4); Assert.Equal(new int[0], oneElement.RemoveRange(0, 1)); Assert.Equal(oneElement.ToArray(), oneElement.RemoveRange(0, 0)); Assert.Equal(new[] { 3, 4 }, fourElements.RemoveRange(0, 2)); Assert.Equal(new[] { 1, 4 }, fourElements.RemoveRange(1, 2)); Assert.Equal(new[] { 1, 2 }, fourElements.RemoveRange(2, 2)); } [Fact] public void RemoveRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveRange(empty)); Assert.Throws<ArgumentNullException>(() => Assert.Equal(empty, empty.RemoveRange(emptyDefault))); Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveRange(oneElement)); Assert.Throws<ArgumentNullException>(() => Assert.Equal(oneElement, oneElement.RemoveRange(emptyDefault))); IEnumerable<int> emptyBoxed = empty; IEnumerable<int> emptyDefaultBoxed = emptyDefault; IEnumerable<int> oneElementBoxed = oneElement; Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveRange(emptyBoxed)); Assert.Throws<InvalidOperationException>(() => empty.RemoveRange(emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveRange(oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => oneElement.RemoveRange(emptyDefaultBoxed)); } [Fact] public void RemoveRangeNoOpIdentity() { Assert.Equal(empty, empty.RemoveRange(empty)); Assert.Equal(empty, empty.RemoveRange(oneElement)); // struct overload Assert.Equal(empty, empty.RemoveRange((IEnumerable<int>)oneElement)); // enumerable overload Assert.Equal(oneElement, oneElement.RemoveRange(empty)); } [Fact] public void RemoveAll() { Assert.Throws<ArgumentNullException>(() => oneElement.RemoveAll(null)); var array = ImmutableArray.CreateRange(Enumerable.Range(1, 10)); var removedEvens = array.RemoveAll(n => n % 2 == 0); var removedOdds = array.RemoveAll(n => n % 2 == 1); var removedAll = array.RemoveAll(n => true); var removedNone = array.RemoveAll(n => false); Assert.Equal(new[] { 1, 3, 5, 7, 9 }, removedEvens); Assert.Equal(new[] { 2, 4, 6, 8, 10 }, removedOdds); Assert.True(removedAll.IsEmpty); Assert.Equal(Enumerable.Range(1, 10), removedNone); Assert.False(empty.RemoveAll(n => false).IsDefault); Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveAll(n => false)); } [Fact] public void RemoveRangeEnumerableTest() { var list = ImmutableArray.Create(1, 2, 3); Assert.Throws<ArgumentNullException>(() => list.RemoveRange(null)); Assert.Throws<NullReferenceException>(() => emptyDefault.RemoveRange(new int[0]).IsDefault); Assert.False(empty.RemoveRange(new int[0]).IsDefault); ImmutableArray<int> removed2 = list.RemoveRange(new[] { 2 }); Assert.Equal(2, removed2.Length); Assert.Equal(new[] { 1, 3 }, removed2); ImmutableArray<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 }); Assert.Equal(1, removed13.Length); Assert.Equal(new[] { 2 }, removed13); Assert.Equal(new[] { 1, 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(new[] { 2, 4, 5, 7, 10 })); Assert.Equal(new[] { 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(new[] { 1, 2, 4, 5, 7, 10 })); Assert.Equal(list, list.RemoveRange(new[] { 5 })); Assert.Equal(ImmutableArray.Create<int>(), ImmutableArray.Create<int>().RemoveRange(new[] { 1 })); var listWithDuplicates = ImmutableArray.Create(1, 2, 2, 3); Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 })); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 })); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2, 2 })); } [Fact] public void Replace() { Assert.Equal(new[] { 5 }, oneElement.Replace(1, 5)); Assert.Equal(new[] { 6, 2, 3 }, manyElements.Replace(1, 6)); Assert.Equal(new[] { 1, 6, 3 }, manyElements.Replace(2, 6)); Assert.Equal(new[] { 1, 2, 6 }, manyElements.Replace(3, 6)); Assert.Equal(new[] { 1, 2, 3, 4 }, ImmutableArray.Create(1, 3, 3, 4).Replace(3, 2)); } [Fact] public void ReplaceMissingThrowsTest() { Assert.Throws<ArgumentException>(() => empty.Replace(5, 3)); } [Fact] public void SetItem() { Assert.Throws<ArgumentOutOfRangeException>(() => empty.SetItem(0, 10)); Assert.Throws<NullReferenceException>(() => emptyDefault.SetItem(0, 10)); Assert.Throws<ArgumentOutOfRangeException>(() => oneElement.SetItem(1, 10)); Assert.Throws<ArgumentOutOfRangeException>(() => empty.SetItem(-1, 10)); Assert.Equal(new[] { 12345 }, oneElement.SetItem(0, 12345)); Assert.Equal(new[] { 12345, 2, 3 }, manyElements.SetItem(0, 12345)); Assert.Equal(new[] { 1, 12345, 3 }, manyElements.SetItem(1, 12345)); Assert.Equal(new[] { 1, 2, 12345 }, manyElements.SetItem(2, 12345)); } [Fact] public void CopyToArray() { { var target = new int[manyElements.Length]; manyElements.CopyTo(target); Assert.Equal(target, manyElements); } { var target = new int[0]; Assert.Throws<NullReferenceException>(() => emptyDefault.CopyTo(target)); } } [Fact] public void CopyToIntArrayIntInt() { var source = ImmutableArray.Create(1, 2, 3); var target = new int[4]; source.CopyTo(1, target, 3, 1); Assert.Equal(new[] { 0, 0, 0, 2 }, target); } [Fact] public void Concat() { var array1 = ImmutableArray.Create(1, 2, 3); var array2 = ImmutableArray.Create(4, 5, 6); var concat = array1.Concat(array2); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, concat); } /// <summary> /// Verifies reuse of the original array when concatenated to an empty array. /// </summary> [Fact] public void ConcatEdgeCases() { // empty arrays Assert.Equal(manyElements, manyElements.Concat(empty)); Assert.Equal(manyElements, empty.Concat(manyElements)); // default arrays manyElements.Concat(emptyDefault); Assert.Throws<InvalidOperationException>(() => manyElements.Concat(emptyDefault).Count()); Assert.Throws<InvalidOperationException>(() => emptyDefault.Concat(manyElements).Count()); } [Fact] public void IsDefault() { Assert.True(emptyDefault.IsDefault); Assert.False(empty.IsDefault); Assert.False(oneElement.IsDefault); } [Fact] public void IsDefaultOrEmpty() { Assert.True(empty.IsDefaultOrEmpty); Assert.True(emptyDefault.IsDefaultOrEmpty); Assert.False(oneElement.IsDefaultOrEmpty); } [Fact] public void IndexGetter() { Assert.Equal(1, oneElement[0]); Assert.Equal(1, ((IList)oneElement)[0]); Assert.Equal(1, ((IList<int>)oneElement)[0]); Assert.Equal(1, ((IReadOnlyList<int>)oneElement)[0]); Assert.Throws<IndexOutOfRangeException>(() => oneElement[1]); Assert.Throws<IndexOutOfRangeException>(() => oneElement[-1]); Assert.Throws<NullReferenceException>(() => emptyDefault[0]); Assert.Throws<InvalidOperationException>(() => ((IList)emptyDefault)[0]); Assert.Throws<InvalidOperationException>(() => ((IList<int>)emptyDefault)[0]); Assert.Throws<InvalidOperationException>(() => ((IReadOnlyList<int>)emptyDefault)[0]); } [Fact] public void ExplicitMethods() { IList<int> c = oneElement; Assert.Throws<NotSupportedException>(() => c.Add(3)); Assert.Throws<NotSupportedException>(() => c.Clear()); Assert.Throws<NotSupportedException>(() => c.Remove(3)); Assert.True(c.IsReadOnly); Assert.Throws<NotSupportedException>(() => c.Insert(0, 2)); Assert.Throws<NotSupportedException>(() => c.RemoveAt(0)); Assert.Equal(oneElement[0], c[0]); Assert.Throws<NotSupportedException>(() => c[0] = 8); var enumerator = c.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(oneElement[0], enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void Sort() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Equal(new[] { 1, 2, 3, 4 }, array.Sort()); Assert.Equal(new[] { 2, 4, 1, 3 }, array); // original array uneffected. } [Fact] public void SortRange() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Throws<ArgumentOutOfRangeException>(() => array.Sort(-1, 2, Comparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => array.Sort(1, 4, Comparer<int>.Default)); Assert.Equal(new int[] { 2, 4, 1, 3 }, array.Sort(array.Length, 0, Comparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => array.Sort(1, 2, null)); Assert.Equal(new[] { 2, 1, 4, 3 }, array.Sort(1, 2, Comparer<int>.Default)); } [Fact] public void SortComparer() { var array = ImmutableArray.Create("c", "B", "a"); Assert.Equal(new[] { "a", "B", "c" }, array.Sort(StringComparer.OrdinalIgnoreCase)); Assert.Equal(new[] { "B", "a", "c" }, array.Sort(StringComparer.Ordinal)); } [Fact] public void SortPreservesArrayWhenAlreadySorted() { var sortedArray = ImmutableArray.Create(1, 2, 3, 4); Assert.Equal(sortedArray, sortedArray.Sort()); var mostlySorted = ImmutableArray.Create(1, 2, 3, 4, 6, 5, 7, 8, 9, 10); Assert.Equal(mostlySorted, mostlySorted.Sort(0, 5, Comparer<int>.Default)); Assert.Equal(mostlySorted, mostlySorted.Sort(5, 5, Comparer<int>.Default)); Assert.Equal(Enumerable.Range(1, 10), mostlySorted.Sort(4, 2, Comparer<int>.Default)); } [Fact] public void ToBuilder() { Assert.Equal(0, empty.ToBuilder().Count); Assert.Throws<NullReferenceException>(() => emptyDefault.ToBuilder().Count); var builder = oneElement.ToBuilder(); Assert.Equal(oneElement.ToArray(), builder); builder = manyElements.ToBuilder(); Assert.Equal(manyElements.ToArray(), builder); // Make sure that changing the builder doesn't change the original immutable array. int expected = manyElements[0]; builder[0] = expected + 1; Assert.Equal(expected, manyElements[0]); Assert.Equal(expected + 1, builder[0]); } [Fact] public void StructuralEquatableEqualsDefault() { IStructuralEquatable eq = emptyDefault; Assert.True(eq.Equals(emptyDefault, EqualityComparer<int>.Default)); Assert.False(eq.Equals(empty, EqualityComparer<int>.Default)); Assert.False(eq.Equals(oneElement, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableEquals() { IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); var otherArray = new object[] { 1, 2, 3 }; var otherImmArray = ImmutableArray.Create(otherArray); var unequalArray = new int[] { 1, 2, 4 }; var unequalImmArray = ImmutableArray.Create(unequalArray); var unrelatedArray = new string[3]; var unrelatedImmArray = ImmutableArray.Create(unrelatedArray); var otherList = new List<int> { 1, 2, 3 }; Assert.Equal(array.Equals(otherArray, EqualityComparer<int>.Default), immArray.Equals(otherImmArray, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(otherList, EqualityComparer<int>.Default), immArray.Equals(otherList, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(unrelatedArray, EverythingEqual<object>.Default), immArray.Equals(unrelatedImmArray, EverythingEqual<object>.Default)); Assert.Equal(array.Equals(new object(), EqualityComparer<int>.Default), immArray.Equals(new object(), EqualityComparer<int>.Default)); Assert.Equal(array.Equals(null, EqualityComparer<int>.Default), immArray.Equals(null, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(unequalArray, EqualityComparer<int>.Default), immArray.Equals(unequalImmArray, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableEqualsArrayInterop() { IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); var unequalArray = new int[] { 1, 2, 4 }; Assert.True(immArray.Equals(array, EqualityComparer<int>.Default)); Assert.False(immArray.Equals(unequalArray, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableGetHashCodeDefault() { IStructuralEquatable defaultImmArray = emptyDefault; Assert.Equal(0, defaultImmArray.GetHashCode(EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableGetHashCode() { IStructuralEquatable emptyArray = new int[0]; IStructuralEquatable emptyImmArray = empty; IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); Assert.Equal(emptyArray.GetHashCode(EqualityComparer<int>.Default), emptyImmArray.GetHashCode(EqualityComparer<int>.Default)); Assert.Equal(array.GetHashCode(EqualityComparer<int>.Default), immArray.GetHashCode(EqualityComparer<int>.Default)); Assert.Equal(array.GetHashCode(EverythingEqual<int>.Default), immArray.GetHashCode(EverythingEqual<int>.Default)); } [Fact] public void StructuralComparableDefault() { IStructuralComparable def = emptyDefault; IStructuralComparable mt = empty; // default to default is fine, and should be seen as equal. Assert.Equal(0, def.CompareTo(emptyDefault, Comparer<int>.Default)); // default to empty and vice versa should throw, on the basis that // arrays compared that are of different lengths throw. Empty vs. default aren't really compatible. Assert.Throws<ArgumentException>(() => def.CompareTo(empty, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => mt.CompareTo(emptyDefault, Comparer<int>.Default)); } [Fact] public void StructuralComparable() { IStructuralComparable array = new int[3] { 1, 2, 3 }; IStructuralComparable equalArray = new int[3] { 1, 2, 3 }; IStructuralComparable immArray = ImmutableArray.Create((int[])array); IStructuralComparable equalImmArray = ImmutableArray.Create((int[])equalArray); IStructuralComparable longerArray = new int[] { 1, 2, 3, 4 }; IStructuralComparable longerImmArray = ImmutableArray.Create((int[])longerArray); Assert.Equal(array.CompareTo(equalArray, Comparer<int>.Default), immArray.CompareTo(equalImmArray, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => array.CompareTo(longerArray, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => immArray.CompareTo(longerImmArray, Comparer<int>.Default)); var list = new List<int> { 1, 2, 3 }; Assert.Throws<ArgumentException>(() => array.CompareTo(list, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => immArray.CompareTo(list, Comparer<int>.Default)); } [Fact] public void StructuralComparableArrayInterop() { IStructuralComparable array = new int[3] { 1, 2, 3 }; IStructuralComparable equalArray = new int[3] { 1, 2, 3 }; IStructuralComparable immArray = ImmutableArray.Create((int[])array); IStructuralComparable equalImmArray = ImmutableArray.Create((int[])equalArray); Assert.Equal(array.CompareTo(equalArray, Comparer<int>.Default), immArray.CompareTo(equalArray, Comparer<int>.Default)); } [Fact] public void BinarySearch() { Assert.Throws<ArgumentNullException>(() => Assert.Equal(Array.BinarySearch(new int[0], 5), ImmutableArray.BinarySearch(default(ImmutableArray<int>), 5))); Assert.Equal(Array.BinarySearch(new int[0], 5), ImmutableArray.BinarySearch(ImmutableArray.Create<int>(), 5)); Assert.Equal(Array.BinarySearch(new int[] { 3 }, 5), ImmutableArray.BinarySearch(ImmutableArray.Create(3), 5)); Assert.Equal(Array.BinarySearch(new int[] { 5 }, 5), ImmutableArray.BinarySearch(ImmutableArray.Create(5), 5)); } [Fact] public void OfType() { Assert.Equal(0, emptyDefault.OfType<int>().Count()); Assert.Equal(0, empty.OfType<int>().Count()); Assert.Equal(1, oneElement.OfType<int>().Count()); Assert.Equal(1, twoElementRefTypeWithNull.OfType<string>().Count()); } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { return ImmutableArray.Create(contents); } /// <summary> /// A structure that takes exactly 3 bytes of memory. /// </summary> private struct ThreeByteStruct : IEquatable<ThreeByteStruct> { public ThreeByteStruct(byte first, byte second, byte third) { this.Field1 = first; this.Field2 = second; this.Field3 = third; } public byte Field1; public byte Field2; public byte Field3; public bool Equals(ThreeByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3; } public override bool Equals(object obj) { if (obj is ThreeByteStruct) { return this.Equals((ThreeByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } /// <summary> /// A structure that takes exactly 9 bytes of memory. /// </summary> private struct NineByteStruct : IEquatable<NineByteStruct> { public NineByteStruct(int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth, int ninth) { this.Field1 = (byte)first; this.Field2 = (byte)second; this.Field3 = (byte)third; this.Field4 = (byte)fourth; this.Field5 = (byte)fifth; this.Field6 = (byte)sixth; this.Field7 = (byte)seventh; this.Field8 = (byte)eighth; this.Field9 = (byte)ninth; } public byte Field1; public byte Field2; public byte Field3; public byte Field4; public byte Field5; public byte Field6; public byte Field7; public byte Field8; public byte Field9; public bool Equals(NineByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3 && this.Field4 == other.Field4 && this.Field5 == other.Field5 && this.Field6 == other.Field6 && this.Field7 == other.Field7 && this.Field8 == other.Field8 && this.Field9 == other.Field9; } public override bool Equals(object obj) { if (obj is NineByteStruct) { return this.Equals((NineByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } /// <summary> /// A structure that requires 9 bytes of memory but occupies 12 because of memory alignment. /// </summary> private struct TwelveByteStruct : IEquatable<TwelveByteStruct> { public TwelveByteStruct(int first, int second, byte third) { this.Field1 = first; this.Field2 = second; this.Field3 = third; } public int Field1; public int Field2; public byte Field3; public bool Equals(TwelveByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3; } public override bool Equals(object obj) { if (obj is TwelveByteStruct) { return this.Equals((TwelveByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } private struct StructWithReferenceTypeField { public string foo; public StructWithReferenceTypeField(string foo) { this.foo = foo; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Validation; using Xunit; using SetTriad = System.Tuple<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>, bool>; namespace System.Collections.Immutable.Test { public abstract class ImmutableSetTest : ImmutablesTestBase { [Fact] public void AddTest() { this.AddTestHelper(this.Empty<int>(), 3, 5, 4, 3); } [Fact] public void AddDuplicatesTest() { var arrayWithDuplicates = Enumerable.Range(1, 100).Concat(Enumerable.Range(1, 100)).ToArray(); this.AddTestHelper(this.Empty<int>(), arrayWithDuplicates); } [Fact] public void RemoveTest() { this.RemoveTestHelper(this.Empty<int>().Add(3).Add(5), 5, 3); } [Fact] public void AddRemoveLoadTest() { var data = this.GenerateDummyFillData(); this.AddRemoveLoadTestHelper(Empty<double>(), data); } [Fact] public void RemoveNonExistingTest() { this.RemoveNonExistingTest(this.Empty<int>()); } [Fact] public void AddBulkFromImmutableToEmpty() { var set = this.Empty<int>().Add(5); var empty2 = this.Empty<int>(); Assert.Same(set, empty2.Union(set)); // "Filling an empty immutable set with the contents of another immutable set with the exact same comparer should return the other set." } [Fact] public void ExceptTest() { this.ExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), 3, 7); } [Fact] public void SymmetricExceptTest() { this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 9).ToArray()); this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 5).ToArray()); } [Fact] public void EnumeratorTest() { IComparer<double> comparer = null; var set = this.Empty<double>(); var sortedSet = set as ISortKeyCollection<double>; if (sortedSet != null) { comparer = sortedSet.KeyComparer; } this.EnumeratorTestHelper(set, comparer, 3, 5, 1); double[] data = this.GenerateDummyFillData(); this.EnumeratorTestHelper(set, comparer, data); } [Fact] public void IntersectTest() { this.IntersectTestHelper(Empty<int>().Union(Enumerable.Range(1, 10)), 8, 3, 5); } [Fact] public void UnionTest() { var values1 = new[] { 2, 4, 6 }; var values2 = new[] { 1, 3, 5, 8 }; this.UnionTestHelper(this.Empty<int>().Union(values1), values2); } [Fact] public void SetEqualsTest() { this.SetCompareTestHelper(s => s.SetEquals, s => s.SetEquals, this.GetSetEqualsScenarios()); } [Fact] public void IsProperSubsetOfTest() { this.SetCompareTestHelper(s => s.IsProperSubsetOf, s => s.IsProperSubsetOf, this.GetIsProperSubsetOfScenarios()); } [Fact] public void IsProperSupersetOfTest() { this.SetCompareTestHelper(s => s.IsProperSupersetOf, s => s.IsProperSupersetOf, this.GetIsProperSubsetOfScenarios().Select(Flip)); } [Fact] public void IsSubsetOfTest() { this.SetCompareTestHelper(s => s.IsSubsetOf, s => s.IsSubsetOf, this.GetIsSubsetOfScenarios()); } [Fact] public void IsSupersetOfTest() { this.SetCompareTestHelper(s => s.IsSupersetOf, s => s.IsSupersetOf, this.GetIsSubsetOfScenarios().Select(Flip)); } [Fact] public void OverlapsTest() { this.SetCompareTestHelper(s => s.Overlaps, s => s.Overlaps, this.GetOverlapsScenarios()); } [Fact] public void EqualsTest() { Assert.False(Empty<int>().Equals(null)); Assert.False(Empty<int>().Equals("hi")); Assert.True(Empty<int>().Equals(Empty<int>())); Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3))); Assert.False(Empty<int>().Add(5).Equals(Empty<int>().Add(3))); Assert.False(Empty<int>().Add(3).Add(5).Equals(Empty<int>().Add(3))); Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3).Add(5))); } [Fact] public void GetHashCodeTest() { // verify that get hash code is the default address based one. Assert.Equal(EqualityComparer<object>.Default.GetHashCode(Empty<int>()), Empty<int>().GetHashCode()); } [Fact] public void ClearTest() { var originalSet = this.Empty<int>(); var nonEmptySet = originalSet.Add(5); var clearedSet = nonEmptySet.Clear(); Assert.Same(originalSet, clearedSet); } [Fact] public void ISetMutationMethods() { var set = (ISet<int>)this.Empty<int>(); Assert.Throws<NotSupportedException>(() => set.Add(0)); Assert.Throws<NotSupportedException>(() => set.ExceptWith(null)); Assert.Throws<NotSupportedException>(() => set.UnionWith(null)); Assert.Throws<NotSupportedException>(() => set.IntersectWith(null)); Assert.Throws<NotSupportedException>(() => set.SymmetricExceptWith(null)); } [Fact] public void ICollectionOfTMembers() { var set = (ICollection<int>)this.Empty<int>(); Assert.Throws<NotSupportedException>(() => set.Add(1)); Assert.Throws<NotSupportedException>(() => set.Clear()); Assert.Throws<NotSupportedException>(() => set.Remove(1)); Assert.True(set.IsReadOnly); } [Fact] public void ICollectionMethods() { var builder = (ICollection)this.Empty<string>().Add("a"); var array = new string[builder.Count + 1]; builder.CopyTo(array, 1); Assert.Equal(new[] { null, "a" }, array); Assert.True(builder.IsSynchronized); Assert.NotNull(builder.SyncRoot); Assert.Same(builder.SyncRoot, builder.SyncRoot); } protected abstract bool IncludesGetHashCodeDerivative { get; } internal static List<T> ToListNonGeneric<T>(System.Collections.IEnumerable sequence) { Contract.Requires(sequence != null); var list = new List<T>(); var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { list.Add((T)enumerator.Current); } return list; } protected abstract IImmutableSet<T> Empty<T>(); protected abstract ISet<T> EmptyMutable<T>(); protected void TryGetValueTestHelper(IImmutableSet<string> set) { Requires.NotNull(set, "set"); string expected = "egg"; set = set.Add(expected); string actual; string lookupValue = expected.ToUpperInvariant(); Assert.True(set.TryGetValue(lookupValue, out actual)); Assert.Same(expected, actual); Assert.False(set.TryGetValue("foo", out actual)); Assert.Equal("foo", actual); Assert.False(set.Clear().TryGetValue("nonexistent", out actual)); Assert.Equal("nonexistent", actual); } protected IImmutableSet<T> SetWith<T>(params T[] items) { return this.Empty<T>().Union(items); } protected void CustomSortTestHelper<T>(IImmutableSet<T> emptySet, bool matchOrder, T[] injectedValues, T[] expectedValues) { Contract.Requires(emptySet != null); Contract.Requires(injectedValues != null); Contract.Requires(expectedValues != null); var set = emptySet; foreach (T value in injectedValues) { set = set.Add(value); } Assert.Equal(expectedValues.Length, set.Count); if (matchOrder) { Assert.Equal<T>(expectedValues, set.ToList()); } else { CollectionAssertAreEquivalent(expectedValues, set.ToList()); } } /// <summary> /// Tests various aspects of a set. This should be called only from the unordered or sorted overloads of this method. /// </summary> /// <typeparam name="T">The type of element stored in the set.</typeparam> /// <param name="emptySet">The empty set.</param> protected void EmptyTestHelper<T>(IImmutableSet<T> emptySet) { Contract.Requires(emptySet != null); Assert.Equal(0, emptySet.Count); //, "Empty set should have a Count of 0"); Assert.Equal(0, emptySet.Count()); //, "Enumeration of an empty set yielded elements."); Assert.Same(emptySet, emptySet.Clear()); } private IEnumerable<SetTriad> GetSetEqualsScenarios() { return new List<SetTriad> { new SetTriad(SetWith<int>(), new int[] { }, true), new SetTriad(SetWith<int>(5), new int[] { 5 }, true), new SetTriad(SetWith<int>(5), new int[] { 5, 5 }, true), new SetTriad(SetWith<int>(5, 8), new int[] { 5, 5 }, false), new SetTriad(SetWith<int>(5, 8), new int[] { 5, 7 }, false), new SetTriad(SetWith<int>(5, 8), new int[] { 5, 8 }, true), new SetTriad(SetWith<int>(5), new int[] { }, false), new SetTriad(SetWith<int>(), new int[] { 5 }, false), new SetTriad(SetWith<int>(5, 8), new int[] { 5 }, false), new SetTriad(SetWith<int>(5), new int[] { 5, 8 }, false), }; } private IEnumerable<SetTriad> GetIsProperSubsetOfScenarios() { return new List<SetTriad> { new SetTriad(new int[] { }, new int[] { }, false), new SetTriad(new int[] { 1 }, new int[] { }, false), new SetTriad(new int[] { 1 }, new int[] { 2 }, false), new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false), new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true), new SetTriad(new int[] { }, new int[] { 1 }, true), }; } private IEnumerable<SetTriad> GetIsSubsetOfScenarios() { var results = new List<SetTriad> { new SetTriad(new int[] { }, new int[] { }, true), new SetTriad(new int[] { 1 }, new int[] { 1 }, true), new SetTriad(new int[] { 1, 2 }, new int[] { 1, 2 }, true), new SetTriad(new int[] { 1 }, new int[] { }, false), new SetTriad(new int[] { 1 }, new int[] { 2 }, false), new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false), }; // By definition, any proper subset is also a subset. // But because a subset may not be a proper subset, we filter the proper- scenarios. results.AddRange(this.GetIsProperSubsetOfScenarios().Where(s => s.Item3)); return results; } private IEnumerable<SetTriad> GetOverlapsScenarios() { return new List<SetTriad> { new SetTriad(new int[] { }, new int[] { }, false), new SetTriad(new int[] { }, new int[] { 1 }, false), new SetTriad(new int[] { 1 }, new int[] { 2 }, false), new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false), new SetTriad(new int[] { 1, 2 }, new int[] { 3 }, false), new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true), new SetTriad(new int[] { 1, 2 }, new int[] { 1 }, true), new SetTriad(new int[] { 1 }, new int[] { 1 }, true), new SetTriad(new int[] { 1, 2 }, new int[] { 2, 3, 4 }, true), }; } private void SetCompareTestHelper<T>(Func<IImmutableSet<T>, Func<IEnumerable<T>, bool>> operation, Func<ISet<T>, Func<IEnumerable<T>, bool>> baselineOperation, IEnumerable<Tuple<IEnumerable<T>, IEnumerable<T>, bool>> scenarios) { //const string message = "Scenario #{0}: Set 1: {1}, Set 2: {2}"; int iteration = 0; foreach (var scenario in scenarios) { iteration++; // Figure out the response expected based on the BCL mutable collections. var baselineSet = this.EmptyMutable<T>(); baselineSet.UnionWith(scenario.Item1); var expectedFunc = baselineOperation(baselineSet); bool expected = expectedFunc(scenario.Item2); Assert.Equal(expected, scenario.Item3); //, "Test scenario has an expected result that is inconsistent with BCL mutable collection behavior."); var actualFunc = operation(this.SetWith(scenario.Item1.ToArray())); var args = new object[] { iteration, ToStringDeferred(scenario.Item1), ToStringDeferred(scenario.Item2) }; Assert.Equal(scenario.Item3, actualFunc(this.SetWith(scenario.Item2.ToArray()))); //, message, args); Assert.Equal(scenario.Item3, actualFunc(scenario.Item2)); //, message, args); } } private static Tuple<IEnumerable<T>, IEnumerable<T>, bool> Flip<T>(Tuple<IEnumerable<T>, IEnumerable<T>, bool> scenario) { return new Tuple<IEnumerable<T>, IEnumerable<T>, bool>(scenario.Item2, scenario.Item1, scenario.Item3); } private void RemoveTestHelper<T>(IImmutableSet<T> set, params T[] values) { Contract.Requires(set != null); Contract.Requires(values != null); Assert.Same(set, set.Except(Enumerable.Empty<T>())); int initialCount = set.Count; int removedCount = 0; foreach (T value in values) { var nextSet = set.Remove(value); Assert.NotSame(set, nextSet); Assert.Equal(initialCount - removedCount, set.Count); Assert.Equal(initialCount - removedCount - 1, nextSet.Count); Assert.Same(nextSet, nextSet.Remove(value)); //, "Removing a non-existing element should not change the set reference."); removedCount++; set = nextSet; } Assert.Equal(initialCount - removedCount, set.Count); } private void RemoveNonExistingTest(IImmutableSet<int> emptySet) { Assert.Same(emptySet, emptySet.Remove(5)); // Also fill up a set with many elements to build up the tree, then remove from various places in the tree. const int Size = 200; var set = emptySet; for (int i = 0; i < Size; i += 2) { // only even numbers! set = set.Add(i); } // Verify that removing odd numbers doesn't change anything. for (int i = 1; i < Size; i += 2) { var setAfterRemoval = set.Remove(i); Assert.Same(set, setAfterRemoval); } } private void AddRemoveLoadTestHelper<T>(IImmutableSet<T> set, T[] data) { Contract.Requires(set != null); Contract.Requires(data != null); foreach (T value in data) { var newSet = set.Add(value); Assert.NotSame(set, newSet); set = newSet; } foreach (T value in data) { Assert.True(set.Contains(value)); } foreach (T value in data) { var newSet = set.Remove(value); Assert.NotSame(set, newSet); set = newSet; } } protected void EnumeratorTestHelper<T>(IImmutableSet<T> emptySet, IComparer<T> comparer, params T[] values) { var set = emptySet; foreach (T value in values) { set = set.Add(value); } var nonGenericEnumerableList = ToListNonGeneric<T>(set); CollectionAssertAreEquivalent(nonGenericEnumerableList, values); var list = set.ToList(); CollectionAssertAreEquivalent(list, values); if (comparer != null) { Array.Sort(values, comparer); Assert.Equal<T>(values, list); } // Apply some less common uses to the enumerator to test its metal. IEnumerator<T> enumerator; using (enumerator = set.GetEnumerator()) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Reset(); // reset isn't usually called before MoveNext Assert.Throws<InvalidOperationException>(() => enumerator.Current); ManuallyEnumerateTest(list, enumerator); Assert.False(enumerator.MoveNext()); // call it again to make sure it still returns false enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); ManuallyEnumerateTest(list, enumerator); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // this time only partially enumerate enumerator.Reset(); enumerator.MoveNext(); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); } Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); } private void ExceptTestHelper<T>(IImmutableSet<T> set, params T[] valuesToRemove) { Contract.Requires(set != null); Contract.Requires(valuesToRemove != null); var expectedSet = new HashSet<T>(set); expectedSet.ExceptWith(valuesToRemove); var actualSet = set.Except(valuesToRemove); CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList()); } private void SymmetricExceptTestHelper<T>(IImmutableSet<T> set, params T[] otherCollection) { Contract.Requires(set != null); Contract.Requires(otherCollection != null); var expectedSet = new HashSet<T>(set); expectedSet.SymmetricExceptWith(otherCollection); var actualSet = set.SymmetricExcept(otherCollection); CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList()); } private void IntersectTestHelper<T>(IImmutableSet<T> set, params T[] values) { Contract.Requires(set != null); Contract.Requires(values != null); Assert.True(set.Intersect(Enumerable.Empty<T>()).Count == 0); var expected = new HashSet<T>(set); expected.IntersectWith(values); var actual = set.Intersect(values); CollectionAssertAreEquivalent(expected.ToList(), actual.ToList()); } private void UnionTestHelper<T>(IImmutableSet<T> set, params T[] values) { Contract.Requires(set != null); Contract.Requires(values != null); var expected = new HashSet<T>(set); expected.UnionWith(values); var actual = set.Union(values); CollectionAssertAreEquivalent(expected.ToList(), actual.ToList()); } private void AddTestHelper<T>(IImmutableSet<T> set, params T[] values) { Contract.Requires(set != null); Contract.Requires(values != null); Assert.Same(set, set.Union(Enumerable.Empty<T>())); int initialCount = set.Count; var uniqueValues = new HashSet<T>(values); var enumerateAddSet = set.Union(values); Assert.Equal(initialCount + uniqueValues.Count, enumerateAddSet.Count); foreach (T value in values) { Assert.True(enumerateAddSet.Contains(value)); } int addedCount = 0; foreach (T value in values) { bool duplicate = set.Contains(value); var nextSet = set.Add(value); Assert.True(nextSet.Count > 0); Assert.Equal(initialCount + addedCount, set.Count); int expectedCount = initialCount + addedCount; if (!duplicate) { expectedCount++; } Assert.Equal(expectedCount, nextSet.Count); Assert.Equal(duplicate, set.Contains(value)); Assert.True(nextSet.Contains(value)); if (!duplicate) { addedCount++; } // Next assert temporarily disabled because Roslyn's set doesn't follow this rule. Assert.Same(nextSet, nextSet.Add(value)); //, "Adding duplicate value {0} should keep the original reference.", value); set = nextSet; } } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using AbpCompanyName.AbpProjectName.EntityFrameworkCore; namespace AbpCompanyName.AbpProjectName.Migrations { [DbContext(typeof(AbpProjectNameDbContext))] [Migration("20170621153937_Added_Description_And_IsActive_To_Role")] partial class Added_Description_And_IsActive_To_Role { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.2") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("CustomData") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("Exception") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Parameters") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Icon") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsDisabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("UserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("Code") .IsRequired() .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("AbpCompanyName.AbpProjectName.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("AbpCompanyName.AbpProjectName.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("Surname") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("AbpCompanyName.AbpProjectName.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConnectionString") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("TenantId") .HasColumnType("int"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("AbpCompanyName.AbpProjectName.Authorization.Roles.Role", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("AbpCompanyName.AbpProjectName.Authorization.Users.User", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("AbpCompanyName.AbpProjectName.MultiTenancy.Tenant", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("AbpCompanyName.AbpProjectName.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
using System; using System.Collections; using System.Data; using System.Data.OleDb; using System.Drawing.Printing; using System.Reflection; using System.Text; using C1.Win.C1Preview; using C1.C1Report; using PCSComUtils.Common; using PCSUtils.Framework.ReportFrame; using PCSUtils.Utils; using C1PrintPreviewDialog = PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog; namespace StdActCostComparision { /// <summary> /// Compare Standard and Actual Cost /// </summary> [Serializable] public class StdActCostComparision : MarshalByRefObject, IDynamicReport { public StdActCostComparision() { // // TODO: Add constructor logic here // } #region IDynamicReport Members private ReportBuilder mReportBuilder; public ReportBuilder PCSReportBuilder { get { return mReportBuilder; } set { mReportBuilder = value; } } private string mConnectionString = string.Empty; public string PCSConnectionString { get { return mConnectionString; } set { mConnectionString = value; } } private string mLayoutFile = string.Empty; public string ReportLayoutFile { get { return mLayoutFile; } set { mLayoutFile = value; } } private object mResult; public object Result { get { return mResult; } set { mResult = value; } } private string mDefFolder = string.Empty; public string ReportDefinitionFolder { get { return mDefFolder; } set { mDefFolder = value; } } private bool mUseEngine; public bool UseReportViewerRenderEngine { get { return mUseEngine; } set { mUseEngine = value; } } public object Invoke(string pstrMethod, object[] pobjParameters) { return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters); } private C1PrintPreviewControl mPreview; public C1PrintPreviewControl PCSReportViewer { get { return mPreview; } set { mPreview = value; } } #endregion #region constants private const string CATEGORY_FLD = "Category"; private const string MODEL_FLD = "Model"; private const string PRODUCTID_FLD = "ProductID"; private const string PART_NO_FLD = "PartNo"; private const string PART_NAME_FLD = "PartName"; private const string UM_FLD = "UM"; private const string COST_ELEMENT_FLD = "CostElement"; private const string STDCOST_FLD = "Std"; private const string ACTUAL_COST_FLD = "Actual"; private const string DIFFERENCE_FLD = "Diff"; private const string FROMDATE_FLD = "FromDate"; private const string TODATE_FLD = "ToDate"; private const string PERIODID_FLD = "ActCostAllocationMasterID"; #endregion public DataTable ExecuteReport(string pstrCCNID, string pstrYear, string pstrCategoryID, string pstrDepartmentID, string pstrProductionLineID, string pstrModel, string pstrProductID) { #region create table schema DataTable dtbData = new DataTable(); dtbData.Columns.Add(new DataColumn(CATEGORY_FLD, typeof(string))); dtbData.Columns.Add(new DataColumn(MODEL_FLD, typeof(string))); dtbData.Columns.Add(new DataColumn(PART_NO_FLD, typeof(string))); dtbData.Columns.Add(new DataColumn(PART_NAME_FLD, typeof(string))); dtbData.Columns.Add(new DataColumn(UM_FLD, typeof(string))); dtbData.Columns.Add(new DataColumn(COST_ELEMENT_FLD, typeof(string))); dtbData.Columns.Add(new DataColumn(PRODUCTID_FLD, typeof(string))); // create 3 columns for each month for (int i = 1; i <= 12; i++) { dtbData.Columns.Add(new DataColumn(STDCOST_FLD + i.ToString("00"), typeof(decimal))); dtbData.Columns.Add(new DataColumn(ACTUAL_COST_FLD + i.ToString("00"), typeof(decimal))); dtbData.Columns.Add(new DataColumn(DIFFERENCE_FLD + i.ToString("00"), typeof(decimal))); } #endregion // list all periods DataTable dtbAllPeriod = GetAllPeriod(pstrCCNID); // list all elements DataTable dtbElements = GetCostElements(); // list all products DataTable dtbAllItems = ListItems(pstrCCNID); // build the periods id which pass thru selected year StringBuilder sbPeriods = new StringBuilder(); sbPeriods.Append("0"); foreach (DataRow drowData in dtbAllPeriod.Rows) { DateTime dtmFromDate = DateTime.Parse(drowData[FROMDATE_FLD].ToString()); DateTime dtmToDate = DateTime.Parse(drowData[TODATE_FLD].ToString()); for (DateTime dtmDate = dtmFromDate; dtmDate <= dtmToDate; dtmDate = dtmDate.AddYears(1)) { if (dtmDate.Year == int.Parse(pstrYear)) { sbPeriods.Append("," + drowData[PERIODID_FLD].ToString()); break; } } } // gets temp report data DataTable dtbReportData = GetReportData(pstrCCNID, sbPeriods.ToString(), pstrCategoryID, pstrDepartmentID, pstrProductionLineID, pstrProductID, pstrModel); // cost center rate data DataTable dtbRate = GetCostCenterRate(pstrCCNID); // standard cost DataTable dtbSTDCost = GetSTDCost(); // allocation DataTable dtbAllocation = GetAllocation(); // get list of product in report data ArrayList arrProducts = new ArrayList(); foreach (DataRow drowData in dtbReportData.Rows) { string strProductID = drowData[PRODUCTID_FLD].ToString(); if (!arrProducts.Contains(strProductID)) arrProducts.Add(strProductID); } // loops thru the product list to build original data foreach (string strProductID in arrProducts) { DataRow drowProductInfo = GetItemInfo(strProductID, dtbAllItems); foreach (DataRow drowElement in dtbElements.Rows) { // each element will appears as one row in report DataRow drowReport = dtbData.NewRow(); drowReport[PRODUCTID_FLD] = strProductID; string strElementID = drowElement["CostElementID"].ToString(); int intElementType = Convert.ToInt32(drowElement["TypeCode"]); decimal decCostRate = 0; string strFilterRate = "CostCenterRateMasterID = " + drowProductInfo["CostCenterRateMasterID"].ToString() + " AND CostElementID = " + strElementID; try { decCostRate = Convert.ToDecimal(dtbRate.Compute("SUM(Cost)", strFilterRate)); } catch{} for (int i = 1; i <= 12; i++) { DateTime dtmMonth = new DateTime(Convert.ToInt32(pstrYear), i, 1); // find the period if of current month string strCurrentPeriodID = FindPeriodOfMonth(dtmMonth, dtbAllPeriod); // current month does not have any period if (strCurrentPeriodID == string.Empty) { drowReport[CATEGORY_FLD] = drowProductInfo[CATEGORY_FLD]; drowReport[MODEL_FLD] = drowProductInfo[MODEL_FLD]; drowReport[PART_NO_FLD] = drowProductInfo[PART_NO_FLD]; drowReport[PART_NAME_FLD] = drowProductInfo[PART_NAME_FLD]; drowReport[UM_FLD] = drowProductInfo[UM_FLD]; drowReport[COST_ELEMENT_FLD] = drowElement["Name"]; #region standard cost decimal decSTDCost = 0; switch (intElementType) { case (int)CostElementType.Material: // item standard cost string strFilterSTD = "ProductID = " + strProductID; try { decSTDCost = Convert.ToDecimal(dtbSTDCost.Compute("SUM(Cost)", strFilterSTD)); } catch{} decSTDCost = decSTDCost + decCostRate; break; default: // std cost = cost rate decSTDCost = decCostRate; break; } if (decSTDCost != 0) { drowReport[STDCOST_FLD + i.ToString("00")] = decSTDCost; drowReport[DIFFERENCE_FLD + i.ToString("00")] = decSTDCost; } else { drowReport[STDCOST_FLD + i.ToString("00")] = DBNull.Value; drowReport[DIFFERENCE_FLD + i.ToString("00")] = DBNull.Value; } #endregion drowReport[ACTUAL_COST_FLD + i.ToString("00")] = DBNull.Value; drowReport[DIFFERENCE_FLD + i.ToString("00")] = DBNull.Value; } else { string strFilter = PRODUCTID_FLD + "='" + strProductID + "'" + " AND ActCostAllocationMasterID ='" + strCurrentPeriodID + "'" + " AND CostElementID = '" + strElementID + "'"; DataRow[] drowsElement = dtbReportData.Select(strFilter); if (drowsElement.Length > 0) { drowReport[CATEGORY_FLD] = drowsElement[0][CATEGORY_FLD]; drowReport[MODEL_FLD] = drowsElement[0][MODEL_FLD]; drowReport[PART_NO_FLD] = drowsElement[0][PART_NO_FLD]; drowReport[PART_NAME_FLD] = drowsElement[0][PART_NAME_FLD]; drowReport[UM_FLD] = drowsElement[0][UM_FLD]; drowReport[COST_ELEMENT_FLD] = drowsElement[0][COST_ELEMENT_FLD]; decimal decSTDCost = 0, decActualCost = 0, decQuantity = 0; decimal decBeginQuantity = 0, decPreviousActCost = 0, decAlloc = 0; decimal decSumComponentValue = 0, decComponentValue = 0; #region standard cost switch (intElementType) { case (int)CostElementType.Material: // item standard cost string strFilterSTD = "ProductID = " + strProductID; try { decSTDCost = Convert.ToDecimal(dtbSTDCost.Compute("SUM(Cost)", strFilterSTD)); } catch{} decSTDCost = decSTDCost + decCostRate; break; default: // std cost = cost rate decSTDCost = decCostRate; break; } if (decSTDCost != 0) { drowReport[STDCOST_FLD + i.ToString("00")] = decSTDCost; drowReport[DIFFERENCE_FLD + i.ToString("00")] = decSTDCost; } else { drowReport[STDCOST_FLD + i.ToString("00")] = DBNull.Value; drowReport[DIFFERENCE_FLD + i.ToString("00")] = DBNull.Value; } #endregion #region Calculate actual cost // quantity of current period try { decQuantity = Convert.ToDecimal(drowsElement[0]["Quantity"]); } catch{} // begin quantity of current period try { decBeginQuantity = Convert.ToDecimal(drowsElement[0]["BeginQuantity"]); } catch{} // allocation amount string strAllocFilter = "ProductID = " + strProductID + " AND CostElementID = " + strElementID; try { decAlloc = Convert.ToDecimal(dtbAllocation.Compute("SUM(Amount)", strAllocFilter)); } catch{} switch (intElementType) { case (int)CostElementType.Material: // // actual cost of current preiod // try // { // decActualCost = Convert.ToDecimal(drowsElement[0]["ActualCost"]); // } // catch{} // // #region actual cost of previous period // try // { // decPreviousActCost = Convert.ToDecimal(drowsElement[0]["BeginCost"]); // } // catch{} // #endregion // // // (CST_ActualCostHistory.ElementType.ActualCost* CST_ActualCostHistory.Qty- // // PreviousPeriod.CST_ActualCostHistory.ElementType.ActualCost* CST_ActualCostHistory.BeginQty )/ // // (CST_ActualCostHistory.Qty- CST_ActualCostHistory.BeginQty) // try // { // decActualCost = (decActualCost*decQuantity - decPreviousActCost*decBeginQuantity)/ // (decQuantity - decBeginQuantity); // } // catch (DivideByZeroException) // { // decActualCost = 0; // } // if (decQuantity == 0) // decActualCost = 0; string strComFilter = "ProductID = " + strProductID + " AND ActCostAllocationMasterID = " + strCurrentPeriodID; try { decSumComponentValue = Convert.ToDecimal(dtbReportData.Compute("SUM(ComponentValue)", strComFilter)); } catch{} // component value of current preiod try { decComponentValue = Convert.ToDecimal(drowsElement[0]["ComponentValue"]); } catch{} // Actual Cost = CST_ActualCostHistory.Material+ Sum(CST_ActualCostHistory.ElementType.ComponentValue) // - CST_ActualCostHistory. Material .ComponentValue- //decActualCost = decActualCost + decSumComponentValue - decComponentValue; decActualCost = decSumComponentValue; break; default: if (decQuantity == 0) decActualCost = 0; else { try { decActualCost = decAlloc/(decQuantity - decBeginQuantity); } catch (DivideByZeroException) { decActualCost = 0; } } break; } #endregion if (decActualCost != 0) drowReport[ACTUAL_COST_FLD + i.ToString("00")] = decActualCost; else drowReport[ACTUAL_COST_FLD + i.ToString("00")] = DBNull.Value; if ((decSTDCost - decActualCost) != 0) drowReport[DIFFERENCE_FLD + i.ToString("00")] = decSTDCost - decActualCost; else drowReport[DIFFERENCE_FLD + i.ToString("00")] = DBNull.Value; } else { drowReport[CATEGORY_FLD] = drowProductInfo[CATEGORY_FLD]; drowReport[MODEL_FLD] = drowProductInfo[MODEL_FLD]; drowReport[PART_NO_FLD] = drowProductInfo[PART_NO_FLD]; drowReport[PART_NAME_FLD] = drowProductInfo[PART_NAME_FLD]; drowReport[UM_FLD] = drowProductInfo[UM_FLD]; drowReport[COST_ELEMENT_FLD] = drowElement["Name"]; #region standard cost decimal decSTDCost = 0; switch (intElementType) { case (int)CostElementType.Material: // item standard cost string strFilterSTD = "ProductID = " + strProductID + " AND CostElementID = " + strElementID; try { decSTDCost = Convert.ToDecimal(dtbSTDCost.Compute("SUM(Cost)", strFilterSTD)); } catch{} decSTDCost = decSTDCost + decCostRate; break; default: // std cost = cost rate decSTDCost = decCostRate; break; } if (decSTDCost != 0) { drowReport[STDCOST_FLD + i.ToString("00")] = decSTDCost; drowReport[DIFFERENCE_FLD + i.ToString("00")] = decSTDCost; } else { drowReport[STDCOST_FLD + i.ToString("00")] = DBNull.Value; drowReport[DIFFERENCE_FLD + i.ToString("00")] = DBNull.Value; } #endregion drowReport[ACTUAL_COST_FLD + i.ToString("00")] = DBNull.Value; } } } // loop year // insert to report data dtbData.Rows.Add(drowReport); } // loop elements } //loop products // report layout C1Report rptReport = new C1Report(); if (mLayoutFile == null || mLayoutFile.Trim() == string.Empty) mLayoutFile = "StdActCostComparision.xml"; string[] arrstrReportInDefinitionFile = rptReport.GetReportInfo(mDefFolder + "\\" + mLayoutFile); rptReport.Load(mDefFolder + "\\" + mLayoutFile, arrstrReportInDefinitionFile[0]); //arrstrReportInDefinitionFile = null; rptReport.Layout.PaperSize = PaperKind.A3; #region PUSH PARAMETER VALUE #region General information try { rptReport.Fields["fldCompany"].Text = SystemProperty.SytemParams.Get("CompanyFullName"); } catch{} try { rptReport.Fields["fldCCN"].Text = GetCCNCode(pstrCCNID);; } catch{} try { rptReport.Fields["fldYear"].Text = pstrYear; } catch{} #endregion #region Category if (pstrCategoryID != null && pstrCategoryID.Trim().Length > 0) { try { rptReport.Fields["fldCategoryParam"].Text = GetCategory(pstrCategoryID); } catch{} } #endregion #region Department if (pstrDepartmentID != null && pstrDepartmentID.Trim().Length > 0) { try { rptReport.Fields["fldDepartmentParam"].Text = GetDepartment(pstrDepartmentID); } catch{} } #endregion #region Production Line if (pstrProductionLineID != null && pstrProductionLineID.Trim().Length > 0) { try { rptReport.Fields["fldProductionLine"].Text = GetProductionLineCode(pstrProductionLineID); } catch{} } #endregion #region Part if (pstrProductID != null && pstrProductID.Trim().Length > 0) { try { string strPartNo = string.Empty, strPartName = string.Empty; DataRow[] drowItems = GetItemsInfo(pstrProductID, dtbAllItems); foreach (DataRow drowItem in drowItems) { strPartNo += drowItem[PART_NO_FLD].ToString() + ","; strPartName += drowItem[PART_NAME_FLD].ToString() + ","; } // remove the last "," if (strPartNo.IndexOf(",") >= 0) strPartNo = strPartNo.Substring(0, strPartNo.Length - 1); if (strPartName.IndexOf(",") >= 0) strPartName = strPartName.Substring(0, strPartName.Length - 1); rptReport.Fields["fldPartNoParam"].Text = strPartNo; rptReport.Fields["fldPartNameParam"].Text = strPartName; } catch{} } #endregion #region Model if (pstrModel != null && pstrModel.Trim().Length > 0) { try { // refine Model string pstrModel = pstrModel.Replace("'", string.Empty); rptReport.Fields["fldModelParam"].Text = pstrModel; } catch{} } #endregion #region Home Currency try { rptReport.Fields["lblCurrency"].Text = rptReport.Fields["lblCurrency"].Text + GetHomeCurrency(pstrCCNID); } catch{} #endregion #endregion // set datasource object that provides data to report. rptReport.DataSource.Recordset = dtbData; // render report rptReport.Render(); // render the report into the PrintPreviewControl C1PrintPreviewDialog ppvViewer = new C1PrintPreviewDialog(); ppvViewer.FormTitle = " STANDARD COST & ACTUAL COST COMPARISON "; ppvViewer.ReportViewer.Document = rptReport.Document; ppvViewer.Show(); return dtbData; } private DataTable GetReportData(string pstrCCNID, string pstrPeriodIDs, string pstrCategoryID, string pstrDepartmentID, string pstrProductionLineID, string pstrProductID, string pstrModel) { OleDbConnection cn = null; OleDbCommand cmd = null; try { cn = new OleDbConnection(mConnectionString); string strSql = "SELECT cst_ActCostAllocationMaster.FromDate, cst_ActCostAllocationMaster.ToDate," + " ITM_Category.Code AS Category, ITM_Product.Revision AS Model, ITM_Product.Code AS PartNo, ITM_Product.Description AS PartName," + " MST_UnitOfMeasure.Code AS UM, ActualCost, StdCost, STD_CostElement.Name AS CostElement," + " CST_ActualCostHistory.ProductID, CST_ActualCostHistory.CostElementID," + " ISNULL(CST_ActualCostHistory.Quantity, 0) AS Quantity, " + " ISNULL(CST_ActualCostHistory.BeginQuantity, 0) AS BeginQuantity," + " ISNULL(CST_ActualCostHistory.BeginCost, 0) AS BeginCost," + " CST_ActualCostHistory.ActCostAllocationMasterID, ComponentValue, ComponentDSAmount" + " FROM CST_ActualCostHistory JOIN cst_ActCostAllocationMaster" + " ON CST_ActualCostHistory.ActCostAllocationMasterID = cst_ActCostAllocationMaster.ActCostAllocationMasterID" + " JOIN STD_CostElement" + " ON CST_ActualCostHistory.CostElementID = STD_CostElement.CostElementID" + " JOIN ITM_Product" + " ON CST_ActualCostHistory.ProductID = ITM_Product.ProductID" + " JOIN MST_UnitOfMeasure" + " ON ITM_Product.StockUMID = MST_UnitOfMeasure.UnitOfMeasureID" + " LEFT JOIN ITM_Category" + " ON ITM_Product.CategoryID = ITM_Category.CategoryID" + " LEFT JOIN PRO_ProductionLine" + " ON ITM_Product.ProductionLineID = PRO_ProductionLine.ProductionLineID" + " WHERE cst_ActCostAllocationMaster.CCNID = " + pstrCCNID + " AND CST_ActualCostHistory.ActCostAllocationMasterID IN (" + pstrPeriodIDs + ")"; if (pstrCategoryID != null && pstrCategoryID.Trim() != string.Empty) strSql += " AND ITM_Product.CategoryID IN (" + pstrCategoryID + ")" ; if (pstrDepartmentID != null && pstrDepartmentID.Trim() != string.Empty) strSql += " AND PRO_ProductionLine.DepartmentID IN (" + pstrDepartmentID + ")"; if (pstrProductionLineID != null && pstrProductionLineID.Trim() != string.Empty) strSql += " AND ITM_Product.ProductionLineID IN (" + pstrProductionLineID + ")"; if (pstrProductID != null && pstrProductID.Trim() != string.Empty) strSql += " AND CST_ActualCostHistory.ProductID IN (" + pstrProductID + ")"; if (pstrModel != null && pstrModel.Trim() != string.Empty) strSql += " AND ITM_Product.Revision IN ( " + pstrModel + " )"; strSql += " ORDER BY CST_ActualCostHistory.ProductID ASC, STD_CostElement.OrderNo ASC"; cmd = new OleDbCommand(strSql, cn); cmd.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odad = new OleDbDataAdapter(cmd); odad.Fill(dtbData); return dtbData; } finally { if (cn != null) if (cn.State != ConnectionState.Closed) cn.Close(); } } private DataTable GetCostCenterRate(string pstrCCNID) { DataTable dtbData = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT * FROM STD_CostCenterRateDetail JOIN STD_CostCenterRateMaster" + " ON STD_CostCenterRateDetail.CostCenterRateMasterID = STD_CostCenterRateMaster.CostCenterRateMasterID" + " WHERE CCNID = " + pstrCCNID; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } private DataTable GetSTDCost() { DataTable dtbData = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT * FROM CST_STDItemCost"; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } private DataTable GetAllocation() { DataTable dtbData = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT * FROM CST_AllocationResult"; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Gets all periods of CCN /// </summary> /// <param name="pstrCCNID">CCN</param> /// <returns>All periods</returns> private DataTable GetAllPeriod(string pstrCCNID) { OleDbConnection cn = null; OleDbCommand cmd = null; try { cn = new OleDbConnection(mConnectionString); string strSql = "SELECT * FROM cst_ActCostAllocationMaster" + " WHERE cst_ActCostAllocationMaster.CCNID = " + pstrCCNID + " ORDER BY FromDate ASC"; cmd = new OleDbCommand(strSql, cn); cmd.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odad = new OleDbDataAdapter(cmd); odad.Fill(dtbData); return dtbData; } finally { if (cn != null) if (cn.State != ConnectionState.Closed) cn.Close(); } } private DataTable GetCostElements() { DataTable dtbData = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT STD_CostElement.*, STD_CostElementType.Code AS TypeCode" + " FROM STD_CostElement JOIN STD_CostElementType" + " ON STD_CostElement.CostElementTypeID = STD_CostElementType.CostElementTypeID" + " WHERE IsLeaf = 1" + " ORDER BY OrderNo ASC"; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } private DataTable ListItems(string pstrCCNID) { DataTable dtbData = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT ITM_Category.Code AS Category, ITM_Product.Revision AS Model," + " ITM_Product.Code AS PartNo, ITM_Product.Description AS PartName," + " MST_UnitOfMeasure.Code AS UM, ITM_Product.ProductID, ITM_Product.CostCenterRateMasterID" + " FROM ITM_Product JOIN MST_UnitOfMeasure" + " ON ITM_Product.StockUMID = MST_UnitOfMeasure.UnitOfMeasureID" + " LEFT JOIN ITM_Category ON ITM_Product.CategoryID = ITM_Category.CategoryID" + " WHERE ITM_Product.CCNID = " + pstrCCNID; oconPCS = new OleDbConnection(mConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } private DataRow GetItemInfo(string pstrProductID, DataTable pdtbAllItems) { return pdtbAllItems.Select(PRODUCTID_FLD + "='" + pstrProductID + "'")[0]; } private DataRow[] GetItemsInfo(string pstrProductIDs, DataTable pdtbAllItems) { return pdtbAllItems.Select(PRODUCTID_FLD + " IN (" + pstrProductIDs + ")"); } /// <summary> /// Get CCN Code from ID /// </summary> /// <param name="pstrCCNID">CCN ID</param> /// <returns>CCN Code</returns> private string GetCCNCode(string pstrCCNID) { OleDbConnection oconPCS = null; try { oconPCS = new OleDbConnection(mConnectionString); string strSql = "SELECT Code + ' (' + Description + ')' FROM MST_CCN WHERE CCNID = " + pstrCCNID; OleDbCommand cmdData = new OleDbCommand(strSql, oconPCS); cmdData.Connection.Open(); object objResult = cmdData.ExecuteScalar(); try { return objResult.ToString(); } catch { return string.Empty; } } finally { if (oconPCS != null) if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); } } /// <summary> /// Get Production Line Code and Name from ID /// </summary> /// <param name="pstrProID">Production Line ID</param> /// <returns>Pro Code (Pro Name)</returns> private string GetProductionLineCode(string pstrProID) { OleDbConnection oconPCS = null; try { oconPCS = new OleDbConnection(mConnectionString); string strSql = "SELECT Code + ' (' + Name + ')' AS 'Code' FROM PRO_ProductionLine WHERE ProductionLineID IN (" + pstrProID + ")"; OleDbCommand cmdData = new OleDbCommand(strSql, oconPCS); cmdData.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odad = new OleDbDataAdapter(cmdData); odad.Fill(dtbData); string strCode = string.Empty; foreach (DataRow drowData in dtbData.Rows) strCode += drowData["Code"].ToString() + ","; if (strCode.IndexOf(",") >= 0) strCode = strCode.Substring(0, strCode.Length - 1); return strCode; } finally { if (oconPCS != null) if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); } } private string GetDepartment(string pstrProID) { OleDbConnection oconPCS = null; try { oconPCS = new OleDbConnection(mConnectionString); string strSql = "SELECT Code + ' (' + Name + ')' AS 'Code' FROM MST_Department WHERE DepartmentID IN (" + pstrProID + ")"; OleDbCommand cmdData = new OleDbCommand(strSql, oconPCS); cmdData.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odad = new OleDbDataAdapter(cmdData); odad.Fill(dtbData); string strCode = string.Empty; foreach (DataRow drowData in dtbData.Rows) strCode += drowData["Code"].ToString() + ","; if (strCode.IndexOf(",") >= 0) strCode = strCode.Substring(0, strCode.Length - 1); return strCode; } finally { if (oconPCS != null) if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); } } private string GetCategory(string pstrProID) { OleDbConnection oconPCS = null; try { oconPCS = new OleDbConnection(mConnectionString); string strSql = "SELECT Code + ' (' + Name + ')' AS 'Code' FROM ITM_Category WHERE CategoryID IN (" + pstrProID + ")"; OleDbCommand cmdData = new OleDbCommand(strSql, oconPCS); cmdData.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odad = new OleDbDataAdapter(cmdData); odad.Fill(dtbData); string strCode = string.Empty; foreach (DataRow drowData in dtbData.Rows) strCode += drowData["Code"].ToString() + ","; if (strCode.IndexOf(",") >= 0) strCode = strCode.Substring(0, strCode.Length - 1); return strCode; } finally { if (oconPCS != null) if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); } } private string GetHomeCurrency(string pstrCCNID) { OleDbConnection oconPCS = null; try { oconPCS = new OleDbConnection(mConnectionString); string strSql = "SELECT Code FROM MST_Currency WHERE CurrencyID = (SELECT HomeCurrencyID FROM MST_CCN WHERE CCNID = " + pstrCCNID + ")"; OleDbCommand cmdData = new OleDbCommand(strSql, oconPCS); cmdData.Connection.Open(); object objResult = cmdData.ExecuteScalar(); if (objResult != null && objResult != DBNull.Value) return objResult.ToString(); else return string.Empty; } finally { if (oconPCS != null) if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); } } private string FindPeriodOfMonth(DateTime pdtmMonth, DataTable pdtbAllPeriod) { DataRow[] drowCurrentPeriod = pdtbAllPeriod.Select("FromDate <='" + pdtmMonth.ToString() + "'" + " AND ToDate >='" + pdtmMonth.ToString() + "'"); string strPeriodID = string.Empty; if (drowCurrentPeriod.Length > 0) strPeriodID = drowCurrentPeriod[0]["ActCostAllocationMasterID"].ToString(); return strPeriodID; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { /// <summary> /// Unit tests for ccrewriter a.k.a. Foxtrot /// </summary> [TestClass] public class RewriterTests { const string FrameworkBinariesToRewritePath = @"Foxtrot\Tests\RewriteExistingBinaries\"; public TestContext TestContext { get; set; } [TestCleanup] public void MyTestCleanup() { if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed && TestContext.DataRow != null) { try { string sourceFile = (string)TestContext.DataRow["Name"]; string options = (string)TestContext.DataRow["Options"]; TestContext.WriteLine("FAILED: Name={0} Options={1}", sourceFile, options); } catch { } } } #region Async tests [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "AsyncTests", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("Roslyn"), TestCategory("VS14")] public void AsyncTestsWithRoslynCompiler() { var options = CreateRoslynOptions("VS14RC3"); TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "AsyncTests", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("V4.5")] public void AsyncTestsWithDotNet45() { var options = new Options(this.TestContext); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @".NETFramework\v4.5"; options.ContractFramework = @".NETFramework\v4.0"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } #endregion [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "AsyncPostconditions", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("Roslyn"), TestCategory("VS14")] public void TestAsyncPostconditions() { var options = CreateRoslynOptions("VS14RC3"); TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "AsyncPostconditions", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("Roslyn"), TestCategory("VS14")] public void TestAsyncPostconditionsV45() { var options = new Options(this.TestContext); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @".NETFramework\v4.5"; options.ContractFramework = @".NETFramework\v4.0"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } #region Roslyn compiler unit tests [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestFile", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("Roslyn"), TestCategory("VS14")] [Timeout(10*60*1000)] public void Roslyn_BuildRewriteRunFromSources() { var options = CreateRoslynOptions("VS14RC3"); TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "RoslynCompatibility", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("Roslyn"), TestCategory("VS14")] public void Roslyn_CompatibilityCheck() { var options = CreateRoslynOptions("VS14RC3"); TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "RoslynCompatibility", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("V4.5")] public void TestTheRoslynCompatibilityCasesWithVS2013Compiler() { var options = new Options(this.TestContext); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @".NETFramework\v4.5"; options.ContractFramework = @".NETFramework\v4.0"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "RoslynCompatibility", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("Roslyn"), TestCategory("VS14")] public void Roslyn_CompatibilityCheckInReleaseMode() { var options = CreateRoslynOptions("VS14RC3"); options.CompilerOptions = "/optimize"; TestDriver.BuildRewriteRun(options); } /// <summary> /// Unit test for #47 - "Could not resolve type reference" for some iterator methods in VS2015 and /// #186 - ccrewrite produces an incorrect type name in IteratorStateMachineAttribute with some generic types /// </summary> [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "IteratorWithComplexGeneric", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("Roslyn"), TestCategory("VS14")] public void Roslyn_IteratorBlockWithComplexGeneric() { var options = CreateRoslynOptions("VS14RC3"); // Bug with metadata reader could be reproduced only with a new mscorlib and new System.dll. options.BuildFramework = @".NetFramework\v4.6"; options.ReferencesFramework = @".NetFramework\v4.6"; options.DeepVerify = true; TestDriver.BuildRewriteRun(options); } /// <summary> /// Creates <see cref="Options"/> instance with default values suitable for testing roslyn-based compiler. /// </summary> /// <param name="compilerVersion">Should be the same as a folder name in the /Imported/Roslyn folder.</param> private Options CreateRoslynOptions(string compilerVersion) { var options = new Options(this.TestContext); // For VS14RC+ version compiler name is the same Csc.exe, and behavior from async/iterator perspective is similar // to old compiler as well. That's why IsLegacyRoslyn should be false in this test case. options.IsLegacyRoslyn = false; options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.CompilerPath = string.Format(@"Roslyn\{0}", compilerVersion); options.BuildFramework = @".NetFramework\v4.5"; options.ReferencesFramework = @".NetFramework\v4.5"; options.ContractFramework = @".NETFramework\v4.5"; options.UseTestHarness = true; return options; } #endregion Roslyn compiler unit tests [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "RewriteExisting", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("Framework"), TestCategory("V4.0"), TestCategory("CoreTest")] public void RewriteFrameworkDlls40() { var options = new Options(this.TestContext); var framework = @".NetFramework\v4.0"; options.ContractFramework = framework; var dllpath = FrameworkBinariesToRewritePath + framework; options.BuildFramework = options.MakeAbsolute(dllpath); var extrareferencedir = options.MakeAbsolute(TestDriver.ReferenceDirRoot); options.LibPaths.Add(extrareferencedir); options.FoxtrotOptions = options.FoxtrotOptions + " /verbose:4"; options.UseContractReferenceAssemblies = false; if (File.Exists(options.MakeAbsolute(Path.Combine(dllpath, options.SourceFile)))) { TestDriver.RewriteBinary(options, dllpath); } } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "RewriteExisting", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("Framework"), TestCategory("V4.5"), TestCategory("CoreTest")] public void RewriteFrameworkDlls45() { var options = new Options(this.TestContext); var framework = @".NetFramework\v4.5"; options.ContractFramework = framework; var dllpath = FrameworkBinariesToRewritePath + framework; var extrareferencedir = options.MakeAbsolute(TestDriver.ReferenceDirRoot); options.LibPaths.Add(extrareferencedir); options.BuildFramework = options.MakeAbsolute(dllpath); options.FoxtrotOptions = options.FoxtrotOptions + " /verbose:4"; options.UseContractReferenceAssemblies = false; if (File.Exists(options.MakeAbsolute(Path.Combine(dllpath, options.SourceFile)))) { TestDriver.RewriteBinary(options, dllpath); } } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestConfiguration", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("ThirdParty"), TestCategory("CoreTest")] public void RewriteQuickGraph() { var options = new Options("QuickGraph", (string)TestContext.DataRow["FoxtrotOptions"], TestContext); options.BuildFramework = @".NetFramework\v4.0"; TestDriver.RewriteAndVerify("", @"Foxtrot\Tests\Quickgraph\QuickGraphBinaries\Quickgraph.dll", options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestConfiguration", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("ThirdParty"), TestCategory("CoreTest")] public void RewriteQuickGraphData() { var options = new Options("QuickGraphData", (string)TestContext.DataRow["FoxtrotOptions"], TestContext); options.BuildFramework = @".NetFramework\v4.0"; options.FoxtrotOptions = options.FoxtrotOptions + " /verbose:4"; options.Delete(@"Foxtrot\Tests\QuickGraph\QuickGraphBinaries\QuickGraph.Contracts.dll"); TestDriver.RewriteAndVerify("", @"Foxtrot\Tests\Quickgraph\QuickGraphBinaries\Quickgraph.Data.dll", options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestConfiguration", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("ThirdParty"), TestCategory("CoreTest")] public void RewriteQuickGraphDataOOB() { var options = new Options("QuickGraphDataOOB", (string)TestContext.DataRow["FoxtrotOptions"], TestContext); options.BuildFramework = @".NetFramework\v4.0"; options.LibPaths.Add(@"Foxtrot\Tests\QuickGraph\QuickGraphBinaries\Contracts"); // subdirectory containing contracts. options.FoxtrotOptions = options.FoxtrotOptions + " /verbose:4"; TestDriver.RewriteAndVerify("", @"Foxtrot\Tests\Quickgraph\QuickGraphBinaries\Quickgraph.Data.dll", options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestFile", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("V3.5")] public void BuildRewriteRunFromSourcesV35() { var options = new Options(this.TestContext); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = "v3.5"; options.ContractFramework = "v3.5"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestFile", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("V4.0")] public void BuildRewriteRunFromSourcesV40() { var options = new Options(this.TestContext); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @".NETFramework\v4.0"; options.ContractFramework = @".NETFramework\v4.0"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestFile", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("V4.5")] public void BuildRewriteRunFromSourcesV45() { var options = new Options(this.TestContext); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @".NETFramework\v4.5"; options.ContractFramework = @".NETFramework\v4.0"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "RoslynCompatibility", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("V4.5")] public void BuildRewriteRunRoslynTestCasesWithV45() { var options = new Options(this.TestContext); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @".NETFramework\v4.5"; options.ContractFramework = @".NETFramework\v4.0"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestFile", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("Roslyn"), TestCategory("V4.5")] [Ignore] // Old Roslyn bits are not compatible with CCRewrite. Test (and old binaries) should be removed in the next iteration. public void BuildRewriteRunFromSourcesRoslynV45() { var options = new Options(this.TestContext); options.IsLegacyRoslyn = true; options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @"Roslyn\v4.5"; options.ReferencesFramework = @".NetFramework\v4.5"; options.ContractFramework = @".NETFramework\v4.0"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "TestFile", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("V4.0"), TestCategory("V3.5")] public void BuildRewriteRunFromSourcesV40AgainstV35Contracts() { var options = new Options(this.TestContext); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @".NETFramework\v4.0"; options.ContractFramework = @"v3.5"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } [DeploymentItem("Foxtrot\\Tests\\TestInputs.xml"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestInputs.xml", "PublicSurfaceOnly", DataAccessMethod.Sequential)] [TestMethod] [TestCategory("Runtime"), TestCategory("CoreTest"), TestCategory("V4.5")] public void BuildRewriteFromSources45WithPublicSurfaceOnly() { var options = new Options(this.TestContext); // For testing purposes you can remove /publicsurface and see what happen. Part of the tests should fail! //options.FoxtrotOptions = options.FoxtrotOptions + String.Format("/throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.FoxtrotOptions = options.FoxtrotOptions + String.Format(" /publicsurface /throwonfailure /rw:{0}.exe,TestInfrastructure.RewriterMethods", Path.GetFileNameWithoutExtension(options.TestName)); options.BuildFramework = @".NETFramework\v4.5"; options.ContractFramework = @".NETFramework\v4.0"; options.UseTestHarness = true; TestDriver.BuildRewriteRun(options); } private void GrabTestOptions(out string sourceFile, out string options, out string cscoptions, out List<string> refs, out List<string> libs) { sourceFile = (string)TestContext.DataRow["Name"]; options = (string)TestContext.DataRow["Options"]; cscoptions = TestContext.DataRow["CSCOptions"] as string; string references = TestContext.DataRow["References"] as string; refs = new List<string>(new[] { "System.dll" }); if (references != null) { refs.AddRange(references.Split(';')); } libs = new List<string>(); string libPaths = TestContext.DataRow["Libpaths"] as string; if (libPaths != null) { libs.AddRange(libPaths.Split(';')); } } } }
// Copyright (c) 2012, Event Store LLP // 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 Event Store LLP 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.Threading; using EventStore.Common.Log; namespace EventStore.Projections.Core.v8 { public class PreludeScript : IDisposable { private readonly ILogger _systemLogger = LogManager.GetLoggerFor<PreludeScript>(); private readonly Func<string, Tuple<string, string>> _getModuleSourceAndFileName; private readonly Action<string> _logger; private readonly CompiledScript _script; private readonly List<CompiledScript> _modules = new List<CompiledScript>(); private readonly Js1.LoadModuleDelegate _loadModuleDelegate; // do not inline. this delegate is required to be kept alive to be available to unmanaged code private readonly Js1.LogDelegate _logDelegate; // a reference must be kept to make a delegate callable from unmanaged world private readonly Action<int, Action> _cancelCallbackFactory; private int _cancelTokenOrStatus = 0; // bot hcore and timer threads private readonly CancelRef _defaultCancelRef = new CancelRef(); private CancelRef _terminateRequested; // core thread only private int _currentCancelToken = 1; // core thread only private readonly Js1.EnterCancellableRegionDelegate _enterCancellableRegion; private readonly Js1.ExitCancellableRegionDelegate _exitCancellableRegion; public PreludeScript( string script, string fileName, Func<string, Tuple<string, string>> getModuleSourceAndFileName, Action<int, Action> cancelCallbackFactory, Action<string> logger = null) { _logDelegate = LogHandler; _loadModuleDelegate = GetModule; _getModuleSourceAndFileName = getModuleSourceAndFileName; _logger = logger; _enterCancellableRegion = EnterCancellableRegion; _exitCancellableRegion = ExitCancellableRegion; _cancelCallbackFactory = cancelCallbackFactory; _script = CompileScript(script, fileName); } private CompiledScript CompileScript(string script, string fileName) { try { ScheduleTerminateExecution(); IntPtr prelude = Js1.CompilePrelude( script, fileName, _loadModuleDelegate, _enterCancellableRegion, _exitCancellableRegion, _logDelegate); CancelTerminateExecution(); CompiledScript.CheckResult(prelude, false, disposeScriptOnException: true); return new CompiledScript(prelude, fileName); } catch (DllNotFoundException ex) { throw new ApplicationException( "The projection subsystem failed to load a libjs1.so/js1.dll/... or one of its dependencies. The original error message is: " + ex.Message, ex); } } private void LogHandler(string message) { if (_logger != null) _logger(message); else Console.WriteLine(message); } private IntPtr GetModule(string moduleName) { try { var moduleSourceAndFileName = GetModuleSourceAndFileName(moduleName); // NOTE: no need to schedule termination; modules are loaded only in context if (_cancelTokenOrStatus == NonScheduled) throw new InvalidOperationException("Requires scheduled terminate execution"); var compiledModuleHandle = Js1.CompileModule( GetHandle(), moduleSourceAndFileName.Item1, moduleSourceAndFileName.Item2); CompiledScript.CheckResult(compiledModuleHandle, terminated: false, disposeScriptOnException: true); var compiledModule = new CompiledScript(compiledModuleHandle, moduleSourceAndFileName.Item2); _modules.Add(compiledModule); return compiledModuleHandle; } catch (Exception ex) { _systemLogger.ErrorException(ex, "Cannot load module '{0}'", moduleName); //TODO: this is not a good way to report missing module and other exceptions back to caller return IntPtr.Zero; } } private Tuple<string, string> GetModuleSourceAndFileName(string moduleName) { return _getModuleSourceAndFileName(moduleName); } public void Dispose() { _modules.ForEach(v => v.Dispose()); _script.Dispose(); } public IntPtr GetHandle() { return _script != null ? _script.GetHandle() : IntPtr.Zero; } private const int NonScheduled = 0; private const int Scheduled = -2; private const int Terminating = -1; private void CancelExecution(IntPtr scriptHandle) { Js1.TerminateExecution(scriptHandle); } private void AnotherThreadCancel(int cancelToken, IntPtr scriptHandle, Action expired) { expired(); // always set our termination timout expired if (Interlocked.CompareExchange(ref _cancelTokenOrStatus, Terminating, cancelToken) == cancelToken) { if (scriptHandle != IntPtr.Zero) // prelude itself does not yet handle. // TODO: handle somehow? CancelExecution(scriptHandle); if (Interlocked.CompareExchange(ref _cancelTokenOrStatus, Scheduled, Terminating) != Terminating) throw new Exception(); } } private class CancelRef { public bool TerminateRequested = false; public void Terminate() { TerminateRequested = true; } } public void ScheduleTerminateExecution() { int currentCancelToken = ++_currentCancelToken; if (Interlocked.CompareExchange(ref _cancelTokenOrStatus, Scheduled, NonScheduled) != NonScheduled) //TODO: no need for interlocked? throw new InvalidOperationException("ScheduleTerminateExecution cannot be called while previous one has not been canceled"); if (_cancelCallbackFactory != null) // allow nulls in tests { var terminateRequested = new CancelRef(); _terminateRequested = terminateRequested; _cancelCallbackFactory( 1000, () => AnotherThreadCancel(currentCancelToken, GetHandle(), terminateRequested.Terminate)); } else { _terminateRequested = _defaultCancelRef; } } public bool CancelTerminateExecution() { //NOTE: cannot be attempted while running, but it can be attempted while terminating while (Interlocked.CompareExchange(ref _cancelTokenOrStatus, NonScheduled, Scheduled) != Scheduled) Thread.SpinWait(1); // exit only if terminated or canceled return _terminateRequested.TerminateRequested; } private bool EnterCancellableRegion() { var entered = Interlocked.CompareExchange(ref _cancelTokenOrStatus, _currentCancelToken, Scheduled) == Scheduled; var result = entered && !_terminateRequested.TerminateRequested; if (!result && entered) { if (Interlocked.CompareExchange(ref _cancelTokenOrStatus, Scheduled, _currentCancelToken) != _currentCancelToken) throw new Exception(); } return result; } /// <summary> /// returns False if terminated (or inappropriate invocation) /// </summary> /// <returns></returns> private bool ExitCancellableRegion() { return Interlocked.CompareExchange(ref _cancelTokenOrStatus, Scheduled, _currentCancelToken) == _currentCancelToken && !_terminateRequested.TerminateRequested; } } }
namespace Ioke.Math { using System; class Division { internal static int[] divide(int[] quot, int quotLength, int[] a, int aLength, int[] b, int bLength) { int[] normA = new int[aLength + 1]; // the normalized dividend // an extra byte is needed for correct shift int[] normB = new int[bLength + 1]; // the normalized divisor; int normBLength = bLength; /* * Step D1: normalize a and b and put the results to a1 and b1 the * normalized divisor's first digit must be >= 2^31 */ int divisorShift = BigDecimal.numberOfLeadingZeros(b[bLength - 1]); if (divisorShift != 0) { BitLevel.shiftLeft(normB, b, 0, divisorShift); BitLevel.shiftLeft(normA, a, 0, divisorShift); } else { Array.Copy(a, normA, aLength); Array.Copy(b, normB, bLength); } int firstDivisorDigit = normB[normBLength - 1]; // Step D2: set the quotient index int i = quotLength - 1; int j = aLength; while (i >= 0) { // Step D3: calculate a guess digit guessDigit int guessDigit = 0; if (normA[j] == firstDivisorDigit) { // set guessDigit to the largest unsigned int value guessDigit = -1; } else { long product = (((normA[j] & 0xffffffffL) << 32) + (normA[j - 1] & 0xffffffffL)); long res = Division.divideLongByInt(product, firstDivisorDigit); guessDigit = (int) res; // the quotient of divideLongByInt int rem = (int) (res >> 32); // the remainder of // divideLongByInt // decrease guessDigit by 1 while leftHand > rightHand if (guessDigit != 0) { long leftHand = 0; long rightHand = 0; bool rOverflowed = false; guessDigit++; // to have the proper value in the loop // below do { guessDigit--; if (rOverflowed) { break; } // leftHand always fits in an unsigned long leftHand = (guessDigit & 0xffffffffL) * (normB[normBLength - 2] & 0xffffffffL); /* * rightHand can overflow; in this case the loop * condition will be true in the next step of the loop */ rightHand = ((long) rem << 32) + (normA[j - 2] & 0xffffffffL); long longR = (rem & 0xffffffffL) + (firstDivisorDigit & 0xffffffffL); /* * checks that longR does not fit in an unsigned int; * this ensures that rightHand will overflow unsigned * long in the next step */ if (BigDecimal.numberOfLeadingZeros((int) ((long)(((ulong)longR) >> 32))) < 32) { rOverflowed = true; } else { rem = (int) longR; } } while (((long)((ulong)leftHand ^ 0x8000000000000000L) > (long)((ulong)rightHand ^ 0x8000000000000000L))); } } // Step D4: multiply normB by guessDigit and subtract the production // from normA. if (guessDigit != 0) { int borrow = Division.multiplyAndSubtract(normA, j - normBLength, normB, normBLength, guessDigit); // Step D5: check the borrow if (borrow != 0) { // Step D6: compensating addition guessDigit--; long carry = 0; for (int k = 0; k < normBLength; k++) { carry += (normA[j - normBLength + k] & 0xffffffffL) + (normB[k] & 0xffffffffL); normA[j - normBLength + k] = (int) carry; carry = (long)(((ulong)carry) >> 32); } } } if (quot != null) { quot[i] = guessDigit; } // Step D7 j--; i--; } /* * Step D8: we got the remainder in normA. Denormalize it id needed */ if (divisorShift != 0) { // reuse normB BitLevel.shiftRight(normB, normBLength, normA, 0, divisorShift); return normB; } Array.Copy(normA, normB, bLength); return normA; } internal static int divideArrayByInt(int[] dest, int[] src, int srcLength, int divisor) { long rem = 0; long bLong = divisor & 0xffffffffL; for (int i = srcLength - 1; i >= 0; i--) { long temp = (rem << 32) | (src[i] & 0xffffffffL); long quot; if (temp >= 0) { quot = (temp / bLong); rem = (temp % bLong); } else { /* * make the dividend positive shifting it right by 1 bit then * get the quotient an remainder and correct them properly */ long aPos = (long)(((ulong)temp) >> 1); long bPos = (int)(((uint)divisor) >> 1); quot = aPos / bPos; rem = aPos % bPos; // double the remainder and add 1 if a is odd rem = (rem << 1) + (temp & 1); if ((divisor & 1) != 0) { // the divisor is odd if (quot <= rem) { rem -= quot; } else { if (quot - rem <= bLong) { rem += bLong - quot; quot -= 1; } else { rem += (bLong << 1) - quot; quot -= 2; } } } } dest[i] = (int) (quot & 0xffffffffL); } return (int) rem; } internal static int remainderArrayByInt(int[] src, int srcLength, int divisor) { long result = 0; for (int i = srcLength - 1; i >= 0; i--) { long temp = (result << 32) + (src[i] & 0xffffffffL); long res = divideLongByInt(temp, divisor); result = (int) (res >> 32); } return (int) result; } internal static int remainder(BigInteger dividend, int divisor) { return remainderArrayByInt(dividend.digits, dividend.numberLength, divisor); } internal static long divideLongByInt(long a, int b) { long quot; long rem; long bLong = b & 0xffffffffL; if (a >= 0) { quot = (a / bLong); rem = (a % bLong); } else { /* * Make the dividend positive shifting it right by 1 bit then get * the quotient an remainder and correct them properly */ long aPos = (long)(((ulong)a) >> 1); long bPos = (int)(((uint)b) >> 1); quot = aPos / bPos; rem = aPos % bPos; // double the remainder and add 1 if a is odd rem = (rem << 1) + (a & 1); if ((b & 1) != 0) { // the divisor is odd if (quot <= rem) { rem -= quot; } else { if (quot - rem <= bLong) { rem += bLong - quot; quot -= 1; } else { rem += (bLong << 1) - quot; quot -= 2; } } } } return (rem << 32) | (quot & 0xffffffffL); } internal static BigInteger[] divideAndRemainderByInteger(BigInteger val, int divisor, int divisorSign) { // res[0] is a quotient and res[1] is a remainder: int[] valDigits = val.digits; int valLen = val.numberLength; int valSign = val.sign; if (valLen == 1) { long a = (valDigits[0] & 0xffffffffL); long b = (divisor & 0xffffffffL); long quo = a / b; long rem = a % b; if (valSign != divisorSign) { quo = -quo; } if (valSign < 0) { rem = -rem; } return new BigInteger[] { BigInteger.valueOf(quo), BigInteger.valueOf(rem) }; } int quotientLength = valLen; int quotientSign = ((valSign == divisorSign) ? 1 : -1); int[] quotientDigits = new int[quotientLength]; int[] remainderDigits; remainderDigits = new int[] { Division.divideArrayByInt( quotientDigits, valDigits, valLen, divisor) }; BigInteger result0 = new BigInteger(quotientSign, quotientLength, quotientDigits); BigInteger result1 = new BigInteger(valSign, 1, remainderDigits); result0.cutOffLeadingZeroes(); result1.cutOffLeadingZeroes(); return new BigInteger[] { result0, result1 }; } internal static int multiplyAndSubtract(int[] a, int start, int[] b, int bLen, int c) { long carry0 = 0; long carry1 = 0; for (int i = 0; i < bLen; i++) { carry0 = Multiplication.unsignedMultAddAdd(b[i], c, (int)carry0, 0); carry1 = (a[start+i] & 0xffffffffL) - (carry0 & 0xffffffffL) + carry1; a[start+i] = (int)carry1; carry1 >>= 32; // -1 or 0 carry0 = (long)(((ulong)carry0) >> 32); } carry1 = (a[start + bLen] & 0xffffffffL) - carry0 + carry1; a[start + bLen] = (int)carry1; return (int)(carry1 >> 32); // -1 or 0 } internal static BigInteger gcdBinary(BigInteger op1, BigInteger op2) { // PRE: (op1 > 0) and (op2 > 0) /* * Divide both number the maximal possible times by 2 without rounding * gcd(2*a, 2*b) = 2 * gcd(a,b) */ int lsb1 = op1.getLowestSetBit(); int lsb2 = op2.getLowestSetBit(); int pow2Count = Math.Min(lsb1, lsb2); BitLevel.inplaceShiftRight(op1, lsb1); BitLevel.inplaceShiftRight(op2, lsb2); BigInteger swap; // I want op2 > op1 if (op1.compareTo(op2) == BigInteger.GREATER) { swap = op1; op1 = op2; op2 = swap; } do { // INV: op2 >= op1 && both are odd unless op1 = 0 // Optimization for small operands // (op2.bitLength() < 64) implies by INV (op1.bitLength() < 64) if (( op2.numberLength == 1 ) || ( ( op2.numberLength == 2 ) && ( op2.digits[1] > 0 ) )) { op2 = BigInteger.valueOf(Division.gcdBinary(op1.longValue(), op2.longValue())); break; } // Implements one step of the Euclidean algorithm // To reduce one operand if it's much smaller than the other one if (op2.numberLength > op1.numberLength * 1.2) { op2 = op2.remainder(op1); if (op2.signum() != 0) { BitLevel.inplaceShiftRight(op2, op2.getLowestSetBit()); } } else { // Use Knuth's algorithm of successive subtract and shifting do { Elementary.inplaceSubtract(op2, op1); // both are odd BitLevel.inplaceShiftRight(op2, op2.getLowestSetBit()); // op2 is even } while (op2.compareTo(op1) >= BigInteger.EQUALS); } // now op1 >= op2 swap = op2; op2 = op1; op1 = swap; } while (op1.sign != 0); return op2.shiftLeft(pow2Count); } internal static long gcdBinary(long op1, long op2) { // PRE: (op1 > 0) and (op2 > 0) int lsb1 = BigDecimal.numberOfTrailingZeros(op1); int lsb2 = BigDecimal.numberOfTrailingZeros(op2); int pow2Count = Math.Min(lsb1, lsb2); if (lsb1 != 0) { op1 = (long)(((ulong)op1) >> lsb1); } if (lsb2 != 0) { op2 = (long)(((ulong)op2) >> lsb2); } do { if (op1 >= op2) { op1 -= op2; op1 = (long)(((ulong)op1) >> BigDecimal.numberOfTrailingZeros(op1)); } else { op2 -= op1; op2 = (long)(((ulong)op2) >> BigDecimal.numberOfTrailingZeros(op2)); } } while (op1 != 0); return ( op2 << pow2Count ); } internal static BigInteger modInverseMontgomery(BigInteger a, BigInteger p) { if (a.sign == 0){ // ZERO hasn't inverse throw new ArithmeticException("BigInteger not invertible"); } if (!p.testBit(0)){ // montgomery inverse require even modulo return modInverseLorencz(a, p); } int m = p.numberLength * 32; // PRE: a \in [1, p - 1] BigInteger u, v, r, s; u = p.copy(); // make copy to use inplace method v = a.copy(); int max = Math.Max(v.numberLength, u.numberLength); r = new BigInteger(1, 1, new int[max + 1]); s = new BigInteger(1, 1, new int[max + 1]); s.digits[0] = 1; // s == 1 && v == 0 int k = 0; int lsbu = u.getLowestSetBit(); int lsbv = v.getLowestSetBit(); int toShift; if (lsbu > lsbv) { BitLevel.inplaceShiftRight(u, lsbu); BitLevel.inplaceShiftRight(v, lsbv); BitLevel.inplaceShiftLeft(r, lsbv); k += lsbu - lsbv; } else { BitLevel.inplaceShiftRight(u, lsbu); BitLevel.inplaceShiftRight(v, lsbv); BitLevel.inplaceShiftLeft(s, lsbu); k += lsbv - lsbu; } r.sign = 1; while (v.signum() > 0) { // INV v >= 0, u >= 0, v odd, u odd (except last iteration when v is even (0)) while (u.compareTo(v) > BigInteger.EQUALS) { Elementary.inplaceSubtract(u, v); toShift = u.getLowestSetBit(); BitLevel.inplaceShiftRight(u, toShift); Elementary.inplaceAdd(r, s); BitLevel.inplaceShiftLeft(s, toShift); k += toShift; } while (u.compareTo(v) <= BigInteger.EQUALS) { Elementary.inplaceSubtract(v, u); if (v.signum() == 0) break; toShift = v.getLowestSetBit(); BitLevel.inplaceShiftRight(v, toShift); Elementary.inplaceAdd(s, r); BitLevel.inplaceShiftLeft(r, toShift); k += toShift; } } if (!u.isOne()){ // in u is stored the gcd throw new ArithmeticException("BigInteger not invertible."); } if (r.compareTo(p) >= BigInteger.EQUALS) { Elementary.inplaceSubtract(r, p); } r = p.subtract(r); // Have pair: ((BigInteger)r, (Integer)k) where r == a^(-1) * 2^k mod (module) int n1 = calcN(p); if (k > m) { r = monPro(r, BigInteger.ONE, p, n1); k = k - m; } r = monPro(r, BigInteger.getPowerOfTwo(m - k), p, n1); return r; } private static int calcN(BigInteger a) { long m0 = a.digits[0] & 0xFFFFFFFFL; long n2 = 1L; // this is a'[0] long powerOfTwo = 2L; do { if (((m0 * n2) & powerOfTwo) != 0) { n2 |= powerOfTwo; } powerOfTwo <<= 1; } while (powerOfTwo < 0x100000000L); n2 = -n2; return (int)(n2 & 0xFFFFFFFFL); } private static bool isPowerOfTwo(BigInteger bi, int exp) { bool result = false; result = ( exp >> 5 == bi.numberLength - 1 ) && ( bi.digits[bi.numberLength - 1] == 1 << ( exp & 31 ) ); if (result) { for (int i = 0; result && i < bi.numberLength - 1; i++) { result = bi.digits[i] == 0; } } return result; } private static int howManyIterations(BigInteger bi, int n) { int i = n - 1; if (bi.sign > 0) { while (!bi.testBit(i)) i--; return n - 1 - i; } else { while (bi.testBit(i)) i--; return n - 1 - Math.Max(i, bi.getLowestSetBit()); } } internal static BigInteger modInverseLorencz(BigInteger a, BigInteger modulo) { int max = Math.Max(a.numberLength, modulo.numberLength); int[] uDigits = new int[max + 1]; // enough place to make all the inplace operation int[] vDigits = new int[max + 1]; Array.Copy(modulo.digits, uDigits, modulo.numberLength); Array.Copy(a.digits, vDigits, a.numberLength); BigInteger u = new BigInteger(modulo.sign, modulo.numberLength, uDigits); BigInteger v = new BigInteger(a.sign, a.numberLength, vDigits); BigInteger r = new BigInteger(0, 1, new int[max + 1]); // BigInteger.ZERO; BigInteger s = new BigInteger(1, 1, new int[max + 1]); s.digits[0] = 1; // r == 0 && s == 1, but with enough place int coefU = 0, coefV = 0; int n = modulo.bitLength(); int k; while (!isPowerOfTwo(u, coefU) && !isPowerOfTwo(v, coefV)) { // modification of original algorithm: I calculate how many times the algorithm will enter in the same branch of if k = howManyIterations(u, n); if (k != 0) { BitLevel.inplaceShiftLeft(u, k); if (coefU >= coefV) { BitLevel.inplaceShiftLeft(r, k); } else { BitLevel.inplaceShiftRight(s, Math.Min(coefV - coefU, k)); if (k - ( coefV - coefU ) > 0) { BitLevel.inplaceShiftLeft(r, k - coefV + coefU); } } coefU += k; } k = howManyIterations(v, n); if (k != 0) { BitLevel.inplaceShiftLeft(v, k); if (coefV >= coefU) { BitLevel.inplaceShiftLeft(s, k); } else { BitLevel.inplaceShiftRight(r, Math.Min(coefU - coefV, k)); if (k - ( coefU - coefV ) > 0) { BitLevel.inplaceShiftLeft(s, k - coefU + coefV); } } coefV += k; } if (u.signum() == v.signum()) { if (coefU <= coefV) { Elementary.completeInPlaceSubtract(u, v); Elementary.completeInPlaceSubtract(r, s); } else { Elementary.completeInPlaceSubtract(v, u); Elementary.completeInPlaceSubtract(s, r); } } else { if (coefU <= coefV) { Elementary.completeInPlaceAdd(u, v); Elementary.completeInPlaceAdd(r, s); } else { Elementary.completeInPlaceAdd(v, u); Elementary.completeInPlaceAdd(s, r); } } if (v.signum() == 0 || u.signum() == 0){ throw new ArithmeticException("BigInteger not invertible"); } } if (isPowerOfTwo(v, coefV)) { r = s; if (v.signum() != u.signum()) u = u.negate(); } if (u.testBit(n)) { if (r.signum() < 0) { r = r.negate(); } else { r = modulo.subtract(r); } } if (r.signum() < 0) { r = r.add(modulo); } return r; } internal static BigInteger squareAndMultiply(BigInteger x2, BigInteger a2, BigInteger exponent,BigInteger modulus, int n2 ){ BigInteger res = x2; for (int i = exponent.bitLength() - 1; i >= 0; i--) { res = monPro(res,res,modulus, n2); if (BitLevel.testBit(exponent, i)) { res = monPro(res, a2, modulus, n2); } } return res; } internal static BigInteger slidingWindow(BigInteger x2, BigInteger a2, BigInteger exponent,BigInteger modulus, int n2){ // fill odd low pows of a2 BigInteger[] pows = new BigInteger[8]; BigInteger res = x2; int lowexp; BigInteger x3; int acc3; pows[0] = a2; x3 = monPro(a2,a2,modulus,n2); for (int i = 1; i <= 7; i++){ pows[i] = monPro(pows[i-1],x3,modulus,n2) ; } for (int i = exponent.bitLength()-1; i>=0;i--){ if( BitLevel.testBit(exponent,i) ) { lowexp = 1; acc3 = i; for(int j = Math.Max(i-3,0);j <= i-1 ;j++) { if (BitLevel.testBit(exponent,j)) { if (j<acc3) { acc3 = j; lowexp = (lowexp << (i-j))^1; } else { lowexp = lowexp^(1<<(j-acc3)); } } } for(int j = acc3; j <= i; j++) { res = monPro(res,res,modulus,n2); } res = monPro(pows[(lowexp-1)>>1], res, modulus,n2); i = acc3 ; }else{ res = monPro(res, res, modulus, n2) ; } } return res; } internal static BigInteger oddModPow(BigInteger _base, BigInteger exponent, BigInteger modulus) { // PRE: (base > 0), (exponent > 0), (modulus > 0) and (odd modulus) int k = (modulus.numberLength << 5); // r = 2^k // n-residue of base [base * r (mod modulus)] BigInteger a2 = _base.shiftLeft(k).mod(modulus); // n-residue of base [1 * r (mod modulus)] BigInteger x2 = BigInteger.getPowerOfTwo(k).mod(modulus); BigInteger res; // Compute (modulus[0]^(-1)) (mod 2^32) for odd modulus int n2 = calcN(modulus); if( modulus.numberLength == 1 ){ res = squareAndMultiply(x2,a2, exponent, modulus,n2); } else { res = slidingWindow(x2, a2, exponent, modulus, n2); } return monPro(res, BigInteger.ONE, modulus, n2); } internal static BigInteger evenModPow(BigInteger _base, BigInteger exponent, BigInteger modulus) { // PRE: (base > 0), (exponent > 0), (modulus > 0) and (modulus even) // STEP 1: Obtain the factorization 'modulus'= q * 2^j. int j = modulus.getLowestSetBit(); BigInteger q = modulus.shiftRight(j); // STEP 2: Compute x1 := base^exponent (mod q). BigInteger x1 = oddModPow(_base, exponent, q); // STEP 3: Compute x2 := base^exponent (mod 2^j). BigInteger x2 = pow2ModPow(_base, exponent, j); // STEP 4: Compute q^(-1) (mod 2^j) and y := (x2-x1) * q^(-1) (mod 2^j) BigInteger qInv = modPow2Inverse(q, j); BigInteger y = (x2.subtract(x1)).multiply(qInv); inplaceModPow2(y, j); if (y.sign < 0) { y = y.add(BigInteger.getPowerOfTwo(j)); } // STEP 5: Compute and return: x1 + q * y return x1.add(q.multiply(y)); } internal static BigInteger pow2ModPow(BigInteger _base, BigInteger exponent, int j) { // PRE: (base > 0), (exponent > 0) and (j > 0) BigInteger res = BigInteger.ONE; BigInteger e = exponent.copy(); BigInteger baseMod2toN = _base.copy(); BigInteger res2; /* * If 'base' is odd then it's coprime with 2^j and phi(2^j) = 2^(j-1); * so we can reduce reduce the exponent (mod 2^(j-1)). */ if (_base.testBit(0)) { inplaceModPow2(e, j - 1); } inplaceModPow2(baseMod2toN, j); for (int i = e.bitLength() - 1; i >= 0; i--) { res2 = res.copy(); inplaceModPow2(res2, j); res = res.multiply(res2); if (BitLevel.testBit(e, i)) { res = res.multiply(baseMod2toN); inplaceModPow2(res, j); } } inplaceModPow2(res, j); return res; } private static void monReduction(int[] res, BigInteger modulus, int n2) { /* res + m*modulus_digits */ int[] modulus_digits = modulus.digits; int modulusLen = modulus.numberLength; long outerCarry = 0; for (int i = 0; i < modulusLen; i++){ long innerCarry = 0; int m = (int) Multiplication.unsignedMultAddAdd(res[i],n2,0,0); for(int j = 0; j < modulusLen; j++){ innerCarry = Multiplication.unsignedMultAddAdd(m, modulus_digits[j], res[i+j], (int)innerCarry); res[i+j] = (int) innerCarry; innerCarry = (long)(((ulong)innerCarry) >> 32); } outerCarry += (res[i+modulusLen] & 0xFFFFFFFFL) + innerCarry; res[i+modulusLen] = (int) outerCarry; outerCarry = (long)(((ulong)outerCarry) >> 32); } res[modulusLen << 1] = (int) outerCarry; /* res / r */ for(int j = 0; j < modulusLen+1; j++){ res[j] = res[j+modulusLen]; } } internal static BigInteger monPro(BigInteger a, BigInteger b, BigInteger modulus, int n2) { int modulusLen = modulus.numberLength; int[] res = new int[(modulusLen << 1) + 1]; Multiplication.multArraysPAP(a.digits, Math.Min(modulusLen, a.numberLength), b.digits, Math.Min(modulusLen, b.numberLength), res); monReduction(res,modulus,n2); return finalSubtraction(res, modulus); } internal static BigInteger finalSubtraction(int[] res, BigInteger modulus){ // skipping leading zeros int modulusLen = modulus.numberLength; bool doSub = res[modulusLen]!=0; if(!doSub) { int[] modulusDigits = modulus.digits; doSub = true; for(int i = modulusLen - 1; i >= 0; i--) { if(res[i] != modulusDigits[i]) { doSub = (res[i] != 0) && ((res[i] & 0xFFFFFFFFL) > (modulusDigits[i] & 0xFFFFFFFFL)); break; } } } BigInteger result = new BigInteger(1, modulusLen+1, res); // if (res >= modulusDigits) compute (res - modulusDigits) if (doSub) { Elementary.inplaceSubtract(result, modulus); } result.cutOffLeadingZeroes(); return result; } internal static BigInteger modPow2Inverse(BigInteger x, int n) { // PRE: (x > 0), (x is odd), and (n > 0) BigInteger y = new BigInteger(1, new int[1 << n]); y.numberLength = 1; y.digits[0] = 1; y.sign = 1; for (int i = 1; i < n; i++) { if (BitLevel.testBit(x.multiply(y), i)) { // Adding 2^i to y (setting the i-th bit) y.digits[i >> 5] |= (1 << (i & 31)); } } return y; } internal static void inplaceModPow2(BigInteger x, int n) { // PRE: (x > 0) and (n >= 0) int fd = n >> 5; int leadingZeros; if ((x.numberLength < fd) || (x.bitLength() <= n)) { return; } leadingZeros = 32 - (n & 31); x.numberLength = fd + 1; unchecked { x.digits[fd] &= (leadingZeros < 32) ? ((int)(((uint)-1) >> leadingZeros)) : 0; } x.cutOffLeadingZeroes(); } } }
using ReactiveUI; using Splat; using System; using System.Collections.ObjectModel; using System.Linq; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading.Tasks; using WalletWasabi.Blockchain.Transactions; using WalletWasabi.Gui.Helpers; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Gui.Models.Sorting; using WalletWasabi.Logging; using WalletWasabi.Models; using WalletWasabi.Wallets; using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class HistoryTabViewModel : WasabiDocumentTabViewModel, IWalletViewModel { private ObservableCollection<TransactionViewModel> _transactions; private TransactionViewModel _selectedTransaction; private SortOrder _dateSortDirection; private SortOrder _amountSortDirection; private SortOrder _transactionSortDirection; private SortOrder _labelSortDirection; public HistoryTabViewModel(Wallet wallet) : base("History") { Global = Locator.Current.GetService<Global>(); Wallet = wallet; _transactions = new ObservableCollection<TransactionViewModel>(); ValidateSavedColumnConfig(); SortCommand = ReactiveCommand.Create(RefreshOrdering); var savedSort = Global.UiConfig.HistoryTabViewSortingPreference; SortColumn(savedSort.SortOrder, savedSort.ColumnTarget, false); RefreshOrdering(); this.WhenAnyValue(x => x.DateSortDirection) .Where(x => x != SortOrder.None) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => SortColumn(x, nameof(DateSortDirection))); this.WhenAnyValue(x => x.AmountSortDirection) .Where(x => x != SortOrder.None) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => SortColumn(x, nameof(AmountSortDirection))); this.WhenAnyValue(x => x.TransactionSortDirection) .Where(x => x != SortOrder.None) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => SortColumn(x, nameof(TransactionSortDirection))); this.WhenAnyValue(x => x.LabelSortDirection) .Where(x => x != SortOrder.None) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => SortColumn(x, nameof(LabelSortDirection))); SortCommand.ThrownExceptions .ObserveOn(RxApp.TaskpoolScheduler) .Subscribe(ex => { Logger.LogError(ex); NotificationHelpers.Error(ex.ToUserFriendlyString()); }); } private Global Global { get; } private Wallet Wallet { get; } Wallet IWalletViewModel.Wallet => Wallet; public ReactiveCommand<Unit, Unit> SortCommand { get; } public ObservableCollection<TransactionViewModel> Transactions { get => _transactions; set => this.RaiseAndSetIfChanged(ref _transactions, value); } public TransactionViewModel SelectedTransaction { get => _selectedTransaction; set => this.RaiseAndSetIfChanged(ref _selectedTransaction, value); } public SortOrder DateSortDirection { get => _dateSortDirection; set => this.RaiseAndSetIfChanged(ref _dateSortDirection, value); } public SortOrder AmountSortDirection { get => _amountSortDirection; set => this.RaiseAndSetIfChanged(ref _amountSortDirection, value); } public SortOrder TransactionSortDirection { get => _transactionSortDirection; set => this.RaiseAndSetIfChanged(ref _transactionSortDirection, value); } public SortOrder LabelSortDirection { get => _labelSortDirection; set => this.RaiseAndSetIfChanged(ref _labelSortDirection, value); } public override void OnOpen(CompositeDisposable disposables) { base.OnOpen(disposables); Observable.FromEventPattern(Wallet, nameof(Wallet.NewFilterProcessed)) .Merge(Observable.FromEventPattern(Wallet.TransactionProcessor, nameof(Wallet.TransactionProcessor.WalletRelevantTransactionProcessed))) .Throttle(TimeSpan.FromSeconds(3)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(async _ => await TryRewriteTableAsync()) .DisposeWith(disposables); Global.UiConfig.WhenAnyValue(x => x.PrivacyMode).ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ => { foreach (var transaction in Transactions) { transaction.Refresh(); } }).DisposeWith(disposables); _ = TryRewriteTableAsync(); } private async Task TryRewriteTableAsync() { try { var historyBuilder = new TransactionHistoryBuilder(Wallet); var txRecordList = await Task.Run(historyBuilder.BuildHistorySummary); var rememberSelectedTransactionId = SelectedTransaction?.TransactionId; Transactions?.Clear(); var trs = txRecordList.Select(txr => new TransactionDetailsViewModel { WalletName = Wallet.WalletName, DateTime = txr.DateTime.ToLocalTime(), Confirmations = txr.Height.Type == HeightType.Chain ? (int)Global.BitcoinStore.SmartHeaderChain.TipHeight - txr.Height.Value + 1 : 0, AmountBtc = $"{txr.Amount.ToString(fplus: true, trimExcessZero: true)}", Label = txr.Label, BlockHeight = txr.Height.Type == HeightType.Chain ? txr.Height.Value : 0, TransactionId = txr.TransactionId.ToString() }).Select(ti => new TransactionViewModel(ti, Global.UiConfig)); Transactions = new ObservableCollection<TransactionViewModel>(trs); if (Transactions.Count > 0 && rememberSelectedTransactionId is { }) { var txToSelect = Transactions.FirstOrDefault(x => x.TransactionId == rememberSelectedTransactionId); if (txToSelect is { }) { SelectedTransaction = txToSelect; } } RefreshOrdering(); } catch (Exception ex) { Logger.LogError(ex); } } private void ValidateSavedColumnConfig() { var savedCol = Global.UiConfig.HistoryTabViewSortingPreference.ColumnTarget; if (savedCol != nameof(DateSortDirection) & savedCol != nameof(AmountSortDirection) & savedCol != nameof(TransactionSortDirection) & savedCol != nameof(LabelSortDirection)) { Global.UiConfig.HistoryTabViewSortingPreference = new SortingPreference(SortOrder.Decreasing, nameof(DateSortDirection)); } } private void SortColumn(SortOrder sortOrder, string target, bool saveToUiConfig = true) { var sortPref = new SortingPreference(sortOrder, target); if (saveToUiConfig) { Global.UiConfig.HistoryTabViewSortingPreference = sortPref; } DateSortDirection = sortPref.Match(sortOrder, nameof(DateSortDirection)); AmountSortDirection = sortPref.Match(sortOrder, nameof(AmountSortDirection)); TransactionSortDirection = sortPref.Match(sortOrder, nameof(TransactionSortDirection)); LabelSortDirection = sortPref.Match(sortOrder, nameof(LabelSortDirection)); } private void RefreshOrdering() { if (LabelSortDirection != SortOrder.None) { switch (LabelSortDirection) { case SortOrder.Increasing: Transactions = new ObservableCollection<TransactionViewModel>(_transactions.OrderBy(t => t.Label)); break; case SortOrder.Decreasing: Transactions = new ObservableCollection<TransactionViewModel>(_transactions.OrderByDescending(t => t.Label)); break; } } else if (TransactionSortDirection != SortOrder.None) { switch (TransactionSortDirection) { case SortOrder.Increasing: Transactions = new ObservableCollection<TransactionViewModel>(_transactions.OrderBy(t => t.TransactionId)); break; case SortOrder.Decreasing: Transactions = new ObservableCollection<TransactionViewModel>(_transactions.OrderByDescending(t => t.TransactionId)); break; } } else if (AmountSortDirection != SortOrder.None) { switch (AmountSortDirection) { case SortOrder.Increasing: Transactions = new ObservableCollection<TransactionViewModel>(_transactions.OrderBy(t => t.Amount)); break; case SortOrder.Decreasing: Transactions = new ObservableCollection<TransactionViewModel>(_transactions.OrderByDescending(t => t.Amount)); break; } } else if (DateSortDirection != SortOrder.None) { switch (DateSortDirection) { case SortOrder.Increasing: Transactions = new ObservableCollection<TransactionViewModel>(_transactions.OrderBy(t => t.DateTime)); break; case SortOrder.Decreasing: Transactions = new ObservableCollection<TransactionViewModel>(_transactions.OrderByDescending(t => t.DateTime)); break; } } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using TddEbook.TddToolkit.TypeResolution.Interfaces; using TddEbook.TypeReflection; namespace TddEbook.TddToolkit.Generators { public class CollectionGenerator : ICollectionGenerator { private readonly GenericMethodProxyCalls _genericMethodProxyCalls; public CollectionGenerator(GenericMethodProxyCalls genericMethodProxyCalls) { _genericMethodProxyCalls = genericMethodProxyCalls; } public IEnumerable<T> EnumerableWith<T>(IEnumerable<T> included, IInstanceGenerator instanceGenerator) { var list = new List<T>(); list.Add(instanceGenerator.Instance<T>()); list.AddRange(included); list.Add(instanceGenerator.Instance<T>()); return list; } public IEnumerable<T> Enumerable<T>(IInstanceGenerator instanceGenerator) { return Enumerable<T>(AllGenerator.Many, instanceGenerator); } public IEnumerable<T> Enumerable<T>(int length, IInstanceGenerator instanceGenerator) { return AddManyTo(new List<T>(), length, instanceGenerator); } public IEnumerable<T> EnumerableWithout<T>(T[] excluded, IInstanceGenerator instanceGenerator) { var result = new List<T> { instanceGenerator.OtherThan(excluded), instanceGenerator.OtherThan(excluded), instanceGenerator.OtherThan(excluded) }; return result; } public T[] Array<T>(IInstanceGenerator instanceGenerator) { return Array<T>(AllGenerator.Many, instanceGenerator); } public T[] Array<T>(int length, IInstanceGenerator instanceGenerator) { return Enumerable<T>(length, instanceGenerator).ToArray(); } public T[] ArrayWithout<T>(T[] excluded, IInstanceGenerator instanceGenerator) { return EnumerableWithout(excluded, instanceGenerator).ToArray(); } public T[] ArrayWith<T>(T[] included, IInstanceGenerator instanceGenerator) { return EnumerableWith(included, instanceGenerator).ToArray(); } public T[] ArrayWithout<T>(IEnumerable<T> excluded, IInstanceGenerator instanceGenerator) { return EnumerableWithout(excluded.ToArray(), instanceGenerator).ToArray(); } public T[] ArrayWith<T>(IInstanceGenerator instanceGenerator, IEnumerable<T> included) { return EnumerableWith(included.ToArray(), instanceGenerator).ToArray(); } public List<T> List<T>(IInstanceGenerator instanceGenerator) { return List<T>(AllGenerator.Many, instanceGenerator); } public List<T> List<T>(int length, IInstanceGenerator instanceGenerator) { return Enumerable<T>(length, instanceGenerator).ToList(); } public List<T> ListWithout<T>(T[] excluded, IInstanceGenerator instanceGenerator) { return EnumerableWithout(excluded, instanceGenerator).ToList(); } public List<T> ListWith<T>(T[] included, IInstanceGenerator instanceGenerator) { return EnumerableWith(included, instanceGenerator).ToList(); } public List<T> ListWithout<T>(IEnumerable<T> excluded, IInstanceGenerator instanceGenerator) { return EnumerableWithout(excluded.ToArray(), instanceGenerator).ToList(); } public List<T> ListWith<T>(IEnumerable<T> included, IInstanceGenerator instanceGenerator) { return EnumerableWith(included.ToArray(), instanceGenerator).ToList(); } public IReadOnlyList<T> ReadOnlyList<T>(IInstanceGenerator instanceGenerator) { return ReadOnlyList<T>(AllGenerator.Many, instanceGenerator); } public IReadOnlyList<T> ReadOnlyList<T>(int length, IInstanceGenerator instanceGenerator) { return List<T>(length, instanceGenerator); } public IReadOnlyList<T> ReadOnlyListWith<T>(IEnumerable<T> items, IInstanceGenerator instanceGenerator) { return ListWith(items, instanceGenerator); } public IReadOnlyList<T> ReadOnlyListWith<T>(T[] items, IInstanceGenerator instanceGenerator) { return ListWith(items, instanceGenerator); } public IReadOnlyList<T> ReadOnlyListWithout<T>(IEnumerable<T> items, IInstanceGenerator instanceGenerator) { return ListWithout(items, instanceGenerator); } public IReadOnlyList<T> ReadOnlyListWithout<T>(T[] items, IInstanceGenerator instanceGenerator) { return ListWithout(items, instanceGenerator); } public SortedList<TKey, TValue> SortedList<TKey, TValue>(IInstanceGenerator instanceGenerator) { return SortedList<TKey, TValue>(AllGenerator.Many, instanceGenerator); } public SortedList<TKey, TValue> SortedList<TKey, TValue>(int length, IInstanceGenerator instanceGenerator) { var list = new SortedList<TKey, TValue>(); for (int i = 0; i < length; ++i) { list.Add(instanceGenerator.Instance<TKey>(), instanceGenerator.Instance<TValue>()); } return list; } public ISet<T> Set<T>(int length, IInstanceGenerator instanceGenerator) { return new HashSet<T>(Enumerable<T>(length, instanceGenerator)); } public ISet<T> Set<T>(IInstanceGenerator instanceGenerator) { return Set<T>(AllGenerator.Many, instanceGenerator); } public ISet<T> SortedSet<T>(int length, IInstanceGenerator instanceGenerator) { return new SortedSet<T>(Enumerable<T>(length, instanceGenerator)); } public ISet<T> SortedSet<T>(IInstanceGenerator instanceGenerator) { return SortedSet<T>(AllGenerator.Many, instanceGenerator); } public Dictionary<TKey, TValue> Dictionary<TKey, TValue>(int length, IInstanceGenerator instanceGenerator) { var dict = new Dictionary<TKey, TValue>(); for (var i = 0; i < length; ++i) { dict.Add(instanceGenerator.Instance<TKey>(), instanceGenerator.Instance<TValue>()); } return dict; } public object Dictionary(Type keyType, Type valueType, IInstanceGenerator generator) { return _genericMethodProxyCalls.ResultOfGenericVersionOfMethod( this, keyType, valueType, MethodBase.GetCurrentMethod().Name, new object[] { generator }); } public Dictionary<T, U> DictionaryWithKeys<T, U>(IEnumerable<T> keys, IInstanceGenerator instanceGenerator) { var dict = Dictionary<T, U>(0, instanceGenerator); foreach (var key in keys) { dict.Add(key, instanceGenerator.InstanceOf<U>()); } return dict; } public Dictionary<TKey, TValue> Dictionary<TKey, TValue>(IInstanceGenerator instanceGenerator) { return Dictionary<TKey, TValue>(AllGenerator.Many, instanceGenerator); } public IReadOnlyDictionary<TKey, TValue> ReadOnlyDictionary<TKey, TValue>(int length, IInstanceGenerator instanceGenerator) { return Dictionary<TKey, TValue>(length, instanceGenerator); } public IReadOnlyDictionary<T, U> ReadOnlyDictionaryWithKeys<T, U>(IEnumerable<T> keys, IInstanceGenerator instanceGenerator) { return DictionaryWithKeys<T, U>(keys, instanceGenerator); } public IReadOnlyDictionary<TKey, TValue> ReadOnlyDictionary<TKey, TValue>(IInstanceGenerator instanceGenerator) { return ReadOnlyDictionary<TKey, TValue>(AllGenerator.Many, instanceGenerator); } public SortedDictionary<TKey, TValue> SortedDictionary<TKey, TValue>(int length, IInstanceGenerator instanceGenerator) { var dict = new SortedDictionary<TKey, TValue>(); for (int i = 0; i < length; ++i) { dict.Add(instanceGenerator.Instance<TKey>(), instanceGenerator.Instance<TValue>()); } return dict; } public object SortedDictionary(Type keyType, Type valueType, IInstanceGenerator generator) { return _genericMethodProxyCalls.ResultOfGenericVersionOfMethod( this, keyType, valueType, MethodBase.GetCurrentMethod().Name, new object[] { generator }); } public SortedDictionary<TKey, TValue> SortedDictionary<TKey, TValue>(IInstanceGenerator instanceGenerator) { return SortedDictionary<TKey, TValue>(AllGenerator.Many, instanceGenerator); } public ConcurrentDictionary<TKey, TValue> ConcurrentDictionary<TKey, TValue>(int length, IInstanceGenerator instanceGenerator) { var dict = new ConcurrentDictionary<TKey, TValue>(); for (var i = 0; i < length; ++i) { dict.TryAdd(instanceGenerator.Instance<TKey>(), instanceGenerator.Instance<TValue>()); } return dict; } public ConcurrentDictionary<TKey, TValue> ConcurrentDictionary<TKey, TValue>(IInstanceGenerator instanceGenerator) { return ConcurrentDictionary<TKey, TValue>(AllGenerator.Many, instanceGenerator); } public ConcurrentStack<T> ConcurrentStack<T>(IInstanceGenerator instanceGenerator) { return ConcurrentStack<T>(AllGenerator.Many, instanceGenerator); } public ConcurrentStack<T> ConcurrentStack<T>(int length, IInstanceGenerator instanceGenerator) { var coll = new ConcurrentStack<T>(); for (var i = 0; i < length; ++i) { coll.Push(instanceGenerator.Instance<T>()); } return coll; } public ConcurrentQueue<T> ConcurrentQueue<T>(IInstanceGenerator instanceGenerator) { return ConcurrentQueue<T>(AllGenerator.Many, instanceGenerator); } public ConcurrentQueue<T> ConcurrentQueue<T>(int length, IInstanceGenerator instanceGenerator) { var coll = new ConcurrentQueue<T>(); for (int i = 0; i < length; ++i) { coll.Enqueue(instanceGenerator.Instance<T>()); } return coll; } public ConcurrentBag<T> ConcurrentBag<T>(IInstanceGenerator instanceGenerator) { return ConcurrentBag<T>(AllGenerator.Many, instanceGenerator); } public ConcurrentBag<T> ConcurrentBag<T>(int length, IInstanceGenerator instanceGenerator) { var coll = new ConcurrentBag<T>(); for (int i = 0; i < length; ++i) { coll.Add(instanceGenerator.Instance<T>()); } return coll; } public IEnumerable<T> EnumerableSortedDescending<T>(int length, IInstanceGenerator instanceGenerator) { return SortedSet<T>(length, instanceGenerator).ToList(); } public IEnumerable<T> EnumerableSortedDescending<T>(IInstanceGenerator instanceGenerator) { return EnumerableSortedDescending<T>(AllGenerator.Many, instanceGenerator); } public IEnumerator<T> Enumerator<T>(IInstanceGenerator instanceGenerator) { return List<T>(instanceGenerator).GetEnumerator(); } public object List(Type type, IInstanceGenerator instanceGenerator) { return ResultOfGenericVersionOfMethod( type, MethodBase.GetCurrentMethod(), instanceGenerator); } public object Set(Type type, IInstanceGenerator instanceGenerator) { return ResultOfGenericVersionOfMethod(type, MethodBase.GetCurrentMethod(), instanceGenerator); } public object SortedList(Type keyType, Type valueType, IInstanceGenerator instanceGenerator) { return _genericMethodProxyCalls.ResultOfGenericVersionOfMethod( this, keyType, valueType, MethodBase.GetCurrentMethod().Name, new object[] {instanceGenerator}); } public object SortedSet(Type type, IInstanceGenerator instanceGenerator) { return _genericMethodProxyCalls.ResultOfGenericVersionOfMethod( this, type, MethodBase.GetCurrentMethod().Name); } public object ConcurrentDictionary(Type keyType, Type valueType, IInstanceGenerator instanceGenerator) { return _genericMethodProxyCalls.ResultOfGenericVersionOfMethod( this, keyType, valueType, MethodBase.GetCurrentMethod().Name, new object[] {instanceGenerator}); } public object Array(Type type, IInstanceGenerator instanceGenerator) { return _genericMethodProxyCalls.ResultOfGenericVersionOfMethod( this, type, MethodBase.GetCurrentMethod().Name, new object[] {instanceGenerator}); } public ICollection<T> AddManyTo<T>(ICollection<T> collection, int many, IInstanceGenerator instanceGenerator) { for (int i = 0; i < many; ++i) { collection.Add(instanceGenerator.Instance<T>()); } return collection; } public object Enumerator(Type type, IInstanceGenerator instanceGenerator) { return _genericMethodProxyCalls.ResultOfGenericVersionOfMethod(this, type, MethodBase.GetCurrentMethod().Name, new object[] {instanceGenerator}); } public object ConcurrentStack(Type type, IInstanceGenerator instanceGenerator) { return ResultOfGenericVersionOfMethod(type, MethodBase.GetCurrentMethod(), instanceGenerator); } public object ConcurrentQueue(Type type, IInstanceGenerator instanceGenerator) { return ResultOfGenericVersionOfMethod(type, MethodBase.GetCurrentMethod(), instanceGenerator); } public object ConcurrentBag(Type type, IInstanceGenerator instanceGenerator) { return ResultOfGenericVersionOfMethod(type, MethodBase.GetCurrentMethod(), instanceGenerator); } private object ResultOfGenericVersionOfMethod(Type type, MethodBase currentMethod, IInstanceGenerator instanceGenerator) { return _genericMethodProxyCalls.ResultOfGenericVersionOfMethod( this, type, currentMethod.Name, new object[] { instanceGenerator }); } public object KeyValuePair(Type keyType, Type valueType, IInstanceGenerator generator) { return Activator.CreateInstance( typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType), generator.Instance(keyType), generator.Instance(valueType) ); } } }
// <copyright file="DesiredCapabilities.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Remote { /// <summary> /// Class to Create the capabilities of the browser you require for <see cref="IWebDriver"/>. /// If you wish to use default values use the static methods /// </summary> [Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")] internal class DesiredCapabilities : IWritableCapabilities, IHasCapabilitiesDictionary { private readonly Dictionary<string, object> capabilities = new Dictionary<string, object>(); /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param> /// <param name="version">Version of the browser</param> /// <param name="platform">The platform it works on</param> public DesiredCapabilities(string browser, string version, Platform platform) { this.SetCapability(CapabilityType.BrowserName, browser); this.SetCapability(CapabilityType.Version, version); this.SetCapability(CapabilityType.Platform, platform); } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> public DesiredCapabilities() { } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="rawMap">Dictionary of items for the remote driver</param> /// <example> /// <code> /// DesiredCapabilities capabilities = new DesiredCapabilities(new Dictionary<![CDATA[<string,object>]]>(){["browserName","firefox"],["version",string.Empty],["javaScript",true]}); /// </code> /// </example> public DesiredCapabilities(Dictionary<string, object> rawMap) { if (rawMap != null) { foreach (string key in rawMap.Keys) { if (key == CapabilityType.Platform) { object raw = rawMap[CapabilityType.Platform]; string rawAsString = raw as string; Platform rawAsPlatform = raw as Platform; if (rawAsString != null) { this.SetCapability(CapabilityType.Platform, Platform.FromString(rawAsString)); } else if (rawAsPlatform != null) { this.SetCapability(CapabilityType.Platform, rawAsPlatform); } } else { this.SetCapability(key, rawMap[key]); } } } } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param> /// <param name="version">Version of the browser</param> /// <param name="platform">The platform it works on</param> /// <param name="isSpecCompliant">Sets a value indicating whether the capabilities are /// compliant with the W3C WebDriver specification.</param> internal DesiredCapabilities(string browser, string version, Platform platform, bool isSpecCompliant) { this.SetCapability(CapabilityType.BrowserName, browser); this.SetCapability(CapabilityType.Version, version); this.SetCapability(CapabilityType.Platform, platform); } /// <summary> /// Gets the browser name /// </summary> public string BrowserName { get { string name = string.Empty; object capabilityValue = this.GetCapability(CapabilityType.BrowserName); if (capabilityValue != null) { name = capabilityValue.ToString(); } return name; } } /// <summary> /// Gets or sets the platform /// </summary> public Platform Platform { get { return this.GetCapability(CapabilityType.Platform) as Platform ?? new Platform(PlatformType.Any); } set { this.SetCapability(CapabilityType.Platform, value); } } /// <summary> /// Gets the browser version /// </summary> public string Version { get { string browserVersion = string.Empty; object capabilityValue = this.GetCapability(CapabilityType.Version); if (capabilityValue != null) { browserVersion = capabilityValue.ToString(); } return browserVersion; } } /// <summary> /// Gets or sets a value indicating whether the browser accepts SSL certificates. /// </summary> public bool AcceptInsecureCerts { get { bool acceptSSLCerts = false; object capabilityValue = this.GetCapability(CapabilityType.AcceptInsecureCertificates); if (capabilityValue != null) { acceptSSLCerts = (bool)capabilityValue; } return acceptSSLCerts; } set { this.SetCapability(CapabilityType.AcceptInsecureCertificates, value); } } /// <summary> /// Gets the underlying Dictionary for a given set of capabilities. /// </summary> Dictionary<string, object> IHasCapabilitiesDictionary.CapabilitiesDictionary { get { return this.CapabilitiesDictionary; } } /// <summary> /// Gets the underlying Dictionary for a given set of capabilities. /// </summary> internal Dictionary<string, object> CapabilitiesDictionary { get { return this.capabilities; } } /// <summary> /// Gets the capability value with the specified name. /// </summary> /// <param name="capabilityName">The name of the capability to get.</param> /// <returns>The value of the capability.</returns> /// <exception cref="ArgumentException"> /// The specified capability name is not in the set of capabilities. /// </exception> public object this[string capabilityName] { get { if (!this.capabilities.ContainsKey(capabilityName)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The capability {0} is not present in this set of capabilities", capabilityName)); } return this.capabilities[capabilityName]; } } /// <summary> /// Gets a value indicating whether the browser has a given capability. /// </summary> /// <param name="capability">The capability to get.</param> /// <returns>Returns <see langword="true"/> if the browser has the capability; otherwise, <see langword="false"/>.</returns> public bool HasCapability(string capability) { return this.capabilities.ContainsKey(capability); } /// <summary> /// Gets a capability of the browser. /// </summary> /// <param name="capability">The capability to get.</param> /// <returns>An object associated with the capability, or <see langword="null"/> /// if the capability is not set on the browser.</returns> public object GetCapability(string capability) { object capabilityValue = null; if (this.capabilities.ContainsKey(capability)) { capabilityValue = this.capabilities[capability]; string capabilityValueString = capabilityValue as string; if (capability == CapabilityType.Platform && capabilityValueString != null) { capabilityValue = Platform.FromString(capabilityValue.ToString()); } } return capabilityValue; } /// <summary> /// Sets a capability of the browser. /// </summary> /// <param name="capability">The capability to get.</param> /// <param name="capabilityValue">The value for the capability.</param> public void SetCapability(string capability, object capabilityValue) { // Handle the special case of Platform objects. These should // be stored in the underlying dictionary as their protocol // string representation. Platform platformCapabilityValue = capabilityValue as Platform; if (platformCapabilityValue != null) { this.capabilities[capability] = platformCapabilityValue.ProtocolPlatformType; } else { this.capabilities[capability] = capabilityValue; } } /// <summary> /// Return HashCode for the DesiredCapabilities that has been created /// </summary> /// <returns>Integer of HashCode generated</returns> public override int GetHashCode() { int result; result = this.BrowserName != null ? this.BrowserName.GetHashCode() : 0; result = (31 * result) + (this.Version != null ? this.Version.GetHashCode() : 0); result = (31 * result) + (this.Platform != null ? this.Platform.GetHashCode() : 0); return result; } /// <summary> /// Return a string of capabilities being used /// </summary> /// <returns>String of capabilities being used</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Capabilities [BrowserName={0}, Platform={1}, Version={2}]", this.BrowserName, this.Platform.PlatformType.ToString(), this.Version); } /// <summary> /// Compare two DesiredCapabilities and will return either true or false /// </summary> /// <param name="obj">DesiredCapabilities you wish to compare</param> /// <returns>true if they are the same or false if they are not</returns> public override bool Equals(object obj) { if (this == obj) { return true; } DesiredCapabilities other = obj as DesiredCapabilities; if (other == null) { return false; } if (this.BrowserName != null ? this.BrowserName != other.BrowserName : other.BrowserName != null) { return false; } if (!this.Platform.IsPlatformType(other.Platform.PlatformType)) { return false; } if (this.Version != null ? this.Version != other.Version : other.Version != null) { return false; } return true; } /// <summary> /// Returns a read-only version of this capabilities object. /// </summary> /// <returns>A read-only version of this capabilities object.</returns> public ICapabilities AsReadOnly() { ReadOnlyDesiredCapabilities readOnlyCapabilities = new ReadOnlyDesiredCapabilities(this); return readOnlyCapabilities; } } }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { partial class DockPanel { [ToolboxItem(false)] public class AutoHideWindowControl : Panel, ISplitterHost { protected class SplitterControl : SplitterBase { public SplitterControl(AutoHideWindowControl autoHideWindow) { m_autoHideWindow = autoHideWindow; } private AutoHideWindowControl m_autoHideWindow; private AutoHideWindowControl AutoHideWindow { get { return m_autoHideWindow; } } protected override int SplitterSize { get { return AutoHideWindow.DockPanel.Theme.Measures.AutoHideSplitterSize; } } protected override void StartDrag() { AutoHideWindow.DockPanel.BeginDrag(AutoHideWindow, AutoHideWindow.RectangleToScreen(Bounds)); } } #region consts private const int ANIMATE_TIME = 100; // in mini-seconds #endregion private Timer m_timerMouseTrack; protected SplitterBase m_splitter { get; private set; } public AutoHideWindowControl(DockPanel dockPanel) { m_dockPanel = dockPanel; m_timerMouseTrack = new Timer(); m_timerMouseTrack.Tick += new EventHandler(TimerMouseTrack_Tick); Visible = false; m_splitter = DockPanel.Theme.Extender.WindowSplitterControlFactory.CreateSplitterControl(this); Controls.Add(m_splitter); } protected override void Dispose(bool disposing) { if (disposing) { m_timerMouseTrack.Dispose(); } base.Dispose(disposing); } public bool IsDockWindow { get { return false; } } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } } private DockPane m_activePane = null; public DockPane ActivePane { get { return m_activePane; } } private void SetActivePane() { DockPane value = (ActiveContent == null ? null : ActiveContent.DockHandler.Pane); if (value == m_activePane) return; m_activePane = value; } private static readonly object AutoHideActiveContentChangedEvent = new object(); public event EventHandler ActiveContentChanged { add { Events.AddHandler(AutoHideActiveContentChangedEvent, value); } remove { Events.RemoveHandler(AutoHideActiveContentChangedEvent, value); } } protected virtual void OnActiveContentChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent]; if (handler != null) handler(this, e); } private IDockContent m_activeContent = null; public IDockContent ActiveContent { get { return m_activeContent; } set { if (value == m_activeContent) return; if (value != null) { if (!DockHelper.IsDockStateAutoHide(value.DockHandler.DockState) || value.DockHandler.DockPanel != DockPanel) throw (new InvalidOperationException(Strings.DockPanel_ActiveAutoHideContent_InvalidValue)); } DockPanel.SuspendLayout(); if (m_activeContent != null) { if (m_activeContent.DockHandler.Form.ContainsFocus) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(m_activeContent); } } AnimateWindow(false); } m_activeContent = value; SetActivePane(); if (ActivePane != null) ActivePane.ActiveContent = m_activeContent; if (m_activeContent != null) AnimateWindow(true); DockPanel.ResumeLayout(); DockPanel.RefreshAutoHideStrip(); SetTimerMouseTrack(); OnActiveContentChanged(EventArgs.Empty); } } public DockState DockState { get { return ActiveContent == null ? DockState.Unknown : ActiveContent.DockHandler.DockState; } } private bool m_flagAnimate = true; private bool FlagAnimate { get { return m_flagAnimate; } set { m_flagAnimate = value; } } private bool m_flagDragging = false; internal bool FlagDragging { get { return m_flagDragging; } set { if (m_flagDragging == value) return; m_flagDragging = value; SetTimerMouseTrack(); } } private void AnimateWindow(bool show) { if (!FlagAnimate && Visible != show) { Visible = show; return; } Parent.SuspendLayout(); Rectangle rectSource = GetRectangle(!show); Rectangle rectTarget = GetRectangle(show); int dxLoc, dyLoc; int dWidth, dHeight; dxLoc = dyLoc = dWidth = dHeight = 0; if (DockState == DockState.DockTopAutoHide) dHeight = show ? 1 : -1; else if (DockState == DockState.DockLeftAutoHide) dWidth = show ? 1 : -1; else if (DockState == DockState.DockRightAutoHide) { dxLoc = show ? -1 : 1; dWidth = show ? 1 : -1; } else if (DockState == DockState.DockBottomAutoHide) { dyLoc = (show ? -1 : 1); dHeight = (show ? 1 : -1); } if (show) { Bounds = DockPanel.GetAutoHideWindowBounds(new Rectangle(-rectTarget.Width, -rectTarget.Height, rectTarget.Width, rectTarget.Height)); if (Visible == false) Visible = true; PerformLayout(); } SuspendLayout(); LayoutAnimateWindow(rectSource); if (Visible == false) Visible = true; int speedFactor = 1; int totalPixels = (rectSource.Width != rectTarget.Width) ? Math.Abs(rectSource.Width - rectTarget.Width) : Math.Abs(rectSource.Height - rectTarget.Height); int remainPixels = totalPixels; DateTime startingTime = DateTime.Now; while (rectSource != rectTarget) { DateTime startPerMove = DateTime.Now; rectSource.X += dxLoc * speedFactor; rectSource.Y += dyLoc * speedFactor; rectSource.Width += dWidth * speedFactor; rectSource.Height += dHeight * speedFactor; if (Math.Sign(rectTarget.X - rectSource.X) != Math.Sign(dxLoc)) rectSource.X = rectTarget.X; if (Math.Sign(rectTarget.Y - rectSource.Y) != Math.Sign(dyLoc)) rectSource.Y = rectTarget.Y; if (Math.Sign(rectTarget.Width - rectSource.Width) != Math.Sign(dWidth)) rectSource.Width = rectTarget.Width; if (Math.Sign(rectTarget.Height - rectSource.Height) != Math.Sign(dHeight)) rectSource.Height = rectTarget.Height; LayoutAnimateWindow(rectSource); if (Parent != null) Parent.Update(); remainPixels -= speedFactor; while (true) { TimeSpan time = new TimeSpan(0, 0, 0, 0, ANIMATE_TIME); TimeSpan elapsedPerMove = DateTime.Now - startPerMove; TimeSpan elapsedTime = DateTime.Now - startingTime; if (((int)((time - elapsedTime).TotalMilliseconds)) <= 0) { speedFactor = remainPixels; break; } else speedFactor = remainPixels * (int)elapsedPerMove.TotalMilliseconds / (int)((time - elapsedTime).TotalMilliseconds); if (speedFactor >= 1) break; } } ResumeLayout(); Parent.ResumeLayout(); } private void LayoutAnimateWindow(Rectangle rect) { Bounds = DockPanel.GetAutoHideWindowBounds(rect); Rectangle rectClient = ClientRectangle; if (DockState == DockState.DockLeftAutoHide) ActivePane.Location = new Point(rectClient.Right - 2 - DockPanel.Theme.Measures.AutoHideSplitterSize - ActivePane.Width, ActivePane.Location.Y); else if (DockState == DockState.DockTopAutoHide) ActivePane.Location = new Point(ActivePane.Location.X, rectClient.Bottom - 2 - DockPanel.Theme.Measures.AutoHideSplitterSize - ActivePane.Height); } private Rectangle GetRectangle(bool show) { if (DockState == DockState.Unknown) return Rectangle.Empty; Rectangle rect = DockPanel.AutoHideWindowRectangle; if (show) return rect; if (DockState == DockState.DockLeftAutoHide) rect.Width = 0; else if (DockState == DockState.DockRightAutoHide) { rect.X += rect.Width; rect.Width = 0; } else if (DockState == DockState.DockTopAutoHide) rect.Height = 0; else { rect.Y += rect.Height; rect.Height = 0; } return rect; } private void SetTimerMouseTrack() { if (ActivePane == null || ActivePane.IsActivated || FlagDragging) { m_timerMouseTrack.Enabled = false; return; } // start the timer int hovertime = SystemInformation.MouseHoverTime ; // assign a default value 400 in case of setting Timer.Interval invalid value exception if (hovertime <= 0) hovertime = 400; m_timerMouseTrack.Interval = 2 * (int)hovertime; m_timerMouseTrack.Enabled = true; } protected virtual Rectangle DisplayingRectangle { get { Rectangle rect = ClientRectangle; // exclude the border and the splitter if (DockState == DockState.DockBottomAutoHide) { rect.Y += 2 + DockPanel.Theme.Measures.AutoHideSplitterSize; rect.Height -= 2 + DockPanel.Theme.Measures.AutoHideSplitterSize; } else if (DockState == DockState.DockRightAutoHide) { rect.X += 2 + DockPanel.Theme.Measures.AutoHideSplitterSize; rect.Width -= 2 + DockPanel.Theme.Measures.AutoHideSplitterSize; } else if (DockState == DockState.DockTopAutoHide) rect.Height -= 2 + DockPanel.Theme.Measures.AutoHideSplitterSize; else if (DockState == DockState.DockLeftAutoHide) rect.Width -= 2 + DockPanel.Theme.Measures.AutoHideSplitterSize; return rect; } } public void RefreshActiveContent() { if (ActiveContent == null) return; if (!DockHelper.IsDockStateAutoHide(ActiveContent.DockHandler.DockState)) { FlagAnimate = false; ActiveContent = null; FlagAnimate = true; } } public void RefreshActivePane() { SetTimerMouseTrack(); } private void TimerMouseTrack_Tick(object sender, EventArgs e) { if (IsDisposed) return; if (ActivePane == null || ActivePane.IsActivated) { m_timerMouseTrack.Enabled = false; return; } DockPane pane = ActivePane; Point ptMouseInAutoHideWindow = PointToClient(Control.MousePosition); Point ptMouseInDockPanel = DockPanel.PointToClient(Control.MousePosition); Rectangle rectTabStrip = DockPanel.GetTabStripRectangle(pane.DockState); if (!ClientRectangle.Contains(ptMouseInAutoHideWindow) && !rectTabStrip.Contains(ptMouseInDockPanel)) { ActiveContent = null; m_timerMouseTrack.Enabled = false; } } #region ISplitterDragSource Members void ISplitterDragSource.BeginDrag(Rectangle rectSplitter) { FlagDragging = true; } void ISplitterDragSource.EndDrag() { FlagDragging = false; } bool ISplitterDragSource.IsVertical { get { return (DockState == DockState.DockLeftAutoHide || DockState == DockState.DockRightAutoHide); } } Rectangle ISplitterDragSource.DragLimitBounds { get { Rectangle rectLimit = DockPanel.DockArea; if ((this as ISplitterDragSource).IsVertical) { rectLimit.X += MeasurePane.MinSize; rectLimit.Width -= 2 * MeasurePane.MinSize; } else { rectLimit.Y += MeasurePane.MinSize; rectLimit.Height -= 2 * MeasurePane.MinSize; } return DockPanel.RectangleToScreen(rectLimit); } } void ISplitterDragSource.MoveSplitter(int offset) { Rectangle rectDockArea = DockPanel.DockArea; IDockContent content = ActiveContent; if (DockState == DockState.DockLeftAutoHide && rectDockArea.Width > 0) { if (content.DockHandler.AutoHidePortion < 1) content.DockHandler.AutoHidePortion += ((double)offset) / (double)rectDockArea.Width; else content.DockHandler.AutoHidePortion = Width + offset; } else if (DockState == DockState.DockRightAutoHide && rectDockArea.Width > 0) { if (content.DockHandler.AutoHidePortion < 1) content.DockHandler.AutoHidePortion -= ((double)offset) / (double)rectDockArea.Width; else content.DockHandler.AutoHidePortion = Width - offset; } else if (DockState == DockState.DockBottomAutoHide && rectDockArea.Height > 0) { if (content.DockHandler.AutoHidePortion < 1) content.DockHandler.AutoHidePortion -= ((double)offset) / (double)rectDockArea.Height; else content.DockHandler.AutoHidePortion = Height - offset; } else if (DockState == DockState.DockTopAutoHide && rectDockArea.Height > 0) { if (content.DockHandler.AutoHidePortion < 1) content.DockHandler.AutoHidePortion += ((double)offset) / (double)rectDockArea.Height; else content.DockHandler.AutoHidePortion = Height + offset; } } #region IDragSource Members Control IDragSource.DragControl { get { return this; } } #endregion #endregion } private AutoHideWindowControl AutoHideWindow { get { return m_autoHideWindow; } } internal Control AutoHideControl { get { return m_autoHideWindow; } } internal void RefreshActiveAutoHideContent() { AutoHideWindow.RefreshActiveContent(); } internal Rectangle AutoHideWindowRectangle { get { DockState state = AutoHideWindow.DockState; Rectangle rectDockArea = DockArea; if (ActiveAutoHideContent == null) return Rectangle.Empty; if (Parent == null) return Rectangle.Empty; Rectangle rect = Rectangle.Empty; double autoHideSize = ActiveAutoHideContent.DockHandler.AutoHidePortion; if (state == DockState.DockLeftAutoHide) { if (autoHideSize < 1) autoHideSize = rectDockArea.Width * autoHideSize; if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize) autoHideSize = rectDockArea.Width - MeasurePane.MinSize; rect.X = rectDockArea.X - Theme.Measures.DockPadding; rect.Y = rectDockArea.Y; rect.Width = (int)autoHideSize; rect.Height = rectDockArea.Height; } else if (state == DockState.DockRightAutoHide) { if (autoHideSize < 1) autoHideSize = rectDockArea.Width * autoHideSize; if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize) autoHideSize = rectDockArea.Width - MeasurePane.MinSize; rect.X = rectDockArea.X + rectDockArea.Width - (int)autoHideSize + Theme.Measures.DockPadding; rect.Y = rectDockArea.Y; rect.Width = (int)autoHideSize; rect.Height = rectDockArea.Height; } else if (state == DockState.DockTopAutoHide) { if (autoHideSize < 1) autoHideSize = rectDockArea.Height * autoHideSize; if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize) autoHideSize = rectDockArea.Height - MeasurePane.MinSize; rect.X = rectDockArea.X; rect.Y = rectDockArea.Y - Theme.Measures.DockPadding; rect.Width = rectDockArea.Width; rect.Height = (int)autoHideSize; } else if (state == DockState.DockBottomAutoHide) { if (autoHideSize < 1) autoHideSize = rectDockArea.Height * autoHideSize; if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize) autoHideSize = rectDockArea.Height - MeasurePane.MinSize; rect.X = rectDockArea.X; rect.Y = rectDockArea.Y + rectDockArea.Height - (int)autoHideSize + Theme.Measures.DockPadding; rect.Width = rectDockArea.Width; rect.Height = (int)autoHideSize; } return rect; } } internal Rectangle GetAutoHideWindowBounds(Rectangle rectAutoHideWindow) { if (DocumentStyle == DocumentStyle.SystemMdi || DocumentStyle == DocumentStyle.DockingMdi) return (Parent == null) ? Rectangle.Empty : Parent.RectangleToClient(RectangleToScreen(rectAutoHideWindow)); else return rectAutoHideWindow; } internal void RefreshAutoHideStrip() { AutoHideStripControl.RefreshChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using Moq; using NuGet.Test.Mocks; using Xunit; namespace NuGet.Test { public class PackageWalkerTest { [Fact] public void ReverseDependencyWalkerUsersVersionAndIdToDetermineVisited() { // Arrange // A 1.0 -> B 1.0 IPackage packageA1 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.0]") }); // A 2.0 -> B 2.0 IPackage packageA2 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[2.0]") }); IPackage packageB1 = PackageUtility.CreatePackage("B", "1.0"); IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0"); var mockRepository = new MockPackageRepository(); mockRepository.AddPackage(packageA1); mockRepository.AddPackage(packageA2); mockRepository.AddPackage(packageB1); mockRepository.AddPackage(packageB2); // Act IDependentsResolver lookup = new DependentsWalker(mockRepository); // Assert Assert.Equal(0, lookup.GetDependents(packageA1).Count()); Assert.Equal(0, lookup.GetDependents(packageA2).Count()); Assert.Equal(1, lookup.GetDependents(packageB1).Count()); Assert.Equal(1, lookup.GetDependents(packageB2).Count()); } [Fact] public void ResolveDependenciesForInstallPackageWithUnknownDependencyThrows() { // Arrange IPackage package = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(), new MockPackageRepository(), NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(package), "Unable to resolve dependency 'B'."); } [Fact] public void ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider() { // Arrange IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B"); var repository = new Mock<PackageRepositoryBase>(); repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable()); var dependencyProvider = repository.As<IDependencyResolver>(); dependencyProvider.Setup(c => c.ResolveDependency(It.Is<PackageDependency>(p => p.Id == "B"), It.IsAny<IPackageConstraintProvider>(), false, true)) .Returns(packageB).Verifiable(); var localRepository = new MockPackageRepository(); IPackageOperationResolver resolver = new InstallWalker(localRepository, repository.Object, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var operations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(2, operations.Count); Assert.Equal(PackageAction.Install, operations.First().Action); Assert.Equal(packageB, operations.First().Package); Assert.Equal(PackageAction.Install, operations.Last().Action); Assert.Equal(packageA, operations.Last().Package); dependencyProvider.Verify(); } [Fact] public void ResolveDependenciesForInstallPackageResolvesDependencyWithConstraintsUsingDependencyResolver() { // Arrange var packageDependency = new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.1") }); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { packageDependency }); IPackage packageB10 = PackageUtility.CreatePackage("B", "1.0"); IPackage packageB12 = PackageUtility.CreatePackage("B", "1.2"); var repository = new Mock<PackageRepositoryBase>(MockBehavior.Strict); repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable()); var dependencyProvider = repository.As<IDependencyResolver>(); dependencyProvider.Setup(c => c.ResolveDependency(packageDependency, It.IsAny<IPackageConstraintProvider>(), false, true)) .Returns(packageB12).Verifiable(); var localRepository = new MockPackageRepository(); IPackageOperationResolver resolver = new InstallWalker(localRepository, repository.Object, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var operations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(2, operations.Count); Assert.Equal(PackageAction.Install, operations.First().Action); Assert.Equal(packageB12, operations.First().Package); Assert.Equal(PackageAction.Install, operations.Last().Action); Assert.Equal(packageA, operations.Last().Package); dependencyProvider.Verify(); } [Fact] public void ResolveDependenciesForInstallCircularReferenceThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("A") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.0'."); } [Fact] public void ResolveDependenciesForInstallDiamondDependencyGraph() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] // A // / \ // B C // \ / // D IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var packages = resolver.ResolveOperations(packageA).ToList(); // Assert var dict = packages.ToDictionary(p => p.Package.Id); Assert.Equal(4, packages.Count); Assert.NotNull(dict["A"]); Assert.NotNull(dict["B"]); Assert.NotNull(dict["C"]); Assert.NotNull(dict["D"]); } [Fact] public void ResolveDependenciesForInstallDiamondDependencyGraphWithDifferntVersionOfSamePackage() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D >= 1, E >= 2] // C -> [D >= 2, E >= 1] // A // / \ // B C // | \ | \ // D1 E2 D2 E1 IPackage packageA = PackageUtility.CreateProjectLevelPackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreateProjectLevelPackage("B", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("D", "1.0"), PackageDependency.CreateDependency("E", "2.0") }); IPackage packageC = PackageUtility.CreateProjectLevelPackage("C", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("D", "2.0"), PackageDependency.CreateDependency("E", "1.0") }); IPackage packageD10 = PackageUtility.CreateProjectLevelPackage("D", "1.0"); IPackage packageD20 = PackageUtility.CreateProjectLevelPackage("D", "2.0"); IPackage packageE10 = PackageUtility.CreateProjectLevelPackage("E", "1.0"); IPackage packageE20 = PackageUtility.CreateProjectLevelPackage("E", "2.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD20); sourceRepository.AddPackage(packageD10); sourceRepository.AddPackage(packageE20); sourceRepository.AddPackage(packageE10); IPackageOperationResolver projectResolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var operations = resolver.ResolveOperations(packageA).ToList(); var projectOperations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(5, operations.Count); Assert.Equal("E", operations[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), operations[0].Package.Version); Assert.Equal("B", operations[1].Package.Id); Assert.Equal("D", operations[2].Package.Id); Assert.Equal(new SemanticVersion("2.0"), operations[2].Package.Version); Assert.Equal("C", operations[3].Package.Id); Assert.Equal("A", operations[4].Package.Id); Assert.Equal(5, projectOperations.Count); Assert.Equal("E", projectOperations[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), projectOperations[0].Package.Version); Assert.Equal("B", projectOperations[1].Package.Id); Assert.Equal("D", projectOperations[2].Package.Id); Assert.Equal(new SemanticVersion("2.0"), projectOperations[2].Package.Version); Assert.Equal("C", projectOperations[3].Package.Id); Assert.Equal("A", projectOperations[4].Package.Id); } [Fact] public void UninstallWalkerIgnoresMissingDependencies() { // Arrange var localRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(3, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["C"]); Assert.NotNull(packages["D"]); } [Fact] public void ResolveDependenciesForUninstallDiamondDependencyGraph() { // Arrange var localRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] // A // / \ // B C // \ / // D IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(4, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); Assert.NotNull(packages["C"]); Assert.NotNull(packages["D"]); } [Fact] public void ResolveDependencyForInstallCircularReferenceWithDifferentVersionOfPackageReferenceThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageA15 = PackageUtility.CreatePackage("A", "1.5", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB10 = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("A", "[1.5]") }); sourceRepository.AddPackage(packageA10); sourceRepository.AddPackage(packageA15); sourceRepository.AddPackage(packageB10); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA10), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.5'."); } [Fact] public void ResolvingDependencyForUpdateWithConflictingDependents() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A 1.0 -> B [1.0] IPackage A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.0]") }, content: new[] { "a1" }); // A 2.0 -> B (any version) IPackage A20 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }, content: new[] { "a2" }); IPackage B10 = PackageUtility.CreatePackage("B", "1.0", content: new[] { "b1" }); IPackage B101 = PackageUtility.CreatePackage("B", "1.0.1", content: new[] { "b101" }); IPackage B20 = PackageUtility.CreatePackage("B", "2.0", content: new[] { "a2" }); localRepository.Add(A10); localRepository.Add(B10); sourceRepository.AddPackage(A10); sourceRepository.AddPackage(A20); sourceRepository.AddPackage(B10); sourceRepository.AddPackage(B101); sourceRepository.AddPackage(B20); IPackageOperationResolver resolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project }; // Act var packages = resolver.ResolveOperations(B101).ToList(); // Assert Assert.Equal(4, packages.Count); AssertOperation("A", "1.0", PackageAction.Uninstall, packages[0]); AssertOperation("B", "1.0", PackageAction.Uninstall, packages[1]); AssertOperation("A", "2.0", PackageAction.Install, packages[2]); AssertOperation("B", "1.0.1", PackageAction.Install, packages[3]); } [Fact] public void ResolvingDependencyForUpdateThatHasAnUnsatisfiedConstraint() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var constraintProvider = new Mock<IPackageConstraintProvider>(); constraintProvider.Setup(m => m.GetConstraint("B")).Returns(VersionUtility.ParseVersionSpec("[1.4]")); constraintProvider.Setup(m => m.Source).Returns("foo"); IPackage A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.5") }); IPackage A20 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0") }); IPackage B15 = PackageUtility.CreatePackage("B", "1.5"); IPackage B20 = PackageUtility.CreatePackage("B", "2.0"); localRepository.Add(A10); localRepository.Add(B15); sourceRepository.AddPackage(A10); sourceRepository.AddPackage(A20); sourceRepository.AddPackage(B15); sourceRepository.AddPackage(B20); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, constraintProvider.Object, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(A20), "Unable to resolve dependency 'B (\u2265 2.0)'.'B' has an additional constraint (= 1.4) defined in foo."); } [Fact] public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetMinimumVersionThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.5") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.4"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (\u2265 1.5)'."); } [Fact] public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetExactVersionThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.5]") }); sourceRepository.AddPackage(packageA); IPackage packageB = PackageUtility.CreatePackage("B", "1.4"); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (= 1.5)'."); } [Fact] public void ResolveOperationsForInstallSameDependencyAtDifferentLevelsInGraph() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A1 -> B1, C1 IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("C", "1.0") }); // B1 IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); // C1 -> B1, D1 IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("D", "1.0") }); // D1 -> B1 IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert var packages = resolver.ResolveOperations(packageA).ToList(); Assert.Equal(4, packages.Count); Assert.Equal("B", packages[0].Package.Id); Assert.Equal("D", packages[1].Package.Id); Assert.Equal("C", packages[2].Package.Id); Assert.Equal("A", packages[3].Package.Id); } [Fact] public void ResolveDependenciesForInstallSameDependencyAtDifferentLevelsInGraphDuringUpdate() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A1 -> B1, C1 IPackage packageA = PackageUtility.CreatePackage("A", "1.0", content: new[] { "A1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("C", "1.0") }); // B1 IPackage packageB = PackageUtility.CreatePackage("B", "1.0", new[] { "B1" }); // C1 -> B1, D1 IPackage packageC = PackageUtility.CreatePackage("C", "1.0", content: new[] { "C1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("D", "1.0") }); // D1 -> B1 IPackage packageD = PackageUtility.CreatePackage("D", "1.0", content: new[] { "A1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0") }); // A2 -> B2, C2 IPackage packageA2 = PackageUtility.CreatePackage("A", "2.0", content: new[] { "A2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0"), PackageDependency.CreateDependency("C", "2.0") }); // B2 IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0", new[] { "B2" }); // C2 -> B2, D2 IPackage packageC2 = PackageUtility.CreatePackage("C", "2.0", content: new[] { "C2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0"), PackageDependency.CreateDependency("D", "2.0") }); // D2 -> B2 IPackage packageD2 = PackageUtility.CreatePackage("D", "2.0", content: new[] { "D2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); sourceRepository.AddPackage(packageA2); sourceRepository.AddPackage(packageB2); sourceRepository.AddPackage(packageC2); sourceRepository.AddPackage(packageD2); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false); var operations = resolver.ResolveOperations(packageA2).ToList(); Assert.Equal(8, operations.Count); AssertOperation("A", "1.0", PackageAction.Uninstall, operations[0]); AssertOperation("C", "1.0", PackageAction.Uninstall, operations[1]); AssertOperation("D", "1.0", PackageAction.Uninstall, operations[2]); AssertOperation("B", "1.0", PackageAction.Uninstall, operations[3]); AssertOperation("B", "2.0", PackageAction.Install, operations[4]); AssertOperation("D", "2.0", PackageAction.Install, operations[5]); AssertOperation("C", "2.0", PackageAction.Install, operations[6]); AssertOperation("A", "2.0", PackageAction.Install, operations[7]); } [Fact] public void ResolveDependenciesForInstallPackageWithDependencyReturnsPackageAndDependency() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(2, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentThrows() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: false, forceRemove: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it."); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentAndRemoveDependenciesThrows() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it."); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentAndForceReturnsPackage() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: false, forceRemove: true); // Act var packages = resolver.ResolveOperations(packageB) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(1, packages.Count); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesExcludesDependencyIfDependencyInUse() { // Arrange var localRepository = new MockPackageRepository(); // A 1.0 -> [B, C] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); IPackage packageC = PackageUtility.CreatePackage("C", "1.0"); // D -> [C] IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C"), }); localRepository.AddPackage(packageD); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(2, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesSetAndForceReturnsAllDependencies() { // Arrange var localRepository = new MockPackageRepository(); // A 1.0 -> [B, C] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); IPackage packageC = PackageUtility.CreatePackage("C", "1.0"); // D -> [C] IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C"), }); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: true); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); Assert.NotNull(packages["C"]); } [Fact] public void ProjectInstallWalkerIgnoresSolutionLevelPackages() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage projectPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.5]") }, content: new[] { "content" }); sourceRepository.AddPackage(projectPackage); IPackage toolsPackage = PackageUtility.CreatePackage("B", "1.5", tools: new[] { "init.ps1" }); sourceRepository.AddPackage(toolsPackage); IPackageOperationResolver resolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project }; // Act var packages = resolver.ResolveOperations(projectPackage) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(1, packages.Count); Assert.NotNull(packages["A"]); } [Fact] public void AfterPackageWalkMetaPackageIsClassifiedTheSameAsDependencies() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage metaPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); IPackage projectPackageB = PackageUtility.CreatePackage("C", "1.0", content: new[] { "contentC" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(projectPackageB); Assert.Equal(PackageTargets.None, walker.GetPackageInfo(metaPackage).Target); // Act walker.Walk(metaPackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(metaPackage).Target); } [Fact] public void LocalizedIntelliSenseFileCountsAsProjectTarget() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { @"lib\A.dll", @"lib\A.xml" }); IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0", dependencies: new[] { new PackageDependency("A") }, satelliteAssemblies: new[] { @"lib\fr-fr\A.xml" }, language: "fr-fr"); mockRepository.AddPackage(runtimePackage); mockRepository.AddPackage(satellitePackage); // Act walker.Walk(satellitePackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target); } [Fact] public void AfterPackageWalkSatellitePackageIsClassifiedTheSameAsDependencies() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { @"lib\A.dll" }); IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0", dependencies: new[] { new PackageDependency("A") }, satelliteAssemblies: new[] { @"lib\fr-fr\A.resources.dll" }, language: "fr-fr"); mockRepository.AddPackage(runtimePackage); mockRepository.AddPackage(satellitePackage); // Act walker.Walk(satellitePackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target); } [Fact] public void MetaPackageWithMixedTargetsThrows() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage metaPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); IPackage solutionPackage = PackageUtility.CreatePackage("C", "1.0", tools: new[] { "tools" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(solutionPackage); // Act && Assert ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(metaPackage), "Child dependencies of dependency only packages cannot mix external and project packages."); } [Fact] public void ExternalPackagesThatDepdendOnProjectLevelPackagesThrows() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage solutionPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }, tools: new[] { "install.ps1" }); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(solutionPackage); // Act && Assert ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(solutionPackage), "External packages cannot depend on packages that target projects."); } [Fact] public void InstallWalkerResolvesLowestMajorAndMinorVersionButHighestBuildAndRevisionForDependencies() { // Arrange // A 1.0 -> B 1.0 // B 1.0 -> C 1.1 // C 1.1 -> D 1.0 var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") }); var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.0.1"), A10, PackageUtility.CreatePackage("D", "2.0"), PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }) }; IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(), repository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var packages = resolver.ResolveOperations(A10).ToList(); // Assert Assert.Equal(4, packages.Count); Assert.Equal("D", packages[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), packages[0].Package.Version); Assert.Equal("C", packages[1].Package.Id); Assert.Equal(new SemanticVersion("1.1.3"), packages[1].Package.Version); Assert.Equal("B", packages[2].Package.Id); Assert.Equal(new SemanticVersion("1.0.9"), packages[2].Package.Version); Assert.Equal("A", packages[3].Package.Id); Assert.Equal(new SemanticVersion("1.0"), packages[3].Package.Version); } private void AssertOperation(string expectedId, string expectedVersion, PackageAction expectedAction, PackageOperation operation) { Assert.Equal(expectedAction, operation.Action); Assert.Equal(expectedId, operation.Package.Id); Assert.Equal(new SemanticVersion(expectedVersion), operation.Package.Version); } private class TestWalker : PackageWalker { private readonly IPackageRepository _repository; public TestWalker(IPackageRepository repository) { _repository = repository; } protected override IPackage ResolveDependency(PackageDependency dependency) { return _repository.ResolveDependency(dependency, AllowPrereleaseVersions, false); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if false using System; using System.Collections.Generic; using System.Text; using Microsoft.Research.DataStructures; using System.IO; using System.Diagnostics.Contracts; namespace Microsoft.Research.CodeAnalysis { class BenigniMain { internal const string BLOCKPREFIX = "b"; internal const string SEPPARAM = ", "; internal const string TRANS = " -> "; internal const string EMPTY = " "; internal const string INITIAL = "(INITIAL {0})"; internal const string VARS = "(VAR {0})"; internal const string BEGIN_RULES = "(RULES "; internal const string END_RULES = ")"; public static void EmitTheEquations(EquationBlock entryPoint, List<EquationBlock> equations, TextWriter where, InvariantQuery<APC> invariantDB) { Set<string> vars = new Set<string>(); foreach (EquationBlock b in equations) { vars.AddRange(b.FormalParameters); } List<string> allVars = new List<string>(vars); allVars.Sort(); where.WriteLine(Vars(allVars)); where.WriteLine(Initial(entryPoint)); where.WriteLine(BEGIN_RULES); foreach (EquationBlock b in equations) { b.EmitEquations(where, invariantDB); } where.WriteLine(END_RULES); } private static string Initial(EquationBlock entry) { return SanitizeString(String.Format(INITIAL, entry.Head())); } private static string Vars(List<string> vars) { return SanitizeString(String.Format(VARS, FormalParametersAsString(vars))); } public static string FormalParametersAsString(List<string> listOfVariables) { StringBuilder tmp = new StringBuilder(); foreach (string p in listOfVariables) { tmp.Append(p + SEPPARAM); } if (tmp.Length > SEPPARAM.Length) { tmp.Remove(tmp.Length - SEPPARAM.Length, SEPPARAM.Length); // remove the last ", " } else { tmp.Append(BenigniMain.EMPTY); } return tmp.ToString(); } /// <summary> /// Replace "svXXX (YYY)" with "svXXX_(YYY)" /// </summary> public static string SanitizeString(string s) { char[] sAsChar = s.ToCharArray(); char[] result = new char[sAsChar.Length]; for (int i = 0, j = 0; i < sAsChar.Length;) { if (i < sAsChar.Length - 1 && sAsChar[i] == 's' && sAsChar[i + 1] == 'v') { result[j++] = sAsChar[i++]; // copy 's' result[j++] = sAsChar[i++]; // copy 'v' while (Char.IsDigit(sAsChar[i])) { result[j++] = sAsChar[i++]; } while (Char.IsWhiteSpace(sAsChar[i])) { result[j++] = '_'; i++; } if (sAsChar[i] == '(') // Skip left parenthesis { i++; } while (Char.IsDigit(sAsChar[i])) { result[j++] = sAsChar[i++]; } if (sAsChar[i] == ')') { i++; } } result[j++] = sAsChar[i++]; } return new String(result); } } /// <summary> /// Represent the equations for a block /// </summary> class EquationBlock { private CFGBlock id; private List<string> formalParameters; // We want to keep it sorted... private List<EquationBody> bodies; private string/*?*/ condition; public List<string> FormalParameters { get { Contract.Ensures(Contract.Result<List<string>>() != null); if (formalParameters.Count == 0) { this.InferParameters(new Set<EquationBlock>()); } return formalParameters; } } public CFGBlock Block { get { return id; } } public EquationBlock(CFGBlock ID) { id = ID; formalParameters = new List<string>(); bodies = new List<EquationBody>(); condition = null; } [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(formalParameters != null); } public void AddBody(EquationBody toAdd) { bodies.Add(toAdd); } public void AddParameters(Set<string> vars) { formalParameters.AddRange(vars); formalParameters.Sort(); // we keep the parameters sorted } public void EmitEquations(TextWriter where, InvariantQuery<APC> invariantDB) { foreach (EquationBody body in bodies) { body.EmitEquation(where, invariantDB); } } public string Condition { set { if (value != null && value.Length != 0) condition = value; else condition = null; } get { return condition; } } internal string Head() { return string.Format("{0}{1} ({2})", BenigniMain.BLOCKPREFIX, id.Index, BenigniMain.FormalParametersAsString(this.FormalParameters)); } private void InferParameters(Set<EquationBlock> visited) { // Console.WriteLine("Visiting {0}", this.Block.Index); if (visited.Contains(this)) return; visited.Add(this); var newParameters = new Set<string>(formalParameters); foreach (EquationBody succ in bodies) { succ.To.InferParameters(visited); newParameters.AddRange(succ.To.formalParameters); } List<string> asList = new List<string>(newParameters); asList.Sort(); formalParameters = asList; } } class EquationBody { private EquationBlock parent; private EquationBlock to; private IFunctionalMap<string, string> renamings; internal EquationBlock To { get { return to; } } public EquationBody(EquationBlock parent, EquationBlock to, IFunctionalMap<string, string> renamings) { this.parent = parent; this.to = to; this.renamings = renamings; } public void EmitEquation(TextWriter where, InvariantQuery<APC> invariantDB) { string head = parent.Head(); // bn(... ) StringBuilder bodyAsString = new StringBuilder(); foreach (string s in to.FormalParameters) { string actualParameter = renamings[s]; if (actualParameter == null) actualParameter = s; // if it is not there, it means that it is not renamed, i.e. it is the identity bodyAsString.Append(actualParameter + BenigniMain.SEPPARAM); } if (bodyAsString.Length > BenigniMain.SEPPARAM.Length) { bodyAsString.Remove(bodyAsString.Length - BenigniMain.SEPPARAM.Length, BenigniMain.SEPPARAM.Length); // remove the last ", " } else if (parent.Condition != null) { // no successors, so I just write down the parameters, bodyAsString.Append(BenigniMain.FormalParametersAsString(parent.FormalParameters)); } else { bodyAsString.Append(BenigniMain.EMPTY); } string succ = BenigniMain.BLOCKPREFIX + this.To.Block.Index; string result = String.Format("{0} {1} {2}( {3} ) ", head, BenigniMain.TRANS, succ, bodyAsString.ToString()); string postState = invariantDB(this.To.Block.First); if (parent.Condition != null) // Is there a condition on the rewriting rule? { result = String.Format("{0} | {1} -> 1", result, parent.Condition); if (postState != null && postState.Length > 0) { result += string.Format(", {0}", postState); } } else if (postState != null && postState.Length > 0) { result = String.Format("{0} | {1}", result, postState); } result = BenigniMain.SanitizeString(result); // Here we output the equation where.WriteLine(result); } } #region Expression visitors /// <summary> /// The crawler used by Benigni to find which variables are used in a block /// </summary> public class BenigniVariableCrawler { class Decoder<Label, Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Attribute, Assembly> : IVisitValueExprIL<ExternalExpression<Label, SymbolicValue>, Type, ExternalExpression<Label, SymbolicValue>, SymbolicValue, Set<string>, Set<string>> where SymbolicValue : IEquatable<SymbolicValue> where Type : IEquatable<Type> { IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<Label, SymbolicValue>, SymbolicValue> decoder; IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder; public Decoder( IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<Label, SymbolicValue>, SymbolicValue> decoder, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder ) { this.decoder = decoder; this.mdDecoder = mdDecoder; } public Set<string> Variables(ExternalExpression<Label, SymbolicValue> expr) { Set<string> emptySet = new Set<string>(); return Recurse(emptySet, expr); } #region IVisitExprIL<Label,Type,ExternalExpression,SymbolicValue,StringBuilder,Unit> Members Set<string> Recurse(Set<string> input, ExternalExpression<Label, SymbolicValue> expr) { return decoder.ExpressionContext.Decode<Set<string>, Set<string>, Decoder<Label, Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Attribute, Assembly>>(expr, this, input); } public Set<string> Binary(ExternalExpression<Label, SymbolicValue> pc, BinaryOperator op, SymbolicValue dest, ExternalExpression<Label, SymbolicValue> s1, ExternalExpression<Label, SymbolicValue> s2, Set<string> data) { data = Recurse(data, s1); data = Recurse(data, s2); return data; } public Set<string> Isinst(ExternalExpression<Label, SymbolicValue> pc, Type type, SymbolicValue dest, ExternalExpression<Label, SymbolicValue> obj, Set<string> data) { return Recurse(data, obj); } public Set<string> Ldconst(ExternalExpression<Label, SymbolicValue> pc, object constant, Type type, SymbolicValue dest, Set<string> data) { return data; } public Set<string> Ldnull(ExternalExpression<Label, SymbolicValue> pc, SymbolicValue dest, Set<string> data) { return data; } public Set<string> Sizeof(ExternalExpression<Label, SymbolicValue> pc, Type type, SymbolicValue dest, Set<string> data) { return data; } public Set<string> Unary(ExternalExpression<Label, SymbolicValue> pc, UnaryOperator op, bool overflow, bool unsigned, SymbolicValue dest, ExternalExpression<Label, SymbolicValue> source, Set<string> data) { return Recurse(data, source); } public Set<string> SymbolicConstant(ExternalExpression<Label, SymbolicValue> pc, SymbolicValue symbol, Set<string> data) { data.Add(symbol.ToString()); return data; } #endregion } public static Converter<ExternalExpression<Label, SymbolicValue>, Set<string>> Crawler<Label, Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, SymbolicValue>( IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<Label, SymbolicValue>, SymbolicValue> decoder, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder) where SymbolicValue : IEquatable<SymbolicValue> where Type : IEquatable<Type> { Decoder<Label, Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Attribute, Assembly> expr = new Decoder<Label, Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Attribute, Assembly>(decoder, mdDecoder); return expr.Variables; } } /// <summary> /// The printer for expressions used by Benigni /// </summary> public class BenigniExprPrinter { class Decoder<Label, Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Attribute, Assembly> : IVisitValueExprIL<ExternalExpression<Label, SymbolicValue>, Type, ExternalExpression<Label, SymbolicValue>, SymbolicValue, StringBuilder, Unit> where SymbolicValue : IEquatable<SymbolicValue> where Type : IEquatable<Type> { IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<Label, SymbolicValue>, SymbolicValue> decoder; IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder; public Decoder( IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<Label, SymbolicValue>, SymbolicValue> decoder, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder ) { this.decoder = decoder; this.mdDecoder = mdDecoder; } public string ToString(ExternalExpression<Label, SymbolicValue> expr) { StringBuilder sb = new StringBuilder(); Recurse(sb, expr); return sb.ToString(); } #region IVisitExprIL<Label,Type,ExternalExpression,SymbolicValue,StringBuilder,Unit> Members void Recurse(StringBuilder tw, ExternalExpression<Label, SymbolicValue> expr) { decoder.ExpressionContext.Decode<StringBuilder, Unit, Decoder<Label, Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Attribute, Assembly>>(expr, this, tw); } public Unit Binary(ExternalExpression<Label, SymbolicValue> pc, BinaryOperator op, SymbolicValue dest, ExternalExpression<Label, SymbolicValue> s1, ExternalExpression<Label, SymbolicValue> s2, StringBuilder data) { data.Append(op.ToString()); data.Append('('); Recurse(data, s1); data.Append(", "); Recurse(data, s2); data.Append(')'); return Unit.Value; } public Unit Isinst(ExternalExpression<Label, SymbolicValue> pc, Type type, SymbolicValue dest, ExternalExpression<Label, SymbolicValue> obj, StringBuilder data) { data.AppendFormat("IsInst({0}) ", mdDecoder.FullName(type)); Recurse(data, obj); return Unit.Value; } public Unit Ldconst(ExternalExpression<Label, SymbolicValue> pc, object constant, Type type, SymbolicValue dest, StringBuilder data) { data.Append(constant.ToString()); return Unit.Value; } public Unit Ldnull(ExternalExpression<Label, SymbolicValue> pc, SymbolicValue dest, StringBuilder data) { data.Append("null"); return Unit.Value; } public Unit Sizeof(ExternalExpression<Label, SymbolicValue> pc, Type type, SymbolicValue dest, StringBuilder data) { data.AppendFormat("sizeof({0})", mdDecoder.FullName(type)); return Unit.Value; } public Unit Unary(ExternalExpression<Label, SymbolicValue> pc, UnaryOperator op, bool overflow, bool unsigned, SymbolicValue dest, ExternalExpression<Label, SymbolicValue> source, StringBuilder data) { data.AppendFormat("{0}(", op.ToString()); Recurse(data, source); data.AppendFormat(")"); return Unit.Value; } public Unit SymbolicConstant(ExternalExpression<Label, SymbolicValue> pc, SymbolicValue symbol, StringBuilder data) { data.Append(symbol.ToString()); return Unit.Value; } #endregion } public static Converter<ExternalExpression<Label, SymbolicValue>, string> Printer<Label, Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, SymbolicValue>( IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<Label, SymbolicValue>, SymbolicValue> decoder, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder) where SymbolicValue : IEquatable<SymbolicValue> where Type : IEquatable<Type> { var exprPrinter = new Decoder<Label, Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Attribute, Assembly>(decoder, mdDecoder); return exprPrinter.ToString; } } #endregion #region Instruction visitor public static class BenigniConditionCrawler { public static AssumptionFinder<Label> Create<Label, Local, Parameter, Method, Field, Property, Event, Type, Source, Dest, Context, Attribute, Assembly, EdgeData>( IDecodeMSIL<Label, Local, Parameter, Method, Field, Type, Source, Dest, Context, EdgeData> ilDecoder, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, Converter<Source, string> sourceName, Converter<Dest, string> destName ) { return new SearchAssumptions<Label, Local, Parameter, Method, Field, Property, Event, Type, Source, Dest, Context, Attribute, Assembly, EdgeData>(ilDecoder, mdDecoder, sourceName, destName).SearchAssumptionAt; } private class SearchAssumptions<Label, Local, Parameter, Method, Field, Property, Event, Type, Source, Dest, Context, Attribute, Assembly, EdgeData> : IVisitMSIL<Label, Local, Parameter, Method, Field, Type, Source, Dest, string, string> { IDecodeMSIL<Label, Local, Parameter, Method, Field, Type, Source, Dest, Context, EdgeData> ilDecoder; IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder; Converter<Source, string> sourceName; Converter<Dest, string> destName; public SearchAssumptions( IDecodeMSIL<Label, Local, Parameter, Method, Field, Type, Source, Dest, Context, EdgeData> ilDecoder, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, Converter<Source, string> sourceName, Converter<Dest, string> destName ) { this.ilDecoder = ilDecoder; this.mdDecoder = mdDecoder; this.sourceName = sourceName; this.destName = destName; } public string SearchAssumptionAt(Label label) { return ilDecoder.ForwardDecode<string, string, SearchAssumptions<Label, Local, Parameter, Method, Field, Property, Event, Type, Source, Dest, Context, Attribute, Assembly, EdgeData>>(label, this, null); } #region IVisitMSIL<Label,Local,Parameter,Method,Field,Type,Source,Dest,string,string> Members private string/*?*/ SourceName(Source src) { if (sourceName != null) { return sourceName(src); } return null; } private string/*?*/ DestName(Dest dest) { if (destName != null) { return destName(dest); } return null; } public string Binary(Label pc, BinaryOperator op, Dest dest, Source s1, Source s2, string data) { return data; } public string Assert(Label pc, string tag, Source s, string data) { // tw.WriteLine("{0}assert({1}) {2}", prefix, tag, SourceName(s)); return data; } public string Assume(Label pc, string tag, Source s, string data) { // tw.WriteLine("{0}assume({1}) {2}", prefix, tag, SourceName(s)); if (data != null) return null; else if (tag.Equals("true")) return SourceName(s); else return "not(" + SourceName(s) + ")"; } public string Arglist(Label pc, Dest d, string data) { return data; } public string BranchCond(Label pc, Label target, BranchOperator bop, Source value1, Source value2, string data) { return data; } public string BranchTrue(Label pc, Label target, Source cond, string data) { return data; } public string BranchFalse(Label pc, Label target, Source cond, string data) { return data; } public string Branch(Label pc, Label target, bool leave, string data) { return data; } public string Break(Label pc, string data) { return data; } public string Call<TypeList, ArgList>(Label pc, Method method, bool tail, bool virt, TypeList extraVarargs, Dest dest, ArgList args, string data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { return data; } public string Calli<TypeList, ArgList>(Label pc, Type returnType, TypeList argTypes, bool tail, bool isInstance, Dest dest, Source fp, ArgList args, string data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { return data; } public string Ckfinite(Label pc, Dest dest, Source source, string data) { return data; } public string Unary(Label pc, UnaryOperator op, bool ovf, bool unsigned, Dest dest, Source source, string data) { return data; } public string Cpblk(Label pc, bool @volatile, Source destaddr, Source srcaddr, Source len, string data) { return data; } public string Endfilter(Label pc, Source condition, string data) { return data; } public string Endfinally(Label pc, string data) { return data; } public string Entry(Label pc, Method method, string data) { return data; } public string Initblk(Label pc, bool @volatile, Source destaddr, Source value, Source len, string data) { return data; } public string Jmp(Label pc, Method method, string data) { return data; } public string Ldarg(Label pc, Parameter argument, bool isOld, Dest dest, string data) { return data; } public string Ldarga(Label pc, Parameter argument, bool isOld, Dest dest, string data) { return data; } public string Ldconst(Label pc, object constant, Type type, Dest dest, string data) { return data; } public string Ldnull(Label pc, Dest dest, string data) { return data; } public string Ldftn(Label pc, Method method, Dest dest, string data) { return data; } public string Ldind(Label pc, Type type, bool @volatile, Dest dest, Source ptr, string data) { return data; } public string Ldloc(Label pc, Local local, Dest dest, string data) { return data; } public string Ldloca(Label pc, Local local, Dest dest, string data) { return data; } public string Ldresult(Label pc, Type type, Dest dest, Source source, string data) { return data; } public string Ldstack(Label pc, int offset, Dest dest, Source s, bool isOld, string data) { return data; } public string Ldstacka(Label pc, int offset, Dest dest, Source s, Type type, bool isOld, string data) { return data; } public string Localloc(Label pc, Dest dest, Source size, string data) { return data; } public string Nop(Label pc, string data) { return data; } public string Pop(Label pc, Source source, string data) { return data; } public string Return(Label pc, Source source, string data) { return data; } public string Starg(Label pc, Parameter argument, Source source, string data) { return data; } public string Stind(Label pc, Type type, bool @volatile, Source ptr, Source value, string data) { return data; } public string Stloc(Label pc, Local local, Source value, string data) { return data; } public string Switch(Label pc, Type type, IEnumerable<Pair<object, Label>> cases, Source value, string data) { return data; } public string Box(Label pc, Type type, Dest dest, Source source, string data) { return data; } public string ConstrainedCallvirt<TypeList, ArgList>(Label pc, Method method, bool tail, Type constraint, TypeList extraVarargs, Dest dest, ArgList args, string data) where TypeList : IIndexable<Type> where ArgList : IIndexable<Source> { return data; } public string Castclass(Label pc, Type type, Dest dest, Source source, string data) { return data; } public string Cpobj(Label pc, Type type, Source destptr, Source srcptr, string data) { return data; } public string Initobj(Label pc, Type type, Source ptr, string data) { return data; } public string Isinst(Label pc, Type type, Dest dest, Source source, string data) { return data; } public string Ldelem(Label pc, Type type, Dest dest, Source array, Source index, string data) { return data; } public string Ldelema(Label pc, Type type, bool @readonly, Dest dest, Source array, Source index, string data) { return data; } public string Ldfld(Label pc, Field field, bool @volatile, Dest dest, Source ptr, string data) { return data; } public string Ldflda(Label pc, Field field, Dest dest, Source ptr, string data) { return data; } public string Ldlen(Label pc, Dest dest, Source array, string data) { return data; } public string Ldsfld(Label pc, Field field, bool @volatile, Dest dest, string data) { return data; } public string Ldsflda(Label pc, Field field, Dest dest, string data) { return data; } public string Ldtypetoken(Label pc, Type type, Dest dest, string data) { return data; } public string Ldfieldtoken(Label pc, Field field, Dest dest, string data) { return data; } public string Ldmethodtoken(Label pc, Method method, Dest dest, string data) { return data; } public string Ldvirtftn(Label pc, Method method, Dest dest, Source obj, string data) { return data; } public string Mkrefany(Label pc, Type type, Dest dest, Source value, string data) { return data; } public string Newarray<ArgList>(Label pc, Type type, Dest dest, ArgList lengths, string data) where ArgList : IIndexable<Source> { return data; } public string Newobj<ArgList>(Label pc, Method ctor, Dest dest, ArgList args, string data) where ArgList : IIndexable<Source> { return data; } public string Refanytype(Label pc, Dest dest, Source source, string data) { return data; } public string Refanyval(Label pc, Type type, Dest dest, Source source, string data) { return data; } public string Rethrow(Label pc, string data) { return data; } public string Sizeof(Label pc, Type type, Dest dest, string data) { return data; } public string Stelem(Label pc, Type type, Source array, Source index, Source value, string data) { return data; } public string Stfld(Label pc, Field field, bool @volatile, Source ptr, Source value, string data) { return data; } public string Stsfld(Label pc, Field field, bool @volatile, Source value, string data) { return data; } public string Throw(Label pc, Source value, string data) { return data; } public string Unbox(Label pc, Type type, Dest dest, Source source, string data) { return data; } public string Unboxany(Label pc, Type type, Dest dest, Source source, string data) { return data; } #endregion #region IVisitSynthIL<Label,Method,Source,Dest,TextWriter,Unit> Members public string BeginOld(Label pc, Label matchingEnd, string data) { return data; } public string EndOld(Label pc, Label matchingBegin, Type type, Dest dest, Source source, string data) { return data; } #endregion } } #endregion } #endif
namespace AngleSharp.Css { using AngleSharp.Css.Declarations; using System; using System.Collections.Generic; /// <summary> /// The default implementation for CSS declaration factory. /// </summary> public class DefaultDeclarationFactory : IDeclarationFactory { private readonly Dictionary<String, DeclarationInfo> _declarations = new Dictionary<String, DeclarationInfo>(StringComparer.OrdinalIgnoreCase) { { BookmarkLabelDeclaration.Name, new DeclarationInfo( name: BookmarkLabelDeclaration.Name, converter: BookmarkLabelDeclaration.Converter, initialValue: BookmarkLabelDeclaration.InitialValue, flags: BookmarkLabelDeclaration.Flags) }, { BookmarkLevelDeclaration.Name, new DeclarationInfo( name: BookmarkLevelDeclaration.Name, converter: BookmarkLevelDeclaration.Converter, initialValue: BookmarkLevelDeclaration.InitialValue, flags: BookmarkLevelDeclaration.Flags) }, { BookmarkStateDeclaration.Name, new DeclarationInfo( name: BookmarkStateDeclaration.Name, converter: BookmarkStateDeclaration.Converter, initialValue: BookmarkStateDeclaration.InitialValue, flags: BookmarkStateDeclaration.Flags) }, { FootnoteDisplayDeclaration.Name, new DeclarationInfo( name: FootnoteDisplayDeclaration.Name, converter: FootnoteDisplayDeclaration.Converter, initialValue: FootnoteDisplayDeclaration.InitialValue, flags: FootnoteDisplayDeclaration.Flags) }, { FootnotePolicyDeclaration.Name, new DeclarationInfo( name: FootnotePolicyDeclaration.Name, converter: FootnotePolicyDeclaration.Converter, initialValue: FootnotePolicyDeclaration.InitialValue, flags: FootnotePolicyDeclaration.Flags) }, { RunningDeclaration.Name, new DeclarationInfo( name: RunningDeclaration.Name, converter: RunningDeclaration.Converter, initialValue: RunningDeclaration.InitialValue, flags: RunningDeclaration.Flags) }, { StringSetDeclaration.Name, new DeclarationInfo( name: StringSetDeclaration.Name, converter: StringSetDeclaration.Converter, initialValue: StringSetDeclaration.InitialValue, flags: StringSetDeclaration.Flags) }, { CaptionSideDeclaration.Name, new DeclarationInfo( name: CaptionSideDeclaration.Name, converter: CaptionSideDeclaration.Converter, initialValue: CaptionSideDeclaration.InitialValue, flags: CaptionSideDeclaration.Flags) }, { CursorDeclaration.Name, new DeclarationInfo( name: CursorDeclaration.Name, converter: CursorDeclaration.Converter, initialValue: CursorDeclaration.InitialValue, flags: CursorDeclaration.Flags) }, { EmptyCellsDeclaration.Name, new DeclarationInfo( name: EmptyCellsDeclaration.Name, converter: EmptyCellsDeclaration.Converter, initialValue: EmptyCellsDeclaration.InitialValue, flags: EmptyCellsDeclaration.Flags) }, { OrphansDeclaration.Name, new DeclarationInfo( name: OrphansDeclaration.Name, converter: OrphansDeclaration.Converter, initialValue: OrphansDeclaration.InitialValue, flags: OrphansDeclaration.Flags) }, { QuotesDeclaration.Name, new DeclarationInfo( name: QuotesDeclaration.Name, converter: QuotesDeclaration.Converter, initialValue: QuotesDeclaration.InitialValue, flags: QuotesDeclaration.Flags) }, { TableLayoutDeclaration.Name, new DeclarationInfo( name: TableLayoutDeclaration.Name, converter: TableLayoutDeclaration.Converter, initialValue: TableLayoutDeclaration.InitialValue, flags: TableLayoutDeclaration.Flags) }, { UnicodeBidiDeclaration.Name, new DeclarationInfo( name: UnicodeBidiDeclaration.Name, converter: UnicodeBidiDeclaration.Converter, initialValue: UnicodeBidiDeclaration.InitialValue, flags: UnicodeBidiDeclaration.Flags) }, { WidowsDeclaration.Name, new DeclarationInfo( name: WidowsDeclaration.Name, converter: WidowsDeclaration.Converter, initialValue: WidowsDeclaration.InitialValue, flags: WidowsDeclaration.Flags) }, { ContentDeclaration.Name, new DeclarationInfo( name: ContentDeclaration.Name, converter: ContentDeclaration.Converter, initialValue: ContentDeclaration.InitialValue, flags: ContentDeclaration.Flags) }, { ContentVisibilityDeclaration.Name, new DeclarationInfo( name: ContentVisibilityDeclaration.Name, converter: ContentVisibilityDeclaration.Converter, initialValue: ContentVisibilityDeclaration.InitialValue, flags: ContentVisibilityDeclaration.Flags) }, { BoxDecorationBreakDeclaration.Name, new DeclarationInfo( name: BoxDecorationBreakDeclaration.Name, converter: BoxDecorationBreakDeclaration.Converter, initialValue: BoxDecorationBreakDeclaration.InitialValue, flags: BoxDecorationBreakDeclaration.Flags) }, { BoxShadowDeclaration.Name, new DeclarationInfo( name: BoxShadowDeclaration.Name, converter: BoxShadowDeclaration.Converter, initialValue: BoxShadowDeclaration.InitialValue, flags: BoxShadowDeclaration.Flags) }, { BoxSizingDeclaration.Name, new DeclarationInfo( name: BoxSizingDeclaration.Name, converter: BoxSizingDeclaration.Converter, initialValue: BoxSizingDeclaration.InitialValue, flags: BoxSizingDeclaration.Flags) }, { ClearDeclaration.Name, new DeclarationInfo( name: ClearDeclaration.Name, converter: ClearDeclaration.Converter, initialValue: ClearDeclaration.InitialValue, flags: ClearDeclaration.Flags) }, { DisplayDeclaration.Name, new DeclarationInfo( name: DisplayDeclaration.Name, converter: DisplayDeclaration.Converter, initialValue: DisplayDeclaration.InitialValue, flags: DisplayDeclaration.Flags) }, { FloatDeclaration.Name, new DeclarationInfo( name: FloatDeclaration.Name, converter: FloatDeclaration.Converter, initialValue: FloatDeclaration.InitialValue, flags: FloatDeclaration.Flags) }, { OverflowDeclaration.Name, new DeclarationInfo( name: OverflowDeclaration.Name, converter: OverflowDeclaration.Converter, initialValue: OverflowDeclaration.InitialValue, flags: OverflowDeclaration.Flags) }, { OverflowXDeclaration.Name, new DeclarationInfo( name: OverflowXDeclaration.Name, converter: OverflowXDeclaration.Converter, initialValue: OverflowXDeclaration.InitialValue, flags: OverflowXDeclaration.Flags) }, { OverflowYDeclaration.Name, new DeclarationInfo( name: OverflowYDeclaration.Name, converter: OverflowYDeclaration.Converter, initialValue: OverflowYDeclaration.InitialValue, flags: OverflowYDeclaration.Flags) }, { PositionDeclaration.Name, new DeclarationInfo( name: PositionDeclaration.Name, converter: PositionDeclaration.Converter, initialValue: PositionDeclaration.InitialValue, flags: PositionDeclaration.Flags) }, { ZIndexDeclaration.Name, new DeclarationInfo( name: ZIndexDeclaration.Name, converter: ZIndexDeclaration.Converter, initialValue: ZIndexDeclaration.InitialValue, flags: ZIndexDeclaration.Flags) }, { CounterResetDeclaration.Name, new DeclarationInfo( name: CounterResetDeclaration.Name, converter: CounterResetDeclaration.Converter, initialValue: CounterResetDeclaration.InitialValue, flags: CounterResetDeclaration.Flags) }, { CounterIncrementDeclaration.Name, new DeclarationInfo( name: CounterIncrementDeclaration.Name, converter: CounterIncrementDeclaration.Converter, initialValue: CounterIncrementDeclaration.InitialValue, flags: CounterIncrementDeclaration.Flags) }, { ObjectFitDeclaration.Name, new DeclarationInfo( name: ObjectFitDeclaration.Name, converter: ObjectFitDeclaration.Converter, initialValue: ObjectFitDeclaration.InitialValue, flags: ObjectFitDeclaration.Flags) }, { ObjectPositionDeclaration.Name, new DeclarationInfo( name: ObjectPositionDeclaration.Name, converter: ObjectPositionDeclaration.Converter, initialValue: ObjectPositionDeclaration.InitialValue, flags: ObjectPositionDeclaration.Flags) }, { StrokeDasharrayDeclaration.Name, new DeclarationInfo( name: StrokeDasharrayDeclaration.Name, converter: StrokeDasharrayDeclaration.Converter, initialValue: StrokeDasharrayDeclaration.InitialValue, flags: StrokeDasharrayDeclaration.Flags) }, { StrokeDashoffsetDeclaration.Name, new DeclarationInfo( name: StrokeDashoffsetDeclaration.Name, converter: StrokeDashoffsetDeclaration.Converter, initialValue: StrokeDashoffsetDeclaration.InitialValue, flags: StrokeDashoffsetDeclaration.Flags) }, { StrokeLinecapDeclaration.Name, new DeclarationInfo( name: StrokeLinecapDeclaration.Name, converter: StrokeLinecapDeclaration.Converter, initialValue: StrokeLinecapDeclaration.InitialValue, flags: StrokeLinecapDeclaration.Flags) }, { StrokeLinejoinDeclaration.Name, new DeclarationInfo( name: StrokeLinejoinDeclaration.Name, converter: StrokeLinejoinDeclaration.Converter, initialValue: StrokeLinejoinDeclaration.InitialValue, flags: StrokeLinejoinDeclaration.Flags) }, { StrokeMiterlimitDeclaration.Name, new DeclarationInfo( name: StrokeMiterlimitDeclaration.Name, converter: StrokeMiterlimitDeclaration.Converter, initialValue: StrokeMiterlimitDeclaration.InitialValue, flags: StrokeMiterlimitDeclaration.Flags) }, { StrokeOpacityDeclaration.Name, new DeclarationInfo( name: StrokeOpacityDeclaration.Name, converter: StrokeOpacityDeclaration.Converter, initialValue: StrokeOpacityDeclaration.InitialValue, flags: StrokeOpacityDeclaration.Flags) }, { StrokeDeclaration.Name, new DeclarationInfo( name: StrokeDeclaration.Name, converter: StrokeDeclaration.Converter, initialValue: StrokeDeclaration.InitialValue, flags: StrokeDeclaration.Flags) }, { StrokeWidthDeclaration.Name, new DeclarationInfo( name: StrokeWidthDeclaration.Name, converter: StrokeWidthDeclaration.Converter, initialValue: StrokeWidthDeclaration.InitialValue, flags: StrokeWidthDeclaration.Flags) }, { DirectionDeclaration.Name, new DeclarationInfo( name: DirectionDeclaration.Name, converter: DirectionDeclaration.Converter, initialValue: DirectionDeclaration.InitialValue, flags: DirectionDeclaration.Flags) }, { OverflowWrapDeclaration.Name, new DeclarationInfo( name: OverflowWrapDeclaration.Name, converter: OverflowWrapDeclaration.Converter, initialValue: OverflowWrapDeclaration.InitialValue, flags: OverflowWrapDeclaration.Flags) }, { WordWrapDeclaration.Name, new DeclarationInfo( name: WordWrapDeclaration.Name, converter: WordWrapDeclaration.Converter, initialValue: WordWrapDeclaration.InitialValue, flags: WordWrapDeclaration.Flags) }, { PerspectiveOriginDeclaration.Name, new DeclarationInfo( name: PerspectiveOriginDeclaration.Name, converter: PerspectiveOriginDeclaration.Converter, initialValue: PerspectiveOriginDeclaration.InitialValue, flags: PerspectiveOriginDeclaration.Flags) }, { PerspectiveDeclaration.Name, new DeclarationInfo( name: PerspectiveDeclaration.Name, converter: PerspectiveDeclaration.Converter, initialValue: PerspectiveDeclaration.InitialValue, flags: PerspectiveDeclaration.Flags) }, { BackfaceVisibilityDeclaration.Name, new DeclarationInfo( name: BackfaceVisibilityDeclaration.Name, converter: BackfaceVisibilityDeclaration.Converter, initialValue: BackfaceVisibilityDeclaration.InitialValue, flags: BackfaceVisibilityDeclaration.Flags) }, { ClipDeclaration.Name, new DeclarationInfo( name: ClipDeclaration.Name, converter: ClipDeclaration.Converter, initialValue: ClipDeclaration.InitialValue, flags: ClipDeclaration.Flags) }, { OpacityDeclaration.Name, new DeclarationInfo( name: OpacityDeclaration.Name, converter: OpacityDeclaration.Converter, initialValue: OpacityDeclaration.InitialValue, flags: OpacityDeclaration.Flags) }, { VisibilityDeclaration.Name, new DeclarationInfo( name: VisibilityDeclaration.Name, converter: VisibilityDeclaration.Converter, initialValue: VisibilityDeclaration.InitialValue, flags: VisibilityDeclaration.Flags) }, { BottomDeclaration.Name, new DeclarationInfo( name: BottomDeclaration.Name, converter: BottomDeclaration.Converter, initialValue: BottomDeclaration.InitialValue, flags: BottomDeclaration.Flags) }, { HeightDeclaration.Name, new DeclarationInfo( name: HeightDeclaration.Name, converter: HeightDeclaration.Converter, initialValue: HeightDeclaration.InitialValue, flags: HeightDeclaration.Flags) }, { LeftDeclaration.Name, new DeclarationInfo( name: LeftDeclaration.Name, converter: LeftDeclaration.Converter, initialValue: LeftDeclaration.InitialValue, flags: LeftDeclaration.Flags) }, { MaxHeightDeclaration.Name, new DeclarationInfo( name: MaxHeightDeclaration.Name, converter: MaxHeightDeclaration.Converter, initialValue: MaxHeightDeclaration.InitialValue, flags: MaxHeightDeclaration.Flags) }, { MaxWidthDeclaration.Name, new DeclarationInfo( name: MaxWidthDeclaration.Name, converter: MaxWidthDeclaration.Converter, initialValue: MaxWidthDeclaration.InitialValue, flags: MaxWidthDeclaration.Flags) }, { MinHeightDeclaration.Name, new DeclarationInfo( name: MinHeightDeclaration.Name, converter: MinHeightDeclaration.Converter, initialValue: MinHeightDeclaration.InitialValue, flags: MinHeightDeclaration.Flags) }, { MinWidthDeclaration.Name, new DeclarationInfo( name: MinWidthDeclaration.Name, converter: MinWidthDeclaration.Converter, initialValue: MinWidthDeclaration.InitialValue, flags: MinWidthDeclaration.Flags) }, { RightDeclaration.Name, new DeclarationInfo( name: RightDeclaration.Name, converter: RightDeclaration.Converter, initialValue: RightDeclaration.InitialValue, flags: RightDeclaration.Flags) }, { TopDeclaration.Name, new DeclarationInfo( name: TopDeclaration.Name, converter: TopDeclaration.Converter, initialValue: TopDeclaration.InitialValue, flags: TopDeclaration.Flags) }, { WidthDeclaration.Name, new DeclarationInfo( name: WidthDeclaration.Name, converter: WidthDeclaration.Converter, initialValue: WidthDeclaration.InitialValue, flags: WidthDeclaration.Flags) }, { ColorDeclaration.Name, new DeclarationInfo( name: ColorDeclaration.Name, converter: ColorDeclaration.Converter, initialValue: ColorDeclaration.InitialValue, flags: ColorDeclaration.Flags) }, { WordSpacingDeclaration.Name, new DeclarationInfo( name: WordSpacingDeclaration.Name, converter: WordSpacingDeclaration.Converter, initialValue: WordSpacingDeclaration.InitialValue, flags: WordSpacingDeclaration.Flags) }, { LineHeightDeclaration.Name, new DeclarationInfo( name: LineHeightDeclaration.Name, converter: LineHeightDeclaration.Converter, initialValue: LineHeightDeclaration.InitialValue, flags: LineHeightDeclaration.Flags, shorthands: LineHeightDeclaration.Shorthands) }, { LetterSpacingDeclaration.Name, new DeclarationInfo( name: LetterSpacingDeclaration.Name, converter: LetterSpacingDeclaration.Converter, initialValue: LetterSpacingDeclaration.InitialValue, flags: LetterSpacingDeclaration.Flags) }, { FontSizeAdjustDeclaration.Name, new DeclarationInfo( name: FontSizeAdjustDeclaration.Name, converter: FontSizeAdjustDeclaration.Converter, initialValue: FontSizeAdjustDeclaration.InitialValue, flags: FontSizeAdjustDeclaration.Flags) }, { BreakAfterDeclaration.Name, new DeclarationInfo( name: BreakAfterDeclaration.Name, converter: BreakAfterDeclaration.Converter, initialValue: BreakAfterDeclaration.InitialValue, flags: BreakAfterDeclaration.Flags) }, { BreakBeforeDeclaration.Name, new DeclarationInfo( name: BreakBeforeDeclaration.Name, converter: BreakBeforeDeclaration.Converter, initialValue: BreakBeforeDeclaration.InitialValue, flags: BreakBeforeDeclaration.Flags) }, { BreakInsideDeclaration.Name, new DeclarationInfo( name: BreakInsideDeclaration.Name, converter: BreakInsideDeclaration.Converter, initialValue: BreakInsideDeclaration.InitialValue, flags: BreakInsideDeclaration.Flags) }, { PageBreakAfterDeclaration.Name, new DeclarationInfo( name: PageBreakAfterDeclaration.Name, converter: PageBreakAfterDeclaration.Converter, initialValue: PageBreakAfterDeclaration.InitialValue, flags: PageBreakAfterDeclaration.Flags) }, { PageBreakBeforeDeclaration.Name, new DeclarationInfo( name: PageBreakBeforeDeclaration.Name, converter: PageBreakBeforeDeclaration.Converter, initialValue: PageBreakBeforeDeclaration.InitialValue, flags: PageBreakBeforeDeclaration.Flags) }, { PageBreakInsideDeclaration.Name, new DeclarationInfo( name: PageBreakInsideDeclaration.Name, converter: PageBreakInsideDeclaration.Converter, initialValue: PageBreakInsideDeclaration.InitialValue, flags: PageBreakInsideDeclaration.Flags) }, { TransformOriginDeclaration.Name, new DeclarationInfo( name: TransformOriginDeclaration.Name, converter: TransformOriginDeclaration.Converter, initialValue: TransformOriginDeclaration.InitialValue, flags: TransformOriginDeclaration.Flags) }, { TransformDeclaration.Name, new DeclarationInfo( name: TransformDeclaration.Name, converter: TransformDeclaration.Converter, initialValue: TransformDeclaration.InitialValue, flags: TransformDeclaration.Flags) }, { TransformStyleDeclaration.Name, new DeclarationInfo( name: TransformStyleDeclaration.Name, converter: TransformStyleDeclaration.Converter, initialValue: TransformStyleDeclaration.InitialValue, flags: TransformStyleDeclaration.Flags) }, { ColumnCountDeclaration.Name, new DeclarationInfo( name: ColumnCountDeclaration.Name, converter: ColumnCountDeclaration.Converter, initialValue: ColumnCountDeclaration.InitialValue, flags: ColumnCountDeclaration.Flags, shorthands: ColumnCountDeclaration.Shorthands) }, { ColumnFillDeclaration.Name, new DeclarationInfo( name: ColumnFillDeclaration.Name, converter: ColumnFillDeclaration.Converter, initialValue: ColumnFillDeclaration.InitialValue, flags: ColumnFillDeclaration.Flags) }, { ColumnGapDeclaration.Name, new DeclarationInfo( name: ColumnGapDeclaration.Name, converter: ColumnGapDeclaration.Converter, initialValue: ColumnGapDeclaration.InitialValue, shorthands: ColumnGapDeclaration.Shorthands, flags: ColumnGapDeclaration.Flags) }, { RowGapDeclaration.Name, new DeclarationInfo( name: RowGapDeclaration.Name, converter: RowGapDeclaration.Converter, initialValue: RowGapDeclaration.InitialValue, shorthands: RowGapDeclaration.Shorthands, flags: RowGapDeclaration.Flags) }, { GapDeclaration.Name, new DeclarationInfo( name: GapDeclaration.Name, converter: GapDeclaration.Converter, initialValue: GapDeclaration.InitialValue, longhands: GapDeclaration.Longhands, flags: GapDeclaration.Flags) }, { ColumnSpanDeclaration.Name, new DeclarationInfo( name: ColumnSpanDeclaration.Name, converter: ColumnSpanDeclaration.Converter, initialValue: ColumnSpanDeclaration.InitialValue, flags: ColumnSpanDeclaration.Flags) }, { ColumnWidthDeclaration.Name, new DeclarationInfo( name: ColumnWidthDeclaration.Name, converter: ColumnWidthDeclaration.Converter, initialValue: ColumnWidthDeclaration.InitialValue, flags: ColumnWidthDeclaration.Flags, shorthands: ColumnWidthDeclaration.Shorthands) }, { BorderCollapseDeclaration.Name, new DeclarationInfo( name: BorderCollapseDeclaration.Name, converter: BorderCollapseDeclaration.Converter, initialValue: BorderCollapseDeclaration.InitialValue, flags: BorderCollapseDeclaration.Flags) }, { BorderSpacingDeclaration.Name, new DeclarationInfo( name: BorderSpacingDeclaration.Name, converter: BorderSpacingDeclaration.Converter, initialValue: BorderSpacingDeclaration.InitialValue, flags: BorderSpacingDeclaration.Flags) }, { WordBreakDeclaration.Name, new DeclarationInfo( name: WordBreakDeclaration.Name, converter: WordBreakDeclaration.Converter, initialValue: WordBreakDeclaration.InitialValue, flags: WordBreakDeclaration.Flags) }, { WhiteSpaceDeclaration.Name, new DeclarationInfo( name: WhiteSpaceDeclaration.Name, converter: WhiteSpaceDeclaration.Converter, initialValue: WhiteSpaceDeclaration.InitialValue, flags: WhiteSpaceDeclaration.Flags) }, { VerticalAlignDeclaration.Name, new DeclarationInfo( name: VerticalAlignDeclaration.Name, converter: VerticalAlignDeclaration.Converter, initialValue: VerticalAlignDeclaration.InitialValue, flags: VerticalAlignDeclaration.Flags) }, { TextShadowDeclaration.Name, new DeclarationInfo( name: TextShadowDeclaration.Name, converter: TextShadowDeclaration.Converter, initialValue: TextShadowDeclaration.InitialValue, flags: TextShadowDeclaration.Flags) }, { TextJustifyDeclaration.Name, new DeclarationInfo( name: TextJustifyDeclaration.Name, converter: TextJustifyDeclaration.Converter, initialValue: TextJustifyDeclaration.InitialValue, flags: TextJustifyDeclaration.Flags) }, { TextIndentDeclaration.Name, new DeclarationInfo( name: TextIndentDeclaration.Name, converter: TextIndentDeclaration.Converter, initialValue: TextIndentDeclaration.InitialValue, flags: TextIndentDeclaration.Flags) }, { TextAnchorDeclaration.Name, new DeclarationInfo( name: TextAnchorDeclaration.Name, converter: TextAnchorDeclaration.Converter, initialValue: TextAnchorDeclaration.InitialValue, flags: TextAnchorDeclaration.Flags) }, { TextAlignDeclaration.Name, new DeclarationInfo( name: TextAlignDeclaration.Name, converter: TextAlignDeclaration.Converter, initialValue: TextAlignDeclaration.InitialValue, flags: TextAlignDeclaration.Flags) }, { TextAlignLastDeclaration.Name, new DeclarationInfo( name: TextAlignLastDeclaration.Name, converter: TextAlignLastDeclaration.Converter, initialValue: TextAlignLastDeclaration.InitialValue, flags: TextAlignLastDeclaration.Flags) }, { TextTransformDeclaration.Name, new DeclarationInfo( name: TextTransformDeclaration.Name, converter: TextTransformDeclaration.Converter, initialValue: TextTransformDeclaration.InitialValue, flags: TextTransformDeclaration.Flags) }, { ListStyleImageDeclaration.Name, new DeclarationInfo( name: ListStyleImageDeclaration.Name, converter: ListStyleImageDeclaration.Converter, initialValue: ListStyleImageDeclaration.InitialValue, flags: ListStyleImageDeclaration.Flags, shorthands: ListStyleImageDeclaration.Shorthands) }, { ListStylePositionDeclaration.Name, new DeclarationInfo( name: ListStylePositionDeclaration.Name, converter: ListStylePositionDeclaration.Converter, initialValue: ListStylePositionDeclaration.InitialValue, flags: ListStylePositionDeclaration.Flags, shorthands: ListStylePositionDeclaration.Shorthands) }, { ListStyleTypeDeclaration.Name, new DeclarationInfo( name: ListStyleTypeDeclaration.Name, converter: ListStyleTypeDeclaration.Converter, initialValue: ListStyleTypeDeclaration.InitialValue, flags: ListStyleTypeDeclaration.Flags, shorthands: ListStyleTypeDeclaration.Shorthands) }, { FontFamilyDeclaration.Name, new DeclarationInfo( name: FontFamilyDeclaration.Name, converter: FontFamilyDeclaration.Converter, initialValue: FontFamilyDeclaration.InitialValue, flags: FontFamilyDeclaration.Flags, shorthands: FontFamilyDeclaration.Shorthands) }, { FontSizeDeclaration.Name, new DeclarationInfo( name: FontSizeDeclaration.Name, converter: FontSizeDeclaration.Converter, initialValue: FontSizeDeclaration.InitialValue, flags: FontSizeDeclaration.Flags, shorthands: FontSizeDeclaration.Shorthands) }, { FontStyleDeclaration.Name, new DeclarationInfo( name: FontStyleDeclaration.Name, converter: FontStyleDeclaration.Converter, initialValue: FontStyleDeclaration.InitialValue, flags: FontStyleDeclaration.Flags, shorthands: FontStyleDeclaration.Shorthands) }, { FontStretchDeclaration.Name, new DeclarationInfo( name: FontStretchDeclaration.Name, converter: FontStretchDeclaration.Converter, initialValue: FontStretchDeclaration.InitialValue, flags: FontStretchDeclaration.Flags) }, { FontVariantDeclaration.Name, new DeclarationInfo( name: FontVariantDeclaration.Name, converter: FontVariantDeclaration.Converter, initialValue: FontVariantDeclaration.InitialValue, flags: FontVariantDeclaration.Flags, shorthands: FontVariantDeclaration.Shorthands) }, { FontWeightDeclaration.Name, new DeclarationInfo( name: FontWeightDeclaration.Name, converter: FontWeightDeclaration.Converter, initialValue: FontWeightDeclaration.InitialValue, flags: FontWeightDeclaration.Flags, shorthands: FontWeightDeclaration.Shorthands) }, { UnicodeRangeDeclaration.Name, new DeclarationInfo( name: UnicodeRangeDeclaration.Name, converter: UnicodeRangeDeclaration.Converter, initialValue: UnicodeRangeDeclaration.InitialValue, flags: UnicodeRangeDeclaration.Flags) }, { SrcDeclaration.Name, new DeclarationInfo( name: SrcDeclaration.Name, converter: SrcDeclaration.Converter, initialValue: SrcDeclaration.InitialValue, flags: SrcDeclaration.Flags) }, { ColumnRuleWidthDeclaration.Name, new DeclarationInfo( name: ColumnRuleWidthDeclaration.Name, converter: ColumnRuleWidthDeclaration.Converter, initialValue: ColumnRuleWidthDeclaration.InitialValue, flags: ColumnRuleWidthDeclaration.Flags, shorthands: ColumnRuleWidthDeclaration.Shorthands) }, { ColumnRuleStyleDeclaration.Name, new DeclarationInfo( name: ColumnRuleStyleDeclaration.Name, converter: ColumnRuleStyleDeclaration.Converter, initialValue: ColumnRuleStyleDeclaration.InitialValue, flags: ColumnRuleStyleDeclaration.Flags, shorthands: ColumnRuleStyleDeclaration.Shorthands) }, { ColumnRuleColorDeclaration.Name, new DeclarationInfo( name: ColumnRuleColorDeclaration.Name, converter: ColumnRuleColorDeclaration.Converter, initialValue: ColumnRuleColorDeclaration.InitialValue, flags: ColumnRuleColorDeclaration.Flags, shorthands: ColumnRuleColorDeclaration.Shorthands) }, { PaddingTopDeclaration.Name, new DeclarationInfo( name: PaddingTopDeclaration.Name, converter: PaddingTopDeclaration.Converter, initialValue: PaddingTopDeclaration.InitialValue, flags: PaddingTopDeclaration.Flags, shorthands: PaddingTopDeclaration.Shorthands) }, { PaddingRightDeclaration.Name, new DeclarationInfo( name: PaddingRightDeclaration.Name, converter: PaddingRightDeclaration.Converter, initialValue: PaddingRightDeclaration.InitialValue, flags: PaddingRightDeclaration.Flags, shorthands: PaddingRightDeclaration.Shorthands) }, { PaddingLeftDeclaration.Name, new DeclarationInfo( name: PaddingLeftDeclaration.Name, converter: PaddingLeftDeclaration.Converter, initialValue: PaddingLeftDeclaration.InitialValue, flags: PaddingLeftDeclaration.Flags, shorthands: PaddingLeftDeclaration.Shorthands) }, { PaddingBottomDeclaration.Name, new DeclarationInfo( name: PaddingBottomDeclaration.Name, converter: PaddingBottomDeclaration.Converter, initialValue: PaddingBottomDeclaration.InitialValue, flags: PaddingBottomDeclaration.Flags, shorthands: PaddingBottomDeclaration.Shorthands) }, { MarginTopDeclaration.Name, new DeclarationInfo( name: MarginTopDeclaration.Name, converter: MarginTopDeclaration.Converter, initialValue: MarginTopDeclaration.InitialValue, flags: MarginTopDeclaration.Flags, shorthands: MarginTopDeclaration.Shorthands) }, { MarginRightDeclaration.Name, new DeclarationInfo( name: MarginRightDeclaration.Name, converter: MarginRightDeclaration.Converter, initialValue: MarginRightDeclaration.InitialValue, flags: MarginRightDeclaration.Flags, shorthands: MarginRightDeclaration.Shorthands) }, { MarginLeftDeclaration.Name, new DeclarationInfo( name: MarginLeftDeclaration.Name, converter: MarginLeftDeclaration.Converter, initialValue: MarginLeftDeclaration.InitialValue, flags: MarginLeftDeclaration.Flags, shorthands: MarginLeftDeclaration.Shorthands) }, { MarginBottomDeclaration.Name, new DeclarationInfo( name: MarginBottomDeclaration.Name, converter: MarginBottomDeclaration.Converter, initialValue: MarginBottomDeclaration.InitialValue, flags: MarginBottomDeclaration.Flags, shorthands: MarginBottomDeclaration.Shorthands) }, { BorderTopRightRadiusDeclaration.Name, new DeclarationInfo( name: BorderTopRightRadiusDeclaration.Name, converter: BorderTopRightRadiusDeclaration.Converter, initialValue: BorderTopRightRadiusDeclaration.InitialValue, flags: BorderTopRightRadiusDeclaration.Flags, shorthands: BorderTopRightRadiusDeclaration.Shorthands) }, { BorderTopLeftRadiusDeclaration.Name, new DeclarationInfo( name: BorderTopLeftRadiusDeclaration.Name, converter: BorderTopLeftRadiusDeclaration.Converter, initialValue: BorderTopLeftRadiusDeclaration.InitialValue, flags: BorderTopLeftRadiusDeclaration.Flags, shorthands: BorderTopLeftRadiusDeclaration.Shorthands) }, { BorderBottomRightRadiusDeclaration.Name, new DeclarationInfo( name: BorderBottomRightRadiusDeclaration.Name, converter: BorderBottomRightRadiusDeclaration.Converter, initialValue: BorderBottomRightRadiusDeclaration.InitialValue, flags: BorderBottomRightRadiusDeclaration.Flags, shorthands: BorderBottomRightRadiusDeclaration.Shorthands) }, { BorderBottomLeftRadiusDeclaration.Name, new DeclarationInfo( name: BorderBottomLeftRadiusDeclaration.Name, converter: BorderBottomLeftRadiusDeclaration.Converter, initialValue: BorderBottomLeftRadiusDeclaration.InitialValue, flags: BorderBottomLeftRadiusDeclaration.Flags, shorthands: BorderBottomLeftRadiusDeclaration.Shorthands) }, { OutlineWidthDeclaration.Name, new DeclarationInfo( name: OutlineWidthDeclaration.Name, converter: OutlineWidthDeclaration.Converter, initialValue: OutlineWidthDeclaration.InitialValue, flags: OutlineWidthDeclaration.Flags, shorthands: OutlineWidthDeclaration.Shorthands) }, { OutlineStyleDeclaration.Name, new DeclarationInfo( name: OutlineStyleDeclaration.Name, converter: OutlineStyleDeclaration.Converter, initialValue: OutlineStyleDeclaration.InitialValue, flags: OutlineStyleDeclaration.Flags, shorthands: OutlineStyleDeclaration.Shorthands) }, { OutlineColorDeclaration.Name, new DeclarationInfo( name: OutlineColorDeclaration.Name, converter: OutlineColorDeclaration.Converter, initialValue: OutlineColorDeclaration.InitialValue, flags: OutlineColorDeclaration.Flags, shorthands: OutlineColorDeclaration.Shorthands) }, { TextDecorationStyleDeclaration.Name, new DeclarationInfo( name: TextDecorationStyleDeclaration.Name, converter: TextDecorationStyleDeclaration.Converter, initialValue: TextDecorationStyleDeclaration.InitialValue, flags: TextDecorationStyleDeclaration.Flags, shorthands: TextDecorationStyleDeclaration.Shorthands) }, { TextDecorationLineDeclaration.Name, new DeclarationInfo( name: TextDecorationLineDeclaration.Name, converter: TextDecorationLineDeclaration.Converter, initialValue: TextDecorationLineDeclaration.InitialValue, flags: TextDecorationLineDeclaration.Flags, shorthands: TextDecorationLineDeclaration.Shorthands) }, { TextDecorationColorDeclaration.Name, new DeclarationInfo( name: TextDecorationColorDeclaration.Name, converter: TextDecorationColorDeclaration.Converter, initialValue: TextDecorationColorDeclaration.InitialValue, flags: TextDecorationColorDeclaration.Flags, shorthands: TextDecorationColorDeclaration.Shorthands) }, { TransitionTimingFunctionDeclaration.Name, new DeclarationInfo( name: TransitionTimingFunctionDeclaration.Name, converter: TransitionTimingFunctionDeclaration.Converter, initialValue: TransitionTimingFunctionDeclaration.InitialValue, flags: TransitionTimingFunctionDeclaration.Flags, shorthands: TransitionTimingFunctionDeclaration.Shorthands) }, { TransitionPropertyDeclaration.Name, new DeclarationInfo( name: TransitionPropertyDeclaration.Name, converter: TransitionPropertyDeclaration.Converter, initialValue: TransitionPropertyDeclaration.InitialValue, flags: TransitionPropertyDeclaration.Flags, shorthands: TransitionPropertyDeclaration.Shorthands) }, { TransitionDurationDeclaration.Name, new DeclarationInfo( name: TransitionDurationDeclaration.Name, converter: TransitionDurationDeclaration.Converter, initialValue: TransitionDurationDeclaration.InitialValue, flags: TransitionDurationDeclaration.Flags, shorthands: TransitionDurationDeclaration.Shorthands) }, { TransitionDelayDeclaration.Name, new DeclarationInfo( name: TransitionDelayDeclaration.Name, converter: TransitionDelayDeclaration.Converter, initialValue: TransitionDelayDeclaration.InitialValue, flags: TransitionDelayDeclaration.Flags, shorthands: TransitionDelayDeclaration.Shorthands) }, { BorderImageWidthDeclaration.Name, new DeclarationInfo( name: BorderImageWidthDeclaration.Name, converter: BorderImageWidthDeclaration.Converter, initialValue: BorderImageWidthDeclaration.InitialValue, flags: BorderImageWidthDeclaration.Flags, shorthands: BorderImageWidthDeclaration.Shorthands) }, { BorderImageSourceDeclaration.Name, new DeclarationInfo( name: BorderImageSourceDeclaration.Name, converter: BorderImageSourceDeclaration.Converter, initialValue: BorderImageSourceDeclaration.InitialValue, flags: BorderImageSourceDeclaration.Flags, shorthands: BorderImageSourceDeclaration.Shorthands) }, { BorderImageSliceDeclaration.Name, new DeclarationInfo( name: BorderImageSliceDeclaration.Name, converter: BorderImageSliceDeclaration.Converter, initialValue: BorderImageSliceDeclaration.InitialValue, flags: BorderImageSliceDeclaration.Flags, shorthands: BorderImageSliceDeclaration.Shorthands) }, { BorderImageRepeatDeclaration.Name, new DeclarationInfo( name: BorderImageRepeatDeclaration.Name, converter: BorderImageRepeatDeclaration.Converter, initialValue: BorderImageRepeatDeclaration.InitialValue, flags: BorderImageRepeatDeclaration.Flags, shorthands: BorderImageRepeatDeclaration.Shorthands) }, { BorderImageOutsetDeclaration.Name, new DeclarationInfo( name: BorderImageOutsetDeclaration.Name, converter: BorderImageOutsetDeclaration.Converter, initialValue: BorderImageOutsetDeclaration.InitialValue, flags: BorderImageOutsetDeclaration.Flags, shorthands: BorderImageOutsetDeclaration.Shorthands) }, { AnimationTimingFunctionDeclaration.Name, new DeclarationInfo( name: AnimationTimingFunctionDeclaration.Name, converter: AnimationTimingFunctionDeclaration.Converter, initialValue: AnimationTimingFunctionDeclaration.InitialValue, flags: AnimationTimingFunctionDeclaration.Flags, shorthands: AnimationTimingFunctionDeclaration.Shorthands) }, { AnimationPlayStateDeclaration.Name, new DeclarationInfo( name: AnimationPlayStateDeclaration.Name, converter: AnimationPlayStateDeclaration.Converter, initialValue: AnimationPlayStateDeclaration.InitialValue, flags: AnimationPlayStateDeclaration.Flags, shorthands: AnimationPlayStateDeclaration.Shorthands) }, { AnimationNameDeclaration.Name, new DeclarationInfo( name: AnimationNameDeclaration.Name, converter: AnimationNameDeclaration.Converter, initialValue: AnimationNameDeclaration.InitialValue, flags: AnimationNameDeclaration.Flags, shorthands: AnimationNameDeclaration.Shorthands) }, { AnimationIterationCountDeclaration.Name, new DeclarationInfo( name: AnimationIterationCountDeclaration.Name, converter: AnimationIterationCountDeclaration.Converter, initialValue: AnimationIterationCountDeclaration.InitialValue, flags: AnimationIterationCountDeclaration.Flags, shorthands: AnimationIterationCountDeclaration.Shorthands) }, { AnimationFillModeDeclaration.Name, new DeclarationInfo( name: AnimationFillModeDeclaration.Name, converter: AnimationFillModeDeclaration.Converter, initialValue: AnimationFillModeDeclaration.InitialValue, flags: AnimationFillModeDeclaration.Flags, shorthands: AnimationFillModeDeclaration.Shorthands) }, { AnimationDurationDeclaration.Name, new DeclarationInfo( name: AnimationDurationDeclaration.Name, converter: AnimationDurationDeclaration.Converter, initialValue: AnimationDurationDeclaration.InitialValue, flags: AnimationDurationDeclaration.Flags, shorthands: AnimationDurationDeclaration.Shorthands) }, { AnimationDirectionDeclaration.Name, new DeclarationInfo( name: AnimationDirectionDeclaration.Name, converter: AnimationDirectionDeclaration.Converter, initialValue: AnimationDirectionDeclaration.InitialValue, flags: AnimationDirectionDeclaration.Flags, shorthands: AnimationDirectionDeclaration.Shorthands) }, { AnimationDelayDeclaration.Name, new DeclarationInfo( name: AnimationDelayDeclaration.Name, converter: AnimationDelayDeclaration.Converter, initialValue: AnimationDelayDeclaration.InitialValue, flags: AnimationDelayDeclaration.Flags, shorthands: AnimationDelayDeclaration.Shorthands) }, { BackgroundSizeDeclaration.Name, new DeclarationInfo( name: BackgroundSizeDeclaration.Name, converter: BackgroundSizeDeclaration.Converter, initialValue: BackgroundSizeDeclaration.InitialValue, flags: BackgroundSizeDeclaration.Flags, shorthands: BackgroundSizeDeclaration.Shorthands) }, { BackgroundRepeatDeclaration.Name, new DeclarationInfo( name: BackgroundRepeatDeclaration.Name, converter: BackgroundRepeatDeclaration.Converter, initialValue: BackgroundRepeatDeclaration.InitialValue, flags: BackgroundRepeatDeclaration.Flags, longhands: BackgroundRepeatDeclaration.Longhands, shorthands: BackgroundRepeatDeclaration.Shorthands) }, { BackgroundRepeatXDeclaration.Name, new DeclarationInfo( name: BackgroundRepeatXDeclaration.Name, converter: BackgroundRepeatXDeclaration.Converter, initialValue: BackgroundRepeatXDeclaration.InitialValue, flags: BackgroundRepeatXDeclaration.Flags, shorthands: BackgroundRepeatXDeclaration.Shorthands) }, { BackgroundRepeatYDeclaration.Name, new DeclarationInfo( name: BackgroundRepeatYDeclaration.Name, converter: BackgroundRepeatYDeclaration.Converter, initialValue: BackgroundRepeatYDeclaration.InitialValue, flags: BackgroundRepeatYDeclaration.Flags, shorthands: BackgroundRepeatYDeclaration.Shorthands) }, { BackgroundPositionDeclaration.Name, new DeclarationInfo( name: BackgroundPositionDeclaration.Name, converter: BackgroundPositionDeclaration.Converter, initialValue: BackgroundPositionDeclaration.InitialValue, flags: BackgroundPositionDeclaration.Flags, shorthands: BackgroundPositionDeclaration.Shorthands, longhands: BackgroundPositionDeclaration.Longhands) }, { BackgroundPositionXDeclaration.Name, new DeclarationInfo( name: BackgroundPositionXDeclaration.Name, converter: BackgroundPositionXDeclaration.Converter, initialValue: BackgroundPositionXDeclaration.InitialValue, flags: BackgroundPositionXDeclaration.Flags, shorthands: BackgroundPositionXDeclaration.Shorthands) }, { BackgroundPositionYDeclaration.Name, new DeclarationInfo( name: BackgroundPositionYDeclaration.Name, converter: BackgroundPositionYDeclaration.Converter, initialValue: BackgroundPositionYDeclaration.InitialValue, flags: BackgroundPositionYDeclaration.Flags, shorthands: BackgroundPositionYDeclaration.Shorthands) }, { BackgroundOriginDeclaration.Name, new DeclarationInfo( name: BackgroundOriginDeclaration.Name, converter: BackgroundOriginDeclaration.Converter, initialValue: BackgroundOriginDeclaration.InitialValue, flags: BackgroundOriginDeclaration.Flags, shorthands: BackgroundOriginDeclaration.Shorthands) }, { BackgroundImageDeclaration.Name, new DeclarationInfo( name: BackgroundImageDeclaration.Name, converter: BackgroundImageDeclaration.Converter, initialValue: BackgroundImageDeclaration.InitialValue, flags: BackgroundImageDeclaration.Flags, shorthands: BackgroundImageDeclaration.Shorthands) }, { BackgroundColorDeclaration.Name, new DeclarationInfo( name: BackgroundColorDeclaration.Name, converter: BackgroundColorDeclaration.Converter, initialValue: BackgroundColorDeclaration.InitialValue, flags: BackgroundColorDeclaration.Flags, shorthands: BackgroundColorDeclaration.Shorthands) }, { BackgroundClipDeclaration.Name, new DeclarationInfo( name: BackgroundClipDeclaration.Name, converter: BackgroundClipDeclaration.Converter, initialValue: BackgroundClipDeclaration.InitialValue, flags: BackgroundClipDeclaration.Flags, shorthands: BackgroundClipDeclaration.Shorthands) }, { BackgroundAttachmentDeclaration.Name, new DeclarationInfo( name: BackgroundAttachmentDeclaration.Name, converter: BackgroundAttachmentDeclaration.Converter, initialValue: BackgroundAttachmentDeclaration.InitialValue, flags: BackgroundAttachmentDeclaration.Flags, shorthands: BackgroundAttachmentDeclaration.Shorthands) }, { BorderTopWidthDeclaration.Name, new DeclarationInfo( name: BorderTopWidthDeclaration.Name, converter: BorderTopWidthDeclaration.Converter, initialValue: BorderTopWidthDeclaration.InitialValue, flags: BorderTopWidthDeclaration.Flags, shorthands: BorderTopWidthDeclaration.Shorthands) }, { BorderTopStyleDeclaration.Name, new DeclarationInfo( name: BorderTopStyleDeclaration.Name, converter: BorderTopStyleDeclaration.Converter, initialValue: BorderTopStyleDeclaration.InitialValue, flags: BorderTopStyleDeclaration.Flags, shorthands: BorderTopStyleDeclaration.Shorthands) }, { BorderTopColorDeclaration.Name, new DeclarationInfo( name: BorderTopColorDeclaration.Name, converter: BorderTopColorDeclaration.Converter, initialValue: BorderTopColorDeclaration.InitialValue, flags: BorderTopColorDeclaration.Flags, shorthands: BorderTopColorDeclaration.Shorthands) }, { BorderRightWidthDeclaration.Name, new DeclarationInfo( name: BorderRightWidthDeclaration.Name, converter: BorderRightWidthDeclaration.Converter, initialValue: BorderRightWidthDeclaration.InitialValue, flags: BorderRightWidthDeclaration.Flags, shorthands: BorderRightWidthDeclaration.Shorthands) }, { BorderRightStyleDeclaration.Name, new DeclarationInfo( name: BorderRightStyleDeclaration.Name, converter: BorderRightStyleDeclaration.Converter, initialValue: BorderRightStyleDeclaration.InitialValue, flags: BorderRightStyleDeclaration.Flags, shorthands: BorderRightStyleDeclaration.Shorthands) }, { BorderRightColorDeclaration.Name, new DeclarationInfo( name: BorderRightColorDeclaration.Name, converter: BorderRightColorDeclaration.Converter, initialValue: BorderRightColorDeclaration.InitialValue, flags: BorderRightColorDeclaration.Flags, shorthands: BorderRightColorDeclaration.Shorthands) }, { BorderLeftWidthDeclaration.Name, new DeclarationInfo( name: BorderLeftWidthDeclaration.Name, converter: BorderLeftWidthDeclaration.Converter, initialValue: BorderLeftWidthDeclaration.InitialValue, flags: BorderLeftWidthDeclaration.Flags, shorthands: BorderLeftWidthDeclaration.Shorthands) }, { BorderLeftStyleDeclaration.Name, new DeclarationInfo( name: BorderLeftStyleDeclaration.Name, converter: BorderLeftStyleDeclaration.Converter, initialValue: BorderLeftStyleDeclaration.InitialValue, flags: BorderLeftStyleDeclaration.Flags, shorthands: BorderLeftStyleDeclaration.Shorthands) }, { BorderLeftColorDeclaration.Name, new DeclarationInfo( name: BorderLeftColorDeclaration.Name, converter: BorderLeftColorDeclaration.Converter, initialValue: BorderLeftColorDeclaration.InitialValue, flags: BorderLeftColorDeclaration.Flags, shorthands: BorderLeftColorDeclaration.Shorthands) }, { BorderBottomWidthDeclaration.Name, new DeclarationInfo( name: BorderBottomWidthDeclaration.Name, converter: BorderBottomWidthDeclaration.Converter, initialValue: BorderBottomWidthDeclaration.InitialValue, flags: BorderBottomWidthDeclaration.Flags, shorthands: BorderBottomWidthDeclaration.Shorthands) }, { BorderBottomStyleDeclaration.Name, new DeclarationInfo( name: BorderBottomStyleDeclaration.Name, converter: BorderBottomStyleDeclaration.Converter, initialValue: BorderBottomStyleDeclaration.InitialValue, flags: BorderBottomStyleDeclaration.Flags, shorthands: BorderBottomStyleDeclaration.Shorthands) }, { BorderBottomColorDeclaration.Name, new DeclarationInfo( name: BorderBottomColorDeclaration.Name, converter: BorderBottomColorDeclaration.Converter, initialValue: BorderBottomColorDeclaration.InitialValue, flags: BorderBottomColorDeclaration.Flags, shorthands: BorderBottomColorDeclaration.Shorthands) }, { AnimationDeclaration.Name, new DeclarationInfo( name: AnimationDeclaration.Name, converter: AnimationDeclaration.Converter, initialValue: AnimationDeclaration.InitialValue, flags: AnimationDeclaration.Flags, longhands: AnimationDeclaration.Longhands) }, { BackgroundDeclaration.Name, new DeclarationInfo( name: BackgroundDeclaration.Name, converter: BackgroundDeclaration.Converter, initialValue: BackgroundDeclaration.InitialValue, flags: BackgroundDeclaration.Flags, longhands: BackgroundDeclaration.Longhands) }, { TransitionDeclaration.Name, new DeclarationInfo( name: TransitionDeclaration.Name, converter: TransitionDeclaration.Converter, initialValue: TransitionDeclaration.InitialValue, flags: TransitionDeclaration.Flags, longhands: TransitionDeclaration.Longhands) }, { TextDecorationDeclaration.Name, new DeclarationInfo( name: TextDecorationDeclaration.Name, converter: TextDecorationDeclaration.Converter, initialValue: TextDecorationDeclaration.InitialValue, flags: TextDecorationDeclaration.Flags, longhands: TextDecorationDeclaration.Longhands) }, { OutlineDeclaration.Name, new DeclarationInfo( name: OutlineDeclaration.Name, converter: OutlineDeclaration.Converter, initialValue: OutlineDeclaration.InitialValue, flags: OutlineDeclaration.Flags, longhands: OutlineDeclaration.Longhands) }, { ListStyleDeclaration.Name, new DeclarationInfo( name: ListStyleDeclaration.Name, converter: ListStyleDeclaration.Converter, initialValue: ListStyleDeclaration.InitialValue, flags: ListStyleDeclaration.Flags, longhands: ListStyleDeclaration.Longhands) }, { FontDeclaration.Name, new DeclarationInfo( name: FontDeclaration.Name, converter: FontDeclaration.Converter, initialValue: FontDeclaration.InitialValue, flags: FontDeclaration.Flags, longhands: FontDeclaration.Longhands) }, { ColumnsDeclaration.Name, new DeclarationInfo( name: ColumnsDeclaration.Name, converter: ColumnsDeclaration.Converter, initialValue: ColumnsDeclaration.InitialValue, flags: ColumnsDeclaration.Flags, longhands: ColumnsDeclaration.Longhands) }, { ColumnRuleDeclaration.Name, new DeclarationInfo( name: ColumnRuleDeclaration.Name, converter: ColumnRuleDeclaration.Converter, initialValue: ColumnRuleDeclaration.InitialValue, flags: ColumnRuleDeclaration.Flags, longhands: ColumnRuleDeclaration.Longhands) }, { PaddingDeclaration.Name, new DeclarationInfo( name: PaddingDeclaration.Name, converter: PaddingDeclaration.Converter, initialValue: PaddingDeclaration.InitialValue, flags: PaddingDeclaration.Flags, longhands: PaddingDeclaration.Longhands) }, { MarginDeclaration.Name, new DeclarationInfo( name: MarginDeclaration.Name, converter: MarginDeclaration.Converter, initialValue: MarginDeclaration.InitialValue, flags: MarginDeclaration.Flags, longhands: MarginDeclaration.Longhands) }, { BorderRadiusDeclaration.Name, new DeclarationInfo( name: BorderRadiusDeclaration.Name, converter: BorderRadiusDeclaration.Converter, initialValue: BorderRadiusDeclaration.InitialValue, flags: BorderRadiusDeclaration.Flags, longhands: BorderRadiusDeclaration.Longhands) }, { BorderImageDeclaration.Name, new DeclarationInfo( name: BorderImageDeclaration.Name, converter: BorderImageDeclaration.Converter, initialValue: BorderImageDeclaration.InitialValue, flags: BorderImageDeclaration.Flags, longhands: BorderImageDeclaration.Longhands) }, { BorderWidthDeclaration.Name, new DeclarationInfo( name: BorderWidthDeclaration.Name, converter: BorderWidthDeclaration.Converter, initialValue: BorderWidthDeclaration.InitialValue, flags: BorderWidthDeclaration.Flags, shorthands: BorderWidthDeclaration.Shorthands, longhands: BorderWidthDeclaration.Longhands) }, { BorderTopDeclaration.Name, new DeclarationInfo( name: BorderTopDeclaration.Name, converter: BorderTopDeclaration.Converter, initialValue: BorderTopDeclaration.InitialValue, flags: BorderTopDeclaration.Flags, shorthands: BorderTopDeclaration.Shorthands, longhands: BorderTopDeclaration.Longhands) }, { BorderStyleDeclaration.Name, new DeclarationInfo( name: BorderStyleDeclaration.Name, converter: BorderStyleDeclaration.Converter, initialValue: BorderStyleDeclaration.InitialValue, flags: BorderStyleDeclaration.Flags, shorthands: BorderStyleDeclaration.Shorthands, longhands: BorderStyleDeclaration.Longhands) }, { BorderRightDeclaration.Name, new DeclarationInfo( name: BorderRightDeclaration.Name, converter: BorderRightDeclaration.Converter, initialValue: BorderRightDeclaration.InitialValue, flags: BorderRightDeclaration.Flags, shorthands: BorderRightDeclaration.Shorthands, longhands: BorderRightDeclaration.Longhands) }, { BorderLeftDeclaration.Name, new DeclarationInfo( name: BorderLeftDeclaration.Name, converter: BorderLeftDeclaration.Converter, initialValue: BorderLeftDeclaration.InitialValue, flags: BorderLeftDeclaration.Flags, shorthands: BorderLeftDeclaration.Shorthands, longhands: BorderLeftDeclaration.Longhands) }, { BorderColorDeclaration.Name, new DeclarationInfo( name: BorderColorDeclaration.Name, converter: BorderColorDeclaration.Converter, initialValue: BorderColorDeclaration.InitialValue, flags: BorderColorDeclaration.Flags, shorthands: BorderColorDeclaration.Shorthands, longhands: BorderColorDeclaration.Longhands) }, { BorderBottomDeclaration.Name, new DeclarationInfo( name: BorderBottomDeclaration.Name, converter: BorderBottomDeclaration.Converter, initialValue: BorderBottomDeclaration.InitialValue, flags: BorderBottomDeclaration.Flags, shorthands: BorderBottomDeclaration.Shorthands, longhands: BorderBottomDeclaration.Longhands) }, { BorderDeclaration.Name, new DeclarationInfo( name: BorderDeclaration.Name, converter: BorderDeclaration.Converter, initialValue: BorderDeclaration.InitialValue, flags: BorderDeclaration.Flags, longhands: BorderDeclaration.Longhands) }, { ResizeDeclaration.Name, new DeclarationInfo( name: ResizeDeclaration.Name, converter: ResizeDeclaration.Converter, initialValue: ResizeDeclaration.InitialValue, flags: ResizeDeclaration.Flags) }, { RubyAlignDeclaration.Name, new DeclarationInfo( name: RubyAlignDeclaration.Name, converter: RubyAlignDeclaration.Converter, initialValue: RubyAlignDeclaration.InitialValue, flags: RubyAlignDeclaration.Flags) }, { RubyOverhangDeclaration.Name, new DeclarationInfo( name: RubyOverhangDeclaration.Name, converter: RubyOverhangDeclaration.Converter, initialValue: RubyOverhangDeclaration.InitialValue, flags: RubyOverhangDeclaration.Flags) }, { RubyPositionDeclaration.Name, new DeclarationInfo( name: RubyPositionDeclaration.Name, converter: RubyPositionDeclaration.Converter, initialValue: RubyPositionDeclaration.InitialValue, flags: RubyPositionDeclaration.Flags) }, { Scrollbar3dLightColorDeclaration.Name, new DeclarationInfo( name: Scrollbar3dLightColorDeclaration.Name, converter: Scrollbar3dLightColorDeclaration.Converter, initialValue: Scrollbar3dLightColorDeclaration.InitialValue, flags: Scrollbar3dLightColorDeclaration.Flags) }, { ScrollbarArrowColorDeclaration.Name, new DeclarationInfo( name: ScrollbarArrowColorDeclaration.Name, converter: ScrollbarArrowColorDeclaration.Converter, initialValue: ScrollbarArrowColorDeclaration.InitialValue, flags: ScrollbarArrowColorDeclaration.Flags) }, { ScrollbarBaseColorDeclaration.Name, new DeclarationInfo( name: ScrollbarBaseColorDeclaration.Name, converter: ScrollbarBaseColorDeclaration.Converter, initialValue: ScrollbarBaseColorDeclaration.InitialValue, flags: ScrollbarBaseColorDeclaration.Flags) }, { ScrollbarDarkshadowColorDeclaration.Name, new DeclarationInfo( name: ScrollbarDarkshadowColorDeclaration.Name, converter: ScrollbarDarkshadowColorDeclaration.Converter, initialValue: ScrollbarDarkshadowColorDeclaration.InitialValue, flags: ScrollbarDarkshadowColorDeclaration.Flags) }, { ScrollbarFaceColorDeclaration.Name, new DeclarationInfo( name: ScrollbarFaceColorDeclaration.Name, converter: ScrollbarFaceColorDeclaration.Converter, initialValue: ScrollbarFaceColorDeclaration.InitialValue, flags: ScrollbarFaceColorDeclaration.Flags) }, { ScrollbarHighlightColorDeclaration.Name, new DeclarationInfo( name: ScrollbarHighlightColorDeclaration.Name, converter: ScrollbarHighlightColorDeclaration.Converter, initialValue: ScrollbarHighlightColorDeclaration.InitialValue, flags: ScrollbarHighlightColorDeclaration.Flags) }, { ScrollbarShadowColorDeclaration.Name, new DeclarationInfo( name: ScrollbarShadowColorDeclaration.Name, converter: ScrollbarShadowColorDeclaration.Converter, initialValue: ScrollbarShadowColorDeclaration.InitialValue, flags: ScrollbarShadowColorDeclaration.Flags) }, { ScrollbarTrackColorDeclaration.Name, new DeclarationInfo( name: ScrollbarTrackColorDeclaration.Name, converter: ScrollbarTrackColorDeclaration.Converter, initialValue: ScrollbarTrackColorDeclaration.InitialValue, flags: ScrollbarTrackColorDeclaration.Flags) }, { PointerEventsDeclaration.Name, new DeclarationInfo( name: PointerEventsDeclaration.Name, converter: PointerEventsDeclaration.Converter, initialValue: PointerEventsDeclaration.InitialValue, flags: PointerEventsDeclaration.Flags) }, { OrderDeclaration.Name, new DeclarationInfo( name: OrderDeclaration.Name, converter: OrderDeclaration.Converter, initialValue: OrderDeclaration.InitialValue, flags: OrderDeclaration.Flags) }, { FlexShrinkDeclaration.Name, new DeclarationInfo( name: FlexShrinkDeclaration.Name, converter: FlexShrinkDeclaration.Converter, initialValue: FlexShrinkDeclaration.InitialValue, shorthands: FlexShrinkDeclaration.Shorthands, flags: FlexShrinkDeclaration.Flags) }, { FlexGrowDeclaration.Name, new DeclarationInfo( name: FlexGrowDeclaration.Name, converter: FlexGrowDeclaration.Converter, initialValue: FlexGrowDeclaration.InitialValue, shorthands: FlexGrowDeclaration.Shorthands, flags: FlexGrowDeclaration.Flags) }, { FlexBasisDeclaration.Name, new DeclarationInfo( name: FlexBasisDeclaration.Name, converter: FlexBasisDeclaration.Converter, initialValue: FlexBasisDeclaration.InitialValue, shorthands: FlexBasisDeclaration.Shorthands, flags: FlexBasisDeclaration.Flags) }, { JustifyContentDeclaration.Name, new DeclarationInfo( name: JustifyContentDeclaration.Name, converter: JustifyContentDeclaration.Converter, initialValue: JustifyContentDeclaration.InitialValue, flags: JustifyContentDeclaration.Flags) }, { AlignContentDeclaration.Name, new DeclarationInfo( name: AlignContentDeclaration.Name, converter: AlignContentDeclaration.Converter, initialValue: AlignContentDeclaration.InitialValue, flags: AlignContentDeclaration.Flags) }, { AlignSelfDeclaration.Name, new DeclarationInfo( name: AlignSelfDeclaration.Name, converter: AlignSelfDeclaration.Converter, initialValue: AlignSelfDeclaration.InitialValue, flags: AlignSelfDeclaration.Flags) }, { AlignItemsDeclaration.Name, new DeclarationInfo( name: AlignItemsDeclaration.Name, converter: AlignItemsDeclaration.Converter, initialValue: AlignItemsDeclaration.InitialValue, flags: AlignItemsDeclaration.Flags) }, { FlexDirectionDeclaration.Name, new DeclarationInfo( name: FlexDirectionDeclaration.Name, converter: FlexDirectionDeclaration.Converter, initialValue: FlexDirectionDeclaration.InitialValue, shorthands: FlexDirectionDeclaration.Shorthands, flags: FlexDirectionDeclaration.Flags) }, { FlexWrapDeclaration.Name, new DeclarationInfo( name: FlexWrapDeclaration.Name, converter: FlexWrapDeclaration.Converter, initialValue: FlexWrapDeclaration.InitialValue, shorthands: FlexWrapDeclaration.Shorthands, flags: FlexWrapDeclaration.Flags) }, { FlexDeclaration.Name, new DeclarationInfo( name: FlexDeclaration.Name, converter: FlexDeclaration.Converter, initialValue: FlexDeclaration.InitialValue, longhands: FlexDeclaration.Longhands, flags: FlexDeclaration.Flags) }, { FlexFlowDeclaration.Name, new DeclarationInfo( name: FlexFlowDeclaration.Name, converter: FlexFlowDeclaration.Converter, initialValue: FlexFlowDeclaration.InitialValue, longhands: FlexFlowDeclaration.Longhands, flags: FlexFlowDeclaration.Flags) }, { GridTemplateColumnsDeclaration.Name, new DeclarationInfo( name: GridTemplateColumnsDeclaration.Name, converter: GridTemplateColumnsDeclaration.Converter, initialValue: GridTemplateColumnsDeclaration.InitialValue, shorthands: GridTemplateAreasDeclaration.Shorthands, flags: GridTemplateColumnsDeclaration.Flags) }, { GridTemplateRowsDeclaration.Name, new DeclarationInfo( name: GridTemplateRowsDeclaration.Name, converter: GridTemplateRowsDeclaration.Converter, initialValue: GridTemplateRowsDeclaration.InitialValue, shorthands: GridTemplateAreasDeclaration.Shorthands, flags: GridTemplateRowsDeclaration.Flags) }, { GridTemplateAreasDeclaration.Name, new DeclarationInfo( name: GridTemplateAreasDeclaration.Name, converter: GridTemplateAreasDeclaration.Converter, initialValue: GridTemplateAreasDeclaration.InitialValue, shorthands: GridTemplateAreasDeclaration.Shorthands, flags: GridTemplateAreasDeclaration.Flags) }, { GridTemplateDeclaration.Name, new DeclarationInfo( name: GridTemplateDeclaration.Name, converter: GridTemplateDeclaration.Converter, initialValue: GridTemplateDeclaration.InitialValue, longhands: GridTemplateDeclaration.Longhands, flags: GridTemplateDeclaration.Flags) }, { GridAutoColumnsDeclaration.Name, new DeclarationInfo( name: GridAutoColumnsDeclaration.Name, converter: GridAutoColumnsDeclaration.Converter, initialValue: GridAutoColumnsDeclaration.InitialValue, flags: GridAutoColumnsDeclaration.Flags) }, { GridAutoRowsDeclaration.Name, new DeclarationInfo( name: GridAutoRowsDeclaration.Name, converter: GridAutoRowsDeclaration.Converter, initialValue: GridAutoRowsDeclaration.InitialValue, flags: GridAutoRowsDeclaration.Flags) }, { GridAutoFlowDeclaration.Name, new DeclarationInfo( name: GridAutoFlowDeclaration.Name, converter: GridAutoFlowDeclaration.Converter, initialValue: GridAutoFlowDeclaration.InitialValue, flags: GridAutoFlowDeclaration.Flags) }, { GridDeclaration.Name, new DeclarationInfo( name: GridDeclaration.Name, converter: GridDeclaration.Converter, initialValue: GridDeclaration.InitialValue, longhands: GridDeclaration.Longhands, flags: GridDeclaration.Flags) }, { GridRowStartDeclaration.Name, new DeclarationInfo( name: GridRowStartDeclaration.Name, converter: GridRowStartDeclaration.Converter, initialValue: GridRowStartDeclaration.InitialValue, shorthands: GridRowStartDeclaration.Shorthands, flags: GridRowStartDeclaration.Flags) }, { GridColumnStartDeclaration.Name, new DeclarationInfo( name: GridColumnStartDeclaration.Name, converter: GridColumnStartDeclaration.Converter, initialValue: GridColumnStartDeclaration.InitialValue, shorthands: GridColumnStartDeclaration.Shorthands, flags: GridColumnStartDeclaration.Flags) }, { GridRowEndDeclaration.Name, new DeclarationInfo( name: GridRowEndDeclaration.Name, converter: GridRowEndDeclaration.Converter, initialValue: GridRowEndDeclaration.InitialValue, shorthands: GridRowEndDeclaration.Shorthands, flags: GridRowEndDeclaration.Flags) }, { GridColumnEndDeclaration.Name, new DeclarationInfo( name: GridColumnEndDeclaration.Name, converter: GridColumnEndDeclaration.Converter, initialValue: GridColumnEndDeclaration.InitialValue, shorthands: GridColumnEndDeclaration.Shorthands, flags: GridColumnEndDeclaration.Flags) }, { GridRowDeclaration.Name, new DeclarationInfo( name: GridRowDeclaration.Name, converter: GridRowDeclaration.Converter, initialValue: GridRowDeclaration.InitialValue, longhands: GridRowDeclaration.Longhands, flags: GridRowDeclaration.Flags) }, { GridColumnDeclaration.Name, new DeclarationInfo( name: GridColumnDeclaration.Name, converter: GridColumnDeclaration.Converter, initialValue: GridColumnDeclaration.InitialValue, longhands: GridColumnDeclaration.Longhands, flags: GridColumnDeclaration.Flags) }, { GridAreaDeclaration.Name, new DeclarationInfo( name: GridAreaDeclaration.Name, converter: GridAreaDeclaration.Converter, initialValue: GridAreaDeclaration.InitialValue, longhands: GridAreaDeclaration.Longhands, flags: GridAreaDeclaration.Flags) }, { GridRowGapDeclaration.Name, new DeclarationInfo( name: GridRowGapDeclaration.Name, converter: GridRowGapDeclaration.Converter, initialValue: GridRowGapDeclaration.InitialValue, shorthands: GridRowGapDeclaration.Shorthands, flags: GridRowGapDeclaration.Flags) }, { GridColumnGapDeclaration.Name, new DeclarationInfo( name: GridColumnGapDeclaration.Name, converter: GridColumnGapDeclaration.Converter, initialValue: GridColumnGapDeclaration.InitialValue, shorthands: GridColumnGapDeclaration.Shorthands, flags: GridColumnGapDeclaration.Flags) }, { GridGapDeclaration.Name, new DeclarationInfo( name: GridGapDeclaration.Name, converter: GridGapDeclaration.Converter, initialValue: GridGapDeclaration.InitialValue, longhands: GridGapDeclaration.Longhands, flags: GridGapDeclaration.Flags) }, { FillDeclaration.Name, new DeclarationInfo( name: FillDeclaration.Name, converter: FillDeclaration.Converter, initialValue: FillDeclaration.InitialValue, flags: FillDeclaration.Flags) }, }; /// <summary> /// Registers a new declaration for the given name. Throws an exception if another /// declaration for the given property name is already added. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="converter">The converter to use.</param> public void Register(String propertyName, DeclarationInfo converter) => _declarations.Add(propertyName, converter); /// <summary> /// Unregisters an existing declaration. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <returns>The registered declaration, if any.</returns> public DeclarationInfo Unregister(String propertyName) { if (_declarations.TryGetValue(propertyName, out DeclarationInfo info)) { _declarations.Remove(propertyName); } return info; } /// <summary> /// Creates a default declaration for the given property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <returns>The default (any) declaration.</returns> protected virtual DeclarationInfo CreateDefault(String propertyName) { if (propertyName.StartsWith("--")) { return new DeclarationInfo(propertyName, ValueConverters.Any, flags: PropertyFlags.Inherited); } return new DeclarationInfo(propertyName, ValueConverters.Any, flags: PropertyFlags.Unknown); } /// <summary> /// Gets an existing declaration for the given property name. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <returns>The associated declaration.</returns> public DeclarationInfo Create(String propertyName) { var info = default(DeclarationInfo); if (!String.IsNullOrEmpty(propertyName) && _declarations.TryGetValue(propertyName, out info)) { return info; } return CreateDefault(propertyName); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DemoGame.DbObjs; using DemoGame.Server.DbObjs; using DemoGame.Server.Queries; using NetGore.Db; using NetGore.Features.Guilds; using NetGore.IO; using NetGore.Network; namespace DemoGame.Server.Guilds { public class Guild : GuildBase, IGuildTable { static readonly CountGuildFoundersQuery _countGuildFoundersQuery; static readonly DeleteGuildQuery _deleteGuildQuery; static readonly SelectGuildEventsQuery _selectGuildEventsQuery; static readonly SelectGuildMembersListQuery _selectGuildMembersListQuery; static readonly UpdateGuildNameQuery _updateGuildNameQuery; static readonly UpdateGuildQuery _updateGuildQuery; static readonly UpdateGuildTagQuery _updateGuildTagQuery; readonly DateTime _created; /// <summary> /// Initializes the <see cref="Guild"/> class. /// </summary> static Guild() { var dbController = DbControllerBase.GetInstance(); _countGuildFoundersQuery = dbController.GetQuery<CountGuildFoundersQuery>(); _deleteGuildQuery = dbController.GetQuery<DeleteGuildQuery>(); _updateGuildNameQuery = dbController.GetQuery<UpdateGuildNameQuery>(); _updateGuildTagQuery = dbController.GetQuery<UpdateGuildTagQuery>(); _selectGuildMembersListQuery = dbController.GetQuery<SelectGuildMembersListQuery>(); _updateGuildQuery = dbController.GetQuery<UpdateGuildQuery>(); _selectGuildEventsQuery = dbController.GetQuery<SelectGuildEventsQuery>(); } /// <summary> /// Initializes a new instance of the <see cref="Guild"/> class. /// </summary> /// <param name="guildManager">The guild manager.</param> /// <param name="guildInfo">The guild info.</param> public Guild(IGuildManager guildManager, IGuildTable guildInfo) : base(guildManager, guildInfo.ID, guildInfo.Name, guildInfo.Tag) { _created = guildInfo.Created; } /// <summary> /// Gets the name and rank for all the members in the guild. /// </summary> /// <returns>The name and rank for all the members in the guild.</returns> public override IEnumerable<GuildMemberNameRank> GetMembers() { return _selectGuildMembersListQuery.Execute(ID); } /// <summary> /// When overridden in the derived class, gets the number of founders (highest rank) in the guild. /// </summary> /// <returns>The number of founders (highest rank) in the guild.</returns> protected override int GetNumberOfFounders() { return _countGuildFoundersQuery.Execute(ID); } /// <summary> /// When overridden in the derived class, handles destroying the guild. This needs to remove all members /// in the guild from the guild, and remove the guild itself from the database. /// </summary> protected override void HandleDestroyed() { // Remove all online members in the guild from the guild foreach (var member in OnlineMembers) { member.Guild = null; } // Delete the guild from the database, which will also remove all members not logged in from the guild _deleteGuildQuery.Execute(ID); } /// <summary> /// When overridden in the derived class, attempts to set the name of this guild to the given /// <paramref name="newName"/> in the database. The <paramref name="newName"/> does not need to /// be checked if valid. /// </summary> /// <param name="newName">The new name for the guild.</param> /// <returns>True if the name was successfully changed; otherwise false.</returns> protected override bool InternalTryChangeName(string newName) { return _updateGuildNameQuery.ExecuteWithResult(new UpdateGuildNameQuery.QueryArgs(ID, newName)) > 0; } /// <summary> /// When overridden in the derived class, attempts to set the tag of this guild to the given /// <paramref name="newTag"/> in the database. The <paramref name="newTag"/> does not need to /// be checked if valid. /// </summary> /// <param name="newTag">The new tag for the guild.</param> /// <returns>True if the tag was successfully changed; otherwise false.</returns> protected override bool InternalTryChangeTag(string newTag) { return _updateGuildTagQuery.ExecuteWithResult(new UpdateGuildTagQuery.QueryArgs(ID, newTag)) > 0; } /// <summary> /// When overridden in the derived class, does the actually handling of viewing the event log for the guild. /// This should send the latest entries of the guild event log to the <paramref name="invoker"/>. /// </summary> /// <param name="invoker">The guild member that invoked the event.</param> /// <returns>True if the <paramref name="invoker"/> successfully viewed the log; otherwise false.</returns> protected override bool InternalTryViewEventLog(IGuildMember invoker) { var user = invoker as INetworkSender; if (user == null) return false; var events = _selectGuildEventsQuery.Execute(ID); foreach (var e in events) { using (var pw = ServerPacket.Chat(e.ID + ": " + (GuildEvents)e.EventID)) { user.Send(pw, ServerMessageType.GUI); } } return true; } /// <summary> /// When overridden in the derived class, displays the members of the guild to the <paramref name="invoker"/>. /// </summary> /// <param name="invoker">The guild member that invoked the event.</param> /// <returns>True if the <paramref name="invoker"/> successfully viewed the member list; otherwise false.</returns> protected override bool InternalTryViewMembers(IGuildMember invoker) { var user = invoker as INetworkSender; if (user == null) return false; // Get the list of members and their ranks SendGuildMemberList(user, "All guild members:", GetMembers()); return true; } /// <summary> /// When overridden in the derived class, displays the online members of the guild to the <paramref name="invoker"/>. /// </summary> /// <param name="invoker">The guild member that invoked the event.</param> /// <returns>True if the <paramref name="invoker"/> successfully viewed the online member list; otherwise false.</returns> protected override bool InternalTryViewOnlineMembers(IGuildMember invoker) { var user = invoker as INetworkSender; if (user == null) return false; var members = OnlineMembers.OrderBy(x => (int)x.GuildRank).Select(x => new GuildMemberNameRank(x.Name, x.GuildRank)); SendGuildMemberList(user, "Online guild members:", members); return true; } /// <summary> /// When overridden in the derived class, allows for additional handling after a new guild member is added. /// Use this instead of the corresponding event when possible. /// </summary> /// <param name="newMember"></param> protected override void OnMemberAdded(IGuildMember newMember) { base.OnMemberAdded(newMember); var v = new GuildMemberNameRank(newMember.Name, newMember.GuildRank); using (var pw = ServerPacket.GuildInfo(x => UserGuildInformation.WriteAddMember(x, v))) { Send(pw); } } /// <summary> /// When overridden in the derived class, allows for additional handling after a guild member is kicked. /// Use this instead of the corresponding event when possible. /// </summary> /// <param name="invoker">The guild member that invoked the event.</param> /// <param name="target">The optional guild member the event involves.</param> protected override void OnMemberKicked(IGuildMember invoker, IGuildMember target) { base.OnMemberKicked(invoker, target); using (var pw = ServerPacket.GuildInfo(x => UserGuildInformation.WriteRemoveMember(x, target.Name))) { Send(pw); } } /// <summary> /// When overridden in the derived class, allows for additional handling after a guild member is promoted. /// Use this instead of the corresponding event when possible. /// </summary> /// <param name="invoker">The guild member that invoked the event.</param> /// <param name="target">The optional guild member the event involves.</param> protected override void OnMemberPromoted(IGuildMember invoker, IGuildMember target) { base.OnMemberPromoted(invoker, target); var v = new GuildMemberNameRank(target.Name, target.GuildRank); using (var pw = ServerPacket.GuildInfo(x => UserGuildInformation.WriteUpdateMemberRank(x, v))) { Send(pw); } } /// <summary> /// When overridden in the derived class, allows for additional handling after the guild's name has changed. /// Use this instead of the corresponding event when possible. /// </summary> /// <param name="invoker">The guild member that invoked the event.</param> /// <param name="oldName">The old name.</param> /// <param name="newName">The new name.</param> protected override void OnNameChanged(IGuildMember invoker, string oldName, string newName) { using (var pw = ServerPacket.SendMessage(GameMessage.GuildRenamed, oldName, newName, invoker.Name)) { Send(pw); } using (var pw = ServerPacket.GuildInfo(x => UserGuildInformation.WriteUpdateNameTag(x, Name, Tag))) { Send(pw); } } /// <summary> /// When overridden in the derived class, allows for additional handling of when a member of this /// guild has come online. /// </summary> /// <param name="guildMember">The guild member that came online.</param> protected override void OnOnlineUserAdded(IGuildMember guildMember) { base.OnOnlineUserAdded(guildMember); using (var pw = ServerPacket.GuildInfo(x => UserGuildInformation.WriteAddOnlineMember(x, guildMember.Name))) { Send(pw); } } /// <summary> /// When overridden in the derived class, allows for additional handling of when a member of this /// guild has gone offline. /// </summary> /// <param name="guildMember">The guild member that went offline.</param> protected override void OnOnlineUserRemoved(IGuildMember guildMember) { base.OnOnlineUserRemoved(guildMember); using (var pw = ServerPacket.GuildInfo(x => UserGuildInformation.WriteRemoveOnlineMember(x, guildMember.Name))) { Send(pw); } } /// <summary> /// When overridden in the derived class, allows for additional handling after the guild's tag has changed. /// Use this instead of the corresponding event when possible. /// </summary> /// <param name="invoker">The guild member that invoked the event.</param> /// <param name="oldTag">The old tag.</param> /// <param name="newTag">The new tag.</param> protected override void OnTagChanged(IGuildMember invoker, string oldTag, string newTag) { using (var pw = ServerPacket.SendMessage(GameMessage.GuildRetagged, oldTag, newTag, invoker.Name)) { Send(pw); } using (var pw = ServerPacket.GuildInfo(x => UserGuildInformation.WriteUpdateNameTag(x, Name, Tag))) { Send(pw); } } /// <summary> /// When overridden in the derived class, saves all of the guild's information to the database. /// </summary> public override void Save() { _updateGuildQuery.Execute(this); } /// <summary> /// Sends a message to all guild members. /// </summary> /// <param name="data">The <see cref="BitStream"/> containing the data to send.</param> public void Send(BitStream data) { foreach (var member in OnlineMembers.OfType<INetworkSender>()) { member.Send(data, ServerMessageType.GUIChat); } } /// <summary> /// Sends a list of guild member names and ranks to a <see cref="User"/>. /// </summary> /// <param name="user">The user to send the information to.</param> /// <param name="header">The heading to give the list.</param> /// <param name="members">The guild members and their ranks to include in the list.</param> static void SendGuildMemberList(INetworkSender user, string header, IEnumerable<GuildMemberNameRank> members) { // Build the string var sb = new StringBuilder(); sb.AppendLine(header); foreach (var member in members) { sb.AppendLine(string.Format("{0}: {1}", member.Name, member.Rank)); } // Send using (var pw = ServerPacket.Chat(sb.ToString())) { user.Send(pw, ServerMessageType.GUI); } } #region IGuildTable Members /// <summary> /// Gets the value of the database column `created`. /// </summary> public DateTime Created { get { return _created; } } /// <summary> /// Gets the value of the database column `id`. /// </summary> GuildID IGuildTable.ID { get { return ID; } } /// <summary> /// Creates a deep copy of this table. All the values will be the same /// but they will be contained in a different object instance. /// </summary> /// <returns> /// A deep copy of this table. /// </returns> IGuildTable IGuildTable.DeepCopy() { return new GuildTable(this); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001; using System; using System.Collections.Generic; public class C { } public interface I { } public class MyClass { public int Field = 0; } public struct MyStruct { public int Number; } public enum MyEnum { First = 1, Second = 2, Third = 3 } public class MemberClass<T> { #region Instance methods public bool Method_ReturnBool() { return false; } public T Method_ReturnsT() { return default(T); } public T Method_ReturnsT(T t) { return t; } public T Method_ReturnsT(out T t) { t = default(T); return t; } public T Method_ReturnsT(ref T t, T tt) { t = default(T); return t; } public T Method_ReturnsT(params T[] t) { return default(T); } public T Method_ReturnsT(float x, T t) { return default(T); } public int Method_ReturnsInt(T t) { return 1; } public float Method_ReturnsFloat(T t, dynamic d) { return 3.4f; } public float Method_ReturnsFloat(T t, dynamic d, ref decimal dec) { dec = 3m; return 3.4f; } public dynamic Method_ReturnsDynamic(T t) { return t; } public dynamic Method_ReturnsDynamic(T t, dynamic d) { return t; } public dynamic Method_ReturnsDynamic(T t, int x, dynamic d) { return t; } // Multiple params // Constraints // Nesting #endregion #region Static methods public static bool? StaticMethod_ReturnBoolNullable() { return (bool?)false; } #endregion } public class MemberClassMultipleParams<T, U, V> { public T Method_ReturnsT(V v, U u) { return default(T); } } public class MemberClassWithClassConstraint<T> where T : class { public int Method_ReturnsInt() { return 1; } public T Method_ReturnsT(decimal dec, dynamic d) { return null; } } public class MemberClassWithNewConstraint<T> where T : new() { public T Method_ReturnsT() { return new T(); } public dynamic Method_ReturnsDynamic(T t) { return new T(); } } public class MemberClassWithAnotherTypeConstraint<T, U> where T : U { public U Method_ReturnsU(dynamic d) { return default(U); } public dynamic Method_ReturnsDynamic(int x, U u, dynamic d) { return default(T); } } #region Negative tests - you should not be able to construct this with a dynamic object public class MemberClassWithUDClassConstraint<T> where T : C, new() { public C Method_ReturnsC() { return new T(); } } public class MemberClassWithStructConstraint<T> where T : struct { public dynamic Method_ReturnsDynamic(int x) { return x; } } public class MemberClassWithInterfaceConstraint<T> where T : I { public dynamic Method_ReturnsDynamic(int x, T v) { return default(T); } } #endregion } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001; // <Title> Tests generic class regular method used in regular method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t.TestMethod() == true) return 1; return 0; } public bool TestMethod() { dynamic mc = new MemberClass<string>(); return (bool)mc.Method_ReturnBool(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002; // <Title> Tests generic class regular method used in argements of method invocation.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); dynamic mc1 = new MemberClass<int>(); int result1 = t.TestMethod((int)mc1.Method_ReturnsT()); dynamic mc2 = new MemberClass<string>(); int result2 = Test.TestMethod((string)mc2.Method_ReturnsT()); if (result1 == 0 && result2 == 0) return 0; else return 1; } public int TestMethod(int i) { if (i == default(int)) { return 0; } else { return 1; } } public static int TestMethod(string s) { if (s == default(string)) { return 0; } else { return 1; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003; // <Title> Tests generic class regular method used in static variable.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { private static dynamic s_mc = new MemberClass<string>(); private static float s_loc = (float)s_mc.Method_ReturnsFloat(null, 1); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (s_loc != 3.4f) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005; // <Title> Tests generic class regular method used in unsafe.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //using System; //[TestClass]public class Test //{ //[Test][Priority(Priority.Priority1)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod());} public static unsafe int MainMethod() //{ //dynamic dy = new MemberClass<int>(); //int value = 1; //int* valuePtr = &value; //int result = dy.Method_ReturnsT(out *valuePtr); //if (result == 0 && value == 0) //return 0; //return 1; //} //} //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006; // <Title> Tests generic class regular method used in generic method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact(Skip = "870811")] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); string s1 = ""; string s2 = ""; string result = t.TestMethod<string>(ref s1, s2); if (result == null && s1 == null) return 0; return 1; } public T TestMethod<T>(ref T t1, T t2) { dynamic mc = new MemberClass<T>(); return (T)mc.Method_ReturnsT(ref t1, t2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008; // <Title> Tests generic class regular method used in extension method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int Field = 10; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = 1.ExReturnTest(); if (t.Field == 1) return 0; return 1; } } static public class Extension { public static Test ExReturnTest(this int t) { dynamic dy = new MemberClass<int>(); float x = 3.3f; int i = -1; return new Test() { Field = t + (int)dy.Method_ReturnsT(x, i) } ; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009; // <Title> Tests generic class regular method used in for loop.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass<MyEnum>(); int result = 0; for (int i = (int)dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++) { result += (int)dy.Method_ReturnsInt((MyEnum)(i % 3 + 1)); } if (result == 9) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a; // <Title> Tests generic class regular method used in for loop.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass<MyEnum>(); int result = 0; for (int i = dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++) { result += dy.Method_ReturnsInt((MyEnum)(i % 3 + 1)); } if (result == 9) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010; // <Title> Tests generic class regular method used in static constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test : I { private static decimal s_dec = 0M; private static float s_result = 0f; static Test() { dynamic dy = new MemberClass<I>(); s_result = (float)dy.Method_ReturnsFloat(new Test(), dy, ref s_dec); } [Fact(Skip = "870811")] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (Test.s_dec == 3M && Test.s_result == 3.4f) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012; // <Title> Tests generic class regular method used in lambda.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass<string>(); dynamic d1 = 3; dynamic d2 = "Test"; Func<string, string, string> fun = (x, y) => (y + x.ToString()); string result = fun((string)dy.Method_ReturnsDynamic("foo", d1), (string)dy.Method_ReturnsDynamic("bar", d2)); if (result == "barfoo") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013; // <Title> Tests generic class regular method used in array initializer list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass<string>(); string[] array = new string[] { (string)dy.Method_ReturnsDynamic(string.Empty, 1, dy), (string)dy.Method_ReturnsDynamic(null, 0, dy), (string)dy.Method_ReturnsDynamic("a", -1, dy)} ; if (array.Length == 3 && array[0] == string.Empty && array[1] == null && array[2] == "a") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014; // <Title> Tests generic class regular method used in null coalescing operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = MemberClass<string>.StaticMethod_ReturnBoolNullable(); if (!((bool?)dy ?? false)) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015; // <Title> Tests generic class regular method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClassMultipleParams<MyEnum, MyStruct, MyClass>(); MyEnum me = dy.Method_ReturnsT(null, new MyStruct()); return (int)me; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016; // <Title> Tests generic class regular method used in query expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { private class M { public int Field1; public int Field2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClassWithClassConstraint<MyClass>(); var list = new List<M>() { new M() { Field1 = 1, Field2 = 2 } , new M() { Field1 = 2, Field2 = 1 } } ; return list.Any(p => p.Field1 == (int)dy.Method_ReturnsInt()) ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017; // <Title> Tests generic class regular method used in ternary operator expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClassWithClassConstraint<string>(); string result = (string)dy.Method_ReturnsT(decimal.MaxValue, dy) == null ? string.Empty : (string)dy.Method_ReturnsT(decimal.MaxValue, dy); return result == string.Empty ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018; // <Title> Tests generic class regular method used in lock expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClassWithNewConstraint<C>(); int result = 1; lock (dy.Method_ReturnsT()) { result = 0; } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019; // <Title> Tests generic class regular method used in switch section statement list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy1 = new MemberClassWithNewConstraint<C>(); dynamic dy2 = new MemberClassWithAnotherTypeConstraint<int, int>(); C result = new C(); int result2 = -1; switch ((int)dy2.Method_ReturnsU(dy1)) // 0 { case 0: result = (C)dy1.Method_ReturnsDynamic(result); // called break; default: result2 = (int)dy2.Method_ReturnsDynamic(0, 0, dy2); // not called break; } return (result.GetType() == typeof(C) && result2 == -1) ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01; // <Title> Tests generic class regular method used in regular method body.</Title> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Ta { public static int i = 2; } public class A<T> { public static implicit operator A<List<string>>(A<T> x) { return new A<List<string>>(); } } public class B { public static void Foo<T>(A<List<T>> x, string y) { Ta.i--; } public static void Foo<T>(object x, string y) { Ta.i++; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var x = new A<Action<object>>(); Foo<string>(x, ""); Foo<string>(x, (dynamic)""); return Ta.i; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Security; namespace Microsoft.PowerShell.Commands { /// <summary> /// The implementation of the "import-alias" cmdlet /// </summary> /// [Cmdlet(VerbsData.Import, "Alias", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113339")] [OutputType(typeof(AliasInfo))] public class ImportAliasCommand : PSCmdlet { #region Statics private const string LiteralPathParameterSetName = "ByLiteralPath"; #endregion #region Parameters /// <summary> /// The path from which to import the aliases /// </summary> /// [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public string Path { get; set; } /// <summary> /// The literal path from which to import the aliases /// </summary> /// [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = LiteralPathParameterSetName)] [Alias("PSPath")] public string LiteralPath { get { return Path; } set { Path = value; } } /// <summary> /// The scope to import the aliases to. /// </summary> /// [Parameter] [ValidateNotNullOrEmpty] public string Scope { get; set; } /// <summary> /// If set to true, the alias that is set is passed to the /// pipeline. /// </summary> /// [Parameter] public SwitchParameter PassThru { get { return _passThru; } set { _passThru = value; } } private bool _passThru; /// <summary> /// If set to true and an existing alias of the same name exists /// and is ReadOnly, the alias will be overwritten. /// </summary> /// [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; #endregion Parameters #region Command code /// <summary> /// The main processing loop of the command. /// </summary> /// protected override void ProcessRecord() { Collection<AliasInfo> importedAliases = GetAliasesFromFile(this.ParameterSetName.Equals(LiteralPathParameterSetName, StringComparison.OrdinalIgnoreCase)); CommandOrigin origin = MyInvocation.CommandOrigin; foreach (AliasInfo alias in importedAliases) { // If not force, then see if the alias already exists // NTRAID#Windows Out Of Band Releases-906910-2006/03/17-JonN string action = AliasCommandStrings.ImportAliasAction; string target = StringUtil.Format(AliasCommandStrings.ImportAliasTarget, alias.Name, alias.Definition); if (!ShouldProcess(target, action)) continue; if (!Force) { AliasInfo existingAlias = null; if (String.IsNullOrEmpty(Scope)) { existingAlias = SessionState.Internal.GetAlias(alias.Name); } else { existingAlias = SessionState.Internal.GetAliasAtScope(alias.Name, Scope); } if (existingAlias != null) { // Write an error for aliases that aren't visible... try { SessionState.ThrowIfNotVisible(origin, existingAlias); } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); // Only report the error once... continue; } // Since the alias already exists, write an error. SessionStateException aliasExists = new SessionStateException( alias.Name, SessionStateCategory.Alias, "AliasAlreadyExists", SessionStateStrings.AliasAlreadyExists, ErrorCategory.ResourceExists); WriteError( new ErrorRecord( aliasExists.ErrorRecord, aliasExists)); continue; } if (VerifyShadowingExistingCommandsAndWriteError(alias.Name)) { continue; } } // if (!Force) // Set the alias in the specified scope or the // current scope. AliasInfo result = null; try { if (String.IsNullOrEmpty(Scope)) { result = SessionState.Internal.SetAliasItem(alias, Force, MyInvocation.CommandOrigin); } else { result = SessionState.Internal.SetAliasItemAtScope(alias, Scope, Force, MyInvocation.CommandOrigin); } } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); continue; } catch (PSArgumentOutOfRangeException argOutOfRange) { WriteError( new ErrorRecord( argOutOfRange.ErrorRecord, argOutOfRange)); continue; } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); continue; } // Write the alias to the pipeline if PassThru was specified if (PassThru && result != null) { WriteObject(result); } } } // ProcessRecord private Dictionary<string, CommandTypes> _existingCommands; private Dictionary<string, CommandTypes> ExistingCommands { get { if (_existingCommands == null) { _existingCommands = new Dictionary<string, CommandTypes>(StringComparer.OrdinalIgnoreCase); CommandSearcher searcher = new CommandSearcher( "*", SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns, CommandTypes.All ^ CommandTypes.Alias, this.Context); foreach (CommandInfo commandInfo in searcher) { _existingCommands[commandInfo.Name] = commandInfo.CommandType; } // Also add commands from the analysis cache foreach (CommandInfo commandInfo in System.Management.Automation.Internal.ModuleUtils.GetMatchingCommands("*", this.Context, this.MyInvocation.CommandOrigin)) { if (!_existingCommands.ContainsKey(commandInfo.Name)) { _existingCommands[commandInfo.Name] = commandInfo.CommandType; } } } return _existingCommands; } } private bool VerifyShadowingExistingCommandsAndWriteError(string aliasName) { CommandSearcher searcher = new CommandSearcher(aliasName, SearchResolutionOptions.None, CommandTypes.All ^ CommandTypes.Alias, this.Context); foreach (string expandedCommandName in searcher.ConstructSearchPatternsFromName(aliasName)) { CommandTypes commandTypeOfExistingCommand; if (this.ExistingCommands.TryGetValue(expandedCommandName, out commandTypeOfExistingCommand)) { // Since the alias already exists, write an error. SessionStateException aliasExists = new SessionStateException( aliasName, SessionStateCategory.Alias, "AliasAlreadyExists", SessionStateStrings.AliasWithCommandNameAlreadyExists, ErrorCategory.ResourceExists, commandTypeOfExistingCommand); WriteError( new ErrorRecord( aliasExists.ErrorRecord, aliasExists)); return true; } } return false; } private Collection<AliasInfo> GetAliasesFromFile(bool isLiteralPath) { Collection<AliasInfo> result = new Collection<AliasInfo>(); string filePath = null; using (StreamReader reader = OpenFile(out filePath, isLiteralPath)) { CSVHelper csvHelper = new CSVHelper(','); Int64 lineNumber = 0; string line = null; while ((line = reader.ReadLine()) != null) { ++lineNumber; // Ignore blank lines if (line.Length == 0) { continue; } // Ignore lines that only contain whitespace if (OnlyContainsWhitespace(line)) { continue; } // Ignore comment lines if (line[0] == '#') { continue; } Collection<string> values = csvHelper.ParseCsv(line); if (values.Count != 4) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileInvalidFormat, filePath, lineNumber); FormatException formatException = new FormatException(message); ErrorRecord errorRecord = new ErrorRecord( formatException, "ImportAliasFileFormatError", ErrorCategory.ReadError, filePath); errorRecord.ErrorDetails = new ErrorDetails(message); ThrowTerminatingError(errorRecord); } ScopedItemOptions options = ScopedItemOptions.None; try { options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), values[3], true); } catch (ArgumentException argException) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasOptionsError, filePath, lineNumber); ErrorRecord errorRecord = new ErrorRecord( argException, "ImportAliasOptionsError", ErrorCategory.ReadError, filePath); errorRecord.ErrorDetails = new ErrorDetails(message); WriteError(errorRecord); continue; } AliasInfo newAlias = new AliasInfo( values[0], values[1], Context, options); if (!String.IsNullOrEmpty(values[2])) { newAlias.Description = values[2]; } result.Add(newAlias); } reader.Dispose(); } return result; } private StreamReader OpenFile(out string filePath, bool isLiteralPath) { StreamReader result = null; filePath = null; ProviderInfo provider = null; Collection<string> paths = null; if (isLiteralPath) { paths = new Collection<string>(); PSDriveInfo drive; paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(this.Path, out provider, out drive)); } else { // first resolve the path paths = SessionState.Path.GetResolvedProviderPathFromPSPath(this.Path, out provider); } // We can only export aliases to the file system if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { throw PSTraceSource.NewNotSupportedException( AliasCommandStrings.ImportAliasFromFileSystemOnly, this.Path, provider.FullName); } // We can only write to a single file at a time. if (paths.Count != 1) { throw PSTraceSource.NewNotSupportedException( AliasCommandStrings.ImportAliasPathResolvedToMultiple, this.Path); } filePath = paths[0]; try { FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); result = new StreamReader(file); } catch (IOException ioException) { ThrowFileOpenError(ioException, filePath); } catch (SecurityException securityException) { ThrowFileOpenError(securityException, filePath); } catch (UnauthorizedAccessException unauthorizedAccessException) { ThrowFileOpenError(unauthorizedAccessException, filePath); } return result; } private void ThrowFileOpenError(Exception e, string pathWithError) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileOpenFailed, pathWithError, e.Message); ErrorRecord errorRecord = new ErrorRecord( e, "FileOpenFailure", ErrorCategory.OpenError, pathWithError); errorRecord.ErrorDetails = new ErrorDetails(message); this.ThrowTerminatingError(errorRecord); } private static bool OnlyContainsWhitespace(string line) { bool result = true; foreach (char c in line) { if (char.IsWhiteSpace(c) && c != '\n' && c != '\r') { continue; } result = false; break; } return result; } #endregion Command code } // class ImportAliasCommand }//Microsoft.PowerShell.Commands
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for JobScheduleOperations. /// </summary> public static partial class JobScheduleOperationsExtensions { /// <summary> /// Delete the job schedule identified by job schedule name. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> public static void Delete(this IJobScheduleOperations operations, string resourceGroupName, string automationAccountName, System.Guid jobScheduleId) { operations.DeleteAsync(resourceGroupName, automationAccountName, jobScheduleId).GetAwaiter().GetResult(); } /// <summary> /// Delete the job schedule identified by job schedule name. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IJobScheduleOperations operations, string resourceGroupName, string automationAccountName, System.Guid jobScheduleId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, automationAccountName, jobScheduleId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve the job schedule identified by job schedule name. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> public static JobSchedule Get(this IJobScheduleOperations operations, string resourceGroupName, string automationAccountName, System.Guid jobScheduleId) { return operations.GetAsync(resourceGroupName, automationAccountName, jobScheduleId).GetAwaiter().GetResult(); } /// <summary> /// Retrieve the job schedule identified by job schedule name. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobSchedule> GetAsync(this IJobScheduleOperations operations, string resourceGroupName, string automationAccountName, System.Guid jobScheduleId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, automationAccountName, jobScheduleId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a job schedule. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> /// <param name='parameters'> /// The parameters supplied to the create job schedule operation. /// </param> public static JobSchedule Create(this IJobScheduleOperations operations, string resourceGroupName, string automationAccountName, System.Guid jobScheduleId, JobScheduleCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, automationAccountName, jobScheduleId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create a job schedule. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='jobScheduleId'> /// The job schedule name. /// </param> /// <param name='parameters'> /// The parameters supplied to the create job schedule operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobSchedule> CreateAsync(this IJobScheduleOperations operations, string resourceGroupName, string automationAccountName, System.Guid jobScheduleId, JobScheduleCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, automationAccountName, jobScheduleId, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of job schedules. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> public static IPage<JobSchedule> ListByAutomationAccount(this IJobScheduleOperations operations, string resourceGroupName, string automationAccountName) { return operations.ListByAutomationAccountAsync(resourceGroupName, automationAccountName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of job schedules. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<JobSchedule>> ListByAutomationAccountAsync(this IJobScheduleOperations operations, string resourceGroupName, string automationAccountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountWithHttpMessagesAsync(resourceGroupName, automationAccountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of job schedules. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </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<JobSchedule> ListByAutomationAccountNext(this IJobScheduleOperations operations, string nextPageLink) { return operations.ListByAutomationAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of job schedules. /// <see href="http://aka.ms/azureautomationsdk/jobscheduleoperations" /> /// </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<JobSchedule>> ListByAutomationAccountNextAsync(this IJobScheduleOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using Semmle.Util.Logging; using System.Linq; using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.IO; using Semmle.Util; using System.Text.RegularExpressions; using Semmle.Autobuild.Shared; namespace Semmle.Autobuild.CSharp { /// <summary> /// A build rule where the build command is of the form "dotnet build". /// Currently unused because the tracer does not work with dotnet. /// </summary> internal class DotNetRule : IBuildRule { public BuildScript Analyse(Autobuilder builder, bool auto) { if (!builder.ProjectsOrSolutionsToBuild.Any()) return BuildScript.Failure; if (auto) { var notDotNetProject = builder.ProjectsOrSolutionsToBuild .SelectMany(p => Enumerators.Singleton(p).Concat(p.IncludedProjects)) .OfType<Project>() .FirstOrDefault(p => !p.DotNetProject); if (notDotNetProject is not null) { builder.Log(Severity.Info, "Not using .NET Core because of incompatible project {0}", notDotNetProject); return BuildScript.Failure; } builder.Log(Severity.Info, "Attempting to build using .NET Core"); } return WithDotNet(builder, (dotNetPath, environment) => { var ret = GetInfoCommand(builder.Actions, dotNetPath, environment); foreach (var projectOrSolution in builder.ProjectsOrSolutionsToBuild) { var cleanCommand = GetCleanCommand(builder.Actions, dotNetPath, environment); cleanCommand.QuoteArgument(projectOrSolution.FullPath); var clean = cleanCommand.Script; var restoreCommand = GetRestoreCommand(builder.Actions, dotNetPath, environment); restoreCommand.QuoteArgument(projectOrSolution.FullPath); var restore = restoreCommand.Script; var build = GetBuildScript(builder, dotNetPath, environment, projectOrSolution.FullPath); ret &= BuildScript.Try(clean) & BuildScript.Try(restore) & build; } return ret; }); } private static BuildScript WithDotNet(Autobuilder builder, Func<string?, IDictionary<string, string>?, BuildScript> f) { var installDir = builder.Actions.PathCombine(builder.Options.RootDirectory, ".dotnet"); var installScript = DownloadDotNet(builder, installDir); return BuildScript.Bind(installScript, installed => { Dictionary<string, string>? env; if (installed == 0) { // The installation succeeded, so use the newly installed .NET Core var path = builder.Actions.GetEnvironmentVariable("PATH"); var delim = builder.Actions.IsWindows() ? ";" : ":"; env = new Dictionary<string, string>{ { "DOTNET_MULTILEVEL_LOOKUP", "false" }, // prevent look up of other .NET Core SDKs { "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "true" }, { "PATH", installDir + delim + path } }; } else { installDir = null; env = null; } if (env is null) env = new Dictionary<string, string>(); env.Add("UseSharedCompilation", "false"); return f(installDir, env); }); } /// <summary> /// Returns a script that attempts to download relevant version(s) of the /// .NET Core SDK, followed by running the script generated by <paramref name="f"/>. /// /// The argument to <paramref name="f"/> is any additional required environment /// variables needed by the installed .NET Core (<code>null</code> when no variables /// are needed). /// </summary> public static BuildScript WithDotNet(Autobuilder builder, Func<IDictionary<string, string>?, BuildScript> f) => WithDotNet(builder, (_1, env) => f(env)); /// <summary> /// Returns a script for downloading relevant versions of the /// .NET Core SDK. The SDK(s) will be installed at <code>installDir</code> /// (provided that the script succeeds). /// </summary> private static BuildScript DownloadDotNet(Autobuilder builder, string installDir) { if (!string.IsNullOrEmpty(builder.Options.DotNetVersion)) // Specific version supplied in configuration: always use that return DownloadDotNetVersion(builder, installDir, builder.Options.DotNetVersion); // Download versions mentioned in `global.json` files // See https://docs.microsoft.com/en-us/dotnet/core/tools/global-json var installScript = BuildScript.Success; var validGlobalJson = false; foreach (var path in builder.Paths.Select(p => p.Item1).Where(p => p.EndsWith("global.json", StringComparison.Ordinal))) { string version; try { var o = JObject.Parse(File.ReadAllText(path)); version = (string)(o?["sdk"]?["version"]!); } catch // lgtm[cs/catch-of-all-exceptions] { // not a valid global.json file continue; } installScript &= DownloadDotNetVersion(builder, installDir, version); validGlobalJson = true; } return validGlobalJson ? installScript : BuildScript.Failure; } /// <summary> /// Returns a script for downloading a specific .NET Core SDK version, if the /// version is not already installed. /// /// See https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-install-script. /// </summary> private static BuildScript DownloadDotNetVersion(Autobuilder builder, string path, string version) { return BuildScript.Bind(GetInstalledSdksScript(builder.Actions), (sdks, sdksRet) => { if (sdksRet == 0 && sdks.Count == 1 && sdks[0].StartsWith(version + " ", StringComparison.Ordinal)) // The requested SDK is already installed (and no other SDKs are installed), so // no need to reinstall return BuildScript.Failure; builder.Log(Severity.Info, "Attempting to download .NET Core {0}", version); if (builder.Actions.IsWindows()) { var psCommand = $"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; &([scriptblock]::Create((Invoke-WebRequest -UseBasicParsing 'https://dot.net/v1/dotnet-install.ps1'))) -Version {version} -InstallDir {path}"; BuildScript GetInstall(string pwsh) => new CommandBuilder(builder.Actions). RunCommand(pwsh). Argument("-NoProfile"). Argument("-ExecutionPolicy"). Argument("unrestricted"). Argument("-Command"). Argument("\"" + psCommand + "\""). Script; return GetInstall("pwsh") | GetInstall("powershell"); } else { var downloadDotNetInstallSh = BuildScript.DownloadFile( "https://dot.net/v1/dotnet-install.sh", "dotnet-install.sh", e => builder.Log(Severity.Warning, $"Failed to download 'dotnet-install.sh': {e.Message}")); var chmod = new CommandBuilder(builder.Actions). RunCommand("chmod"). Argument("u+x"). Argument("dotnet-install.sh"); var install = new CommandBuilder(builder.Actions). RunCommand("./dotnet-install.sh"). Argument("--channel"). Argument("release"). Argument("--version"). Argument(version). Argument("--install-dir"). Argument(path); var removeScript = new CommandBuilder(builder.Actions). RunCommand("rm"). Argument("dotnet-install.sh"); return downloadDotNetInstallSh & chmod.Script & install.Script & BuildScript.Try(removeScript.Script); } }); } private static BuildScript GetInstalledSdksScript(IBuildActions actions) { var listSdks = new CommandBuilder(actions, silent: true). RunCommand("dotnet"). Argument("--list-sdks"); return listSdks.Script; } private static string DotNetCommand(IBuildActions actions, string? dotNetPath) => dotNetPath is not null ? actions.PathCombine(dotNetPath, "dotnet") : "dotnet"; private static BuildScript GetInfoCommand(IBuildActions actions, string? dotNetPath, IDictionary<string, string>? environment) { var info = new CommandBuilder(actions, null, environment). RunCommand(DotNetCommand(actions, dotNetPath)). Argument("--info"); return info.Script; } private static CommandBuilder GetCleanCommand(IBuildActions actions, string? dotNetPath, IDictionary<string, string>? environment) { var clean = new CommandBuilder(actions, null, environment). RunCommand(DotNetCommand(actions, dotNetPath)). Argument("clean"); return clean; } private static CommandBuilder GetRestoreCommand(IBuildActions actions, string? dotNetPath, IDictionary<string, string>? environment) { var restore = new CommandBuilder(actions, null, environment). RunCommand(DotNetCommand(actions, dotNetPath)). Argument("restore"); return restore; } /// <summary> /// Gets the `dotnet build` script. /// </summary> private static BuildScript GetBuildScript(Autobuilder builder, string? dotNetPath, IDictionary<string, string>? environment, string projOrSln) { var build = new CommandBuilder(builder.Actions, null, environment); var script = builder.MaybeIndex(build, DotNetCommand(builder.Actions, dotNetPath)). Argument("build"). Argument("--no-incremental"); return script.Argument("/p:UseSharedCompilation=false"). Argument(builder.Options.DotNetArguments). QuoteArgument(projOrSln). Script; } } }
// 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.Globalization; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Threading; namespace System.Globalization { // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class GregorianCalendar : Calendar { /* A.D. = anno Domini */ public const int ADEra = 1; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal const int MaxYear = 9999; internal GregorianCalendarTypes m_type; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private static volatile Calendar s_defaultInstance; [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (m_type < GregorianCalendarTypes.Localized || m_type > GregorianCalendarTypes.TransliteratedFrench) { throw new SerializationException( String.Format(CultureInfo.CurrentCulture, SR.Serialization_MemberOutOfRange, "type", "GregorianCalendar")); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new GregorianCalendar(); } return (s_defaultInstance); } // Construct an instance of gregorian calendar. public GregorianCalendar() : this(GregorianCalendarTypes.Localized) { } public GregorianCalendar(GregorianCalendarTypes type) { if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException( "type", SR.Format(SR.ArgumentOutOfRange_Range, GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } Contract.EndContractBlock(); this.m_type = type; } public virtual GregorianCalendarTypes CalendarType { get { return (m_type); } set { VerifyWritable(); switch (value) { case GregorianCalendarTypes.Localized: case GregorianCalendarTypes.USEnglish: case GregorianCalendarTypes.MiddleEastFrench: case GregorianCalendarTypes.Arabic: case GregorianCalendarTypes.TransliteratedEnglish: case GregorianCalendarTypes.TransliteratedFrench: m_type = value; break; default: throw new ArgumentOutOfRangeException("m_type", SR.ArgumentOutOfRange_Enum); } } } internal override CalendarId ID { get { // By returning different ID for different variations of GregorianCalendar, // we can support the Transliterated Gregorian calendar. // DateTimeFormatInfo will use this ID to get formatting information about // the calendar. return ((CalendarId)m_type); } } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear ? DaysToMonth366 : DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal virtual long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day) * TicksPerDay); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } Contract.EndContractBlock(); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { if (era == CurrentEra || era == ADEra) { if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException("year", SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return (days[month] - days[month - 1]); } throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365); } throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (ADEra); } public override int[] Eras { get { return (new int[] { ADEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (12); } throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } Contract.EndContractBlock(); if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( "year", SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (day < 1 || day > GetDaysInMonth(year, month)) { throw new ArgumentOutOfRangeException("day", SR.Format(SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month))); } if (!IsLeapYear(year)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } Contract.EndContractBlock(); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } Contract.EndContractBlock(); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (era == CurrentEra || era == ADEra) { return new DateTime(year, month, day, hour, minute, second, millisecond); } throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { if (era == CurrentEra || era == ADEra) { try { result = new DateTime(year, month, day, hour, minute, second, millisecond); return true; } catch (ArgumentOutOfRangeException) { result = DateTime.Now; return false; } catch (ArgumentException) { result = DateTime.Now; return false; } } result = DateTime.MinValue; return false; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } return (base.ToFourDigitYear(year)); } } }
// // PeerBEncryption.cs // // Authors: // Yiduo Wang [email protected] // Alan McGovern [email protected] // // Copyright (C) 2007 Yiduo Wang // // 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.Text; using OctoTorrent.Common; using OctoTorrent.Client.Messages; namespace OctoTorrent.Client.Encryption { /// <summary> /// Class to handle message stream encryption for receiving connections /// </summary> class PeerBEncryption : EncryptedSocket { private readonly InfoHash[] _possibleSKEYs; private byte[] _verifyBytes; private readonly AsyncCallback _gotVerificationCallback; private readonly AsyncCallback _gotPadCCallback; public PeerBEncryption(InfoHash[] possibleSKEYs, EncryptionTypes allowedEncryption) : base(allowedEncryption) { _possibleSKEYs = possibleSKEYs; _gotVerificationCallback = GotVerification; _gotPadCCallback = gotPadC; } protected override void doneReceiveY() { try { base.doneReceiveY(); // 1 A->B: Diffie Hellman Ya, PadA byte[] req1 = Hash(Encoding.ASCII.GetBytes("req1"), S); Synchronize(req1, 628); // 3 A->B: HASH('req1', S) } catch (Exception ex) { AsyncResult.Complete(ex); } } protected override void DoneSynchronize() { try { base.DoneSynchronize(); _verifyBytes = new byte[20 + VerificationConstant.Length + 4 + 2]; // ... HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)) ReceiveMessage(_verifyBytes, _verifyBytes.Length, _gotVerificationCallback); } catch (Exception ex) { AsyncResult.Complete(ex); } } byte[] _b; private void GotVerification(IAsyncResult result) { try { var torrentHash = new byte[20]; var myVC = new byte[8]; var myCP = new byte[4]; var lenPadC = new byte[2]; Array.Copy(_verifyBytes, 0, torrentHash, 0, torrentHash.Length); // HASH('req2', SKEY) xor HASH('req3', S) if (!MatchSKEY(torrentHash)) { AsyncResult.Complete(new EncryptionException("No valid SKey found")); return; } CreateCryptors("keyB", "keyA"); DoDecrypt(_verifyBytes, 20, 14); // ENCRYPT(VC, ... Array.Copy(_verifyBytes, 20, myVC, 0, myVC.Length); if (!Toolbox.ByteMatch(myVC, VerificationConstant)) { AsyncResult.Complete(new EncryptionException("Verification constant was invalid")); return; } Array.Copy(_verifyBytes, 28, myCP, 0, myCP.Length); // ...crypto_provide ... // We need to select the crypto *after* we send our response, otherwise the wrong // encryption will be used on the response _b = myCP; Array.Copy(_verifyBytes, 32, lenPadC, 0, lenPadC.Length); // ... len(padC) ... PadC = new byte[DeLen(lenPadC) + 2]; ReceiveMessage(PadC, PadC.Length, _gotPadCCallback); // padC } catch (Exception ex) { AsyncResult.Complete(ex); } } private void gotPadC(IAsyncResult result) { try { DoDecrypt(PadC, 0, PadC.Length); byte[] lenInitialPayload = new byte[2]; // ... len(IA)) Array.Copy(PadC, PadC.Length - 2, lenInitialPayload, 0, 2); RemoteInitialPayload = new byte[DeLen(lenInitialPayload)]; // ... ENCRYPT(IA) ReceiveMessage(RemoteInitialPayload, RemoteInitialPayload.Length, gotInitialPayload); } catch (Exception ex) { AsyncResult.Complete(ex); } } private void gotInitialPayload(IAsyncResult result) { try { DoDecrypt(RemoteInitialPayload, 0, RemoteInitialPayload.Length); // ... ENCRYPT(IA) StepFour(); } catch (Exception ex) { AsyncResult.Complete(ex); } } private void StepFour() { try { byte[] padD = GeneratePad(); SelectCrypto(_b, false); // 4 B->A: ENCRYPT(VC, crypto_select, len(padD), padD) byte[] buffer = new byte[VerificationConstant.Length + CryptoSelect.Length + 2 + padD.Length]; int offset = 0; offset += Message.Write(buffer, offset, VerificationConstant); offset += Message.Write(buffer, offset, CryptoSelect); offset += Message.Write(buffer, offset, Len(padD)); offset += Message.Write(buffer, offset, padD); DoEncrypt(buffer, 0, buffer.Length); SendMessage(buffer); SelectCrypto(_b, true); Ready(); } catch (Exception ex) { AsyncResult.Complete(ex); } } /// <summary> /// Matches a torrent based on whether the HASH('req2', SKEY) xor HASH('req3', S) matches, where SKEY is the InfoHash of the torrent /// and sets the SKEY to the InfoHash of the matched torrent. /// </summary> /// <returns>true if a match has been found</returns> private bool MatchSKEY(byte[] torrentHash) { try { foreach (var infoHash in _possibleSKEYs) { byte[] req2 = Hash(Encoding.ASCII.GetBytes("req2"), infoHash.Hash); byte[] req3 = Hash(Encoding.ASCII.GetBytes("req3"), S); bool match = true; for (int j = 0; j < req2.Length && match; j++) match = torrentHash[j] == (req2[j] ^ req3[j]); if (match) { SKEY = infoHash; return true; } } } catch (Exception ex) { AsyncResult.Complete(ex); } return false; } } }
// 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; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; using WebsitePanel.Portal; using WebsitePanel.Providers.HeliconZoo; using WebsitePanel.Server; public partial class HeliconZoo_Settings : WebsitePanelControlBase, IHostingServiceProviderSettings { private class EnvBoxPair { public TextBox Name; public TextBox Value; public EnvBoxPair(TextBox name, TextBox value) { Name = name; Value = value; } } private EnvBoxPair[] _envBoxsPair; protected void Page_Load(object sender, EventArgs e) { _envBoxsPair = new EnvBoxPair[] { new EnvBoxPair(EnvKey1, EnvValue1), new EnvBoxPair(EnvKey2, EnvValue2), new EnvBoxPair(EnvKey3, EnvValue3), new EnvBoxPair(EnvKey4, EnvValue4), new EnvBoxPair(EnvKey5, EnvValue5), new EnvBoxPair(EnvKey6, EnvValue6), new EnvBoxPair(EnvKey7, EnvValue7), new EnvBoxPair(EnvKey8, EnvValue8), }; if (!IsPostBack) { BindHostingPackages(); EngineTransport.Items.Clear(); EngineTransport.Items.AddRange( new ListItem[] { new ListItem("Named pipe", "namedpipe"), new ListItem("TCP", "tcp"), } ); EngineProtocol.Items.Clear(); EngineProtocol.Items.AddRange( new ListItem[] { new ListItem("FastCGI", "fastcgi"), new ListItem("HTTP", "http"), } ); BindEngines(); } } private void BindHostingPackages() { WPIProduct[] products = null; try { products = GetHostingPackages(); } catch(Exception e) { HostingPackagesGrid.Visible = false; HostingPackagesInstallButtonsPanel.Visible = false; HostingPackagesErrorsPanel.Visible = true; if (e.InnerException != null) { e = e.InnerException; } HostingPackagesLoadingError.Text = e.Message; } HostingPackagesGrid.DataSource = products; HostingPackagesGrid.DataBind(); } private void BindEngines() { WPIProduct zooModule = ES.Services.Servers.GetWPIProductById(PanelRequest.ServerId, "HeliconZooModule"); if (!zooModule.IsInstalled || zooModule.IsUpgrade) { HostModule.ShowWarningMessage("Zoo Module is not installed or out-of-date. To proceed press 'Add' or 'Update' next to Helicon Zoo Module below, then press 'Install'."); } // get all engines from IIS HeliconZooEngine[] engineList = ES.Services.HeliconZoo.GetEngines(PanelRequest.ServiceId); if (null != engineList && engineList.Length > 0) { // convert list to dict Dictionary<string, HeliconZooEngine> enginesDict = new Dictionary<string, HeliconZooEngine>(); foreach (HeliconZooEngine engine in engineList) { enginesDict[engine.name] = engine; } // save engines in view state ViewState["HeliconZooEngines"] = enginesDict; // bind to grid EngineGrid.DataSource = engineList; EngineGrid.DataBind(); // bind 'Enable quotas' checkbox bool enabled = ES.Services.HeliconZoo.IsEnginesEnabled(PanelRequest.ServiceId); QuotasEnabled.Checked = !enabled; WebCosoleEnabled.Checked = ES.Services.HeliconZoo.IsWebCosoleEnabled(PanelRequest.ServiceId); } else { EnginesPanel.Visible = false; } } private void RebindEngines() { Dictionary<string, HeliconZooEngine> engines = GetEngines(); EngineGrid.DataSource = engines.Values; EngineGrid.DataBind(); } public void BindSettings(StringDictionary settings) { } public void SaveSettings(StringDictionary settings) { // save engines ES.Services.HeliconZoo.SetEngines(PanelRequest.ServiceId, new List<HeliconZooEngine>(GetEngines().Values).ToArray()); // save switcher ES.Services.HeliconZoo.SwithEnginesEnabled(PanelRequest.ServiceId, !QuotasEnabled.Checked); ES.Services.HeliconZoo.SetWebCosoleEnabled(PanelRequest.ServiceId, WebCosoleEnabled.Checked); } protected void ClearEngineForm() { EngineName.Text = string.Empty; EngineFriendlyName.Text = string.Empty; EngineFullPath.Text = string.Empty; EngineArguments.Text = string.Empty; EngineProtocol.SelectedIndex = 0; EngineTransport.SelectedIndex = 0; foreach (EnvBoxPair envBoxPair in _envBoxsPair) { envBoxPair.Name.Text = string.Empty; envBoxPair.Value.Text = string.Empty; } } protected void ShowEngineForm() { EngineForm.Visible = true; EngineFormButtons.Visible = true; } protected void HideEngineForm() { EngineForm.Visible = false; EngineFormButtons.Visible = false; } protected void ButtonAddEngine_Click(object sender, EventArgs e) { ClearEngineForm(); ShowEngineForm(); } protected void ButtonSaveEngine_Click(object sender, EventArgs e) { HeliconZooEngine engine = EngineFromForm(); HeliconZooEngine savedEngine = FindEngineByName(engine.name); Dictionary<string, HeliconZooEngine> engines = GetEngines(); // new user engine or update existing engines[engine.name] = engine; ClearEngineForm(); HideEngineForm(); // rebind grid RebindEngines(); } public static long ParseLong(string s, long deflt) { long result; if (!long.TryParse(s, out result)) { result = deflt; } return result; } private HeliconZooEngine EngineFromForm() { HeliconZooEngine engine = new HeliconZooEngine() { name = EngineName.Text.Trim(), displayName = EngineFriendlyName.Text.Trim(), arguments = EngineArguments.Text.Trim(), fullPath = EngineFullPath.Text.Trim(), transport = EngineTransport.SelectedValue, protocol = EngineProtocol.SelectedValue, portLower = ParseLong(EnginePortLower.Text, -1), portUpper = ParseLong(EnginePortUpper.Text, -1), minInstances = ParseLong(EngineMinInstances.Text, -1), maxInstances = ParseLong(EngineMaxInstances.Text, -1), timeLimit = ParseLong(EngineTimeLimit.Text, -1), gracefulShutdownTimeout = ParseLong(EngineGracefulShutdownTimeout.Text, -1), memoryLimit = ParseLong(EngineMemoryLimit.Text, -1), isUserEngine = true }; // envs List<HeliconZooEnv> tempEnvList = new List<HeliconZooEnv>(); for (int i = 0; i < _envBoxsPair.Length; i++) { EnvBoxPair pair = _envBoxsPair[i]; if (!string.IsNullOrEmpty(pair.Name.Text.Trim()) && !string.IsNullOrEmpty(pair.Value.Text.Trim())) { tempEnvList.Add(new HeliconZooEnv(){Name = pair.Name.Text.Trim(), Value = pair.Value.Text.Trim()}); } } engine.environmentVariables = tempEnvList.ToArray(); return engine; } protected void ButtonCancelEngineForm_Click(object sender, EventArgs e) { ClearEngineForm(); HideEngineForm(); } protected void EngineGrid_OnRowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "EngineEdit") { HeliconZooEngine engine = FindEngineByName((string)e.CommandArgument); if (null != engine) { BindEngineForm(engine); ShowEngineForm(); } } if (e.CommandName == "EngineDisable") { HeliconZooEngine engine = FindEngineByName((string)e.CommandArgument); if (null != engine) { engine.disabled = !engine.disabled; RebindEngines(); } } if (e.CommandName == "EngineDelete") { HeliconZooEngine engine = FindEngineByName((string)e.CommandArgument); if (null != engine) { Dictionary<string, HeliconZooEngine> engines = GetEngines(); engines.Remove(engine.name); RebindEngines(); } } } public static string ToStringClearDeafult(long l) { if (-1 == l) { return string.Empty; } return l.ToString(CultureInfo.InvariantCulture); } private void BindEngineForm(HeliconZooEngine engine) { EngineName.Text = engine.name; EngineFriendlyName.Text = engine.displayName; EngineFullPath.Text = engine.fullPath; EngineArguments.Text = engine.arguments; EngineTransport.Text = engine.transport.ToLower(); EngineProtocol.Text = engine.protocol.ToLower(); EnginePortLower.Text = ToStringClearDeafult(engine.portLower); EnginePortUpper.Text = ToStringClearDeafult(engine.portUpper); EngineMinInstances.Text = ToStringClearDeafult(engine.minInstances); EngineMaxInstances.Text = ToStringClearDeafult(engine.maxInstances); EngineTimeLimit.Text = ToStringClearDeafult(engine.timeLimit); EngineGracefulShutdownTimeout.Text = ToStringClearDeafult(engine.gracefulShutdownTimeout); EngineMemoryLimit.Text = ToStringClearDeafult(engine.memoryLimit); for (int i = 0; i < engine.environmentVariables.Length && i < _envBoxsPair.Length; i++) { HeliconZooEnv env = engine.environmentVariables[i]; _envBoxsPair[i].Name.Text = env.Name; _envBoxsPair[i].Value.Text = env.Value; } } private Dictionary<string, HeliconZooEngine> GetEngines() { return ViewState["HeliconZooEngines"] as Dictionary<string, HeliconZooEngine>; } private HeliconZooEngine FindEngineByName(string engineName) { Dictionary<string, HeliconZooEngine> engines = GetEngines(); if (null != engines) { if (engines.ContainsKey(engineName)) { return engines[engineName]; } } return null; } protected void HostingPackagesGrid_OnRowCommand(object sender, GridViewCommandEventArgs e) { ArrayList wpiProductsForInstall = GetProductsToInstallList(); int productIndex = int.Parse((string)e.CommandArgument); WPIProduct wpiProduct = GetHostingPackages()[productIndex]; if (null != wpiProduct) { if (e.CommandName == "WpiAdd") { wpiProductsForInstall = GetProductsToInstallList(); wpiProductsForInstall.Add(wpiProduct.ProductId); SetProductsToInstallList(wpiProductsForInstall); ((Button)e.CommandSource).Text = AddUpgradeRemoveText(wpiProduct); ; ((Button)e.CommandSource).CommandName = "WpiRemove"; } if (e.CommandName == "WpiRemove") { wpiProductsForInstall = GetProductsToInstallList(); wpiProductsForInstall.Remove(wpiProduct.ProductId); SetProductsToInstallList(wpiProductsForInstall); ((Button)e.CommandSource).Text = AddUpgradeRemoveText(wpiProduct); ((Button)e.CommandSource).CommandName = "WpiAdd"; } btnInstall.Enabled = wpiProductsForInstall.Count > 0; } } private ArrayList GetProductsToInstallList() { if (ViewState["wpiProductsForInstall"] != null) { return (ArrayList)ViewState["wpiProductsForInstall"]; } return new ArrayList(); } private void SetProductsToInstallList(ArrayList wpiProductsForInstall) { ViewState["wpiProductsForInstall"] = wpiProductsForInstall; } private WPIProduct[] GetHostingPackages() { if (ViewState["HeliconZooHostingPackages"] == null) { ViewState["HeliconZooHostingPackages"] = RequestHostingPackages(); } return (WPIProduct[])ViewState["HeliconZooHostingPackages"]; } private static WPIProduct[] RequestHostingPackages() { List<WPIProduct> result = new List<WPIProduct>(); result.Add(ES.Services.Servers.GetWPIProductById(PanelRequest.ServerId, "HeliconZooModule")); result.AddRange(ES.Services.Servers.GetWPIProducts(PanelRequest.ServerId, null, "ZooPackage")); return result.ToArray(); } protected string AddUpgradeRemoveText(WPIProduct wpiProduct) { if (GetProductsToInstallList().Contains(wpiProduct.ProductId)) { return "- cancel"; } else { return wpiProduct.IsUpgrade ? "+ upgrade" : "+ add"; } } protected void btnInstall_Click(object sender, EventArgs e) { ArrayList wpiProductsForInstall = GetProductsToInstallList(); List<string> qsParts = new List<string>(); qsParts.Add("pid=Servers"); qsParts.Add("ctl=edit_platforminstaller"); qsParts.Add("mid=" + Request.QueryString["mid"]); qsParts.Add("ServerID=" + Request.QueryString["ServerID"]); qsParts.Add("WPIProduct=" + string.Join(",", wpiProductsForInstall.ToArray())); qsParts.Add("ReturnUrl=" + Server.UrlEncode(Request.RawUrl)); string installUrl = "Default.aspx?" + String.Join("&", qsParts.ToArray()); Response.Redirect(installUrl); } }
//============================================================================== // TorqueLab -> // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== //============================================================================== // DetailTree Init //============================================================================== //============================================================================== function ShapeLab_DetailTree::onDefineIcons(%this) { // Set the tree view icon indices and texture paths %this._imageNone = 0; %this._imageHidden = 1; %icons = ":" @ // no icon "tlab/art/buttons/default/visible_i:"; // hidden %this.buildIconTable( %icons ); } //------------------------------------------------------------------------------ //============================================================================== // DetailTree Functions //============================================================================== //============================================================================== function ShapeLab_DetailTree::onSelect( %this, %id ) { %name = %this.getItemText( %id ); %value = %this.getItemValue( %id ); %baseName = stripTrailingNumber( %name ); %size = getTrailingNumber( %name ); ShapeLabDetails-->meshName.setText( %baseName ); ShapeLabDetails-->meshSize.setText( %size ); // Select the appropriate detail level %dl = %this.getDetailLevelFromItem( %id ); ShapeLabShapeView.currentDL = %dl; devLog("ShapeLab_DetailTree onSelect ID:",%id,"Text",%name,"Value",%value); //Check if it's a detail node, Mesh can't have childs if ( ShapeLab_DetailTree.isParentItem( %id ) ) { // Selected a detail => disable mesh controls ShapeLabDetails-->editMeshActive.setVisible( false ); ShapeLabShapeView.selectedObject = -1; ShapeLabShapeView.selectedObjDetail = 0; } else { // Selected a mesh => sync mesh controls ShapeLabDetails-->editMeshActive.setVisible( true ); switch$ ( ShapeLab.shape.getMeshType( %name ) ) { case "normal": ShapeLabDetails-->bbType.setSelected( 0, false ); case "billboard": ShapeLabDetails-->bbType.setSelected( 1, false ); case "billboardzaxis": ShapeLabDetails-->bbType.setSelected( 2, false ); } %node = ShapeLab.shape.getObjectNode( %baseName ); if ( %node $= "" ) %node = "<root>"; ShapeLabDetails-->objectNode.setSelected( ShapeLabDetails-->objectNode.findText( %node ), false ); ShapeLabShapeView.selectedObject = ShapeLab.shape.getObjectIndex( %baseName ); ShapeLabShapeView.selectedObjDetail = %dl; } } //------------------------------------------------------------------------------ //============================================================================== function ShapeLab_DetailTree::onRightMouseUp( %this, %itemId, %mouse ) { // Open context menu if this is a Mesh item if ( !%this.isParentItem( %itemId ) ) { if( !isObject( "ShapeLabMeshPopup" ) ) { new PopupMenu( ShapeLabMeshPopup ) { superClass = "MenuBuilder"; isPopup = "1"; item[ 0 ] = "Hidden" TAB "" TAB "ShapeLab_DetailTree.onHideMeshItem( %this._objName, !%this._itemHidden );"; item[ 1 ] = "-"; item[ 2 ] = "Hide all" TAB "" TAB "ShapeLab_DetailTree.onHideMeshItem( \"\", true );"; item[ 3 ] = "Show all" TAB "" TAB "ShapeLab_DetailTree.onHideMeshItem( \"\", false );"; }; } ShapeLabMeshPopup._objName = stripTrailingNumber( %this.getItemText( %itemId ) ); ShapeLabMeshPopup._itemHidden = ShapeLabShapeView.getMeshHidden( ShapeLabMeshPopup._objName ); ShapeLabMeshPopup.checkItem( 0, ShapeLabMeshPopup._itemHidden ); ShapeLabMeshPopup.showPopup( Canvas ); } } //------------------------------------------------------------------------------ //============================================================================== function ShapeLab_DetailTree::addMeshEntry( %this, %name, %noSync ) { // Add new detail level if required //Get the Detail Size by getting the ending numbers %size = getTrailingNumber( %name ); //Find a detail item for this size (detailSIZE) %detailID = %this.findItemByValue( %size ); //If no detail item foound create one if ( %detailID <= 0 ) { %detailID = %this.addDetailEntry(%size,%noSync); } return %this.insertItem( %detailID, %name, "M_"@%size, "" ); } //------------------------------------------------------------------------------ //============================================================================== function ShapeLab_DetailTree::addDetailEntry( %this, %size, %noSync ) { %dl = ShapeLab.shape.getDetailLevelIndex( %size ); %detName = ShapeLab.shape.getDetailLevelName( %dl ); %detailID = ShapeLab_DetailTree.insertItem( 1, %detName, %size, "" ); %this.reorderDetails(%detailID,%size); if ( !%noSync ) ShapeLab.updateDetail(); return %detailID; } //------------------------------------------------------------------------------ //============================================================================== function ShapeLab_DetailTree::reorderDetails( %this, %detailID, %size ) { // Sort details by decreasing size for ( %sibling = ShapeLab_DetailTree.getPrevSibling( %detailID ); ( %sibling > 0 ) && ( ShapeLab_DetailTree.getItemValue( %sibling ) < %size ); %sibling = ShapeLab_DetailTree.getPrevSibling( %detailID ) ) ShapeLab_DetailTree.moveItemUp( %detailID ); } //------------------------------------------------------------------------------ //============================================================================== function ShapeLab_DetailTree::removeMeshItem( %this, %id, %name, %size ) { //%size = getTrailingNumber( %name ); //Check if collision mesh if (%id >= 0) %this.removeItem( %id ); ShapeLabDetails.selectedShapeChanged(); } //------------------------------------------------------------------------------ //============================================================================== function ShapeLab_DetailTree::removeMeshEntry( %this, %name, %size ) { //%size = getTrailingNumber( %name ); //Check if collision mesh if (%size < 0) %this.removeItem( %id ); %id = ShapeLab_DetailTree.findItemByName( %name ); if ( ShapeLab.shape.getDetailLevelIndex( %size ) < 0 ) { // Last mesh of a detail level has been removed => remove the detail level %this.removeItem( %this.getParent( %id ) ); ShapeLab.updateDetail(); } else %this.removeItem( %id ); } //------------------------------------------------------------------------------ //============================================================================== function ShapeLab_DetailTree::onHideMeshItem( %this, %objName, %hide ) { if ( %hide ) %imageId = %this._imageHidden; else %imageId = %this._imageNone; if ( %objName $= "" ) { // Show/hide all ShapeLabShapeView.setAllMeshesHidden( %hide ); for ( %parent = %this.getChild(%this.getFirstRootItem()); %parent > 0; %parent = %this.getNextSibling(%parent) ) for ( %child = %this.getChild(%parent); %child > 0; %child = %this.getNextSibling(%child) ) %this.setItemImages( %child, %imageId, %imageId ); } else { // Show/hide all meshes for this object ShapeLabShapeView.setMeshHidden( %objName, %hide ); %count = ShapeLab.shape.getMeshCount( %objName ); for ( %i = 0; %i < %count; %i++ ) { %meshName = ShapeLab.shape.getMeshName( %objName, %i ); %id = ShapeLab_DetailTree.findItemByName( %meshName ); if ( %id > 0 ) %this.setItemImages( %id, %imageId, %imageId ); } } } //------------------------------------------------------------------------------ //============================================================================== function ShapeLab_DetailTree::onDeleteObject( %this, %obj ) { devLog("ShapeLab_DetailTree::onDeleteObject OBJ:",%obj); } function ShapeLab_DetailTree::onDeleteSelection( %this ) { devLog("ShapeLab_DetailTree::onDeleteSelection"); } //============================================================================== // DetailTree Helpers //============================================================================== //============================================================================== // Get the detail level index from the ID of an item in the details tree view function ShapeLab_DetailTree::getDetailLevelFromItem( %this, %id ) { devLog("ShapeLab_DetailTree::getDetailLevelFromItem ID:",%id,"IsDetaik",%this.isParentItem( %id )); //Get detailSize (Mesh have a M_ prefix before detailSize so replace it with "" %detSize = strreplace(ShapeLab_DetailTree.getItemValue( %id ),"M_",""); devLog("ShapeLab_DetailTree::getDetailLevelFromItem Detail:",%detSize); return ShapeLab.shape.getDetailLevelIndex( %detSize ); } //------------------------------------------------------------------------------
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Input; using ActiproSoftware.Windows.Extensions; using ArcGIS.Core.CIM; using ArcGIS.Core.Data; using ArcGIS.Desktop.Catalog; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Core.Events; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Internal.Core; using ArcGIS.Desktop.Mapping; using Newtonsoft.Json.Linq; using MessageBox = ArcGIS.Desktop.Framework.Dialogs.MessageBox; namespace DynamicJoins { internal class JoinsDockpaneViewModel : DockPane { #region Private members private const string _dockPaneID = "DynamicJoins_JoinsDockpane"; private string _heading = "Joins DockPane"; private ICommand _cmdGenerateJoin; private ICommand _cmdClearJoin; private Field _leftField; private Field _rightField; private GDBProjectItem _selectedLeftGDBProjectItem; private GDBProjectItem _selectedRightGDBProjectItem; private TableInfo _selectedLeftTable; private TableInfo _selectedRightTable; private Visibility _visibleRelationship = Visibility.Hidden; private readonly object _lockCollection = new object(); private readonly ObservableCollection<GDBProjectItem> _leftGdbProjectItems = new ObservableCollection<GDBProjectItem>(); private readonly ObservableCollection<TableInfo> _leftTables = new ObservableCollection<TableInfo>(); private readonly ObservableCollection<FieldListItem> _leftFields = new ObservableCollection<FieldListItem>(); private readonly ObservableCollection<GDBProjectItem> _rightGdbProjectItems = new ObservableCollection<GDBProjectItem>(); private readonly ObservableCollection<TableInfo> _rightTables = new ObservableCollection<TableInfo>(); private readonly ObservableCollection<FieldListItem> _rightFields = new ObservableCollection<FieldListItem>(); #endregion Private members private static bool IsOnUiThread => ArcGIS.Desktop.Framework.FrameworkApplication.TestMode || System.Windows.Application.Current.Dispatcher.CheckAccess(); protected JoinsDockpaneViewModel() { BindingOperations.EnableCollectionSynchronization(_leftGdbProjectItems, _lockCollection); BindingOperations.EnableCollectionSynchronization(_leftTables, _lockCollection); BindingOperations.EnableCollectionSynchronization(_leftFields, _lockCollection); BindingOperations.EnableCollectionSynchronization(_rightGdbProjectItems, _lockCollection); BindingOperations.EnableCollectionSynchronization(_rightTables, _lockCollection); BindingOperations.EnableCollectionSynchronization(_rightFields, _lockCollection); ProjectItemsChangedEvent.Subscribe(OnProjectCollectionChanged, false); RefreshDatabaseItems(); } public ObservableCollection<GDBProjectItem> LeftDataItems => _leftGdbProjectItems; public ObservableCollection<GDBProjectItem> RightDataItems => _rightGdbProjectItems; public GDBProjectItem SelectedLeftGDBProjectItem { get { return _selectedLeftGDBProjectItem; } set { SetProperty(ref _selectedLeftGDBProjectItem, value, () => SelectedLeftGDBProjectItem); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed UpdateTables(SelectedLeftGDBProjectItem, _leftTables); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } public GDBProjectItem SelectedRightGDBProjectItem { get { return _selectedRightGDBProjectItem; } set { SetProperty(ref _selectedRightGDBProjectItem, value, () => SelectedRightGDBProjectItem); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed UpdateTables(SelectedRightGDBProjectItem, _rightTables); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } public ObservableCollection<TableInfo> LeftTables => _leftTables; public ObservableCollection<TableInfo> RightTables => _rightTables; public TableInfo SelectedLeftTable { get { return _selectedLeftTable; } set { SetProperty(ref _selectedLeftTable, value, () => SelectedLeftTable); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed UpdateFields(SelectedLeftTable, _leftFields); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } public TableInfo SelectedRightTable { get { return _selectedRightTable; } set { SetProperty(ref _selectedRightTable, value, () => SelectedRightTable); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed UpdateFields(SelectedRightTable, _rightFields); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } public ObservableCollection<FieldListItem> LeftFields => _leftFields; public ObservableCollection<FieldListItem> RightFields => _rightFields; public FieldListItem SelectedLeftField { set { LeftField = value?.Field?.Name; } } public FieldListItem SelectedRightField { set { RightField = value?.Field?.Name; } } public Visibility VisibleRelationship { get { return _visibleRelationship; } set { SetProperty(ref _visibleRelationship, value, () => VisibleRelationship); } } public ICommand CmdClearJoin { get { return _cmdClearJoin ?? (_cmdClearJoin = new RelayCommand(() => { LeftField = null; RightField = null; }, () => !string.IsNullOrEmpty(LeftField) || !string.IsNullOrEmpty(RightField))); } } public String LayerName { get; set; } public bool IsLeftOuterJoin { get; set; } public string LeftField { get { return _leftField?.Name; } set { if (string.IsNullOrEmpty(value)) { _leftField = null; } else { var field = LeftFields.FirstOrDefault((f) => f.Name == value); _leftField = field.Field; } NotifyPropertyChanged(() => LeftField); VisibleRelationship = string.IsNullOrEmpty(LeftField) && string.IsNullOrEmpty(RightField) ? Visibility.Hidden : Visibility.Visible; } } public string RightField { get { return _rightField?.Name; } set { if (string.IsNullOrEmpty(value)) { _rightField = null; } else { var field = RightFields.FirstOrDefault((f) => f.Name == value); _rightField = field.Field; } NotifyPropertyChanged(() => RightField); VisibleRelationship = string.IsNullOrEmpty(LeftField) && string.IsNullOrEmpty(RightField) ? Visibility.Hidden : Visibility.Visible; } } public List<CardinalityInfo> Cardinalities => new List<CardinalityInfo> { new CardinalityInfo {Name = "OneToOne", RelationshipCardinality = RelationshipCardinality.OneToOne}, new CardinalityInfo {Name = "OneToMany", RelationshipCardinality = RelationshipCardinality.OneToMany}, new CardinalityInfo {Name = "ManyToMany", RelationshipCardinality = RelationshipCardinality.ManyToMany} }; public CardinalityInfo SelectedCardinality { get; set; } public ICommand CmdGenerateJoin { get { return _cmdGenerateJoin ?? (_cmdGenerateJoin = new RelayCommand(() => { QueuedTask.Run(() => { Table leftTable = null; Table rightTable = null; RelationshipClass relationshipClass = null; try { leftTable = GetTable(SelectedLeftGDBProjectItem, SelectedLeftTable); rightTable = GetTable(SelectedRightGDBProjectItem, SelectedRightTable); if (leftTable.GetDatastore().GetConnectionString().Equals(rightTable.GetDatastore().GetConnectionString())) { string commaSeparatedFields = null; if (LeftFields.Count > 1 || RightFields.Count > 1) { var fields = new List<string>(); fields.AddRange(LeftFields.Select(item => $"{leftTable.GetName()}.{item.Field.Name}")); fields.AddRange(RightFields.Select(item => $"{rightTable.GetName()}.{item.Field.Name}")); var stringBuilder = new StringBuilder(); foreach (var field in fields) stringBuilder.Append(field).Append(","); stringBuilder.Remove(stringBuilder.Length - 1, 1); commaSeparatedFields = stringBuilder.ToString(); } if (leftTable.GetDatastore() is Geodatabase && rightTable.GetDatastore() is Geodatabase) { MakeQueryTableLayer(leftTable, rightTable, commaSeparatedFields); return; } if (leftTable.GetDatastore() is Database && rightTable.GetDatastore() is Database) { MakeQueryLayer(commaSeparatedFields, leftTable, rightTable); return; } } relationshipClass = MakeJoin(relationshipClass, leftTable, rightTable); } catch (Exception e) { } finally { leftTable?.Dispose(); rightTable?.Dispose(); relationshipClass?.Dispose(); } }); }, () => !string.IsNullOrEmpty(LeftField) && !string.IsNullOrEmpty(RightField) && !string.IsNullOrEmpty(LayerName))); } } private void MakeQueryLayer(string commaSeparatedFields, Table leftTable, Table rightTable) { string fields = string.IsNullOrEmpty(commaSeparatedFields) ? "*" : commaSeparatedFields; var database = leftTable.GetDatastore() as Database; var joinClause = IsLeftOuterJoin ? $"{leftTable.GetName()} LEFT OUTER JOIN {rightTable.GetName()} ON {leftTable.GetName()}.{_leftField.Name} = {rightTable.GetName()}.{_rightField.Name}" : $"{leftTable.GetName()} INNER JOIN {rightTable.GetName()} ON {leftTable.GetName()}.{_leftField.Name} = {rightTable.GetName()}.{_rightField.Name}"; var queryDescription = database.GetQueryDescription($"SELECT {fields} FROM {joinClause}", LayerName); var table = database.OpenTable(queryDescription); LayerFactory.Instance.CreateFeatureLayer(table as FeatureClass, MapView.Active.Map, 0, LayerName); } private RelationshipClass MakeJoin(RelationshipClass relationshipClass, Table leftTable, Table rightTable) { var virtualRelationshipClassDescription = new VirtualRelationshipClassDescription(_leftField, _rightField, SelectedCardinality.RelationshipCardinality); relationshipClass = leftTable.RelateTo(rightTable, virtualRelationshipClassDescription); var joinDescription = new JoinDescription(relationshipClass) { JoinDirection = JoinDirection.Forward }; joinDescription.JoinType = IsLeftOuterJoin ? JoinType.LeftOuterJoin : JoinType.InnerJoin; if (LeftFields.Count > 1) joinDescription.TargetFields = LeftFields.Select(item => item.Field).ToList(); var join = new Join(joinDescription); var joinedTable = @join.GetJoinedTable(); if (joinedTable is FeatureClass) LayerFactory.Instance.CreateFeatureLayer(joinedTable as FeatureClass, MapView.Active.Map, 0, LayerName); return relationshipClass; } private void RefreshDatabaseItems() { _leftGdbProjectItems.Clear(); _rightGdbProjectItems.Clear(); QueuedTask.Run(() => { var gdbProjectItems = Project.Current.GetItems<GDBProjectItem>(); foreach (var candidate in gdbProjectItems) { if (!_leftGdbProjectItems.Any( gdbProjectItem => gdbProjectItem.GetDatastore().GetConnectionString().Equals(candidate.GetDatastore().GetConnectionString()))) _leftGdbProjectItems.Add(candidate); if (!_rightGdbProjectItems.Any( gdbProjectItem => gdbProjectItem.GetDatastore().GetConnectionString().Equals(candidate.GetDatastore().GetConnectionString()))) _rightGdbProjectItems.Add(candidate); } }); } private void OnProjectCollectionChanged(ProjectItemsChangedEventArgs args) { var dataItem = args?.ProjectItem as GDBProjectItem; if (dataItem == null) return; QueuedTask.Run(() => { switch (args.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Add: { if (!_leftGdbProjectItems.Any( gdbProjectItem => gdbProjectItem.GetDatastore().GetConnectionString().Equals(dataItem.GetDatastore().GetConnectionString()))) _leftGdbProjectItems.Add(dataItem); if (!_rightGdbProjectItems.Any( gdbProjectItem => gdbProjectItem.GetDatastore().GetConnectionString().Equals(dataItem.GetDatastore().GetConnectionString()))) _rightGdbProjectItems.Add(dataItem); } break; case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: { var matchingItem = _leftGdbProjectItems.FirstOrDefault( item => item.GetDatastore().GetConnectionString().Equals(dataItem.GetDatastore().GetConnectionString())); if (matchingItem != null) _leftGdbProjectItems.Remove(matchingItem); matchingItem = _rightGdbProjectItems.FirstOrDefault( item => item.GetDatastore().GetConnectionString().Equals(dataItem.GetDatastore().GetConnectionString())); if (matchingItem != null) _rightGdbProjectItems.Remove(matchingItem); } break; } }); } private async Task UpdateTables(GDBProjectItem selectedLeftGDBProjectItem, ObservableCollection<TableInfo> observedTables) { var tables = new List<TableInfo>(); await QueuedTask.Run(() => { var datastore = selectedLeftGDBProjectItem.GetDatastore(); if (datastore is Geodatabase) { var geodatabase = datastore as Geodatabase; var featureClassDefinitions = geodatabase.GetDefinitions<FeatureClassDefinition>(); var tableDefinitions = geodatabase.GetDefinitions<TableDefinition>(); tables.AddRange( featureClassDefinitions.Select( definition => new TableInfo { Definition = definition, Name = definition.GetName() })); tables.AddRange( tableDefinitions.Select(definition => new TableInfo { Definition = definition, Name = definition.GetName() })); } if (datastore is Database) { var database = datastore as Database; var tableNames = database.GetTableNames(); foreach (var tableName in tableNames) { var tableDefinition = database.GetDefinition(database.GetQueryDescription(tableName)); tables.Add(new TableInfo { Definition = tableDefinition, Name = tableDefinition.GetName() }); } } }); observedTables.Clear(); observedTables.AddRange(tables); } private async Task UpdateFields(TableInfo selectedTable, ObservableCollection<FieldListItem> observableFields) { if (selectedTable == null) return; IReadOnlyList<Field> fields = null; await QueuedTask.Run(() => { fields = selectedTable.Definition.GetFields(); }); observableFields.Clear(); observableFields.AddRange(fields.Select(field => new FieldListItem { Field = field, Name = field.Name })); } private void MakeQueryTableLayer(Table leftTable, Table rightTable, string commaSeparatedFields) { var tables = IsLeftOuterJoin ? $"{leftTable.GetName()} LEFT OUTER JOIN {rightTable.GetName()} On {leftTable.GetName()}.{_leftField.Name} = {rightTable.GetName()}.{_rightField.Name}" : $"{leftTable.GetName()} INNER JOIN {rightTable.GetName()} On {leftTable.GetName()}.{_leftField.Name} = {rightTable.GetName()}.{_rightField.Name}"; var queryDef = new QueryDef { Tables = tables }; if (!string.IsNullOrEmpty(commaSeparatedFields)) queryDef.SubFields = commaSeparatedFields; var queryTableDescription = new QueryTableDescription(queryDef); var geodatabase = leftTable.GetDatastore() as Geodatabase; var queryTable = geodatabase.OpenQueryTable(queryTableDescription); LayerFactory.Instance.CreateFeatureLayer(queryTable as FeatureClass, MapView.Active.Map, 0, LayerName); } private Table GetTable(GDBProjectItem selectedProjectItem, TableInfo selectedTable) { Table table = null; var datastore = selectedProjectItem.GetDatastore(); if (datastore is Geodatabase) { table = (datastore as Geodatabase).OpenDataset<Table>(selectedTable.Name); } if (datastore is Database) { var database = (datastore as Database); var queryDescription = database.GetQueryDescription(selectedTable.Name); table = database.OpenTable(queryDescription); } return table; } /// <summary> /// Show the DockPane. /// </summary> internal static void Show() { DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID); if (pane == null) return; pane.Activate(); } public string Heading { get { return _heading; } set { SetProperty(ref _heading, value, () => Heading); } } } /// <summary> /// Button implementation to show the DockPane. /// </summary> internal class JoinsDockpane_ShowButton : Button { protected override void OnClick() { JoinsDockpaneViewModel.Show(); } } /// <summary> /// Encapsulates Table name and defintions /// </summary> internal class TableInfo { /// <summary> /// Name /// </summary> public string Name { get; set; } /// <summary> /// table definition /// </summary> public TableDefinition Definition { get; set; } } /// <summary> /// Encapsulates Cadinality settins /// </summary> internal class CardinalityInfo { /// <summary> /// Description /// </summary> public string Name { get; set; } /// <summary> /// Relationship cardinality /// </summary> public RelationshipCardinality RelationshipCardinality { get; set; } } /// <summary> /// /// </summary> internal class FieldListItem { /// <summary> /// Field info /// </summary> public Field Field { get; set; } /// <summary> /// Name /// </summary> public string Name { get; set; } /// <summary> /// Flag selection /// </summary> public bool IsSelected { get; set; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.SearchableList; using osu.Game.Overlays.Social; using osu.Game.Users; using osu.Framework.Threading; namespace osu.Game.Overlays { public class SocialOverlay : SearchableListOverlay<SocialTab, SocialSortCriteria, SortDirection>, IOnlineComponent { private IAPIProvider api; private readonly LoadingAnimation loading; private FillFlowContainer<SocialPanel> panels; protected override Color4 BackgroundColour => OsuColour.FromHex(@"60284b"); protected override Color4 TrianglesColourLight => OsuColour.FromHex(@"672b51"); protected override Color4 TrianglesColourDark => OsuColour.FromHex(@"5c2648"); protected override SearchableListHeader<SocialTab> CreateHeader() => new Header(); protected override SearchableListFilterControl<SocialSortCriteria, SortDirection> CreateFilterControl() => new FilterControl(); private IEnumerable<User> users; public IEnumerable<User> Users { get => users; set { if (users?.Equals(value) ?? false) return; users = value?.ToList(); } } public SocialOverlay() { Waves.FirstWaveColour = OsuColour.FromHex(@"cb5fa0"); Waves.SecondWaveColour = OsuColour.FromHex(@"b04384"); Waves.ThirdWaveColour = OsuColour.FromHex(@"9b2b6e"); Waves.FourthWaveColour = OsuColour.FromHex(@"6d214d"); Add(loading = new LoadingAnimation()); Filter.Search.Current.ValueChanged += text => { if (!string.IsNullOrEmpty(text.NewValue)) { // force searching in players until searching for friends is supported Header.Tabs.Current.Value = SocialTab.AllPlayers; if (Filter.Tabs.Current.Value != SocialSortCriteria.Rank) Filter.Tabs.Current.Value = SocialSortCriteria.Rank; } }; Header.Tabs.Current.ValueChanged += _ => Scheduler.AddOnce(updateSearch); Filter.Tabs.Current.ValueChanged += _ => Scheduler.AddOnce(updateSearch); Filter.DisplayStyleControl.DisplayStyle.ValueChanged += style => recreatePanels(style.NewValue); Filter.DisplayStyleControl.Dropdown.Current.ValueChanged += _ => Scheduler.AddOnce(updateSearch); currentQuery.ValueChanged += query => { queryChangedDebounce?.Cancel(); if (string.IsNullOrEmpty(query.NewValue)) Scheduler.AddOnce(updateSearch); else queryChangedDebounce = Scheduler.AddDelayed(updateSearch, 500); }; currentQuery.BindTo(Filter.Search.Current); } [BackgroundDependencyLoader] private void load(IAPIProvider api) { this.api = api; api.Register(this); } private void recreatePanels(PanelDisplayStyle displayStyle) { clearPanels(); if (Users == null) return; var newPanels = new FillFlowContainer<SocialPanel> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(10f), Margin = new MarginPadding { Top = 10 }, ChildrenEnumerable = Users.Select(u => { SocialPanel panel; switch (displayStyle) { case PanelDisplayStyle.Grid: panel = new SocialGridPanel(u) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre }; break; default: panel = new SocialListPanel(u); break; } panel.Status.BindTo(u.Status); return panel; }) }; LoadComponentAsync(newPanels, f => { if (panels != null) ScrollFlow.Remove(panels); ScrollFlow.Add(panels = newPanels); }); } private APIRequest getUsersRequest; private readonly Bindable<string> currentQuery = new Bindable<string>(); private ScheduledDelegate queryChangedDebounce; private void updateSearch() { queryChangedDebounce?.Cancel(); if (!IsLoaded) return; Users = null; clearPanels(); loading.Hide(); getUsersRequest?.Cancel(); if (api?.IsLoggedIn != true) return; switch (Header.Tabs.Current.Value) { case SocialTab.Friends: var friendRequest = new GetFriendsRequest(); // TODO filter arguments? friendRequest.Success += updateUsers; api.Queue(getUsersRequest = friendRequest); break; default: var userRequest = new GetUsersRequest(); // TODO filter arguments! userRequest.Success += response => updateUsers(response.Select(r => r.User)); api.Queue(getUsersRequest = userRequest); break; } loading.Show(); } private void updateUsers(IEnumerable<User> newUsers) { Users = newUsers; loading.Hide(); recreatePanels(Filter.DisplayStyleControl.DisplayStyle.Value); } private void clearPanels() { if (panels != null) { panels.Expire(); panels = null; } } public void APIStateChanged(IAPIProvider api, APIState state) { switch (state) { case APIState.Online: Scheduler.AddOnce(updateSearch); break; default: Users = null; clearPanels(); break; } } } public enum SortDirection { Ascending, Descending } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Tests { using System; using System.Collections.Generic; using NUnit.Framework; [TestFixture] public class CollectionValidatorTests { Person person; [SetUp] public void Setup() { person = new Person() { Orders = new List<Order>() { new Order { Amount = 5}, new Order { ProductName = "Foo"} } }; } [Test] public void Validates_collection() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()) }; var results = validator.Validate(person); results.Errors.Count.ShouldEqual(3); results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName"); results.Errors[2].PropertyName.ShouldEqual("Orders[1].Amount"); } [Test] public void Collection_should_be_explicitly_included_with_expression() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()) }; var results = validator.Validate(person, x => x.Orders); results.Errors.Count.ShouldEqual(2); } [Test] public void Collection_should_be_explicitly_included_with_string() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()) }; var results = validator.Validate(person, "Orders"); results.Errors.Count.ShouldEqual(2); } [Test] public void Collection_should_be_excluded() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()) }; var results = validator.Validate(person, x => x.Forename); results.Errors.Count.ShouldEqual(0); } [Test] public void Condition_should_work_with_child_collection() { var validator = new TestValidator() { v => v.RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()).When(x => x.Orders.Count == 3 /*there are only 2*/) }; var result = validator.Validate(person); result.IsValid.ShouldBeTrue(); } [Test] public void Skips_null_items() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()) }; person.Orders[0] = null; var results = validator.Validate(person); results.Errors.Count.ShouldEqual(2); //2 errors - 1 for person, 1 for 2nd Order. } [Test] public void Can_validate_collection_using_validator_for_base_type() { var validator = new TestValidator() { v => v.RuleFor(x => x.Orders).SetCollectionValidator(new OrderInterfaceValidator()) }; var result = validator.Validate(person); result.IsValid.ShouldBeFalse(); } [Test] public void Can_specifiy_condition_for_individual_collection_elements() { var validator = new TestValidator { v => v.RuleFor(x => x.Orders) .SetCollectionValidator(new OrderValidator()) .Where(x => x.ProductName != null) }; var results = validator.Validate(person); results.Errors.Count.ShouldEqual(1); } [Test] public void Should_override_property_name() { var validator = new TestValidator { v => v.RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()) .OverridePropertyName("Orders2") }; var results = validator.Validate(person); results.Errors[0].PropertyName.ShouldEqual("Orders2[0].ProductName"); } #region old style - for compatibility with v2 and earlier before we had the explicit SetCollectionValidator #pragma warning disable 612,618 [Test] public void Validates_collection_old_style() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetValidator(new OrderValidator()) }; var results = validator.Validate(person); results.Errors.Count.ShouldEqual(3); results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName"); results.Errors[2].PropertyName.ShouldEqual("Orders[1].Amount"); } [Test] public void Collection_should_be_explicitly_included_with_expression_old_style() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetValidator(new OrderValidator()) }; var results = validator.Validate(person, x => x.Orders); results.Errors.Count.ShouldEqual(2); } [Test] public void Collection_should_be_explicitly_included_with_string_old_style() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetValidator(new OrderValidator()) }; var results = validator.Validate(person, "Orders"); results.Errors.Count.ShouldEqual(2); } [Test] public void Collection_should_be_excluded_old_style() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetValidator(new OrderValidator()) }; var results = validator.Validate(person, x => x.Forename); results.Errors.Count.ShouldEqual(0); } [Test] public void Condition_should_work_with_child_collection_old_style() { var validator = new TestValidator() { v => v.RuleFor(x => x.Orders).SetValidator(new OrderValidator()).When(x => x.Orders.Count == 3 /*there are only 2*/) }; var result = validator.Validate(person); result.IsValid.ShouldBeTrue(); } [Test] public void Skips_null_items_old_style() { var validator = new TestValidator { v => v.RuleFor(x => x.Surname).NotNull(), v => v.RuleFor(x => x.Orders).SetValidator(new OrderValidator()) }; person.Orders[0] = null; var results = validator.Validate(person); results.Errors.Count.ShouldEqual(2); //2 errors - 1 for person, 1 for 2nd Order. } #pragma warning restore 612,618 #endregion public class OrderValidator : AbstractValidator<Order> { public OrderValidator() { RuleFor(x => x.ProductName).NotEmpty(); RuleFor(x => x.Amount).NotEqual(0); } } public class OrderInterfaceValidator : AbstractValidator<IOrder> { public OrderInterfaceValidator() { RuleFor(x => x.Amount).NotEqual(0); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightArithmeticInt321() { var test = new SimpleUnaryOpTest__ShiftRightArithmeticInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftRightArithmeticInt321 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static SimpleUnaryOpTest__ShiftRightArithmeticInt321() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightArithmeticInt321() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftRightArithmetic( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftRightArithmetic( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftRightArithmetic( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftRightArithmetic( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightArithmetic(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightArithmetic(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightArithmetic(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightArithmeticInt321(); var result = Sse2.ShiftRightArithmetic(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftRightArithmetic(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { if ((int)(firstOp[0] >> 1) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(firstOp[i] >> 1) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightArithmetic)}<Int32>(Vector128<Int32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; using Shouldly; using Xunit; #pragma warning disable 0219 namespace Microsoft.Build.UnitTests { public class TaskItemTests { // Make sure a TaskItem can be constructed using an ITaskItem [Fact] public void ConstructWithITaskItem() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.SetMetadata("Dog", "Bingo"); from.SetMetadata("Cat", "Morris"); TaskItem to = new TaskItem((ITaskItem)from); to.ItemSpec.ShouldBe("Monkey.txt"); ((string)to).ShouldBe("Monkey.txt"); to.GetMetadata("Dog").ShouldBe("Bingo"); to.GetMetadata("Cat").ShouldBe("Morris"); // Test that item metadata are case-insensitive. to.SetMetadata("CaT", ""); to.GetMetadata("Cat").ShouldBe(""); // manipulate the item-spec a bit to.GetMetadata(FileUtilities.ItemSpecModifiers.Filename).ShouldBe("Monkey"); to.GetMetadata(FileUtilities.ItemSpecModifiers.Extension).ShouldBe(".txt"); to.GetMetadata(FileUtilities.ItemSpecModifiers.RelativeDir).ShouldBe(string.Empty); } // Make sure metadata can be cloned from an existing ITaskItem [Fact] public void CopyMetadataFromITaskItem() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.SetMetadata("Dog", "Bingo"); from.SetMetadata("Cat", "Morris"); from.SetMetadata("Bird", "Big"); TaskItem to = new TaskItem(); to.ItemSpec = "Bonobo.txt"; to.SetMetadata("Sponge", "Bob"); to.SetMetadata("Dog", "Harriet"); to.SetMetadata("Cat", "Mike"); from.CopyMetadataTo(to); to.ItemSpec.ShouldBe("Bonobo.txt"); // ItemSpec is never overwritten to.GetMetadata("Sponge").ShouldBe("Bob"); // Metadata not in source are preserved. to.GetMetadata("Dog").ShouldBe("Harriet"); // Metadata present on destination are not overwritten. to.GetMetadata("Cat").ShouldBe("Mike"); to.GetMetadata("Bird").ShouldBe("Big"); } [Fact] public void NullITaskItem() { Should.Throw<ArgumentNullException>(() => { ITaskItem item = null; TaskItem taskItem = new TaskItem(item); // no NullReferenceException } ); } /// <summary> /// Even without any custom metadata metadatanames should /// return the built in metadata /// </summary> [Fact] public void MetadataNamesNoCustomMetadata() { TaskItem taskItem = new TaskItem("x"); taskItem.MetadataNames.Count.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length); taskItem.MetadataCount.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length); // Now add one taskItem.SetMetadata("m", "m1"); taskItem.MetadataNames.Count.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length + 1); taskItem.MetadataCount.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length + 1); } [Fact] public void NullITaskItemCast() { Should.Throw<ArgumentNullException>(() => { TaskItem item = null; string result = (string)item; // no NullReferenceException } ); } [Fact] public void ConstructFromDictionary() { Hashtable h = new Hashtable(); h[FileUtilities.ItemSpecModifiers.Filename] = "foo"; h[FileUtilities.ItemSpecModifiers.Extension] = "bar"; h["custom"] = "hello"; TaskItem t = new TaskItem("bamboo.baz", h); // item-spec modifiers were not overridden by dictionary passed to constructor t.GetMetadata(FileUtilities.ItemSpecModifiers.Filename).ShouldBe("bamboo"); t.GetMetadata(FileUtilities.ItemSpecModifiers.Extension).ShouldBe(".baz"); t.GetMetadata("CUSTOM").ShouldBe("hello"); } [Fact] public void CannotChangeModifiers() { Should.Throw<ArgumentException>(() => { TaskItem t = new TaskItem("foo"); try { t.SetMetadata(FileUtilities.ItemSpecModifiers.FullPath, "bazbaz"); } catch (Exception e) { // so I can see the exception message in NUnit's "Standard Out" window Console.WriteLine(e.Message); throw; } } ); } [Fact] public void CannotRemoveModifiers() { Should.Throw<ArgumentException>(() => { TaskItem t = new TaskItem("foor"); try { t.RemoveMetadata(FileUtilities.ItemSpecModifiers.RootDir); } catch (Exception e) { // so I can see the exception message in NUnit's "Standard Out" window Console.WriteLine(e.Message); throw; } } ); } [Fact] public void CheckMetadataCount() { TaskItem t = new TaskItem("foo"); t.MetadataCount.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length); t.SetMetadata("grog", "RUM"); t.MetadataCount.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length + 1); } [Fact] public void NonexistentRequestFullPath() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.FullPath).ShouldBe( Path.Combine ( Directory.GetCurrentDirectory(), "Monkey.txt" ) ); } [Fact] public void NonexistentRequestRootDir() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.RootDir).ShouldBe(Path.GetPathRoot(from.GetMetadata(FileUtilities.ItemSpecModifiers.FullPath))); } [Fact] public void NonexistentRequestFilename() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Filename).ShouldBe("Monkey"); } [Fact] public void NonexistentRequestExtension() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Extension).ShouldBe(".txt"); } [Fact] public void NonexistentRequestRelativeDir() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.RelativeDir).Length.ShouldBe(0); } [Fact] public void NonexistentRequestDirectory() { TaskItem from = new TaskItem(); from.ItemSpec = NativeMethodsShared.IsWindows ? @"c:\subdir\Monkey.txt" : "/subdir/Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Directory).ShouldBe(NativeMethodsShared.IsWindows ? @"subdir\" : "subdir/"); } [Fact] public void NonexistentRequestDirectoryUNC() { if (!NativeMethodsShared.IsWindows) { return; // "UNC is not implemented except under Windows" } TaskItem from = new TaskItem(); from.ItemSpec = @"\\local\share\subdir\Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Directory).ShouldBe(@"subdir\"); } [Fact] public void NonexistentRequestRecursiveDir() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.RecursiveDir).Length.ShouldBe(0); } [Fact] public void NonexistentRequestIdentity() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Identity).ShouldBe("Monkey.txt"); } [Fact] public void RequestTimeStamps() { TaskItem from = new TaskItem(); from.ItemSpec = FileUtilities.GetTemporaryFile(); from.GetMetadata(FileUtilities.ItemSpecModifiers.ModifiedTime).Length.ShouldBeGreaterThan(0); from.GetMetadata(FileUtilities.ItemSpecModifiers.CreatedTime).Length.ShouldBeGreaterThan(0); from.GetMetadata(FileUtilities.ItemSpecModifiers.AccessedTime).Length.ShouldBeGreaterThan(0); File.Delete(from.ItemSpec); from.GetMetadata(FileUtilities.ItemSpecModifiers.ModifiedTime).Length.ShouldBe(0); from.GetMetadata(FileUtilities.ItemSpecModifiers.CreatedTime).Length.ShouldBe(0); from.GetMetadata(FileUtilities.ItemSpecModifiers.AccessedTime).Length.ShouldBe(0); } /// <summary> /// Verify metadata cannot be created with null name /// </summary> [Fact] public void CreateNullNamedMetadata() { Should.Throw<ArgumentNullException>(() => { TaskItem item = new TaskItem("foo"); item.SetMetadata(null, "x"); } ); } /// <summary> /// Verify metadata cannot be created with empty name /// </summary> [Fact] public void CreateEmptyNamedMetadata() { Should.Throw<ArgumentException>(() => { TaskItem item = new TaskItem("foo"); item.SetMetadata("", "x"); } ); } /// <summary> /// Create a TaskItem with a null metadata value -- this is allowed, but /// internally converted to the empty string. /// </summary> [Fact] public void CreateTaskItemWithNullMetadata() { IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add("m", null); TaskItem item = new TaskItem("bar", (IDictionary)metadata); item.GetMetadata("m").ShouldBe(string.Empty); } /// <summary> /// Set metadata value to null value -- this is allowed, but /// internally converted to the empty string. /// </summary> [Fact] public void SetNullMetadataValue() { TaskItem item = new TaskItem("bar"); item.SetMetadata("m", null); item.GetMetadata("m").ShouldBe(string.Empty); } #if FEATURE_APPDOMAIN /// <summary> /// Test that task items can be successfully constructed based on a task item from another appdomain. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] [Trait("Category", "mono-windows-failing")] public void RemoteTaskItem() { AppDomain appDomain = null; try { appDomain = AppDomain.CreateDomain ( "generateResourceAppDomain", null, AppDomain.CurrentDomain.SetupInformation ); object obj = appDomain.CreateInstanceFromAndUnwrap ( typeof(TaskItemCreator).Module.FullyQualifiedName, typeof(TaskItemCreator).FullName ); TaskItemCreator creator = (TaskItemCreator)obj; IDictionary<string, string> metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); metadata.Add("c", "C"); metadata.Add("d", "D"); creator.Run(new[] { "a", "b" }, metadata); ITaskItem[] itemsInThisAppDomain = new ITaskItem[creator.CreatedTaskItems.Length]; for (int i = 0; i < creator.CreatedTaskItems.Length; i++) { itemsInThisAppDomain[i] = new TaskItem(creator.CreatedTaskItems[i]); itemsInThisAppDomain[i].ItemSpec.ShouldBe(creator.CreatedTaskItems[i].ItemSpec); itemsInThisAppDomain[i].MetadataCount.ShouldBe(creator.CreatedTaskItems[i].MetadataCount + 1); foreach (string metadatum in creator.CreatedTaskItems[i].MetadataNames) { if (!string.Equals("OriginalItemSpec", metadatum)) { itemsInThisAppDomain[i].GetMetadata(metadatum).ShouldBe(creator.CreatedTaskItems[i].GetMetadata(metadatum)); } } } } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } } /// <summary> /// Miniature class to be remoted to another appdomain that just creates some TaskItems and makes them available for returning. /// </summary> private sealed class TaskItemCreator #if FEATURE_APPDOMAIN : MarshalByRefObject #endif { /// <summary> /// Task items that will be consumed by the other appdomain /// </summary> public ITaskItem[] CreatedTaskItems { get; private set; } /// <summary> /// Creates task items /// </summary> public void Run(string[] includes, IDictionary<string, string> metadataToAdd) { ErrorUtilities.VerifyThrowArgumentNull(includes, "includes"); CreatedTaskItems = new TaskItem[includes.Length]; for (int i = 0; i < includes.Length; i++) { CreatedTaskItems[i] = new TaskItem(includes[i], (IDictionary)metadataToAdd); } } } #endif } }
using J2N.Collections.Generic.Extensions; using J2N.Text; using Antlr.Runtime; using Antlr.Runtime.Tree; using Lucene.Net.Queries.Function; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using JCG = J2N.Collections.Generic; using J2N; using System.Text; namespace Lucene.Net.Expressions.JS { /* * 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. */ /// <summary>An expression compiler for javascript expressions.</summary> /// <remarks> /// An expression compiler for javascript expressions. /// <para/> /// Example: /// <code> /// Expression foo = JavascriptCompiler.Compile("((0.3*popularity)/10.0)+(0.7*score)"); /// </code> /// <para/> /// See the <see cref="Lucene.Net.Expressions.JS">package documentation</see> for /// the supported syntax and default functions. /// <para> /// You can compile with an alternate set of functions via <see cref="Compile(string, IDictionary{string, MethodInfo})"/>. /// For example: /// <code> /// IDictionary&lt;string, MethodInfo&gt; functions = new Dictionary&lt;string, MethodInfo&gt;(); /// // add all the default functions /// functions.PutAll(JavascriptCompiler.DEFAULT_FUNCTIONS); /// // add sqrt() /// functions.Put("sqrt", (typeof(Math)).GetMethod("Sqrt", new Type[] { typeof(double) })); /// // call compile with customized function map /// Expression foo = JavascriptCompiler.Compile("sqrt(score)+ln(popularity)", functions); /// </code> /// </para> /// @lucene.experimental /// </remarks> public class JavascriptCompiler { private static readonly string COMPILED_EXPRESSION_CLASS = typeof(Expression).Namespace + ".CompiledExpression"; //private static readonly string COMPILED_EXPRESSION_INTERNAL = COMPILED_EXPRESSION_CLASS.Replace('.', '/'); // LUCENENET: Not used private static readonly Type EXPRESSION_TYPE = Type.GetType(typeof(Expression).FullName); private static readonly Type FUNCTION_VALUES_TYPE = typeof(FunctionValues); private static readonly ConstructorInfo EXPRESSION_CTOR = typeof(Expression). GetConstructor(new Type[] { typeof(string), typeof(string[]) }); private static readonly MethodInfo EVALUATE_METHOD = GetMethod(EXPRESSION_TYPE, "Evaluate", new[] { typeof(int), typeof(FunctionValues[]) }); private static readonly MethodInfo DOUBLE_VAL_METHOD = GetMethod(FUNCTION_VALUES_TYPE, "DoubleVal", new[] { typeof(int) }); // We use the same class name for all generated classes as they all have their own class loader. // The source code is displayed as "source file name" in stack trace. // to work around import clash: private static MethodInfo GetMethod(Type type, string method, Type[] parms) { return type.GetMethod(method, parms); } private readonly string sourceText; private readonly IDictionary<string, int> externalsMap = new JCG.LinkedDictionary<string, int>(); private TypeBuilder dynamicType; private readonly IDictionary<string, MethodInfo> functions; private ILGenerator gen; private AssemblyBuilder asmBuilder; private MethodBuilder evalMethod; private ModuleBuilder modBuilder; // This maximum length is theoretically 65535 bytes, but as its CESU-8 encoded we dont know how large it is in bytes, so be safe // rcmuir: "If your ranking function is that large you need to check yourself into a mental institution!" /// <summary>Compiles the given expression.</summary> /// <param name="sourceText">The expression to compile</param> /// <returns>A new compiled expression</returns> /// <exception cref="ParseException">on failure to compile</exception> // LUCENENET TODO: ParseException not being thrown here - need to check // where this is thrown in Java and throw the equivalent in .NET public static Expression Compile(string sourceText) { return new JavascriptCompiler(sourceText).CompileExpression(); } /// <summary>Compiles the given expression with the supplied custom functions.</summary> /// <remarks> /// Compiles the given expression with the supplied custom functions. /// <para/> /// Functions must be <c>public static</c>, return <see cref="double"/> and /// can take from zero to 256 <see cref="double"/> parameters. /// </remarks> /// <param name="sourceText">The expression to compile</param> /// <param name="functions">map of <see cref="string"/> names to functions</param> /// <returns>A new compiled expression</returns> /// <exception cref="ParseException">on failure to compile</exception> public static Expression Compile(string sourceText, IDictionary<string, MethodInfo> functions) { foreach (MethodInfo m in functions.Values) { CheckFunction(m); } return new JavascriptCompiler(sourceText, functions).CompileExpression(); } /// <summary>This method is unused, it is just here to make sure that the function signatures don't change.</summary> /// <remarks> /// This method is unused, it is just here to make sure that the function signatures don't change. /// If this method fails to compile, you also have to change the byte code generator to correctly /// use the <see cref="FunctionValues"/> class. /// </remarks> private static void UnusedTestCompile() { FunctionValues f = null; double ret = f.DoubleVal(2); } /// <summary>Constructs a compiler for expressions.</summary> /// <param name="sourceText">The expression to compile</param> private JavascriptCompiler(string sourceText) : this(sourceText, DEFAULT_FUNCTIONS) { } /// <summary>Constructs a compiler for expressions with specific set of functions</summary> /// <param name="sourceText">The expression to compile</param> /// <param name="functions">The set of functions to compile with</param> private JavascriptCompiler(string sourceText, IDictionary<string, MethodInfo> functions) { this.sourceText = sourceText ?? throw new ArgumentNullException(nameof(sourceText)); this.functions = functions; } /// <summary>Compiles the given expression with the specified parent classloader</summary> /// <returns>A new compiled expression</returns> /// <exception cref="ParseException">on failure to compile</exception> private Expression CompileExpression() { try { ITree antlrTree = GetAntlrComputedExpressionTree(); BeginCompile(); RecursiveCompile(antlrTree, typeof(double)); EndCompile(); return (Expression) Activator.CreateInstance(dynamicType.CreateTypeInfo().AsType(), sourceText, externalsMap.Keys.ToArray()); } catch (MemberAccessException exception) { throw new InvalidOperationException("An internal error occurred attempting to compile the expression (" + sourceText + ").", exception); } catch (TargetInvocationException exception) { throw new InvalidOperationException("An internal error occurred attempting to compile the expression (" + sourceText + ").", exception); } } private void BeginCompile() { var assemblyName = new AssemblyName("Lucene.Net.Expressions.Dynamic" + new Random().Next()); asmBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect); modBuilder = asmBuilder.DefineDynamicModule(assemblyName.Name + ".dll"); dynamicType = modBuilder.DefineType(COMPILED_EXPRESSION_CLASS, TypeAttributes.AnsiClass | TypeAttributes.AutoClass | TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, EXPRESSION_TYPE); ConstructorBuilder constructorBuilder = dynamicType.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new[] { typeof(string), typeof(string[]) }); ILGenerator ctorGen = constructorBuilder.GetILGenerator(); ctorGen.Emit(OpCodes.Ldarg_0); ctorGen.Emit(OpCodes.Ldarg_1); ctorGen.Emit(OpCodes.Ldarg_2); ctorGen.Emit(OpCodes.Call, EXPRESSION_CTOR); ctorGen.Emit(OpCodes.Nop); ctorGen.Emit(OpCodes.Nop); ctorGen.Emit(OpCodes.Ret); evalMethod = dynamicType.DefineMethod("Evaluate", MethodAttributes.Public | MethodAttributes.Virtual, typeof(double), new[] { typeof(int), typeof(FunctionValues[]) }); gen = evalMethod.GetILGenerator(); } private void RecursiveCompile(ITree current, Type expected) { int type = current.Type; string text = current.Text; switch (type) { case JavascriptParser.AT_CALL: { ITree identifier = current.GetChild(0); string call = identifier.Text; int arguments = current.ChildCount - 1; MethodInfo method; if (!functions.TryGetValue(call, out method) || method == null) { throw new ArgumentException("Unrecognized method call (" + call + ")."); } int arity = method.GetParameters().Length; if (arguments != arity) { throw new ArgumentException("Expected (" + arity + ") arguments for method call (" + call + "), but found (" + arguments + ")."); } for (int argument = 1; argument <= arguments; ++argument) { RecursiveCompile(current.GetChild(argument), typeof(double)); } gen.Emit(OpCodes.Call, method); break; } case JavascriptParser.NAMESPACE_ID: { if (!externalsMap.TryGetValue(text, out int index)) { externalsMap[text] = index = externalsMap.Count; } gen.Emit(OpCodes.Nop); gen.Emit(OpCodes.Ldarg_2); gen.Emit(OpCodes.Ldc_I4, index); gen.Emit(OpCodes.Ldelem_Ref); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Callvirt, DOUBLE_VAL_METHOD); break; } case JavascriptParser.HEX: { PushInt64(Convert.ToInt64(text, 16)); break; } case JavascriptParser.OCTAL: { PushInt64(Convert.ToInt64(text, 8)); break; } case JavascriptParser.DECIMAL: { //.NET Port. This is a bit hack-y but was needed since .NET can't perform bitwise ops on longs & doubles var bitwiseOps = new[]{ ">>","<<","&","~","|","^"}; if (bitwiseOps.Any(s => sourceText.Contains(s))) { int val; if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) { gen.Emit(OpCodes.Ldc_I4, val); } else { gen.Emit(OpCodes.Ldc_I8,long.Parse(text, CultureInfo.InvariantCulture)); gen.Emit(OpCodes.Conv_Ovf_U4_Un); } } else { gen.Emit(OpCodes.Ldc_R8, double.Parse(text, CultureInfo.InvariantCulture)); } break; } case JavascriptParser.AT_NEGATE: { RecursiveCompile(current.GetChild(0), typeof(double)); gen.Emit(OpCodes.Neg); break; } case JavascriptParser.AT_ADD: { PushArith(OpCodes.Add, current, expected); break; } case JavascriptParser.AT_SUBTRACT: { PushArith(OpCodes.Sub, current, expected); break; } case JavascriptParser.AT_MULTIPLY: { PushArith(OpCodes.Mul, current, expected); break; } case JavascriptParser.AT_DIVIDE: { PushArith(OpCodes.Div, current, expected); break; } case JavascriptParser.AT_MODULO: { PushArith(OpCodes.Rem, current, expected); break; } case JavascriptParser.AT_BIT_SHL: { PushShift(OpCodes.Shl, current); break; } case JavascriptParser.AT_BIT_SHR: { PushShift(OpCodes.Shr, current); break; } case JavascriptParser.AT_BIT_SHU: { PushShift(OpCodes.Shr_Un, current); break; } case JavascriptParser.AT_BIT_AND: { PushBitwise(OpCodes.And, current); break; } case JavascriptParser.AT_BIT_OR: { PushBitwise(OpCodes.Or, current); break; } case JavascriptParser.AT_BIT_XOR: { PushBitwise(OpCodes.Xor, current); break; } case JavascriptParser.AT_BIT_NOT: { RecursiveCompile(current.GetChild(0), typeof(long)); gen.Emit(OpCodes.Not); gen.Emit(OpCodes.Conv_R8); break; } case JavascriptParser.AT_COMP_EQ: { PushCond(OpCodes.Ceq, current, expected); break; } case JavascriptParser.AT_COMP_NEQ: { PushCondEq(OpCodes.Ceq, current, expected); break; } case JavascriptParser.AT_COMP_LT: { PushCond(OpCodes.Clt, current, expected); break; } case JavascriptParser.AT_COMP_GT: { PushCond(OpCodes.Cgt, current, expected); break; } case JavascriptParser.AT_COMP_LTE: { PushCondEq(OpCodes.Cgt, current, expected); break; } case JavascriptParser.AT_COMP_GTE: { PushCondEq(OpCodes.Clt, current, expected); break; } case JavascriptParser.AT_BOOL_NOT: { RecursiveCompile(current.GetChild(0), typeof(int)); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ceq); gen.Emit(OpCodes.Conv_R8); break; } case JavascriptParser.AT_BOOL_AND: { RecursiveCompile(current.GetChild(0), typeof(int)); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ceq); RecursiveCompile(current.GetChild(1), typeof(int)); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ceq); gen.Emit(OpCodes.Or); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ceq); gen.Emit(OpCodes.Conv_R8); break; } case JavascriptParser.AT_BOOL_OR: { RecursiveCompile(current.GetChild(0), typeof(int)); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ceq); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Xor); RecursiveCompile(current.GetChild(1), typeof(int)); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ceq); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Xor); gen.Emit(OpCodes.Or); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Ceq); gen.Emit(OpCodes.Conv_R8); break; } case JavascriptParser.AT_COND_QUE: { Label condFalse = gen.DefineLabel(); Label condEnd = gen.DefineLabel(); RecursiveCompile(current.GetChild(0), typeof(int)); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Beq,condFalse); RecursiveCompile(current.GetChild(1), expected); gen.Emit(OpCodes.Br_S,condEnd); gen.MarkLabel(condFalse); RecursiveCompile(current.GetChild(2), expected); gen.MarkLabel(condEnd); break; } default: { throw new InvalidOperationException("Unknown operation specified: (" + current.Text + ")."); } } } private void PushCondEq(OpCode opCode, ITree current, Type expected) { RecursiveCompile(current.GetChild(0), expected); RecursiveCompile(current.GetChild(1), expected); gen.Emit(opCode); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Xor); gen.Emit(OpCodes.Conv_R8); } private void PushArith(OpCode op, ITree current, Type expected) { PushBinaryOp(op, current, typeof(double), typeof(double)); } private void PushShift(OpCode op, ITree current) { PushBinaryShiftOp(op, current, typeof(int), typeof(int)); } private void PushBinaryShiftOp(OpCode op, ITree current, Type arg1, Type arg2) { gen.Emit(OpCodes.Nop); RecursiveCompile(current.GetChild(0), arg1); RecursiveCompile(current.GetChild(1), arg2); gen.Emit(op); gen.Emit(OpCodes.Conv_R8); } private void PushBitwise(OpCode op, ITree current) { PushBinaryOp(op, current, typeof(long), typeof(long)); } private void PushBinaryOp(OpCode op, ITree current, Type arg1, Type arg2) { gen.Emit(OpCodes.Nop); RecursiveCompile(current.GetChild(0), arg1); RecursiveCompile(current.GetChild(1), arg2); gen.Emit(op); gen.Emit(OpCodes.Conv_R8); } private void PushCond(OpCode opCode, ITree current, Type expected) { RecursiveCompile(current.GetChild(0), expected); RecursiveCompile(current.GetChild(1), expected); gen.Emit(opCode); gen.Emit(OpCodes.Conv_R8); } /// <summary> /// NOTE: This was pushLong() in Lucene /// </summary> private void PushInt64(long i) { gen.Emit(OpCodes.Ldc_I8,i); if (!sourceText.Contains("<<")) { gen.Emit(OpCodes.Conv_R8); } } private void EndCompile() { gen.Emit(OpCodes.Ret); dynamicType.DefineMethodOverride(evalMethod, EVALUATE_METHOD); } private ITree GetAntlrComputedExpressionTree() { ICharStream input = new ANTLRStringStream(sourceText); JavascriptLexer lexer = new JavascriptLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); JavascriptParser parser = new JavascriptParser(tokens); try { return parser.Expression().Tree; } catch (RecognitionException re) { throw new ArgumentException(re.Message, re); } } /// <summary>The default set of functions available to expressions.</summary> /// <remarks> /// The default set of functions available to expressions. /// <para/> /// See the <see cref="Lucene.Net.Expressions.JS">package documentation</see> for a list. /// </remarks> public static readonly IDictionary<string, MethodInfo> DEFAULT_FUNCTIONS = LoadDefaultFunctions(); private static IDictionary<string, MethodInfo> LoadDefaultFunctions() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { IDictionary<string, MethodInfo> map = new Dictionary<string, MethodInfo>(); try { foreach (var property in GetDefaultSettings()) { string[] vals = property.Value.Split(',').TrimEnd(); if (vals.Length != 3) { throw new Exception("Error reading Javascript functions from settings"); } string typeName = vals[0]; Type clazz; if (vals[0].Contains("Lucene.Net")) { clazz = GetType(vals[0] + ", Lucene.Net"); } else { clazz = GetType(typeName); } string methodName = vals[1].Trim(); int arity = int.Parse(vals[2], CultureInfo.InvariantCulture); Type[] args = new Type[arity]; Arrays.Fill(args, typeof(double)); MethodInfo method = clazz.GetMethod(methodName, args); CheckFunction(method); map[property.Key] = method; } } catch (Exception e) { throw new Exception("Cannot resolve function", e); } return map.AsReadOnly(); } private static Type GetType(string typeName) { try { return Type.GetType(typeName, true); } catch { return null; } } private static IDictionary<string, string> GetDefaultSettings() { var settings = new Dictionary<string, string>(); var type = typeof(JavascriptCompiler); using (var reader = new StreamReader(type.FindAndGetManifestResourceStream(type.Name + ".properties"), Encoding.UTF8)) settings.LoadProperties(reader); return settings; } private static void CheckFunction(MethodInfo method) { // do some checks if the signature is "compatible": if (!(method.IsStatic)) { throw new ArgumentException(method + " is not static."); } if (!(method.IsPublic)) { throw new ArgumentException(method + " is not public."); } if (!method.DeclaringType.IsPublic) { //.NET Port. Inner class is being returned as not public even when declared public if (method.DeclaringType.IsNestedAssembly) { throw new ArgumentException(method.DeclaringType.FullName + " is not public."); } } if (method.GetParameters().Any(parmType => parmType.ParameterType != (typeof(double)))) { throw new ArgumentException(method + " must take only double parameters"); } if (method.ReturnType != typeof(double)) { throw new ArgumentException(method + " does not return a double."); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using System; using System.Collections.Generic; using System.Reflection; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.World.Estate { public class EstateConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected XEstateModule m_EstateModule; public EstateConnector(XEstateModule module) { m_EstateModule = module; } public void SendTeleportHomeOneUser(uint EstateID, UUID PreyID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "teleport_home_one_user"; sendData["EstateID"] = EstateID.ToString(); sendData["PreyID"] = PreyID.ToString(); SendToEstate(EstateID, sendData); } public void SendTeleportHomeAllUsers(uint EstateID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "teleport_home_all_users"; sendData["EstateID"] = EstateID.ToString(); SendToEstate(EstateID, sendData); } public bool SendUpdateCovenant(uint EstateID, UUID CovenantID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "update_covenant"; sendData["CovenantID"] = CovenantID.ToString(); sendData["EstateID"] = EstateID.ToString(); // Handle local regions locally // foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == EstateID) s.RegionInfo.RegionSettings.Covenant = CovenantID; // s.ReloadEstateData(); } SendToEstate(EstateID, sendData); return true; } public bool SendUpdateEstate(uint EstateID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "update_estate"; sendData["EstateID"] = EstateID.ToString(); // Handle local regions locally // foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == EstateID) s.ReloadEstateData(); } SendToEstate(EstateID, sendData); return true; } public void SendEstateMessage(uint EstateID, UUID FromID, string FromName, string Message) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["METHOD"] = "estate_message"; sendData["EstateID"] = EstateID.ToString(); sendData["FromID"] = FromID.ToString(); sendData["FromName"] = FromName; sendData["Message"] = Message; SendToEstate(EstateID, sendData); } private void SendToEstate(uint EstateID, Dictionary<string, object> sendData) { List<UUID> regions = m_EstateModule.Scenes[0].GetEstateRegions((int)EstateID); UUID ScopeID = UUID.Zero; // Handle local regions locally // foreach (Scene s in m_EstateModule.Scenes) { if (regions.Contains(s.RegionInfo.RegionID)) { // All regions in one estate are in the same scope. // Use that scope. // ScopeID = s.RegionInfo.ScopeID; regions.Remove(s.RegionInfo.RegionID); } } // Our own region should always be in the above list. // In a standalone this would not be true. But then, // Scope ID is not relevat there. Use first scope. // if (ScopeID == UUID.Zero) ScopeID = m_EstateModule.Scenes[0].RegionInfo.ScopeID; // Don't send to the same instance twice // List<string> done = new List<string>(); // Send to remote regions // foreach (UUID regionID in regions) { GridRegion region = m_EstateModule.Scenes[0].GridService.GetRegionByUUID(ScopeID, regionID); if (region != null) { string url = "http://" + region.ExternalHostName + ":" + region.HttpPort; if (done.Contains(url)) continue; Call(region, sendData); done.Add(url); } } } private bool Call(GridRegion region, Dictionary<string, object> sendData) { string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[XESTATE CONNECTOR]: queryString = {0}", reqString); try { string url = "http://" + region.ExternalHostName + ":" + region.HttpPort; string reply = SynchronousRestFormsRequester.MakeRequest("POST", url + "/estate", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("RESULT")) { if (replyData["RESULT"].ToString().ToLower() == "true") return true; else return false; } else m_log.DebugFormat("[XESTATE CONNECTOR]: reply data does not contain result field"); } else m_log.DebugFormat("[XESTATE CONNECTOR]: received empty reply"); } catch (Exception e) { m_log.DebugFormat("[XESTATE CONNECTOR]: Exception when contacting remote sim: {0}", e.Message); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq.Expressions; using Xunit; namespace System.Linq.Tests { public class SumTests : EnumerableBasedTests { [Fact] public void SumOfInt_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<int> sourceInt = null; Assert.Throws<ArgumentNullException>("source", () => sourceInt.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceInt.Sum(x => x)); } [Fact] public void SumOfNullableOfInt_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<int?> sourceNullableInt = null; Assert.Throws<ArgumentNullException>("source", () => sourceNullableInt.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceNullableInt.Sum(x => x)); } [Fact] public void SumOfLong_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<long> sourceLong = null; Assert.Throws<ArgumentNullException>("source", () => sourceLong.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceLong.Sum(x => x)); } [Fact] public void SumOfNullableOfLong_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<long?> sourceNullableLong = null; Assert.Throws<ArgumentNullException>("source", () => sourceNullableLong.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceNullableLong.Sum(x => x)); } [Fact] public void SumOfFloat_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<float> sourceFloat = null; Assert.Throws<ArgumentNullException>("source", () => sourceFloat.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceFloat.Sum(x => x)); } [Fact] public void SumOfNullableOfFloat_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<float?> sourceNullableFloat = null; Assert.Throws<ArgumentNullException>("source", () => sourceNullableFloat.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceNullableFloat.Sum(x => x)); } [Fact] public void SumOfDouble_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<double> sourceDouble = null; Assert.Throws<ArgumentNullException>("source", () => sourceDouble.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceDouble.Sum(x => x)); } [Fact] public void SumOfNullableOfDouble_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<double?> sourceNullableDouble = null; Assert.Throws<ArgumentNullException>("source", () => sourceNullableDouble.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceNullableDouble.Sum(x => x)); } [Fact] public void SumOfDecimal_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<decimal> sourceDecimal = null; Assert.Throws<ArgumentNullException>("source", () => sourceDecimal.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceDecimal.Sum(x => x)); } [Fact] public void SumOfNullableOfDecimal_SourceIsNull_ArgumentNullExceptionThrown() { IQueryable<decimal?> sourceNullableDecimal = null; Assert.Throws<ArgumentNullException>("source", () => sourceNullableDecimal.Sum()); Assert.Throws<ArgumentNullException>("source", () => sourceNullableDecimal.Sum(x => x)); } [Fact] public void SumOfInt_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<int> sourceInt = Enumerable.Empty<int>().AsQueryable(); Expression<Func<int, int>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceInt.Sum(selector)); } [Fact] public void SumOfNullableOfInt_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<int?> sourceNullableInt = Enumerable.Empty<int?>().AsQueryable(); Expression<Func<int?, int?>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceNullableInt.Sum(selector)); } [Fact] public void SumOfLong_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<long> sourceLong = Enumerable.Empty<long>().AsQueryable(); Expression<Func<long, long>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceLong.Sum(selector)); } [Fact] public void SumOfNullableOfLong_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<long?> sourceNullableLong = Enumerable.Empty<long?>().AsQueryable(); Expression<Func<long?, long?>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceNullableLong.Sum(selector)); } [Fact] public void SumOfFloat_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<float> sourceFloat = Enumerable.Empty<float>().AsQueryable(); Expression<Func<float, float>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceFloat.Sum(selector)); } [Fact] public void SumOfNullableOfFloat_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<float?> sourceNullableFloat = Enumerable.Empty<float?>().AsQueryable(); Expression<Func<float?, float?>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceNullableFloat.Sum(selector)); } [Fact] public void SumOfDouble_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<double> sourceDouble = Enumerable.Empty<double>().AsQueryable(); Expression<Func<double, double>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceDouble.Sum(selector)); } [Fact] public void SumOfNullableOfDouble_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<double?> sourceNullableDouble = Enumerable.Empty<double?>().AsQueryable(); Expression<Func<double?, double?>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceNullableDouble.Sum(selector)); } [Fact] public void SumOfDecimal_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<decimal> sourceDecimal = Enumerable.Empty<decimal>().AsQueryable(); Expression<Func<decimal, decimal>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceDecimal.Sum(selector)); } [Fact] public void SumOfNullableOfDecimal_SelectorIsNull_ArgumentNullExceptionThrown() { IQueryable<decimal?> sourceNullableDecimal = Enumerable.Empty<decimal?>().AsQueryable(); Expression<Func<decimal?, decimal?>> selector = null; Assert.Throws<ArgumentNullException>("selector", () => sourceNullableDecimal.Sum(selector)); } [Fact] public void SumOfInt_SourceIsEmptyCollection_ZeroReturned() { IQueryable<int> sourceInt = Enumerable.Empty<int>().AsQueryable(); Assert.Equal(0, sourceInt.Sum()); Assert.Equal(0, sourceInt.Sum(x => x)); } [Fact] public void SumOfNullableOfInt_SourceIsEmptyCollection_ZeroReturned() { IQueryable<int?> sourceNullableInt = Enumerable.Empty<int?>().AsQueryable(); Assert.Equal(0, sourceNullableInt.Sum()); Assert.Equal(0, sourceNullableInt.Sum(x => x)); } [Fact] public void SumOfLong_SourceIsEmptyCollection_ZeroReturned() { IQueryable<long> sourceLong = Enumerable.Empty<long>().AsQueryable(); Assert.Equal(0L, sourceLong.Sum()); Assert.Equal(0L, sourceLong.Sum(x => x)); } [Fact] public void SumOfNullableOfLong_SourceIsEmptyCollection_ZeroReturned() { IQueryable<long?> sourceNullableLong = Enumerable.Empty<long?>().AsQueryable(); Assert.Equal(0L, sourceNullableLong.Sum()); Assert.Equal(0L, sourceNullableLong.Sum(x => x)); } [Fact] public void SumOfFloat_SourceIsEmptyCollection_ZeroReturned() { IQueryable<float> sourceFloat = Enumerable.Empty<float>().AsQueryable(); Assert.Equal(0f, sourceFloat.Sum()); Assert.Equal(0f, sourceFloat.Sum(x => x)); } [Fact] public void SumOfNullableOfFloat_SourceIsEmptyCollection_ZeroReturned() { IQueryable<float?> sourceNullableFloat = Enumerable.Empty<float?>().AsQueryable(); Assert.Equal(0f, sourceNullableFloat.Sum()); Assert.Equal(0f, sourceNullableFloat.Sum(x => x)); } [Fact] public void SumOfDouble_SourceIsEmptyCollection_ZeroReturned() { IQueryable<double> sourceDouble = Enumerable.Empty<double>().AsQueryable(); Assert.Equal(0d, sourceDouble.Sum()); Assert.Equal(0d, sourceDouble.Sum(x => x)); } [Fact] public void SumOfNullableOfDouble_SourceIsEmptyCollection_ZeroReturned() { IQueryable<double?> sourceNullableDouble = Enumerable.Empty<double?>().AsQueryable(); Assert.Equal(0d, sourceNullableDouble.Sum()); Assert.Equal(0d, sourceNullableDouble.Sum(x => x)); } [Fact] public void SumOfDecimal_SourceIsEmptyCollection_ZeroReturned() { IQueryable<decimal> sourceDecimal = Enumerable.Empty<decimal>().AsQueryable(); Assert.Equal(0m, sourceDecimal.Sum()); Assert.Equal(0m, sourceDecimal.Sum(x => x)); } [Fact] public void SumOfNullableOfDecimal_SourceIsEmptyCollection_ZeroReturned() { IQueryable<decimal?> sourceNullableDecimal = Enumerable.Empty<decimal?>().AsQueryable(); Assert.Equal(0m, sourceNullableDecimal.Sum()); Assert.Equal(0m, sourceNullableDecimal.Sum(x => x)); } [Fact] public void Sum1() { var val = (new int[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((int)3, val); } [Fact] public void Sum2() { var val = (new int?[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((int)3, val); } [Fact] public void Sum3() { var val = (new long[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((long)3, val); } [Fact] public void Sum4() { var val = (new long?[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((long)3, val); } [Fact] public void Sum5() { var val = (new float[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((float)3, val); } [Fact] public void Sum6() { var val = (new float?[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((float)3, val); } [Fact] public void Sum7() { var val = (new double[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((double)3, val); } [Fact] public void Sum8() { var val = (new double?[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((double)3, val); } [Fact] public void Sum9() { var val = (new decimal[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((decimal)3, val); } [Fact] public void Sum10() { var val = (new decimal?[] { 0, 2, 1 }).AsQueryable().Sum(); Assert.Equal((decimal)3, val); } [Fact] public void Sum11() { var val = (new int[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((int)3, val); } [Fact] public void Sum12() { var val = (new int?[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((int)3, val); } [Fact] public void Sum13() { var val = (new long[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((long)3, val); } [Fact] public void Sum14() { var val = (new long?[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((long)3, val); } [Fact] public void Sum15() { var val = (new float[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((float)3, val); } [Fact] public void Sum16() { var val = (new float?[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((float)3, val); } [Fact] public void Sum17() { var val = (new double[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((double)3, val); } [Fact] public void Sum18() { var val = (new double?[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((double)3, val); } [Fact] public void Sum19() { var val = (new decimal[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((decimal)3, val); } [Fact] public void Sum20() { var val = (new decimal?[] { 0, 2, 1 }).AsQueryable().Sum(n => n); Assert.Equal((decimal)3, val); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using Aurora.Modules.Archivers; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace Aurora.Modules.DefaultInventoryIARLoader { public class DefaultInventoryIARLoader : IDefaultLibraryLoader { protected Dictionary<string, AssetType> m_assetTypes = new Dictionary<string, AssetType>(); protected IRegistryCore m_registry; protected ILibraryService m_service; protected IInventoryData m_Database; #region IDefaultLibraryLoader Members public void LoadLibrary(ILibraryService service, IConfigSource source, IRegistryCore registry) { m_service = service; m_registry = registry; m_Database = Aurora.DataManager.DataManager.RequestPlugin<IInventoryData>(); IConfig libConfig = source.Configs["InventoryIARLoader"]; const string pLibrariesLocation = "DefaultInventory/"; AddDefaultAssetTypes(); if (libConfig != null) { if (libConfig.GetBoolean("WipeLibrariesOnNextLoad", false)) { service.ClearDefaultInventory();//Nuke it libConfig.Set("WipeLibrariesOnNextLoad", false); source.Save(); } if (libConfig.GetBoolean("PreviouslyLoaded", false)) return; //If it is loaded, don't reload foreach (string iarFileName in Directory.GetFiles(pLibrariesLocation, "*.iar")) { LoadLibraries(iarFileName); } } } #endregion private void AddDefaultAssetTypes() { m_assetTypes.Add("Animation", AssetType.Animation); m_assetTypes.Add("Bodypart", AssetType.Bodypart); m_assetTypes.Add("Body part", AssetType.Bodypart); m_assetTypes.Add("CallingCard", AssetType.CallingCard); m_assetTypes.Add("Calling Card", AssetType.CallingCard); m_assetTypes.Add("Clothing", AssetType.Clothing); m_assetTypes.Add("CurrentOutfit", AssetType.CurrentOutfitFolder); m_assetTypes.Add("Current Outfit", AssetType.CurrentOutfitFolder); m_assetTypes.Add("Gesture", AssetType.Gesture); m_assetTypes.Add("Landmark", AssetType.Landmark); m_assetTypes.Add("Script", AssetType.LSLText); m_assetTypes.Add("Scripts", AssetType.LSLText); m_assetTypes.Add("Mesh", AssetType.Mesh); m_assetTypes.Add("Notecard", AssetType.Notecard); m_assetTypes.Add("Object", AssetType.Object); m_assetTypes.Add("Photo", AssetType.SnapshotFolder); m_assetTypes.Add("Snapshot", AssetType.SnapshotFolder); m_assetTypes.Add("Sound", AssetType.Sound); m_assetTypes.Add("Texture", AssetType.Texture); m_assetTypes.Add("Images", AssetType.Texture); } /// <summary> /// Use the asset set information at path to load assets /// </summary> /// <param name = "path"></param> /// <param name = "assets"></param> protected void LoadLibraries(string iarFileName) { RegionInfo regInfo = new RegionInfo(); IScene m_MockScene = null; //Make the scene for the IAR loader if (m_registry is IScene) m_MockScene = (IScene)m_registry; else { m_MockScene = new Scene(); m_MockScene.Initialize(regInfo); m_MockScene.AddModuleInterfaces(m_registry.GetInterfaces()); } UserAccount uinfo = m_MockScene.UserAccountService.GetUserAccount(null, m_service.LibraryOwner); //Make the user account for the default IAR if (uinfo == null) { MainConsole.Instance.Warn("Creating user " + m_service.LibraryOwnerName); m_MockScene.UserAccountService.CreateUser(m_service.LibraryOwner, UUID.Zero, m_service.LibraryOwnerName, "", ""); uinfo = m_MockScene.UserAccountService.GetUserAccount(null, m_service.LibraryOwner); m_MockScene.InventoryService.CreateUserInventory(uinfo.PrincipalID, false); } if (m_MockScene.InventoryService.GetRootFolder(m_service.LibraryOwner) == null) m_MockScene.InventoryService.CreateUserInventory(uinfo.PrincipalID, false); List<InventoryFolderBase> rootFolders = m_MockScene.InventoryService.GetFolderFolders(uinfo.PrincipalID, UUID.Zero); #if (!ISWIN) bool alreadyExists = false; foreach (InventoryFolderBase folder in rootFolders) { if (folder.Name == iarFileName) { alreadyExists = true; break; } } #else bool alreadyExists = rootFolders.Any(folder => folder.Name == iarFileName); #endif if (alreadyExists) { MainConsole.Instance.InfoFormat("[LIBRARY INVENTORY]: Found previously loaded iar file {0}, ignoring.", iarFileName); return; } MainConsole.Instance.InfoFormat("[LIBRARY INVENTORY]: Loading iar file {0}", iarFileName); InventoryFolderBase rootFolder = m_MockScene.InventoryService.GetRootFolder(uinfo.PrincipalID); if (null == rootFolder) { //We need to create the root folder, otherwise the IAR freaks m_MockScene.InventoryService.CreateUserInventory(uinfo.PrincipalID, false); } InventoryArchiveReadRequest archread = new InventoryArchiveReadRequest(m_MockScene, uinfo, "/", iarFileName, false, m_service.LibraryOwner); try { archread.ReplaceAssets = true;//Replace any old assets List<InventoryNodeBase> nodes = new List<InventoryNodeBase>(archread.Execute(true)); if (nodes.Count == 0) return; InventoryFolderBase f = (InventoryFolderBase)nodes[0]; UUID IARRootID = f.ID; TraverseFolders(IARRootID, m_MockScene); FixParent(IARRootID, m_MockScene, m_service.LibraryRootFolderID); f.Name = iarFileName; f.ParentID = UUID.Zero; f.ID = m_service.LibraryRootFolderID; f.Type = (int)AssetType.RootFolder; f.Version = 1; m_MockScene.InventoryService.UpdateFolder(f); } catch (Exception e) { MainConsole.Instance.DebugFormat("[LIBRARY MODULE]: Exception when processing archive {0}: {1}", iarFileName, e.StackTrace); } finally { archread.Close(); } } private void TraverseFolders(UUID ID, IScene m_MockScene) { List<InventoryFolderBase> folders = m_MockScene.InventoryService.GetFolderFolders(m_service.LibraryOwner, ID); foreach (InventoryFolderBase folder in folders) { InventoryFolderBase folder1 = folder; #if (!ISWIN) foreach (KeyValuePair<string, AssetType> type in m_assetTypes) { if (folder1.Name.ToLower().StartsWith(type.Key.ToLower())) { if (folder.Type == (short)type.Value) break; folder.Type = (short)type.Value; m_MockScene.InventoryService.UpdateFolder(folder); break; } } #else foreach (KeyValuePair<string, AssetType> type in m_assetTypes.Where(type => folder1.Name.ToLower().StartsWith(type.Key.ToLower())).TakeWhile(type => folder.Type != (short) type.Value)) { folder.Type = (short) type.Value; m_MockScene.InventoryService.UpdateFolder(folder); break; } #endif if (folder.Type == -1) { folder.Type = (int)AssetType.Folder; m_MockScene.InventoryService.UpdateFolder(folder); } TraverseFolders(folder.ID, m_MockScene); } } private void FixParent(UUID ID, IScene m_MockScene, UUID LibraryRootID) { List<InventoryFolderBase> folders = m_MockScene.InventoryService.GetFolderFolders(m_service.LibraryOwner, ID); foreach (InventoryFolderBase folder in folders) { if (folder.ParentID == ID) { folder.ParentID = LibraryRootID; m_Database.StoreFolder(folder); } } } private void FixPerms(InventoryNodeBase node) { if (node is InventoryItemBase) { InventoryItemBase item = (InventoryItemBase)node; item.BasePermissions = 0x7FFFFFFF; item.EveryOnePermissions = 0x7FFFFFFF; item.CurrentPermissions = 0x7FFFFFFF; item.NextPermissions = 0x7FFFFFFF; } } private string GetInventoryPathFromName(string name) { string[] parts = name.Split(new[] { ' ' }); if (parts.Length == 3) { name = string.Empty; // cut the last part for (int i = 0; i < parts.Length - 1; i++) name = name + ' ' + parts[i]; } return name; } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.IO; using OSGeo.GDAL; namespace DotSpatial.Data.Rasters.GdalExtension { /// <summary> /// GdalRasterProvider. /// </summary> public class GdalRasterProvider : IRasterProvider { #region Constructors static GdalRasterProvider() { GdalConfiguration.ConfigureGdal(); } /// <summary> /// Initializes a new instance of the <see cref="GdalRasterProvider"/> class. /// </summary> public GdalRasterProvider() { // Add ourself in for these extensions, unless another provider is registered for them. string[] extensions = { ".tif", ".tiff", ".adf" }; foreach (string extension in extensions) { if (!DataManager.DefaultDataManager.PreferredProviders.ContainsKey(extension)) { DataManager.DefaultDataManager.PreferredProviders.Add(extension, this); } } } #endregion #region Properties // This function checks if a GeoTiff dataset should be interpreted as a one-band raster // or as an image. Returns true if the dataset is a valid one-band raster. /// <summary> /// Gets the description of the raster. /// </summary> public string Description => "GDAL Integer Raster"; /// <summary> /// Gets the dialog filter to use when opening a file. /// </summary> public string DialogReadFilter => "GDAL Rasters|*.asc;*.adf;*.bil;*.gen;*.thf;*.blx;*.xlb;*.bt;*.dt0;*.dt1;*.dt2;*.tif;*.dem;*.ter;*.mem;*.img;*.nc"; /// <summary> /// Gets the dialog filter to use when saving to a file. /// </summary> public string DialogWriteFilter => "AAIGrid|*.asc;*.adf|DTED|*.dt0;*.dt1;*.dt2|GTiff|*.tif;*.tiff|TERRAGEN|*.ter|GenBin|*.bil|netCDF|*.nc|Imagine|*.img|GFF|*.gff|Terragen|*.ter"; /// <summary> /// Gets the name of the provider. /// </summary> public string Name => "GDAL Raster Provider"; /// <summary> /// Gets or sets the progress handler that gets updated with progress information. /// </summary> public IProgressHandler ProgressHandler { get; set; } #endregion #region Methods /// <summary> /// This create new method implies that this provider has the priority for creating a new file. /// An instance of the dataset should be created and then returned. By this time, the fileName /// will already be checked to see if it exists, and deleted if the user wants to overwrite it. /// </summary> /// <param name="name">The string fileName for the new instance.</param> /// <param name="driverCode">The string short name of the driver for creating the raster.</param> /// <param name="xSize">The number of columns in the raster.</param> /// <param name="ySize">The number of rows in the raster.</param> /// <param name="numBands">The number of bands to create in the raster.</param> /// <param name="dataType">The data type to use for the raster.</param> /// <param name="options">The options to be used.</param> /// <returns>An IRaster.</returns> public IRaster Create(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options) { if (File.Exists(name)) File.Delete(name); if (string.IsNullOrEmpty(driverCode)) { driverCode = GetDriverCode(Path.GetExtension(name)); } Driver d = Gdal.GetDriverByName(driverCode); if (d == null) { // We didn't find a matching driver. return null; } // Assign the Gdal dataType. DataType dt; if (dataType == typeof(int)) dt = DataType.GDT_Int32; else if (dataType == typeof(short)) dt = DataType.GDT_Int16; else if (dataType == typeof(uint)) dt = DataType.GDT_UInt32; else if (dataType == typeof(ushort)) dt = DataType.GDT_UInt16; else if (dataType == typeof(double)) dt = DataType.GDT_Float64; else if (dataType == typeof(float)) dt = DataType.GDT_Float32; else if (dataType == typeof(byte)) dt = DataType.GDT_Byte; else dt = DataType.GDT_Unknown; // Width, Height, and bands must "be positive" if (numBands == 0) numBands = 1; Dataset dataset = d.Create(name, xSize, ySize, numBands, dt, options); return WrapDataSetInRaster(name, dataType, dataset); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="fileName">Name of the file that gets opened.</param> /// <returns>The file as IRaster.</returns> public IRaster Open(string fileName) { IRaster result = null; var dataset = Helpers.Open(fileName); if (dataset != null) { // Single band rasters are easy, just return the band as the raster. // TODO: make a more complicated raster structure with individual bands. result = GetBand(fileName, dataset, dataset.GetRasterBand(1)); // If we opened the dataset but did not find a raster to return, close the dataset if (result == null) { dataset.Dispose(); } } return result; } /// <summary> /// Opens the specified file. /// </summary> /// <param name="fileName">Name of the file that gets opened.</param> /// <returns>The file as IDataSet.</returns> IDataSet IDataProvider.Open(string fileName) { return Open(fileName); } private static IRaster GetBand(string fileName, Dataset dataset, Band band) { Raster result = null; switch (band.DataType) { case DataType.GDT_Byte: result = new GdalRaster<byte>(fileName, dataset, band); break; case DataType.GDT_CFloat32: case DataType.GDT_CFloat64: case DataType.GDT_CInt16: case DataType.GDT_CInt32: break; case DataType.GDT_Float32: result = new GdalRaster<float>(fileName, dataset, band); break; case DataType.GDT_Float64: result = new GdalRaster<double>(fileName, dataset, band); break; case DataType.GDT_Int16: result = new GdalRaster<short>(fileName, dataset, band); break; case DataType.GDT_UInt16: case DataType.GDT_Int32: result = new GdalRaster<int>(fileName, dataset, band); break; case DataType.GDT_TypeCount: break; case DataType.GDT_UInt32: result = new GdalRaster<long>(fileName, dataset, band); break; case DataType.GDT_Unknown: break; default: break; } result?.Open(); return result; } private static string GetDriverCode(string fileExtension) { if (string.IsNullOrEmpty(fileExtension)) { return null; } switch (fileExtension.ToLower()) { case ".asc": return "AAIGrid"; case ".adf": return "AAIGrid"; case ".tiff": case ".tif": return "GTiff"; case ".img": return "HFA"; case ".gff": return "GFF"; case ".dt0": case ".dt1": case ".dt2": return "DTED"; case ".ter": return "Terragen"; case ".nc": return "netCDF"; default: return null; } } private static IRaster WrapDataSetInRaster(string name, Type dataType, Dataset dataset) { // todo: what about UInt32? if (dataType == typeof(int) || dataType == typeof(ushort)) { return new GdalRaster<int>(name, dataset); } if (dataType == typeof(short)) { return new GdalRaster<short>(name, dataset); } if (dataType == typeof(float)) { return new GdalRaster<float>(name, dataset); } if (dataType == typeof(double)) { return new GdalRaster<double>(name, dataset); } if (dataType == typeof(byte)) { return new GdalRaster<byte>(name, dataset); } // It was an unsupported type. if (dataset != null) { dataset.Dispose(); if (File.Exists(name)) File.Delete(name); } return null; } #endregion } }
using GuiLabs.Editor.Blocks; using GuiLabs.Editor.Actions; using GuiLabs.Editor.UI; using GuiLabs.Canvas.DrawStyle; using GuiLabs.Undo; namespace GuiLabs.Editor.CSharp { [BlockSerialization("accessors")] public class InterfaceAccessorsBlock : HContainerBlock { public InterfaceAccessorsBlock() { Empty = new TextBoxBlock(); Empty.MyTextBox.MinWidth = 1; Empty.MyTextBox.Box.Margins.SetLeftAndRight(ShapeStyle.DefaultFontSize / 2); Empty.MyTextBox.Box.SetMouseSensitivityToMargins(); this.MyControl.Focusable = true; this.MyControl.Stretch = GuiLabs.Canvas.Controls.StretchMode.None; this.MyControl.Box.Margins.SetLeftAndRight(ShapeStyle.DefaultFontSize); this.MyControl.Box.SetMouseSensitivityToMargins(); InternalContainer = new HContainerBlock(); this.Add("{"); this.Add(InternalContainer); this.Add("}"); InternalContainer.Add(Empty); } #region OnEvents protected override void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == System.Windows.Forms.Keys.G) { AddGetter(); e.Handled = true; } else if (e.KeyCode == System.Windows.Forms.Keys.S) { AddSetter(); e.Handled = true; } if (!e.Handled) { base.OnKeyDown(sender, e); } } #endregion private HContainerBlock mInternalContainer; public HContainerBlock InternalContainer { get { return mInternalContainer; } set { if (mInternalContainer != null) { mInternalContainer.Children.CollectionChanged -= Children_CollectionChanged; } mInternalContainer = value; if (mInternalContainer != null) { mInternalContainer.Children.CollectionChanged += Children_CollectionChanged; } } } void Children_CollectionChanged() { UpdateGetterAndSetter(); } private void UpdateGetterAndSetter() { bool getterFound = false; bool setterFound = false; foreach (Block b in InternalContainer.Children) { InterfacePropertyAccessor accessor = b as InterfacePropertyAccessor; if (accessor != null) { if (accessor.Text == Keywords.Get) { getterFound = true; if (mGetter != accessor) { mGetter = accessor; } } else if (accessor.Text == Keywords.Set) { setterFound = true; if (mSetter != accessor) { mSetter = accessor; } } } } if (!getterFound && mGetter != null) { mGetter = null; } if (!setterFound && mSetter != null) { mSetter = null; } Empty.Hidden = Getter != null && Setter != null; InternalContainer.CheckVisibility(); InternalContainer.MyControl.Redraw(); } private TextBoxBlock mEmpty; public TextBoxBlock Empty { get { return mEmpty; } set { if (mEmpty != null) { mEmpty.MyTextBox.PreviewKeyPress -= MyTextBox_PreviewKeyPress; mEmpty.MyTextBox.KeyDown -= MyTextBox_KeyDown; } mEmpty = value; if (mEmpty != null) { mEmpty.MyTextBox.PreviewKeyPress += MyTextBox_PreviewKeyPress; mEmpty.MyTextBox.KeyDown += MyTextBox_KeyDown; } } } void MyTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == System.Windows.Forms.Keys.Back) { if (Getter != null) { Getter = null; e.Handled = true; } else if (Setter == null) { this.Delete(); e.Handled = true; } } if (e.KeyCode == System.Windows.Forms.Keys.Delete) { if (Setter != null) { Setter = null; e.Handled = true; } else if (Getter == null) { this.Delete(); e.Handled = true; } } } void MyTextBox_PreviewKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if (e.KeyChar == 's') { AddSetter(); } else if (e.KeyChar == 'g') { AddGetter(); } e.Handled = true; } #region API public void AddGetter() { if (Getter == null) { Getter = new InterfacePropertyAccessor(Keywords.Get); } } public void AddSetter() { if (Setter == null) { Setter = new InterfacePropertyAccessor(Keywords.Set); } } #endregion private InterfacePropertyAccessor mGetter; public InterfacePropertyAccessor Getter { get { return mGetter; } set { if (ActionManager != null) { using (Transaction.Create(this.ActionManager)) { if (mGetter != null) { mGetter.KeyDown -= mGetter_KeyDown; mGetter.Delete(); } mGetter = value; if (mGetter != null) { if (mSetter != null) { Empty.Hidden = false; } InternalContainer.AddToBeginning(mGetter); if (!Empty.Hidden) { Empty.SetFocus(); } mGetter.Deleted += mGetter_Deleted; mGetter.KeyDown += mGetter_KeyDown; } } } else { if (mGetter != null) { mGetter.KeyDown -= mGetter_KeyDown; mGetter.Delete(); } mGetter = value; if (mGetter != null) { if (mSetter != null) { Empty.Hidden = false; } InternalContainer.AddToBeginning(mGetter); if (!Empty.Hidden) { Empty.SetFocus(); } mGetter.Deleted += mGetter_Deleted; mGetter.KeyDown += mGetter_KeyDown; } } } } void mGetter_KeyDown(Block block, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == System.Windows.Forms.Keys.Delete || e.KeyCode == System.Windows.Forms.Keys.Back) { Getter = null; e.Handled = true; } if (e.KeyCode == System.Windows.Forms.Keys.S) { AddSetter(); } } void mGetter_Deleted(Block itemChanged) { using (Redrawer r = new Redrawer(this.Root)) { if (mGetter != null) { mGetter.Deleted -= mGetter_Deleted; mGetter = null; } Empty.Hidden = false; Empty.SetFocus(); } } private InterfacePropertyAccessor mSetter; public InterfacePropertyAccessor Setter { get { return mSetter; } set { if (ActionManager != null) { using (ActionManager.CreateTransaction()) { if (mSetter != null) { mSetter.KeyDown -= mSetter_KeyDown; mSetter.Delete(); } mSetter = value; if (mSetter != null) { if (mGetter != null) { Empty.Hidden = true; } InternalContainer.Add(mSetter); if (Empty.IsVisible) { Empty.SetFocus(); } mSetter.Deleted += mSetter_Deleted; mSetter.KeyDown += mSetter_KeyDown; } } } else { if (mSetter != null) { mSetter.KeyDown -= mSetter_KeyDown; mSetter.Delete(); } mSetter = value; if (mSetter != null) { if (mGetter != null) { Empty.Hidden = true; } InternalContainer.Add(mSetter); if (Empty.IsVisible) { Empty.SetFocus(); } mSetter.Deleted += mSetter_Deleted; mSetter.KeyDown += mSetter_KeyDown; } } } } void mSetter_KeyDown(Block block, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == System.Windows.Forms.Keys.Back || e.KeyCode == System.Windows.Forms.Keys.Delete) { Setter = null; e.Handled = true; } if (e.KeyCode == System.Windows.Forms.Keys.G) { AddGetter(); } } void mSetter_Deleted(Block itemChanged) { using (Redrawer r = new Redrawer(this.Root)) { if (mSetter != null) { mSetter.Deleted -= mSetter_Deleted; mSetter = null; } Empty.Hidden = false; Empty.SetFocus(); } } #region DefaultFocusableBlock public override GuiLabs.Canvas.Controls.Control DefaultFocusableControl() { if (Empty.IsVisible) { return Empty.MyTextBox; } if (Getter != null) { return Getter.MyControl; } if (Setter != null) { return Setter.MyControl; } return this.MyControl; } #endregion #region Style protected override string StyleName() { return "InterfaceAccessorsBlock"; } #endregion } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Diagnostics; using Astrid.Core; namespace Astrid.FarseerPhysics.Dynamics.Joints { public enum JointType { Unknown, Revolute, Prismatic, Distance, Pulley, //Mouse, <- We have fixed mouse Gear, Wheel, Weld, Friction, Rope, Motor, //FPE note: From here on and down, it is only FPE joints Angle, FixedMouse, FixedRevolute, FixedDistance, FixedLine, FixedPrismatic, FixedAngle, FixedFriction, } public enum LimitState { Inactive, AtLower, AtUpper, Equal, } /// <summary> /// A joint edge is used to connect bodies and joints together /// in a joint graph where each body is a node and each joint /// is an edge. A joint edge belongs to a doubly linked list /// maintained in each attached body. Each joint has two joint /// nodes, one for each attached body. /// </summary> public sealed class JointEdge { /// <summary> /// The joint. /// </summary> public Joint Joint; /// <summary> /// The next joint edge in the body's joint list. /// </summary> public JointEdge Next; /// <summary> /// Provides quick access to the other body attached. /// </summary> public Body Other; /// <summary> /// The previous joint edge in the body's joint list. /// </summary> public JointEdge Prev; } public abstract class Joint { private float _breakpoint; private double _breakpointSquared; /// <summary> /// Indicate if this join is enabled or not. Disabling a joint /// means it is still in the simulation, but inactive. /// </summary> public bool Enabled = true; internal JointEdge EdgeA = new JointEdge(); internal JointEdge EdgeB = new JointEdge(); internal bool IslandFlag; protected Joint() { Breakpoint = float.MaxValue; //Connected bodies should not collide by default CollideConnected = false; } protected Joint(Body bodyA, Body bodyB) : this() { //Can't connect a joint to the same body twice. Debug.Assert(bodyA != bodyB); BodyA = bodyA; BodyB = bodyB; } /// <summary> /// Constructor for fixed joint /// </summary> protected Joint(Body body) : this() { BodyA = body; } /// <summary> /// Gets or sets the type of the joint. /// </summary> /// <value>The type of the joint.</value> public JointType JointType { get; protected set; } /// <summary> /// Get the first body attached to this joint. /// </summary> public Body BodyA { get; internal set; } /// <summary> /// Get the second body attached to this joint. /// </summary> public Body BodyB { get; internal set; } /// <summary> /// Get the anchor point on bodyA in world coordinates. /// On some joints, this value indicate the anchor point within the world. /// </summary> public abstract Vector2 WorldAnchorA { get; set; } /// <summary> /// Get the anchor point on bodyB in world coordinates. /// On some joints, this value indicate the anchor point within the world. /// </summary> public abstract Vector2 WorldAnchorB { get; set; } /// <summary> /// Set the user data pointer. /// </summary> /// <value>The data.</value> public object UserData { get; set; } /// <summary> /// Set this flag to true if the attached bodies should collide. /// </summary> public bool CollideConnected { get; set; } /// <summary> /// The Breakpoint simply indicates the maximum Value the JointError can be before it breaks. /// The default value is float.MaxValue, which means it never breaks. /// </summary> public float Breakpoint { get { return _breakpoint; } set { _breakpoint = value; _breakpointSquared = _breakpoint * _breakpoint; } } /// <summary> /// Fires when the joint is broken. /// </summary> public event Action<Joint, float> Broke; /// <summary> /// Get the reaction force on body at the joint anchor in Newtons. /// </summary> /// <param name="invDt">The inverse delta time.</param> public abstract Vector2 GetReactionForce(float invDt); /// <summary> /// Get the reaction torque on the body at the joint anchor in N*m. /// </summary> /// <param name="invDt">The inverse delta time.</param> public abstract float GetReactionTorque(float invDt); protected void WakeBodies() { if (BodyA != null) BodyA.Awake = true; if (BodyB != null) BodyB.Awake = true; } /// <summary> /// Return true if the joint is a fixed type. /// </summary> public bool IsFixedType() { return JointType == JointType.FixedRevolute || JointType == JointType.FixedDistance || JointType == JointType.FixedPrismatic || JointType == JointType.FixedLine || JointType == JointType.FixedMouse || JointType == JointType.FixedAngle || JointType == JointType.FixedFriction; } internal abstract void InitVelocityConstraints(ref SolverData data); internal void Validate(float invDt) { if (!Enabled) return; float jointErrorSquared = GetReactionForce(invDt).LengthSquared(); if (Math.Abs(jointErrorSquared) <= _breakpointSquared) return; Enabled = false; if (Broke != null) Broke(this, (float)Math.Sqrt(jointErrorSquared)); } internal abstract void SolveVelocityConstraints(ref SolverData data); /// <summary> /// Solves the position constraints. /// </summary> /// <param name="data"></param> /// <returns>returns true if the position errors are within tolerance.</returns> internal abstract bool SolvePositionConstraints(ref SolverData data); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; namespace Microsoft.AzureStack.Management { public static partial class ManagedOfferOperationsExtensions { /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferCreateOrUpdateResult CreateOrUpdate(this IManagedOfferOperations operations, string resourceGroupName, ManagedOfferCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferCreateOrUpdateResult> CreateOrUpdateAsync(this IManagedOfferOperations operations, string resourceGroupName, ManagedOfferCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IManagedOfferOperations operations, string resourceGroupName, string offerId) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).DeleteAsync(resourceGroupName, offerId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId) { return operations.DeleteAsync(resourceGroupName, offerId, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferGetResult Get(this IManagedOfferOperations operations, string resourceGroupName, string offerId) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).GetAsync(resourceGroupName, offerId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferGetResult> GetAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId) { return operations.GetAsync(resourceGroupName, offerId, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <param name='metricDefinitionId'> /// Required. Your documentation here. /// </param> /// <param name='filter'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferGetMetricDefinitionsResult GetMetricDefinitions(this IManagedOfferOperations operations, string resourceGroupName, string offerId, string metricDefinitionId, string filter) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).GetMetricDefinitionsAsync(resourceGroupName, offerId, metricDefinitionId, filter); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <param name='metricDefinitionId'> /// Required. Your documentation here. /// </param> /// <param name='filter'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferGetMetricDefinitionsResult> GetMetricDefinitionsAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId, string metricDefinitionId, string filter) { return operations.GetMetricDefinitionsAsync(resourceGroupName, offerId, metricDefinitionId, filter, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <param name='metricId'> /// Required. Your documentation here. /// </param> /// <param name='filter'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferGetMetricsResult GetMetrics(this IManagedOfferOperations operations, string resourceGroupName, string offerId, string metricId, string filter) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).GetMetricsAsync(resourceGroupName, offerId, metricId, filter); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerId'> /// Required. Your documentation here. /// </param> /// <param name='metricId'> /// Required. Your documentation here. /// </param> /// <param name='filter'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferGetMetricsResult> GetMetricsAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId, string metricId, string filter) { return operations.GetMetricsAsync(resourceGroupName, offerId, metricId, filter, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferLinkResult Link(this IManagedOfferOperations operations, string resourceGroupName, string offerName, ManagedOfferLinkParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).LinkAsync(resourceGroupName, offerName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferLinkResult> LinkAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerName, ManagedOfferLinkParameters parameters) { return operations.LinkAsync(resourceGroupName, offerName, parameters, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='includeDetails'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferListResult List(this IManagedOfferOperations operations, string resourceGroupName, bool includeDetails) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).ListAsync(resourceGroupName, includeDetails); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='includeDetails'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferListResult> ListAsync(this IManagedOfferOperations operations, string resourceGroupName, bool includeDetails) { return operations.ListAsync(resourceGroupName, includeDetails, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferListResult ListNext(this IManagedOfferOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferListResult> ListNextAsync(this IManagedOfferOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='includeDetails'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferListResult ListWithoutResourceGroup(this IManagedOfferOperations operations, bool includeDetails) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).ListWithoutResourceGroupAsync(includeDetails); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='includeDetails'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferListResult> ListWithoutResourceGroupAsync(this IManagedOfferOperations operations, bool includeDetails) { return operations.ListWithoutResourceGroupAsync(includeDetails, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ManagedOfferUnlinkResult Unlink(this IManagedOfferOperations operations, string resourceGroupName, string offerName, ManagedOfferUnlinkParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IManagedOfferOperations)s).UnlinkAsync(resourceGroupName, offerName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IManagedOfferOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <param name='offerName'> /// Required. Your documentation here. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ManagedOfferUnlinkResult> UnlinkAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerName, ManagedOfferUnlinkParameters parameters) { return operations.UnlinkAsync(resourceGroupName, offerName, parameters, CancellationToken.None); } } }
namespace Krystals4Application { partial class MainWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.constantkrystalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.expansionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.graftkrystalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.justifiedkrystalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.linekrystalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.modulatedkrystalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.NewModulatedKrystalMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openKrystalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.OpenConstantToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.OpenExpansionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.extractionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.graftToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.justificationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.OpenLineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.OpenModulatedKrystalMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MenuItemQuit = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutKrystals40ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.NewLineKrysButton = new System.Windows.Forms.Button(); this.NewConstKrysButton = new System.Windows.Forms.Button(); this.NewExpKrysButton = new System.Windows.Forms.Button(); this.NewModKrysButton = new System.Windows.Forms.Button(); this.MenuItemRebuildKrystalFamily = new System.Windows.Forms.ToolStripMenuItem(); this.RebuildKrystalFamilyButton = new System.Windows.Forms.Button(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(424, 24); this.menuStrip1.TabIndex = 4; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem, this.openKrystalToolStripMenuItem, this.MenuItemRebuildKrystalFamily, this.MenuItemQuit}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "File"; // // newToolStripMenuItem // this.newToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.constantkrystalToolStripMenuItem, this.expansionToolStripMenuItem, this.graftkrystalToolStripMenuItem, this.justifiedkrystalToolStripMenuItem, this.linekrystalToolStripMenuItem, this.modulatedkrystalToolStripMenuItem, this.NewModulatedKrystalMenuItem}); this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.newToolStripMenuItem.Text = "New krystal..."; // // constantkrystalToolStripMenuItem // this.constantkrystalToolStripMenuItem.Name = "constantkrystalToolStripMenuItem"; this.constantkrystalToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.constantkrystalToolStripMenuItem.Text = "constant..."; this.constantkrystalToolStripMenuItem.Click += new System.EventHandler(this.NewConstantKrystalMenuItem_Click); // // expansionToolStripMenuItem // this.expansionToolStripMenuItem.Name = "expansionToolStripMenuItem"; this.expansionToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.expansionToolStripMenuItem.Text = "expansion..."; this.expansionToolStripMenuItem.Click += new System.EventHandler(this.NewExpansionKrystalMenuItem_Click); // // graftkrystalToolStripMenuItem // this.graftkrystalToolStripMenuItem.Enabled = false; this.graftkrystalToolStripMenuItem.Name = "graftkrystalToolStripMenuItem"; this.graftkrystalToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.graftkrystalToolStripMenuItem.Text = "extraction..."; // // justifiedkrystalToolStripMenuItem // this.justifiedkrystalToolStripMenuItem.Enabled = false; this.justifiedkrystalToolStripMenuItem.Name = "justifiedkrystalToolStripMenuItem"; this.justifiedkrystalToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.justifiedkrystalToolStripMenuItem.Text = "graft..."; // // linekrystalToolStripMenuItem // this.linekrystalToolStripMenuItem.Enabled = false; this.linekrystalToolStripMenuItem.Name = "linekrystalToolStripMenuItem"; this.linekrystalToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.linekrystalToolStripMenuItem.Text = "justification..."; // // modulatedkrystalToolStripMenuItem // this.modulatedkrystalToolStripMenuItem.Name = "modulatedkrystalToolStripMenuItem"; this.modulatedkrystalToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.modulatedkrystalToolStripMenuItem.Text = "line..."; this.modulatedkrystalToolStripMenuItem.Click += new System.EventHandler(this.NewLineKrystalMenuItem_Click); // // NewModulatedKrystalMenuItem // this.NewModulatedKrystalMenuItem.Name = "NewModulatedKrystalMenuItem"; this.NewModulatedKrystalMenuItem.Size = new System.Drawing.Size(141, 22); this.NewModulatedKrystalMenuItem.Text = "modulation..."; this.NewModulatedKrystalMenuItem.Click += new System.EventHandler(this.NewModulatedKrystalMenuItem_Click); // // openKrystalToolStripMenuItem // this.openKrystalToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.OpenConstantToolStripMenuItem, this.OpenExpansionToolStripMenuItem, this.extractionToolStripMenuItem, this.graftToolStripMenuItem, this.justificationToolStripMenuItem, this.OpenLineToolStripMenuItem, this.OpenModulatedKrystalMenuItem}); this.openKrystalToolStripMenuItem.Name = "openKrystalToolStripMenuItem"; this.openKrystalToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.openKrystalToolStripMenuItem.Text = "Open krystal..."; // // OpenConstantToolStripMenuItem // this.OpenConstantToolStripMenuItem.Name = "OpenConstantToolStripMenuItem"; this.OpenConstantToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.OpenConstantToolStripMenuItem.Text = "constant..."; this.OpenConstantToolStripMenuItem.Click += new System.EventHandler(this.OpenConstantKrystalMenuItem_Click); // // OpenExpansionToolStripMenuItem // this.OpenExpansionToolStripMenuItem.Name = "OpenExpansionToolStripMenuItem"; this.OpenExpansionToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.OpenExpansionToolStripMenuItem.Text = "expansion..."; this.OpenExpansionToolStripMenuItem.Click += new System.EventHandler(this.OpenExpansionKrystalMenuItem_Click); // // extractionToolStripMenuItem // this.extractionToolStripMenuItem.Enabled = false; this.extractionToolStripMenuItem.Name = "extractionToolStripMenuItem"; this.extractionToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.extractionToolStripMenuItem.Text = "extraction..."; // // graftToolStripMenuItem // this.graftToolStripMenuItem.Enabled = false; this.graftToolStripMenuItem.Name = "graftToolStripMenuItem"; this.graftToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.graftToolStripMenuItem.Text = "graft..."; // // justificationToolStripMenuItem // this.justificationToolStripMenuItem.Enabled = false; this.justificationToolStripMenuItem.Name = "justificationToolStripMenuItem"; this.justificationToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.justificationToolStripMenuItem.Text = "justification..."; // // OpenLineToolStripMenuItem // this.OpenLineToolStripMenuItem.Name = "OpenLineToolStripMenuItem"; this.OpenLineToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.OpenLineToolStripMenuItem.Text = "line..."; this.OpenLineToolStripMenuItem.Click += new System.EventHandler(this.OpenLineKrystalMenuItem_Click); // // OpenModulatedKrystalMenuItem // this.OpenModulatedKrystalMenuItem.Name = "OpenModulatedKrystalMenuItem"; this.OpenModulatedKrystalMenuItem.Size = new System.Drawing.Size(141, 22); this.OpenModulatedKrystalMenuItem.Text = "modulation..."; this.OpenModulatedKrystalMenuItem.Click += new System.EventHandler(this.OpenModulatedKrystalMenuItem_Click); // // MenuItemQuit // this.MenuItemQuit.Name = "MenuItemQuit"; this.MenuItemQuit.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Q))); this.MenuItemQuit.Size = new System.Drawing.Size(175, 22); this.MenuItemQuit.Text = "Quit"; this.MenuItemQuit.Click += new System.EventHandler(this.MenuItemQuit_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.editToolStripMenuItem.Text = "Edit"; // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutKrystals40ToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.helpToolStripMenuItem.Text = "Help"; // // aboutKrystals40ToolStripMenuItem // this.aboutKrystals40ToolStripMenuItem.Name = "aboutKrystals40ToolStripMenuItem"; this.aboutKrystals40ToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.aboutKrystals40ToolStripMenuItem.Text = "About Krystals 4.0..."; this.aboutKrystals40ToolStripMenuItem.Click += new System.EventHandler(this.About_Click); // // NewLineKrysButton // this.NewLineKrysButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.NewLineKrysButton.Location = new System.Drawing.Point(42, 127); this.NewLineKrysButton.Name = "NewLineKrysButton"; this.NewLineKrysButton.Size = new System.Drawing.Size(160, 42); this.NewLineKrysButton.TabIndex = 2; this.NewLineKrysButton.Text = "new line krystal"; this.NewLineKrysButton.Click += new System.EventHandler(this.NewLineKrystalMenuItem_Click); // // NewConstKrysButton // this.NewConstKrysButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.NewConstKrysButton.Location = new System.Drawing.Point(42, 67); this.NewConstKrysButton.Name = "NewConstKrysButton"; this.NewConstKrysButton.Size = new System.Drawing.Size(160, 42); this.NewConstKrysButton.TabIndex = 3; this.NewConstKrysButton.Text = "new constant krystal"; this.NewConstKrysButton.Click += new System.EventHandler(this.NewConstantKrystalMenuItem_Click); // // NewExpKrysButton // this.NewExpKrysButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.NewExpKrysButton.Location = new System.Drawing.Point(42, 187); this.NewExpKrysButton.Name = "NewExpKrysButton"; this.NewExpKrysButton.Size = new System.Drawing.Size(160, 42); this.NewExpKrysButton.TabIndex = 1; this.NewExpKrysButton.Text = "open expansion editor"; this.NewExpKrysButton.Click += new System.EventHandler(this.NewExpansionKrystalMenuItem_Click); // // NewModKrysButton // this.NewModKrysButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.NewModKrysButton.Location = new System.Drawing.Point(42, 247); this.NewModKrysButton.Name = "NewModKrysButton"; this.NewModKrysButton.Size = new System.Drawing.Size(160, 42); this.NewModKrysButton.TabIndex = 0; this.NewModKrysButton.Text = "open modulation editor"; this.NewModKrysButton.Click += new System.EventHandler(this.NewModulatedKrystalMenuItem_Click); // // MenuItemRebuildKrystalFamily // this.MenuItemRebuildKrystalFamily.Name = "MenuItemRebuildKrystalFamily"; this.MenuItemRebuildKrystalFamily.Size = new System.Drawing.Size(175, 22); this.MenuItemRebuildKrystalFamily.Text = "Rebuild krystal family"; this.MenuItemRebuildKrystalFamily.Click += new System.EventHandler(this.MenuItemRebuildKrystalFamily_Click); // // RebuildKrystalFamilyButton // this.RebuildKrystalFamilyButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.RebuildKrystalFamilyButton.Location = new System.Drawing.Point(231, 67); this.RebuildKrystalFamilyButton.Name = "RebuildKrystalFamilyButton"; this.RebuildKrystalFamilyButton.Size = new System.Drawing.Size(160, 42); this.RebuildKrystalFamilyButton.TabIndex = 5; this.RebuildKrystalFamilyButton.Text = "rebuild krystal family"; this.RebuildKrystalFamilyButton.Click += new System.EventHandler(this.MenuItemRebuildKrystalFamily_Click); // // MainWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ControlLight; this.ClientSize = new System.Drawing.Size(424, 410); this.Controls.Add(this.RebuildKrystalFamilyButton); this.Controls.Add(this.NewModKrysButton); this.Controls.Add(this.NewExpKrysButton); this.Controls.Add(this.NewConstKrysButton); this.Controls.Add(this.NewLineKrysButton); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "MainWindow"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Krystals 4.0"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem constantkrystalToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem expansionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutKrystals40ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem graftkrystalToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem justifiedkrystalToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem linekrystalToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem modulatedkrystalToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem NewModulatedKrystalMenuItem; private System.Windows.Forms.Button NewLineKrysButton; private System.Windows.Forms.Button NewConstKrysButton; private System.Windows.Forms.Button NewExpKrysButton; private System.Windows.Forms.ToolStripMenuItem openKrystalToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem OpenConstantToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem OpenExpansionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem extractionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem graftToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem justificationToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem OpenLineToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem OpenModulatedKrystalMenuItem; private System.Windows.Forms.Button NewModKrysButton; private System.Windows.Forms.ToolStripMenuItem MenuItemQuit; private System.Windows.Forms.ToolStripMenuItem MenuItemRebuildKrystalFamily; private System.Windows.Forms.Button RebuildKrystalFamilyButton; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Drawing.Imaging; using System.Drawing; using System.Drawing.Drawing2D; using System.ComponentModel; using System.Windows.Forms; using Project31.Controls; using System.Diagnostics; using Project31.CoreServices; namespace Project31.ApplicationFramework { /// <summary> /// Lightweight work pane control. /// </summary> internal class WorkPaneLightweightControl : LightweightControl { /// <summary> /// Top left bitmap. /// </summary> private static Bitmap topLeftBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.Application.WorkPaneTopLeft.png"); /// <summary> /// Top right bitmap. /// </summary> private static Bitmap topRightBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.Application.WorkPaneTopRight.png"); /// <summary> /// Bottom left bitmap. /// </summary> private static Bitmap bottomLeftBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.Application.WorkPaneBottomLeft.png"); /// <summary> /// Bottom right bitmap. /// </summary> private static Bitmap bottomRightBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.Application.WorkPaneBottomRight.png"); /// <summary> /// Top bitmap. /// </summary> private static Bitmap topBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.Application.WorkPaneTop.png"); /// <summary> /// Bottom bitmap. /// </summary> private static Bitmap bottomBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.Application.WorkPaneBottom.png"); /// <summary> /// Left bitmap. /// </summary> private static Bitmap leftBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.Application.WorkPaneLeft.png"); /// <summary> /// Right bitmap. /// </summary> private static Bitmap rightBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.Application.WorkPaneRight.png"); /// <summary> /// The command bar lightweight control. /// </summary> private Project31.ApplicationFramework.CommandBarLightweightControl commandBarLightweightControl; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components; /// <summary> /// The control. /// </summary> private Control control; /// <summary> /// Gets or sets the control. /// </summary> public Control Control { get { return control; } set { if (control != null && Parent != null && Parent.Controls.Contains(control)) Parent.Controls.Remove(control); control = value; PerformLayout(); Invalidate(); } } /// <summary> /// Initializes a new instance of the WorkPaneLightweightControl class. /// </summary> public WorkPaneLightweightControl(System.ComponentModel.IContainer container) { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> container.Add(this); InitializeComponent(); } /// <summary> /// Initializes a new instance of the WorkPaneLightweightControl class. /// </summary> public WorkPaneLightweightControl() { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> InitializeComponent(); } /// <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.commandBarLightweightControl = new Project31.ApplicationFramework.CommandBarLightweightControl(this.components); // // commandBarLightweightControl // this.commandBarLightweightControl.LightweightControlContainerControl = this; } /// <summary> /// Gets the command bar rectangle. /// </summary> private Rectangle CommandBarRectangle { get { return new Rectangle( topLeftBitmap.Width, topBitmap.Height, VirtualWidth-(topLeftBitmap.Width+topRightBitmap.Width), topLeftBitmap.Height-topBitmap.Height); } } /// <summary> /// Gets the control rectangle. /// </summary> private Rectangle ControlRectangle { get { return new Rectangle( leftBitmap.Width, topLeftBitmap.Height, VirtualWidth-(leftBitmap.Width+rightBitmap.Width+1), VirtualHeight-(topLeftBitmap.Height+bottomBitmap.Height+1)); } } /// <summary> /// Raises the Layout event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnLayout(System.EventArgs e) { // Call the base class's method so registered delegates receive the event. base.OnLayout(e); // Set the bounds of the command bar lightweight control. commandBarLightweightControl.VirtualBounds = CommandBarRectangle; if (control != null) { if (Parent != null && !Parent.Controls.Contains(control)) { Parent.Controls.Add(control); if (control is ICommandBarProvider) commandBarLightweightControl.CommandBarDefinition = ((ICommandBarProvider)control).CommandBarDefinition; } control.Bounds = VirtualClientRectangleToParent(ControlRectangle); } } /// <summary> /// Raises the Paint event. /// </summary> /// <param name="e">A PaintEventArgs that contains the event data.</param> protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { // Create a rectangle representing the header area to be filled. Rectangle headerRectangle = new Rectangle( 0, 0, VirtualWidth-(topLeftBitmap.Width+topRightBitmap.Width), topLeftBitmap.Height-1); if (!headerRectangle.IsEmpty) { // Construct an offscreen bitmap. Bitmap bitmap = new Bitmap(headerRectangle.Width, headerRectangle.Height); Graphics bitmapGraphics = Graphics.FromImage(bitmap); LinearGradientBrush linearGradientBrush = new LinearGradientBrush( headerRectangle, Color.FromArgb(231, 231, 232), Color.FromArgb(185, 218, 233), LinearGradientMode.Horizontal); bitmapGraphics.FillRectangle(linearGradientBrush, headerRectangle); linearGradientBrush.Dispose(); bitmapGraphics.Dispose(); e.Graphics.DrawImageUnscaled(bitmap, topLeftBitmap.Width, 1); } // Fill in the client rectangle. Rectangle clientArea = new Rectangle( leftBitmap.Width-1, topLeftBitmap.Height, VirtualWidth-((leftBitmap.Width-1)+rightBitmap.Width), VirtualHeight-(topLeftBitmap.Height+bottomBitmap.Height)); e.Graphics.FillRectangle(System.Drawing.Brushes.White, clientArea); // Draw the border. DrawBorder(e.Graphics); // Call the base class's method so that registered delegates receive the event. base.OnPaint(e); } /// <summary> /// Helper to draw the work pane border. /// </summary> /// <param name="graphics">Graphics context into which the border is drawn.</param> private void DrawBorder(Graphics graphics) { // Draw the top left corner of the border. if (topLeftBitmap != null) graphics.DrawImageUnscaled(topLeftBitmap, 0, 0); // Draw the top right corner of the border. if (topRightBitmap != null) graphics.DrawImageUnscaled(topRightBitmap, VirtualWidth-topRightBitmap.Width, 0); // Draw the bottom left corner of the border. if (bottomLeftBitmap != null) graphics.DrawImageUnscaled(bottomLeftBitmap, 0, VirtualHeight-bottomLeftBitmap.Height); // Draw the bottom right corner of the border. if (bottomRightBitmap != null) graphics.DrawImageUnscaled(bottomRightBitmap, VirtualWidth-bottomRightBitmap.Width, VirtualHeight-bottomRightBitmap.Height); // Fill the top. if (topBitmap != null) { Rectangle fillRectangle = new Rectangle(topLeftBitmap.Width, 0, VirtualWidth-(topLeftBitmap.Width+topRightBitmap.Width), topBitmap.Height); GraphicsHelper.TileFillUnscaledImageHorizontally(graphics, topBitmap, fillRectangle); } // Fill the left. if (leftBitmap != null) { Rectangle fillRectangle = new Rectangle(0, topLeftBitmap.Height, leftBitmap.Width, VirtualHeight-(topLeftBitmap.Height+bottomLeftBitmap.Height)); GraphicsHelper.TileFillUnscaledImageVertically(graphics, leftBitmap, fillRectangle); } // Fill the right. if (rightBitmap != null) { Rectangle fillRectangle = new Rectangle(VirtualWidth-rightBitmap.Width, topRightBitmap.Height, rightBitmap.Width, VirtualHeight-(topRightBitmap.Height+bottomRightBitmap.Height)); GraphicsHelper.TileFillUnscaledImageVertically(graphics, rightBitmap, fillRectangle); } // Fill the bottom. if (bottomBitmap != null) { Rectangle fillRectangle = new Rectangle(bottomLeftBitmap.Width, VirtualHeight-bottomBitmap.Height, VirtualWidth-(bottomLeftBitmap.Width+bottomRightBitmap.Width), bottomBitmap.Height); GraphicsHelper.TileFillUnscaledImageHorizontally(graphics, bottomBitmap, fillRectangle); } } } }
/* **************************************************************************** * * 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.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace Microsoft.Scripting.Interpreter { internal abstract class NumericConvertInstruction : Instruction { internal readonly TypeCode _from, _to; protected NumericConvertInstruction(TypeCode from, TypeCode to) { _from = from; _to = to; } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override string ToString() { return InstructionName + "(" + _from + "->" + _to + ")"; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public sealed class Unchecked : NumericConvertInstruction { public override string InstructionName { get { return "UncheckedConvert"; } } public Unchecked(TypeCode from, TypeCode to) : base(from, to) { } public override int Run(InterpretedFrame frame) { frame.Push(Convert(frame.Pop())); return +1; } private object Convert(object obj) { switch (_from) { case TypeCode.Byte: return ConvertInt32((Byte)obj); case TypeCode.SByte: return ConvertInt32((SByte)obj); case TypeCode.Int16: return ConvertInt32((Int16)obj); case TypeCode.Char: return ConvertInt32((Char)obj); case TypeCode.Int32: return ConvertInt32((Int32)obj); case TypeCode.Int64: return ConvertInt64((Int64)obj); case TypeCode.UInt16: return ConvertInt32((UInt16)obj); case TypeCode.UInt32: return ConvertInt64((UInt32)obj); case TypeCode.UInt64: return ConvertUInt64((UInt64)obj); case TypeCode.Single: return ConvertDouble((Single)obj); case TypeCode.Double: return ConvertDouble((Double)obj); default: throw Assert.Unreachable; } } private object ConvertInt32(int obj) { unchecked { switch (_to) { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (Char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (Double)obj; default: throw Assert.Unreachable; } } } private object ConvertInt64(Int64 obj) { unchecked { switch (_to) { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (Char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (Double)obj; default: throw Assert.Unreachable; } } } private object ConvertUInt64(UInt64 obj) { unchecked { switch (_to) { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (Char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (Double)obj; default: throw Assert.Unreachable; } } } private object ConvertDouble(Double obj) { unchecked { switch (_to) { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (Char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (Double)obj; default: throw Assert.Unreachable; } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public sealed class Checked : NumericConvertInstruction { public override string InstructionName { get { return "CheckedConvert"; } } public Checked(TypeCode from, TypeCode to) : base(from, to) { } public override int Run(InterpretedFrame frame) { frame.Push(Convert(frame.Pop())); return +1; } private object Convert(object obj) { switch (_from) { case TypeCode.Byte: return ConvertInt32((Byte)obj); case TypeCode.SByte: return ConvertInt32((SByte)obj); case TypeCode.Int16: return ConvertInt32((Int16)obj); case TypeCode.Char: return ConvertInt32((Char)obj); case TypeCode.Int32: return ConvertInt32((Int32)obj); case TypeCode.Int64: return ConvertInt64((Int64)obj); case TypeCode.UInt16: return ConvertInt32((UInt16)obj); case TypeCode.UInt32: return ConvertInt64((UInt32)obj); case TypeCode.UInt64: return ConvertUInt64((UInt64)obj); case TypeCode.Single: return ConvertDouble((Single)obj); case TypeCode.Double: return ConvertDouble((Double)obj); default: throw Assert.Unreachable; } } private object ConvertInt32(int obj) { checked { switch (_to) { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (Char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (Double)obj; default: throw Assert.Unreachable; } } } private object ConvertInt64(Int64 obj) { checked { switch (_to) { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (Char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (Double)obj; default: throw Assert.Unreachable; } } } private object ConvertUInt64(UInt64 obj) { checked { switch (_to) { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (Char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (Double)obj; default: throw Assert.Unreachable; } } } private object ConvertDouble(Double obj) { checked { switch (_to) { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (Char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (Double)obj; default: throw Assert.Unreachable; } } } } } }
/* * @author Valentin Simonov / http://va.lent.in/ */ using System; using System.Collections.Generic; using TouchScript.Gestures.TransformGestures.Base; using TouchScript.Layers; using TouchScript.Utils; using TouchScript.Pointers; using UnityEngine.Profiling; #if TOUCHSCRIPT_DEBUG using TouchScript.Debugging.GL; #endif using UnityEngine; namespace TouchScript.Gestures.TransformGestures { /// <summary> /// Recognizes a transform gesture, i.e. translation, rotation, scaling or a combination of these. /// </summary> [AddComponentMenu("TouchScript/Gestures/Transform Gesture")] [HelpURL("http://touchscript.github.io/docs/html/T_TouchScript_Gestures_TransformGestures_TransformGesture.htm")] public class TransformGesture : TwoPointTransformGestureBase { #region Constants /// <summary> /// Types of transformation. /// </summary> [Flags] public enum TransformType { /// <summary> /// No transform. /// </summary> None = 0, /// <summary> /// Translation. /// </summary> Translation = 0x1, /// <summary> /// Rotation. /// </summary> Rotation = 0x2, /// <summary> /// Scaling. /// </summary> Scaling = 0x4 } /// <summary> /// Transform's projection type. /// </summary> public enum ProjectionType { /// <summary> /// Use a plane with normal vector defined by layer. /// </summary> Layer, /// <summary> /// Use a plane with certain normal vector in local coordinates. /// </summary> Object, /// <summary> /// Use a plane with certain normal vector in global coordinates. /// </summary> Global, } #endregion #region Public properties /// <summary> /// Gets or sets transform's projection type. /// </summary> /// <value> Projection type. </value> public ProjectionType Projection { get { return projection; } set { if (projection == value) return; projection = value; if (Application.isPlaying) updateProjectionPlane(); } } /// <summary> /// Gets or sets transform's projection plane normal. /// </summary> /// <value> Projection plane normal. </value> public Vector3 ProjectionPlaneNormal { get { if (projection == ProjectionType.Layer) return projectionLayer.WorldProjectionNormal; return projectionPlaneNormal; } set { if (projection == ProjectionType.Layer) projection = ProjectionType.Object; value.Normalize(); if (projectionPlaneNormal == value) return; projectionPlaneNormal = value; if (Application.isPlaying) updateProjectionPlane(); } } /// <summary> /// Plane where transformation occured. /// </summary> public Plane TransformPlane { get { return transformPlane; } } /// <summary> /// Gets delta position in local coordinates. /// </summary> /// <value>Delta position between this frame and the last frame in local coordinates.</value> public Vector3 LocalDeltaPosition { get { return TransformUtils.GlobalToLocalVector(cachedTransform, DeltaPosition); } } #endregion #region Private variables [SerializeField] private bool projectionProps; // Used in the custom inspector [SerializeField] private ProjectionType projection = ProjectionType.Layer; [SerializeField] private Vector3 projectionPlaneNormal = Vector3.forward; private TouchLayer projectionLayer; private Plane transformPlane; private CustomSampler gestureSampler; #endregion #region Public methods #endregion #region Unity methods /// <inheritdoc /> protected override void Awake() { base.Awake(); transformPlane = new Plane(); gestureSampler = CustomSampler.Create("[TouchScript] Transform Gesture"); } /// <inheritdoc /> protected override void OnEnable() { base.OnEnable(); updateProjectionPlane(); } [ContextMenu("Basic Editor")] private void switchToBasicEditor() { basicEditor = true; } #endregion #region Gesture callbacks /// <inheritdoc /> protected override void pointersPressed(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersPressed(pointers); if (NumPointers == pointers.Count) { projectionLayer = activePointers[0].GetPressData().Layer; updateProjectionPlane(); } gestureSampler.End(); } /// <inheritdoc /> protected override void pointersUpdated(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersUpdated(pointers); gestureSampler.End(); } /// <inheritdoc /> protected override void pointersReleased(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersReleased(pointers); #if TOUCHSCRIPT_DEBUG if (getNumPoints() == 0) clearDebug(); else drawDebugDelayed(getNumPoints()); #endif gestureSampler.End(); } #endregion #region Protected methods /// <summary> /// Projects the point which was scaled and rotated. /// </summary> /// <param name="point">The point.</param> /// <param name="dR">Delta rotation.</param> /// <param name="dS">Delta scale.</param> /// <param name="projectionParams">The projection parameters.</param> /// <returns></returns> protected Vector3 projectScaledRotated(Vector2 point, float dR, float dS, ProjectionParams projectionParams) { var center = targetPositionOverridden ? targetPosition : cachedTransform.position; var delta = projectionParams.ProjectTo(point, transformPlane) - center; if (dR != 0) delta = Quaternion.AngleAxis(dR, RotationAxis) * delta; if (dS != 0) delta = delta * dS; return center + delta; } /// <inheritdoc /> protected override float doRotation(Vector2 oldScreenPos1, Vector2 oldScreenPos2, Vector2 newScreenPos1, Vector2 newScreenPos2, ProjectionParams projectionParams) { var newVector = projectionParams.ProjectTo(newScreenPos2, TransformPlane) - projectionParams.ProjectTo(newScreenPos1, TransformPlane); var oldVector = projectionParams.ProjectTo(oldScreenPos2, TransformPlane) - projectionParams.ProjectTo(oldScreenPos1, TransformPlane); var angle = Vector3.Angle(oldVector, newVector); if (Vector3.Dot(Vector3.Cross(oldVector, newVector), TransformPlane.normal) < 0) angle = -angle; return angle; } /// <inheritdoc /> protected override float doScaling(Vector2 oldScreenPos1, Vector2 oldScreenPos2, Vector2 newScreenPos1, Vector2 newScreenPos2, ProjectionParams projectionParams) { var newVector = projectionParams.ProjectTo(newScreenPos2, TransformPlane) - projectionParams.ProjectTo(newScreenPos1, TransformPlane); var oldVector = projectionParams.ProjectTo(oldScreenPos2, TransformPlane) - projectionParams.ProjectTo(oldScreenPos1, TransformPlane); return newVector.magnitude / oldVector.magnitude; } /// <inheritdoc /> protected override Vector3 doOnePointTranslation(Vector2 oldScreenPos, Vector2 newScreenPos, ProjectionParams projectionParams) { if (isTransforming) { return projectionParams.ProjectTo(newScreenPos, TransformPlane) - projectionParams.ProjectTo(oldScreenPos, TransformPlane); } screenPixelTranslationBuffer += newScreenPos - oldScreenPos; if (screenPixelTranslationBuffer.sqrMagnitude > screenTransformPixelThresholdSquared) { isTransforming = true; return projectionParams.ProjectTo(newScreenPos, TransformPlane) - projectionParams.ProjectTo(newScreenPos - screenPixelTranslationBuffer, TransformPlane); } return Vector3.zero; } /// <inheritdoc /> protected override Vector3 doTwoPointTranslation(Vector2 oldScreenPos1, Vector2 oldScreenPos2, Vector2 newScreenPos1, Vector2 newScreenPos2, float dR, float dS, ProjectionParams projectionParams) { if (isTransforming) { return projectionParams.ProjectTo(newScreenPos1, TransformPlane) - projectScaledRotated(oldScreenPos1, dR, dS, projectionParams); } screenPixelTranslationBuffer += newScreenPos1 - oldScreenPos1; if (screenPixelTranslationBuffer.sqrMagnitude > screenTransformPixelThresholdSquared) { isTransforming = true; return projectionParams.ProjectTo(newScreenPos1, TransformPlane) - projectScaledRotated(newScreenPos1 - screenPixelTranslationBuffer, dR, dS, projectionParams); } return Vector3.zero; } #if TOUCHSCRIPT_DEBUG protected override void clearDebug() { base.clearDebug(); GLDebug.RemoveFigure(debugID + 3); } protected override void drawDebug(int pointers) { base.drawDebug(pointers); if (!DebugMode) return; switch (pointers) { case 1: if (projection == ProjectionType.Global || projection == ProjectionType.Object) { GLDebug.DrawPlaneWithNormal(debugID + 3, cachedTransform.position, RotationAxis, 4f, GLDebug.MULTIPLY, float.PositiveInfinity); } break; default: if (projection == ProjectionType.Global || projection == ProjectionType.Object) { GLDebug.DrawPlaneWithNormal(debugID + 3, cachedTransform.position, RotationAxis, 4f, GLDebug.MULTIPLY, float.PositiveInfinity); } break; } } #endif #endregion #region Private functions /// <summary> /// Updates projection plane based on options set. /// </summary> private void updateProjectionPlane() { if (!Application.isPlaying) return; switch (projection) { case ProjectionType.Layer: if (projectionLayer == null) transformPlane = new Plane(cachedTransform.TransformDirection(Vector3.forward), cachedTransform.position); else transformPlane = new Plane(projectionLayer.WorldProjectionNormal, cachedTransform.position); break; case ProjectionType.Object: transformPlane = new Plane(cachedTransform.TransformDirection(projectionPlaneNormal), cachedTransform.position); break; case ProjectionType.Global: transformPlane = new Plane(projectionPlaneNormal, cachedTransform.position); break; } rotationAxis = transformPlane.normal; } #endregion } }
/* * Copyright 2012-2021 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI41; using NUnit.Framework; using NativeULong = System.UInt32; // Note: Code in this file is maintained manually. namespace Net.Pkcs11Interop.Tests.LowLevelAPI41 { /// <summary> /// Helper methods for LowLevelAPI tests. /// </summary> public static class Helpers { /// <summary> /// Checks whether test can be executed on this platform /// </summary> public static void CheckPlatform() { if (Platform.NativeULongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); } /// <summary> /// Finds slot containing the token that matches criteria specified in Settings class /// </summary> /// <param name='pkcs11Library'>Initialized PKCS11 wrapper</param> /// <returns>Slot containing the token that matches criteria</returns> public static NativeULong GetUsableSlot(Pkcs11Library pkcs11Library) { CKR rv = CKR.CKR_OK; // Get list of available slots with token present NativeULong slotCount = 0; rv = pkcs11Library.C_GetSlotList(true, null, ref slotCount); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(slotCount > 0); NativeULong[] slotList = new NativeULong[slotCount]; rv = pkcs11Library.C_GetSlotList(true, slotList, ref slotCount); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Return first slot with token present when both TokenSerial and TokenLabel are null... if (Settings.TokenSerial == null && Settings.TokenLabel == null) return slotList[0]; // First slot with token present is OK... NativeULong? matchingSlot = slotList[0]; // ...unless there are matching criteria specified in Settings class if (Settings.TokenSerial != null || Settings.TokenLabel != null) { matchingSlot = null; foreach (NativeULong slot in slotList) { CK_TOKEN_INFO tokenInfo = new CK_TOKEN_INFO(); rv = pkcs11Library.C_GetTokenInfo(slot, ref tokenInfo); if (rv != CKR.CKR_OK) { if (rv == CKR.CKR_TOKEN_NOT_RECOGNIZED || rv == CKR.CKR_TOKEN_NOT_PRESENT) continue; else Assert.Fail(rv.ToString()); } if (!string.IsNullOrEmpty(Settings.TokenSerial)) if (0 != string.Compare(Settings.TokenSerial, ConvertUtils.BytesToUtf8String(tokenInfo.SerialNumber, true), StringComparison.Ordinal)) continue; if (!string.IsNullOrEmpty(Settings.TokenLabel)) if (0 != string.Compare(Settings.TokenLabel, ConvertUtils.BytesToUtf8String(tokenInfo.Label, true), StringComparison.Ordinal)) continue; matchingSlot = slot; break; } } Assert.IsTrue(matchingSlot != null, "Token matching criteria specified in Settings class is not present"); return matchingSlot.Value; } /// <summary> /// Creates the data object. /// </summary> /// <param name='pkcs11Library'>Initialized PKCS11 wrapper</param> /// <param name='session'>Read-write session with user logged in</param> /// <param name='objectId'>Output parameter for data object handle</param> /// <returns>Return value of C_CreateObject</returns> public static CKR CreateDataObject(Pkcs11Library pkcs11Library, NativeULong session, ref NativeULong objectId) { CKR rv = CKR.CKR_OK; // Prepare attribute template of new data object CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[5]; template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA); template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true); template[2] = CkaUtils.CreateAttribute(CKA.CKA_APPLICATION, Settings.ApplicationName); template[3] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName); template[4] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "Data object content"); // Create object rv = pkcs11Library.C_CreateObject(session, template, ConvertUtils.UInt32FromInt32(template.Length), ref objectId); // In LowLevelAPI caller has to free unmanaged memory taken by attributes for (int i = 0; i < template.Length; i++) { UnmanagedMemory.Free(ref template[i].value); template[i].valueLen = 0; } return rv; } /// <summary> /// Generates symetric key. /// </summary> /// <param name='pkcs11Library'>Initialized PKCS11 wrapper</param> /// <param name='session'>Read-write session with user logged in</param> /// <param name='keyId'>Output parameter for key object handle</param> /// <returns>Return value of C_GenerateKey</returns> public static CKR GenerateKey(Pkcs11Library pkcs11Library, NativeULong session, ref NativeULong keyId) { CKR rv = CKR.CKR_OK; // Prepare attribute template of new key CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[6]; template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY); template[1] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3); template[2] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true); template[3] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true); template[4] = CkaUtils.CreateAttribute(CKA.CKA_DERIVE, true); template[5] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, true); // Specify key generation mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_KEY_GEN); // Generate key rv = pkcs11Library.C_GenerateKey(session, ref mechanism, template, ConvertUtils.UInt32FromInt32(template.Length), ref keyId); // In LowLevelAPI we have to free unmanaged memory taken by attributes for (int i = 0; i < template.Length; i++) { UnmanagedMemory.Free(ref template[i].value); template[i].valueLen = 0; } return rv; } /// <summary> /// Generates asymetric key pair. /// </summary> /// <param name='pkcs11Library'>Initialized PKCS11 wrapper</param> /// <param name='session'>Read-write session with user logged in</param> /// <param name='pubKeyId'>Output parameter for public key object handle</param> /// <param name='privKeyId'>Output parameter for private key object handle</param> /// <returns>Return value of C_GenerateKeyPair</returns> public static CKR GenerateKeyPair(Pkcs11Library pkcs11Library, NativeULong session, ref NativeULong pubKeyId, ref NativeULong privKeyId) { CKR rv = CKR.CKR_OK; // The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject byte[] ckaId = new byte[20]; rv = pkcs11Library.C_GenerateRandom(session, ckaId, ConvertUtils.UInt32FromInt32(ckaId.Length)); if (rv != CKR.CKR_OK) return rv; // Prepare attribute template of new public key CK_ATTRIBUTE[] pubKeyTemplate = new CK_ATTRIBUTE[10]; pubKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true); pubKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false); pubKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName); pubKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId); pubKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true); pubKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY, true); pubKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY_RECOVER, true); pubKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_WRAP, true); pubKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_MODULUS_BITS, 1024); pubKeyTemplate[9] = CkaUtils.CreateAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 }); // Prepare attribute template of new private key CK_ATTRIBUTE[] privKeyTemplate = new CK_ATTRIBUTE[9]; privKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true); privKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true); privKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName); privKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId); privKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, true); privKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true); privKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_SIGN, true); privKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SIGN_RECOVER, true); privKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_UNWRAP, true); // Specify key generation mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN); // Generate key pair rv = pkcs11Library.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, ConvertUtils.UInt32FromInt32(pubKeyTemplate.Length), privKeyTemplate, ConvertUtils.UInt32FromInt32(privKeyTemplate.Length), ref pubKeyId, ref privKeyId); // In LowLevelAPI we have to free unmanaged memory taken by attributes for (int i = 0; i < privKeyTemplate.Length; i++) { UnmanagedMemory.Free(ref privKeyTemplate[i].value); privKeyTemplate[i].valueLen = 0; } for (int i = 0; i < pubKeyTemplate.Length; i++) { UnmanagedMemory.Free(ref pubKeyTemplate[i].value); pubKeyTemplate[i].valueLen = 0; } return rv; } } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:40 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.direct { #region RemotingProvider /// <inheritdocs /> /// <summary> /// <p>The <see cref="Ext.direct.RemotingProvider">RemotingProvider</see> exposes access to /// server side methods on the client (a remote procedure call (RPC) type of /// connection where the client can initiate a procedure on the server).</p> /// <p>This allows for code to be organized in a fashion that is maintainable, /// while providing a clear path between client and server, something that is /// not always apparent when using URLs.</p> /// <p>To accomplish this the server-side needs to describe what classes and methods /// are available on the client-side. This configuration will typically be /// outputted by the server-side <see cref="Ext.direct.Manager">Ext.Direct</see> stack when the API description is built.</p> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class RemotingProvider : JsonProvider { /// <summary> /// Object literal defining the server side actions and methods. For example, if /// the Provider is configured with: /// <code>"actions":{ // each property within the 'actions' object represents a server side Class /// "TestAction":[ // array of methods within each server side Class to be /// { // stubbed out on client /// "name":"doEcho", /// "len":1 /// },{ /// "name":"multiply",// name of method /// "len":2 // The number of parameters that will be used to create an /// // array of data to send to the server side function. /// // Ensure the server sends back a Number, not a String. /// },{ /// "name":"doForm", /// "formHandler":true, // direct the client to use specialized form handling method /// "len":1 /// }] /// } /// </code> /// Note that a Store is not required, a server method can be called at any time. /// In the following example a <b>client side</b> handler is used to call the /// server side method "multiply" in the server-side "TestAction" Class: /// <code>TestAction.multiply( /// 2, 4, // pass two arguments to server, so specify len=2 /// // callback function after the server is called /// // result: the result returned by the server /// // e: <see cref="Ext.direct.RemotingEvent">Ext.direct.RemotingEvent</see> object /// function(result, e){ /// var t = e.getTransaction(); /// var action = t.action; // server side Class called /// var method = t.method; // server side method called /// if(e.status){ /// var answer = <see cref="Ext.ExtContext.encode">Ext.encode</see>(result); // 8 /// }else{ /// var msg = e.message; // failure message /// } /// } /// ); /// </code> /// In the example above, the server side "multiply" function will be passed two /// arguments (2 and 4). The "multiply" method should return the value 8 which will be /// available as the <tt>result</tt> in the example above. /// </summary> public JsObject actions; /// <summary> /// true or false to enable or disable combining of method /// calls. If a number is specified this is the amount of time in milliseconds /// to wait before sending a batched request. /// Calls which are received within the specified timeframe will be /// <p>concatenated together and sent in a single request, optimizing the /// application by reducing the amount of round trips that have to be made /// to the server.</p> /// Defaults to: <c>10</c> /// </summary> public object enableBuffer; /// <summary> /// Specify which param will hold the arguments for the method. /// Defaults to 'data'. /// </summary> public JsString enableUrlEncode; /// <summary> /// Number of times to re-attempt delivery on failure of a call. /// Defaults to: <c>1</c> /// </summary> public JsNumber maxRetries; /// <summary> /// Namespace for the Remoting Provider (defaults to the browser global scope of window). /// Explicitly specify the namespace Object, or specify a String to have a /// namespace created implicitly. /// </summary> public object @namespace; /// <summary> /// The timeout to use for each request. /// </summary> public JsNumber timeout; /// <summary> /// Required. The url to connect to the Ext.direct.Manager server-side router. /// </summary> public JsString url; /// <summary> /// Combine any buffered requests and send them off /// </summary> private void combineAndSend(){} /// <summary> /// Configure a form submission request /// </summary> /// <param name="action"><p>The action being executed</p> /// </param> /// <param name="method"><p>The method being executed</p> /// </param> /// <param name="form"><p>The form being submitted</p> /// </param> /// <param name="callback"><p>A callback to run after the form submits</p> /// </param> /// <param name="scope"><p>A scope to execute the callback in</p> /// </param> private void configureFormRequest(JsString action, object method, object form, object callback=null, object scope=null){} /// <summary> /// Configure a direct request /// </summary> /// <param name="action"><p>The action being executed</p> /// </param> /// <param name="method"><p>The being executed</p> /// </param> private void configureRequest(JsString action, object method){} /// <summary> /// Create a handler function for a direct call. /// </summary> /// <param name="action"><p>The action the call is for</p> /// </param> /// <param name="method"><p>The details of the method</p> /// </param> /// <returns> /// <span><see cref="Function">Function</see></span><div><p>A JS function that will kick off the call</p> /// </div> /// </returns> private System.Delegate createHandler(JsString action, object method){return null;} /// <summary> /// Gets the Ajax call info for a transaction /// </summary> /// <param name="transaction"><p>The transaction</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>The call params</p> /// </div> /// </returns> private object getCallData(Transaction transaction){return null;} /// <summary> /// Get transaction from XHR options /// </summary> /// <param name="options"><p>The options sent to the Ajax request</p> /// </param> /// <returns> /// <span><see cref="Ext.direct.Transaction">Ext.direct.Transaction</see></span><div><p>The transaction, null if not found</p> /// </div> /// </returns> private Transaction getTransaction(object options){return null;} /// <summary> /// Initialize the API /// </summary> private void initAPI(){} /// <summary> /// React to the ajax request being completed /// </summary> /// <param name="options"> /// </param> /// <param name="success"> /// </param> /// <param name="response"> /// </param> private void onData(object options, object success, object response){} /// <summary> /// Add a new transaction to the queue /// </summary> /// <param name="transaction"><p>The transaction</p> /// </param> private void queueTransaction(Transaction transaction){} /// <summary> /// Run any callbacks related to the transaction. /// </summary> /// <param name="transaction"><p>The transaction</p> /// </param> /// <param name="event"><p>The event</p> /// </param> private void runCallback(Transaction transaction, Ext.direct.Event @event){} /// <summary> /// Sends a form request /// </summary> /// <param name="transaction"><p>The transaction to send</p> /// </param> private void sendFormRequest(Transaction transaction){} /// <summary> /// Sends a request to the server /// </summary> /// <param name="data"><p>The data to send</p> /// </param> private void sendRequest(object data){} public RemotingProvider(RemotingProviderConfig config){} public RemotingProvider(){} public RemotingProvider(params object[] args){} } #endregion #region RemotingProviderConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class RemotingProviderConfig : JsonProviderConfig { /// <summary> /// Object literal defining the server side actions and methods. For example, if /// the Provider is configured with: /// <code>"actions":{ // each property within the 'actions' object represents a server side Class /// "TestAction":[ // array of methods within each server side Class to be /// { // stubbed out on client /// "name":"doEcho", /// "len":1 /// },{ /// "name":"multiply",// name of method /// "len":2 // The number of parameters that will be used to create an /// // array of data to send to the server side function. /// // Ensure the server sends back a Number, not a String. /// },{ /// "name":"doForm", /// "formHandler":true, // direct the client to use specialized form handling method /// "len":1 /// }] /// } /// </code> /// Note that a Store is not required, a server method can be called at any time. /// In the following example a <b>client side</b> handler is used to call the /// server side method "multiply" in the server-side "TestAction" Class: /// <code>TestAction.multiply( /// 2, 4, // pass two arguments to server, so specify len=2 /// // callback function after the server is called /// // result: the result returned by the server /// // e: <see cref="Ext.direct.RemotingEvent">Ext.direct.RemotingEvent</see> object /// function(result, e){ /// var t = e.getTransaction(); /// var action = t.action; // server side Class called /// var method = t.method; // server side method called /// if(e.status){ /// var answer = <see cref="Ext.ExtContext.encode">Ext.encode</see>(result); // 8 /// }else{ /// var msg = e.message; // failure message /// } /// } /// ); /// </code> /// In the example above, the server side "multiply" function will be passed two /// arguments (2 and 4). The "multiply" method should return the value 8 which will be /// available as the <tt>result</tt> in the example above. /// </summary> public JsObject actions; /// <summary> /// true or false to enable or disable combining of method /// calls. If a number is specified this is the amount of time in milliseconds /// to wait before sending a batched request. /// Calls which are received within the specified timeframe will be /// <p>concatenated together and sent in a single request, optimizing the /// application by reducing the amount of round trips that have to be made /// to the server.</p> /// Defaults to: <c>10</c> /// </summary> public object enableBuffer; /// <summary> /// Specify which param will hold the arguments for the method. /// Defaults to 'data'. /// </summary> public JsString enableUrlEncode; /// <summary> /// Number of times to re-attempt delivery on failure of a call. /// Defaults to: <c>1</c> /// </summary> public JsNumber maxRetries; /// <summary> /// Namespace for the Remoting Provider (defaults to the browser global scope of window). /// Explicitly specify the namespace Object, or specify a String to have a /// namespace created implicitly. /// </summary> public object @namespace; /// <summary> /// The timeout to use for each request. /// </summary> public JsNumber timeout; /// <summary> /// Required. The url to connect to the Ext.direct.Manager server-side router. /// </summary> public JsString url; public RemotingProviderConfig(params object[] args){} } #endregion #region RemotingProviderEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class RemotingProviderEvents : JsonProviderEvents { /// <summary> /// Fires immediately before the client-side sends off the RPC call. /// By returning false from an event handler you can prevent the call from /// executing. /// </summary> /// <param name="provider"> /// </param> /// <param name="transaction"> /// </param> /// <param name="meta"><p>The meta data</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforecall(RemotingProvider provider, Transaction transaction, object meta, object eOpts){} /// <summary> /// Fires immediately after the request to the server-side is sent. This does /// NOT fire after the response has come back from the call. /// </summary> /// <param name="provider"> /// </param> /// <param name="transaction"> /// </param> /// <param name="meta"><p>The meta data</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void call(RemotingProvider provider, Transaction transaction, object meta, object eOpts){} public RemotingProviderEvents(params object[] args){} } #endregion }
// <copyright file="SvdTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization { /// <summary> /// Svd factorization tests for a dense matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class SvdTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = DenseMatrix.CreateIdentity(order); var factorSvd = matrixI.Svd(); var u = factorSvd.U; var vt = factorSvd.VT; var w = factorSvd.W; Assert.AreEqual(matrixI.RowCount, u.RowCount); Assert.AreEqual(matrixI.RowCount, u.ColumnCount); Assert.AreEqual(matrixI.ColumnCount, vt.RowCount); Assert.AreEqual(matrixI.ColumnCount, vt.ColumnCount); Assert.AreEqual(matrixI.RowCount, w.RowCount); Assert.AreEqual(matrixI.ColumnCount, w.ColumnCount); for (var i = 0; i < w.RowCount; i++) { for (var j = 0; j < w.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0 : 0.0, w[i, j]); } } } /// <summary> /// Can factorize a random matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrix(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var factorSvd = matrixA.Svd(); var u = factorSvd.U; var vt = factorSvd.VT; var w = factorSvd.W; // Make sure the U has the right dimensions. Assert.AreEqual(row, u.RowCount); Assert.AreEqual(row, u.ColumnCount); // Make sure the VT has the right dimensions. Assert.AreEqual(column, vt.RowCount); Assert.AreEqual(column, vt.ColumnCount); // Make sure the W has the right dimensions. Assert.AreEqual(row, w.RowCount); Assert.AreEqual(column, w.ColumnCount); // Make sure the U*W*VT is the original matrix. var matrix = u*w*vt; for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j], matrix[i, j], 1e-4); } } } /// <summary> /// Can check rank of a non-square matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(10, 8)] [TestCase(48, 52)] [TestCase(100, 93)] public void CanCheckRankOfNonSquare(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var factorSvd = matrixA.Svd(); var mn = Math.Min(row, column); Assert.AreEqual(factorSvd.Rank, mn); } /// <summary> /// Can check rank of a square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(9)] [TestCase(50)] [TestCase(90)] public void CanCheckRankSquare(int order) { var matrixA = Matrix<float>.Build.Random(order, order, 1); var factorSvd = matrixA.Svd(); if (factorSvd.Determinant != 0) { Assert.AreEqual(factorSvd.Rank, order); } else { Assert.AreEqual(factorSvd.Rank, order - 1); } } /// <summary> /// Can check rank of a square singular matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanCheckRankOfSquareSingular(int order) { var matrixA = new DenseMatrix(order, order); matrixA[0, 0] = 1; matrixA[order - 1, order - 1] = 1; for (var i = 1; i < order - 1; i++) { matrixA[i, i - 1] = 1; matrixA[i, i + 1] = 1; matrixA[i - 1, i] = 1; matrixA[i + 1, i] = 1; } var factorSvd = matrixA.Svd(); Assert.AreEqual(factorSvd.Determinant, 0); Assert.AreEqual(factorSvd.Rank, order - 1); } [Test] public void RankAcceptance() { // http://discuss.mathdotnet.com/t/wrong-compute-of-the-matrix-rank/120 Matrix<float> m = DenseMatrix.OfArray(new float[,] { { 4, 4, 1, 3 }, { 1,-2, 1, 0 }, { 4, 0, 2, 2 }, { 7, 6, 2, 5 } }); Assert.That(m.Svd(true).Rank, Is.EqualTo(2)); Assert.That(m.Svd(false).Rank, Is.EqualTo(2)); } /// <summary> /// Solve for matrix if vectors are not computed throws <c>InvalidOperationException</c>. /// </summary> [Test] public void SolveMatrixIfVectorsNotComputedThrowsInvalidOperationException() { var matrixA = Matrix<float>.Build.Random(10, 10, 1); var factorSvd = matrixA.Svd(false); var matrixB = Matrix<float>.Build.Random(10, 10, 1); Assert.That(() => factorSvd.Solve(matrixB), Throws.InvalidOperationException); } /// <summary> /// Solve for vector if vectors are not computed throws <c>InvalidOperationException</c>. /// </summary> [Test] public void SolveVectorIfVectorsNotComputedThrowsInvalidOperationException() { var matrixA = Matrix<float>.Build.Random(10, 10, 1); var factorSvd = matrixA.Svd(false); var vectorb = Vector<float>.Build.Random(10, 1); Assert.That(() => factorSvd.Solve(vectorb), Throws.InvalidOperationException); } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(9, 10)] [TestCase(50, 50)] [TestCase(90, 100)] public void CanSolveForRandomVector(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var vectorb = Vector<float>.Build.Random(row, 1); var resultx = factorSvd.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(4, 4)] [TestCase(7, 8)] [TestCase(10, 10)] [TestCase(45, 50)] [TestCase(80, 100)] public void CanSolveForRandomMatrix(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var matrixB = Matrix<float>.Build.Random(row, column, 1); var matrixX = factorSvd.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(9, 10)] [TestCase(50, 50)] [TestCase(90, 100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var vectorb = Vector<float>.Build.Random(row, 1); var vectorbCopy = vectorb.Clone(); var resultx = new DenseVector(column); factorSvd.Solve(vectorb, resultx); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(4, 4)] [TestCase(7, 8)] [TestCase(10, 10)] [TestCase(45, 50)] [TestCase(80, 100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var matrixB = Matrix<float>.Build.Random(row, column, 1); var matrixBCopy = matrixB.Clone(); var matrixX = new DenseMatrix(column, column); factorSvd.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Xml; using System.Text; using System.Globalization; using System.Diagnostics; using Google.GData.Client; namespace Google.GData.Photos { ////////////////////////////////////////////////////////////////////// /// <summary> /// A subclass of FeedQuery, to create an PicasaQuery query URI. /// Provides public properties that describe the different /// aspects of the URI, as well as a composite URI. /// The PicasaQuery supports the following GData parameters: /// start-index and max-results parameters. It does not currently support the other standard parameters. /// in addition, the following parameters: /// Parameter Meaning /// kind what feed to retrieve /// access Visibility parameter /// thumbsize Thumbnail size parameter /// </summary> ////////////////////////////////////////////////////////////////////// public class PicasaQuery : FeedQuery { /// <summary> /// The kind parameter lets you request information about a particular kind /// of item. The parameter value should be a comma-separated list of requested kinds. /// If you omit the kind parameter, Picasa Web Albums chooses a default kind /// depending on the level of feed you're requesting. For a user-based feed, /// the default kind is album; for an album-based feed, the default kind is /// photo; for a photo-based feed, the default kind is comment; for a community /// search feed, the default kind is photo. /// </summary> public enum Kinds { /// <summary> /// Feed includes some or all of the albums the specified /// user has in their gallery. Which albums are returned /// depends on the visibility value specified. /// </summary> album, /// <summary> /// Feed includes the photos in an album (album-based), /// recent photos uploaded by a user (user-based) or /// photos uploaded by all users (community search). /// </summary> photo, /// <summary> /// Feed includes the comments that have been made on a photo. /// </summary> comment, /// <summary> /// Includes all tags associated with the specified user, album, /// or photo. For user-based and album-based feeds, the tags /// include a weight value indicating how often they occurred. /// </summary> tag, /// <summary> /// using none implies the server default /// </summary> none } /// <summary> /// describing the visibility level of picasa feeds /// </summary> public enum AccessLevel { /// <summary> /// no parameter. Setting the accessLevel to undefined /// implies the server default /// </summary> AccessUndefined, /// <summary> /// Shows both public and private data. /// Requires authentication. Default for authenticated users. /// </summary> AccessAll, /// <summary> /// Shows only private data. Requires authentication. /// </summary> AccessPrivate, /// <summary> /// Shows only public data. /// Does not require authentication. Default for unauthenticated users. /// </summary> AccessPublic, } /// <summary> /// holds the kind parameters a query can have /// </summary> protected string kindsAsText = ""; /// <summary> /// holds the tag parameters a query can have /// </summary> private string tags = ""; private AccessLevel access; private string thumbsize; /// <summary> /// picasa base URI /// </summary> public static string picasaBaseUri = "http://picasaweb.google.com/data/feed/api/user/"; /// <summary> /// picasa base URI for posting against the default album /// </summary> public static string picasaDefaultPostUri = "http://picasaweb.google.com/data/feed/api/user/default/albumid/default"; /// <summary> /// base constructor /// </summary> public PicasaQuery() : base() { this.kindsAsText = Kinds.tag.ToString(); } /// <summary> /// base constructor, with initial queryUri /// </summary> /// <param name="queryUri">the query to use</param> public PicasaQuery(string queryUri) : base(queryUri) { this.kindsAsText = Kinds.tag.ToString(); } /// <summary> /// convienience method to create an URI based on a userID for a picasafeed /// </summary> /// <param name="userID"></param> /// <returns>string</returns> public static string CreatePicasaUri(string userID) { return PicasaQuery.picasaBaseUri + Utilities.UriEncodeUnsafe(userID); } /// <summary> /// convienience method to create an URI based on a userID /// and an album ID for a picasafeed /// </summary> /// <param name="userID"></param> /// <param name="albumID"></param> /// <returns>string</returns> public static string CreatePicasaUri(string userID, string albumID) { return CreatePicasaUri(userID) +"/albumid/"+ Utilities.UriEncodeUnsafe(albumID); } /// <summary> /// Convenience method to create a URI based on a user id, albumID, and photoid /// </summary> /// <param name="userID">The username that owns the content</param> /// <param name="albumID"></param> /// <param name="photoID">The ID of the photo that contains the content</param> /// <returns>A URI to a Picasa Web Albums feed</returns> public static string CreatePicasaUri(string userID, string albumID, string photoID) { return CreatePicasaUri(userID, albumID) + "/photoid/" + Utilities.UriEncodeUnsafe(photoID); } ////////////////////////////////////////////////////////////////////// /// <summary>comma separated list of kinds to retrieve</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public virtual string KindParameter { get {return this.kindsAsText;} set {this.kindsAsText = value;} } // end of accessor public WebAlbumKinds /// <summary> /// comma separated list of the tags to search for in the feed. /// </summary> public string Tags { get { return this.tags; } set { this.tags = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>indicates the access</summary> ////////////////////////////////////////////////////////////////////// public AccessLevel Access { get {return this.access;} set {this.access = value;} } // end of accessor public Access ////////////////////////////////////////////////////////////////////// /// <summary>indicates the thumbsize required</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Thumbsize { get {return this.thumbsize;} set {this.thumbsize = value;} } // end of accessor public Thumbsize #if WindowsCE || PocketPC #else ////////////////////////////////////////////////////////////////////// /// <summary>protected void ParseUri</summary> /// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param> /// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns> ////////////////////////////////////////////////////////////////////// protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; TokenCollection tokens = new TokenCollection(targetUri.Query, deli); foreach (String token in tokens) { if (token.Length > 0) { char[] otherDeli = { '=' }; String[] parameters = token.Split(otherDeli, 2); switch (parameters[0]) { case "kind": this.kindsAsText = parameters[1]; break; case "tag": this.tags = parameters[1]; break; case "thumbsize": this.thumbsize = parameters[1]; break; case "access": if (String.Compare("all", parameters[1], false, CultureInfo.InvariantCulture) == 0) { this.Access = AccessLevel.AccessAll; } else if (String.Compare("private", parameters[1], false, CultureInfo.InvariantCulture) == 0) { this.Access = AccessLevel.AccessPrivate; } else { this.Access = AccessLevel.AccessPublic; } break; } } } } return this.Uri; } #endif ////////////////////////////////////////////////////////////////////// /// <summary>Resets object state to default, as if newly created. /// </summary> ////////////////////////////////////////////////////////////////////// protected override void Reset() { base.Reset(); } ////////////////////////////////////////////////////////////////////// /// <summary>Creates the partial URI query string based on all /// set properties.</summary> /// <returns> string => the query part of the URI </returns> ////////////////////////////////////////////////////////////////////// protected override string CalculateQuery(string basePath) { string path = base.CalculateQuery(basePath); StringBuilder newPath = new StringBuilder(path, 2048); char paramInsertion = InsertionParameter(path); if (this.KindParameter.Length > 0) { newPath.Append(paramInsertion); newPath.AppendFormat(CultureInfo.InvariantCulture, "kind={0}", Utilities.UriEncodeReserved(this.KindParameter)); paramInsertion = '&'; } if (this.Tags.Length > 0) { newPath.Append(paramInsertion); newPath.AppendFormat(CultureInfo.InvariantCulture, "tag={0}", Utilities.UriEncodeReserved(this.Tags)); paramInsertion = '&'; } if (Utilities.IsPersistable(this.Thumbsize)) { newPath.Append(paramInsertion); newPath.AppendFormat(CultureInfo.InvariantCulture, "thumbsize={0}", Utilities.UriEncodeReserved(this.Thumbsize)); paramInsertion = '&'; } if (this.Access != AccessLevel.AccessUndefined) { String acc; if (this.Access == AccessLevel.AccessAll) { acc = "all"; } else if (this.Access == AccessLevel.AccessPrivate) { acc = "private"; } else { acc = "public"; } newPath.Append(paramInsertion); newPath.AppendFormat(CultureInfo.InvariantCulture, "access={0}", acc); } return newPath.ToString(); } } }
// // AssemblyNameReference.cs // // Author: // Jb Evain ([email protected]) // // 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.Globalization; using System.Security.Cryptography; using System.Text; namespace Mono.Cecil { public class AssemblyNameReference : IMetadataScope { string name; string culture; Version version; uint attributes; byte [] public_key; byte [] public_key_token; AssemblyHashAlgorithm hash_algorithm; byte [] hash; internal MetadataToken token; string full_name; public string Name { get { return name; } set { name = value; full_name = null; } } public string Culture { get { return culture; } set { culture = value; full_name = null; } } public Version Version { get { return version; } set { version = value; full_name = null; } } public AssemblyAttributes Attributes { get { return (AssemblyAttributes) attributes; } set { attributes = (uint) value; } } public bool HasPublicKey { get { return attributes.GetAttributes ((uint) AssemblyAttributes.PublicKey); } set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.PublicKey, value); } } public bool IsSideBySideCompatible { get { return attributes.GetAttributes ((uint) AssemblyAttributes.SideBySideCompatible); } set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.SideBySideCompatible, value); } } public bool IsRetargetable { get { return attributes.GetAttributes ((uint) AssemblyAttributes.Retargetable); } set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.Retargetable, value); } } public bool IsWindowsRuntime { get { return attributes.GetAttributes ((uint) AssemblyAttributes.WindowsRuntime); } set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.WindowsRuntime, value); } } public byte [] PublicKey { get { return public_key ?? Empty<byte>.Array; } set { public_key = value; HasPublicKey = !public_key.IsNullOrEmpty (); public_key_token = Empty<byte>.Array; full_name = null; } } public byte [] PublicKeyToken { get { if (public_key_token.IsNullOrEmpty () && !public_key.IsNullOrEmpty ()) { var hash = HashPublicKey (); // we need the last 8 bytes in reverse order var local_public_key_token = new byte [8]; Array.Copy (hash, (hash.Length - 8), local_public_key_token, 0, 8); Array.Reverse (local_public_key_token, 0, 8); public_key_token = local_public_key_token; // publish only once finished (required for thread-safety) } return public_key_token ?? Empty<byte>.Array; } set { public_key_token = value; full_name = null; } } byte [] HashPublicKey () { HashAlgorithm algorithm; switch (hash_algorithm) { case AssemblyHashAlgorithm.Reserved: #if SILVERLIGHT throw new NotSupportedException (); #else algorithm = MD5.Create (); break; #endif default: // None default to SHA1 #if SILVERLIGHT algorithm = new SHA1Managed (); break; #else algorithm = SHA1.Create (); break; #endif } using (algorithm) return algorithm.ComputeHash (public_key); } public virtual MetadataScopeType MetadataScopeType { get { return MetadataScopeType.AssemblyNameReference; } } public string FullName { get { if (full_name != null) return full_name; const string sep = ", "; var builder = new StringBuilder (); builder.Append (name); if (version != null) { builder.Append (sep); builder.Append ("Version="); builder.Append (version.ToString ()); } builder.Append (sep); builder.Append ("Culture="); builder.Append (string.IsNullOrEmpty (culture) ? "neutral" : culture); builder.Append (sep); builder.Append ("PublicKeyToken="); var pk_token = PublicKeyToken; if (!pk_token.IsNullOrEmpty () && pk_token.Length > 0) { for (int i = 0 ; i < pk_token.Length ; i++) { builder.Append (pk_token [i].ToString ("x2")); } } else builder.Append ("null"); return full_name = builder.ToString (); } } public static AssemblyNameReference Parse (string fullName) { if (fullName == null) throw new ArgumentNullException ("fullName"); if (fullName.Length == 0) throw new ArgumentException ("Name can not be empty"); var name = new AssemblyNameReference (); var tokens = fullName.Split (','); for (int i = 0; i < tokens.Length; i++) { var token = tokens [i].Trim (); if (i == 0) { name.Name = token; continue; } var parts = token.Split ('='); if (parts.Length != 2) throw new ArgumentException ("Malformed name"); switch (parts [0].ToLowerInvariant ()) { case "version": name.Version = new Version (parts [1]); break; case "culture": name.Culture = parts [1]; break; case "publickeytoken": var pk_token = parts [1]; if (pk_token == "null") break; name.PublicKeyToken = new byte [pk_token.Length / 2]; for (int j = 0; j < name.PublicKeyToken.Length; j++) name.PublicKeyToken [j] = Byte.Parse (pk_token.Substring (j * 2, 2), NumberStyles.HexNumber); break; } } return name; } public AssemblyHashAlgorithm HashAlgorithm { get { return hash_algorithm; } set { hash_algorithm = value; } } public virtual byte [] Hash { get { return hash; } set { hash = value; } } public MetadataToken MetadataToken { get { return token; } set { token = value; } } internal AssemblyNameReference () { } public AssemblyNameReference (string name, Version version) { if (name == null) throw new ArgumentNullException ("name"); this.name = name; this.version = version; this.hash_algorithm = AssemblyHashAlgorithm.None; this.token = new MetadataToken (TokenType.AssemblyRef); } public override string ToString () { return this.FullName; } } }
using ClosedXML.Excel.Caching; using ClosedXML.Excel.CalcEngine; using ClosedXML.Excel.Drawings; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using ClosedXML.Excel.Ranges.Index; namespace ClosedXML.Excel { internal class XLWorksheet : XLRangeBase, IXLWorksheet { #region Fields private readonly Dictionary<Int32, Int32> _columnOutlineCount = new Dictionary<Int32, Int32>(); private readonly Dictionary<Int32, Int32> _rowOutlineCount = new Dictionary<Int32, Int32>(); private readonly XLRangeFactory _rangeFactory; private readonly XLRangeRepository _rangeRepository; private readonly List<IXLRangeIndex> _rangeIndices; internal Int32 ZOrder = 1; private String _name; internal Int32 _position; private Double _rowHeight; private Boolean _tabActive; internal Boolean EventTrackingEnabled; /// <summary> /// Fake address to be used everywhere the invalid address is needed. /// </summary> internal readonly XLAddress InvalidAddress; #endregion Fields #region Constructor public XLWorksheet(String sheetName, XLWorkbook workbook) : base( new XLRangeAddress( new XLAddress(null, XLHelper.MinRowNumber, XLHelper.MinColumnNumber, false, false), new XLAddress(null, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber, false, false)), (workbook.Style as XLStyle).Value) { EventTrackingEnabled = workbook.EventTracking == XLEventTracking.Enabled; Workbook = workbook; InvalidAddress = new XLAddress(this, 0, 0, false, false); var firstAddress = new XLAddress(this, RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.FirstAddress.FixedRow, RangeAddress.FirstAddress.FixedColumn); var lastAddress = new XLAddress(this, RangeAddress.LastAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber, RangeAddress.LastAddress.FixedRow, RangeAddress.LastAddress.FixedColumn); RangeAddress = new XLRangeAddress(firstAddress, lastAddress); _rangeFactory = new XLRangeFactory(this); _rangeRepository = new XLRangeRepository(workbook, _rangeFactory.Create); _rangeIndices = new List<IXLRangeIndex>(); Pictures = new XLPictures(this); NamedRanges = new XLNamedRanges(this); SheetView = new XLSheetView(); Tables = new XLTables(); Hyperlinks = new XLHyperlinks(); DataValidations = new XLDataValidations(); PivotTables = new XLPivotTables(this); Protection = new XLSheetProtection(); AutoFilter = new XLAutoFilter(); ConditionalFormats = new XLConditionalFormats(); Internals = new XLWorksheetInternals(new XLCellsCollection(), new XLColumnsCollection(), new XLRowsCollection(), new XLRanges()); PageSetup = new XLPageSetup((XLPageSetup)workbook.PageOptions, this); Outline = new XLOutline(workbook.Outline); _columnWidth = workbook.ColumnWidth; _rowHeight = workbook.RowHeight; RowHeightChanged = Math.Abs(workbook.RowHeight - XLWorkbook.DefaultRowHeight) > XLHelper.Epsilon; Name = sheetName; Charts = new XLCharts(); ShowFormulas = workbook.ShowFormulas; ShowGridLines = workbook.ShowGridLines; ShowOutlineSymbols = workbook.ShowOutlineSymbols; ShowRowColHeaders = workbook.ShowRowColHeaders; ShowRuler = workbook.ShowRuler; ShowWhiteSpace = workbook.ShowWhiteSpace; ShowZeros = workbook.ShowZeros; RightToLeft = workbook.RightToLeft; TabColor = XLColor.NoColor; SelectedRanges = new XLRanges(); Author = workbook.Author; } #endregion Constructor public override XLRangeType RangeType { get { return XLRangeType.Worksheet; } } //private IXLStyle _style; private const String InvalidNameChars = @":\/?*[]"; public string LegacyDrawingId; public Boolean LegacyDrawingIsNew; private Double _columnWidth; public XLWorksheetInternals Internals { get; private set; } public XLRangeFactory RangeFactory { get { return _rangeFactory; } } public override IEnumerable<IXLStyle> Styles { get { yield return GetStyle(); foreach (XLCell c in Internals.CellsCollection.GetCells()) yield return c.Style; } } protected override IEnumerable<XLStylizedBase> Children { get { foreach (var col in ColumnsUsed(true).OfType<XLColumn>()) yield return col; foreach (var row in RowsUsed(true).OfType<XLRow>()) yield return row; } } internal Boolean RowHeightChanged { get; set; } internal Boolean ColumnWidthChanged { get; set; } public Int32 SheetId { get; set; } internal String RelId { get; set; } public XLDataValidations DataValidations { get; private set; } public IXLCharts Charts { get; private set; } public XLSheetProtection Protection { get; private set; } public XLAutoFilter AutoFilter { get; private set; } #region IXLWorksheet Members public XLWorkbook Workbook { get; private set; } public Double ColumnWidth { get { return _columnWidth; } set { ColumnWidthChanged = true; _columnWidth = value; } } public Double RowHeight { get { return _rowHeight; } set { RowHeightChanged = true; _rowHeight = value; } } public String Name { get { return _name; } set { if (String.IsNullOrWhiteSpace(value)) throw new ArgumentException("Worksheet names cannot be empty"); if (value.IndexOfAny(InvalidNameChars.ToCharArray()) != -1) throw new ArgumentException("Worksheet names cannot contain any of the following characters: " + InvalidNameChars); if (value.Length > 31) throw new ArgumentException("Worksheet names cannot be more than 31 characters"); if (value.StartsWith("'", StringComparison.Ordinal)) throw new ArgumentException("Worksheet names cannot start with an apostrophe"); if (value.EndsWith("'", StringComparison.Ordinal)) throw new ArgumentException("Worksheet names cannot end with an apostrophe"); Workbook.WorksheetsInternal.Rename(_name, value); _name = value; } } public Int32 Position { get { return _position; } set { if (value > Workbook.WorksheetsInternal.Count + Workbook.UnsupportedSheets.Count + 1) throw new ArgumentOutOfRangeException(nameof(value), "Index must be equal or less than the number of worksheets + 1."); if (value < _position) { Workbook.WorksheetsInternal .Where<XLWorksheet>(w => w.Position >= value && w.Position < _position) .ForEach(w => w._position += 1); } if (value > _position) { Workbook.WorksheetsInternal .Where<XLWorksheet>(w => w.Position <= value && w.Position > _position) .ForEach(w => (w)._position -= 1); } _position = value; } } public IXLPageSetup PageSetup { get; private set; } public IXLOutline Outline { get; private set; } IXLRow IXLWorksheet.FirstRowUsed() { return FirstRowUsed(); } IXLRow IXLWorksheet.FirstRowUsed(Boolean includeFormats) { return FirstRowUsed(includeFormats); } IXLRow IXLWorksheet.LastRowUsed() { return LastRowUsed(); } IXLRow IXLWorksheet.LastRowUsed(Boolean includeFormats) { return LastRowUsed(includeFormats); } IXLColumn IXLWorksheet.LastColumn() { return LastColumn(); } IXLColumn IXLWorksheet.FirstColumn() { return FirstColumn(); } IXLRow IXLWorksheet.FirstRow() { return FirstRow(); } IXLRow IXLWorksheet.LastRow() { return LastRow(); } IXLColumn IXLWorksheet.FirstColumnUsed() { return FirstColumnUsed(); } IXLColumn IXLWorksheet.FirstColumnUsed(Boolean includeFormats) { return FirstColumnUsed(includeFormats); } IXLColumn IXLWorksheet.LastColumnUsed() { return LastColumnUsed(); } IXLColumn IXLWorksheet.LastColumnUsed(Boolean includeFormats) { return LastColumnUsed(includeFormats); } public IXLColumns Columns() { var retVal = new XLColumns(this); var columnList = new List<Int32>(); if (Internals.CellsCollection.Count > 0) columnList.AddRange(Internals.CellsCollection.ColumnsUsed.Keys); if (Internals.ColumnsCollection.Count > 0) columnList.AddRange(Internals.ColumnsCollection.Keys.Where(c => !columnList.Contains(c))); foreach (int c in columnList) retVal.Add(Column(c)); return retVal; } public IXLColumns Columns(String columns) { var retVal = new XLColumns(null); var columnPairs = columns.Split(','); foreach (string tPair in columnPairs.Select(pair => pair.Trim())) { String firstColumn; String lastColumn; if (tPair.Contains(':') || tPair.Contains('-')) { var columnRange = XLHelper.SplitRange(tPair); firstColumn = columnRange[0]; lastColumn = columnRange[1]; } else { firstColumn = tPair; lastColumn = tPair; } if (Int32.TryParse(firstColumn, out int tmp)) { foreach (IXLColumn col in Columns(Int32.Parse(firstColumn), Int32.Parse(lastColumn))) retVal.Add((XLColumn)col); } else { foreach (IXLColumn col in Columns(firstColumn, lastColumn)) retVal.Add((XLColumn)col); } } return retVal; } public IXLColumns Columns(String firstColumn, String lastColumn) { return Columns(XLHelper.GetColumnNumberFromLetter(firstColumn), XLHelper.GetColumnNumberFromLetter(lastColumn)); } public IXLColumns Columns(Int32 firstColumn, Int32 lastColumn) { var retVal = new XLColumns(null); for (int co = firstColumn; co <= lastColumn; co++) retVal.Add(Column(co)); return retVal; } public IXLRows Rows() { var retVal = new XLRows(this); var rowList = new List<Int32>(); if (Internals.CellsCollection.Count > 0) rowList.AddRange(Internals.CellsCollection.RowsUsed.Keys); if (Internals.RowsCollection.Count > 0) rowList.AddRange(Internals.RowsCollection.Keys.Where(r => !rowList.Contains(r))); foreach (int r in rowList) retVal.Add(Row(r)); return retVal; } public IXLRows Rows(String rows) { var retVal = new XLRows(null); var rowPairs = rows.Split(','); foreach (string tPair in rowPairs.Select(pair => pair.Trim())) { String firstRow; String lastRow; if (tPair.Contains(':') || tPair.Contains('-')) { var rowRange = XLHelper.SplitRange(tPair); firstRow = rowRange[0]; lastRow = rowRange[1]; } else { firstRow = tPair; lastRow = tPair; } Rows(Int32.Parse(firstRow), Int32.Parse(lastRow)) .ForEach(row => retVal.Add((XLRow)row)); } return retVal; } public IXLRows Rows(Int32 firstRow, Int32 lastRow) { var retVal = new XLRows(null); for (int ro = firstRow; ro <= lastRow; ro++) retVal.Add(Row(ro)); return retVal; } IXLRow IXLWorksheet.Row(Int32 row) { return Row(row); } IXLColumn IXLWorksheet.Column(Int32 column) { return Column(column); } IXLColumn IXLWorksheet.Column(String column) { return Column(column); } IXLCell IXLWorksheet.Cell(int row, int column) { return Cell(row, column); } IXLCell IXLWorksheet.Cell(string cellAddressInRange) { return Cell(cellAddressInRange); } IXLCell IXLWorksheet.Cell(int row, string column) { return Cell(row, column); } IXLCell IXLWorksheet.Cell(IXLAddress cellAddressInRange) { return Cell(cellAddressInRange); } IXLRange IXLWorksheet.Range(IXLRangeAddress rangeAddress) { return Range(rangeAddress); } IXLRange IXLWorksheet.Range(string rangeAddress) { return Range(rangeAddress); } IXLRange IXLWorksheet.Range(IXLCell firstCell, IXLCell lastCell) { return Range(firstCell, lastCell); } IXLRange IXLWorksheet.Range(string firstCellAddress, string lastCellAddress) { return Range(firstCellAddress, lastCellAddress); } IXLRange IXLWorksheet.Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress) { return Range(firstCellAddress, lastCellAddress); } IXLRange IXLWorksheet.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn) { return Range(firstCellRow, firstCellColumn, lastCellRow, lastCellColumn); } public IXLWorksheet CollapseRows() { Enumerable.Range(1, 8).ForEach(i => CollapseRows(i)); return this; } public IXLWorksheet CollapseColumns() { Enumerable.Range(1, 8).ForEach(i => CollapseColumns(i)); return this; } public IXLWorksheet ExpandRows() { Enumerable.Range(1, 8).ForEach(i => ExpandRows(i)); return this; } public IXLWorksheet ExpandColumns() { Enumerable.Range(1, 8).ForEach(i => ExpandColumns(i)); return this; } public IXLWorksheet CollapseRows(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Collapse()); return this; } public IXLWorksheet CollapseColumns(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Collapse()); return this; } public IXLWorksheet ExpandRows(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Expand()); return this; } public IXLWorksheet ExpandColumns(Int32 outlineLevel) { if (outlineLevel < 1 || outlineLevel > 8) throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8."); Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Expand()); return this; } public void Delete() { Workbook.WorksheetsInternal.Delete(Name); } public IXLNamedRanges NamedRanges { get; private set; } public IXLNamedRange NamedRange(String rangeName) { return NamedRanges.NamedRange(rangeName); } public IXLSheetView SheetView { get; private set; } public IXLTables Tables { get; private set; } public IXLTable Table(Int32 index) { return Tables.Table(index); } public IXLTable Table(String name) { return Tables.Table(name); } public IXLWorksheet CopyTo(String newSheetName) { return CopyTo(Workbook, newSheetName, Workbook.WorksheetsInternal.Count + 1); } public IXLWorksheet CopyTo(String newSheetName, Int32 position) { return CopyTo(Workbook, newSheetName, position); } public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName) { return CopyTo(workbook, newSheetName, workbook.WorksheetsInternal.Count + 1); } public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName, Int32 position) { var targetSheet = (XLWorksheet)workbook.WorksheetsInternal.Add(newSheetName, position); Internals.ColumnsCollection.ForEach(kp => kp.Value.CopyTo(targetSheet.Column(kp.Key))); Internals.RowsCollection.ForEach(kp => kp.Value.CopyTo(targetSheet.Row(kp.Key))); Internals.CellsCollection.GetCells().ForEach(c => targetSheet.Cell(c.Address).CopyFrom(c, false, false)); DataValidations.ForEach(dv => targetSheet.DataValidations.Add(new XLDataValidation(dv))); targetSheet.Visibility = Visibility; targetSheet.ColumnWidth = ColumnWidth; targetSheet.ColumnWidthChanged = ColumnWidthChanged; targetSheet.RowHeight = RowHeight; targetSheet.RowHeightChanged = RowHeightChanged; targetSheet.InnerStyle = InnerStyle; targetSheet.PageSetup = new XLPageSetup((XLPageSetup)PageSetup, targetSheet); (targetSheet.PageSetup.Header as XLHeaderFooter).Changed = true; (targetSheet.PageSetup.Footer as XLHeaderFooter).Changed = true; targetSheet.Outline = new XLOutline(Outline); targetSheet.SheetView = new XLSheetView(SheetView); targetSheet.SelectedRanges.RemoveAll(); Pictures.ForEach(picture => picture.CopyTo(targetSheet)); NamedRanges.ForEach(nr => nr.CopyTo(targetSheet)); Tables.Cast<XLTable>().ForEach(t => t.CopyTo(targetSheet, false)); ConditionalFormats.ForEach(cf => cf.CopyTo(targetSheet)); MergedRanges.ForEach(mr => targetSheet.Range(((XLRangeAddress)mr.RangeAddress).WithoutWorksheet()).Merge()); SelectedRanges.ForEach(sr => targetSheet.SelectedRanges.Add(targetSheet.Range(((XLRangeAddress)sr.RangeAddress).WithoutWorksheet()))); if (AutoFilter.Enabled) { var range = targetSheet.Range(((XLRangeAddress)AutoFilter.Range.RangeAddress).WithoutWorksheet()); range.SetAutoFilter(); } return targetSheet; } public new IXLHyperlinks Hyperlinks { get; private set; } IXLDataValidations IXLWorksheet.DataValidations { get { return DataValidations; } } private XLWorksheetVisibility _visibility; public XLWorksheetVisibility Visibility { get { return _visibility; } set { if (value != XLWorksheetVisibility.Visible) TabSelected = false; _visibility = value; } } public IXLWorksheet Hide() { Visibility = XLWorksheetVisibility.Hidden; return this; } public IXLWorksheet Unhide() { Visibility = XLWorksheetVisibility.Visible; return this; } IXLSheetProtection IXLWorksheet.Protection { get { return Protection; } } public IXLSheetProtection Protect() { return Protection.Protect(); } public IXLSheetProtection Protect(String password) { return Protection.Protect(password); } public IXLSheetProtection Unprotect() { return Protection.Unprotect(); } public IXLSheetProtection Unprotect(String password) { return Protection.Unprotect(password); } public new IXLRange Sort() { return GetRangeForSort().Sort(); } public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().Sort(columnsToSortBy, sortOrder, matchCase, ignoreBlanks); } public new IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().Sort(columnToSortBy, sortOrder, matchCase, ignoreBlanks); } public new IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return GetRangeForSort().SortLeftToRight(sortOrder, matchCase, ignoreBlanks); } public Boolean ShowFormulas { get; set; } public Boolean ShowGridLines { get; set; } public Boolean ShowOutlineSymbols { get; set; } public Boolean ShowRowColHeaders { get; set; } public Boolean ShowRuler { get; set; } public Boolean ShowWhiteSpace { get; set; } public Boolean ShowZeros { get; set; } public IXLWorksheet SetShowFormulas() { ShowFormulas = true; return this; } public IXLWorksheet SetShowFormulas(Boolean value) { ShowFormulas = value; return this; } public IXLWorksheet SetShowGridLines() { ShowGridLines = true; return this; } public IXLWorksheet SetShowGridLines(Boolean value) { ShowGridLines = value; return this; } public IXLWorksheet SetShowOutlineSymbols() { ShowOutlineSymbols = true; return this; } public IXLWorksheet SetShowOutlineSymbols(Boolean value) { ShowOutlineSymbols = value; return this; } public IXLWorksheet SetShowRowColHeaders() { ShowRowColHeaders = true; return this; } public IXLWorksheet SetShowRowColHeaders(Boolean value) { ShowRowColHeaders = value; return this; } public IXLWorksheet SetShowRuler() { ShowRuler = true; return this; } public IXLWorksheet SetShowRuler(Boolean value) { ShowRuler = value; return this; } public IXLWorksheet SetShowWhiteSpace() { ShowWhiteSpace = true; return this; } public IXLWorksheet SetShowWhiteSpace(Boolean value) { ShowWhiteSpace = value; return this; } public IXLWorksheet SetShowZeros() { ShowZeros = true; return this; } public IXLWorksheet SetShowZeros(Boolean value) { ShowZeros = value; return this; } public XLColor TabColor { get; set; } public IXLWorksheet SetTabColor(XLColor color) { TabColor = color; return this; } public Boolean TabSelected { get; set; } public Boolean TabActive { get { return _tabActive; } set { if (value && !_tabActive) { foreach (XLWorksheet ws in Worksheet.Workbook.WorksheetsInternal) ws._tabActive = false; } _tabActive = value; } } public IXLWorksheet SetTabSelected() { TabSelected = true; return this; } public IXLWorksheet SetTabSelected(Boolean value) { TabSelected = value; return this; } public IXLWorksheet SetTabActive() { TabActive = true; return this; } public IXLWorksheet SetTabActive(Boolean value) { TabActive = value; return this; } IXLPivotTable IXLWorksheet.PivotTable(String name) { return PivotTable(name); } public IXLPivotTables PivotTables { get; private set; } public Boolean RightToLeft { get; set; } public IXLWorksheet SetRightToLeft() { RightToLeft = true; return this; } public IXLWorksheet SetRightToLeft(Boolean value) { RightToLeft = value; return this; } public new IXLRanges Ranges(String ranges) { var retVal = new XLRanges(); foreach (string rangeAddressStr in ranges.Split(',').Select(s => s.Trim())) { if (XLHelper.IsValidRangeAddress(rangeAddressStr)) { retVal.Add(Range(new XLRangeAddress(Worksheet, rangeAddressStr))); } else if (NamedRanges.Any(n => String.Compare(n.Name, rangeAddressStr, true) == 0)) { NamedRange(rangeAddressStr).Ranges.ForEach(retVal.Add); } else { Workbook.NamedRanges.First(n => String.Compare(n.Name, rangeAddressStr, true) == 0 && n.Ranges.First().Worksheet == this).Ranges .ForEach(retVal.Add); } } return retVal; } IXLBaseAutoFilter IXLWorksheet.AutoFilter { get { return AutoFilter; } } public IXLRows RowsUsed(Boolean includeFormats = false, Func<IXLRow, Boolean> predicate = null) { var rows = new XLRows(Worksheet); var rowsUsed = new HashSet<Int32>(); Internals.RowsCollection.Keys.ForEach(r => rowsUsed.Add(r)); Internals.CellsCollection.RowsUsed.Keys.ForEach(r => rowsUsed.Add(r)); foreach (var rowNum in rowsUsed) { var row = Row(rowNum); if (!row.IsEmpty(includeFormats) && (predicate == null || predicate(row))) rows.Add(row); } return rows; } public IXLRows RowsUsed(Func<IXLRow, Boolean> predicate = null) { return RowsUsed(false, predicate); } public IXLColumns ColumnsUsed(Boolean includeFormats = false, Func<IXLColumn, Boolean> predicate = null) { var columns = new XLColumns(Worksheet); var columnsUsed = new HashSet<Int32>(); Internals.ColumnsCollection.Keys.ForEach(r => columnsUsed.Add(r)); Internals.CellsCollection.ColumnsUsed.Keys.ForEach(r => columnsUsed.Add(r)); foreach (var columnNum in columnsUsed) { var column = Column(columnNum); if (!column.IsEmpty(includeFormats) && (predicate == null || predicate(column))) columns.Add(column); } return columns; } public IXLColumns ColumnsUsed(Func<IXLColumn, Boolean> predicate = null) { return ColumnsUsed(false, predicate); } internal void RegisterRangeIndex(IXLRangeIndex rangeIndex) { _rangeIndices.Add(rangeIndex); } public void Dispose() { Internals.Dispose(); Pictures.ForEach(p => p.Dispose()); _rangeRepository.Clear(); _rangeIndices.Clear(); } #endregion IXLWorksheet Members #region Outlines public void IncrementColumnOutline(Int32 level) { if (level <= 0) return; if (!_columnOutlineCount.ContainsKey(level)) _columnOutlineCount.Add(level, 0); _columnOutlineCount[level]++; } public void DecrementColumnOutline(Int32 level) { if (level <= 0) return; if (!_columnOutlineCount.ContainsKey(level)) _columnOutlineCount.Add(level, 0); if (_columnOutlineCount[level] > 0) _columnOutlineCount[level]--; } public Int32 GetMaxColumnOutline() { var list = _columnOutlineCount.Where(kp => kp.Value > 0).ToList(); return list.Count == 0 ? 0 : list.Max(kp => kp.Key); } public void IncrementRowOutline(Int32 level) { if (level <= 0) return; if (!_rowOutlineCount.ContainsKey(level)) _rowOutlineCount.Add(level, 0); _rowOutlineCount[level]++; } public void DecrementRowOutline(Int32 level) { if (level <= 0) return; if (!_rowOutlineCount.ContainsKey(level)) _rowOutlineCount.Add(level, 0); if (_rowOutlineCount[level] > 0) _rowOutlineCount[level]--; } public Int32 GetMaxRowOutline() { return _rowOutlineCount.Count == 0 ? 0 : _rowOutlineCount.Where(kp => kp.Value > 0).Max(kp => kp.Key); } #endregion Outlines public XLRow FirstRowUsed() { return FirstRowUsed(false); } public XLRow FirstRowUsed(Boolean includeFormats) { var rngRow = AsRange().FirstRowUsed(includeFormats); return rngRow != null ? Row(rngRow.RangeAddress.FirstAddress.RowNumber) : null; } public XLRow LastRowUsed() { return LastRowUsed(false); } public XLRow LastRowUsed(Boolean includeFormats) { var rngRow = AsRange().LastRowUsed(includeFormats); return rngRow != null ? Row(rngRow.RangeAddress.LastAddress.RowNumber) : null; } public XLColumn LastColumn() { return Column(XLHelper.MaxColumnNumber); } public XLColumn FirstColumn() { return Column(1); } public XLRow FirstRow() { return Row(1); } public XLRow LastRow() { return Row(XLHelper.MaxRowNumber); } public XLColumn FirstColumnUsed() { return FirstColumnUsed(false); } public XLColumn FirstColumnUsed(Boolean includeFormats) { var rngColumn = AsRange().FirstColumnUsed(includeFormats); return rngColumn != null ? Column(rngColumn.RangeAddress.FirstAddress.ColumnNumber) : null; } public XLColumn LastColumnUsed() { return LastColumnUsed(false); } public XLColumn LastColumnUsed(Boolean includeFormats) { var rngColumn = AsRange().LastColumnUsed(includeFormats); return rngColumn != null ? Column(rngColumn.RangeAddress.LastAddress.ColumnNumber) : null; } public XLRow Row(Int32 row) { return Row(row, true); } public XLColumn Column(Int32 columnNumber) { if (columnNumber <= 0 || columnNumber > XLHelper.MaxColumnNumber) throw new IndexOutOfRangeException(String.Format("Column number must be between 1 and {0}", XLHelper.MaxColumnNumber)); XLColumn column; if (Internals.ColumnsCollection.TryGetValue(columnNumber, out column)) return column; else { // This is a new column so we're going to reference all // cells in this column to preserve their formatting Internals.RowsCollection.Keys.ForEach(r => Cell(r, columnNumber)); column = RangeFactory.CreateColumn(columnNumber); Internals.ColumnsCollection.Add(columnNumber, column); } return column; } public IXLColumn Column(String column) { return Column(XLHelper.GetColumnNumberFromLetter(column)); } public override XLRange AsRange() { return Range(1, 1, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber); } public void Clear() { Internals.CellsCollection.Clear(); Internals.ColumnsCollection.Clear(); Internals.MergedRanges.Clear(); Internals.RowsCollection.Clear(); } internal override void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted) { if (!range.IsEntireColumn()) { var model = new XLRangeAddress( range.RangeAddress.FirstAddress, new XLAddress(range.RangeAddress.LastAddress.RowNumber, XLHelper.MaxColumnNumber, false, false)); var rangesToSplit = Worksheet.MergedRanges .GetIntersectedRanges(model) .Where(r => r.RangeAddress.FirstAddress.RowNumber < range.RangeAddress.FirstAddress.RowNumber || r.RangeAddress.LastAddress.RowNumber > range.RangeAddress.LastAddress.RowNumber) .ToList(); foreach (var rangeToSplit in rangesToSplit) { Worksheet.MergedRanges.Remove(rangeToSplit); } } Workbook.Worksheets.ForEach(ws => MoveNamedRangesColumns(range, columnsShifted, ws.NamedRanges)); MoveNamedRangesColumns(range, columnsShifted, Workbook.NamedRanges); ShiftConditionalFormattingColumns(range, columnsShifted); ShiftPageBreaksColumns(range, columnsShifted); } private void ShiftPageBreaksColumns(XLRange range, int columnsShifted) { for (var i = 0; i < PageSetup.ColumnBreaks.Count; i++) { int br = PageSetup.ColumnBreaks[i]; if (range.RangeAddress.FirstAddress.ColumnNumber <= br) { PageSetup.ColumnBreaks[i] = br + columnsShifted; } } } private void ShiftConditionalFormattingColumns(XLRange range, int columnsShifted) { if (!ConditionalFormats.Any()) return; Int32 firstCol = range.RangeAddress.FirstAddress.ColumnNumber; if (firstCol == 1) return; int colNum = columnsShifted > 0 ? firstCol - 1 : firstCol; var model = Column(colNum).AsRange(); foreach (var cf in ConditionalFormats.ToList()) { var cfRanges = cf.Ranges.ToList(); cf.Ranges.RemoveAll(); foreach (var cfRange in cfRanges) { var cfAddress = cfRange.RangeAddress; IXLRange newRange; if (cfRange.Intersects(model)) { newRange = Range(cfAddress.FirstAddress.RowNumber, cfAddress.FirstAddress.ColumnNumber, cfAddress.LastAddress.RowNumber, cfAddress.LastAddress.ColumnNumber + columnsShifted); } else if (cfAddress.FirstAddress.ColumnNumber >= firstCol) { newRange = Range(cfAddress.FirstAddress.RowNumber, Math.Max(cfAddress.FirstAddress.ColumnNumber + columnsShifted, firstCol), cfAddress.LastAddress.RowNumber, cfAddress.LastAddress.ColumnNumber + columnsShifted); } else newRange = cfRange; if (newRange.RangeAddress.IsValid && newRange.RangeAddress.FirstAddress.ColumnNumber <= newRange.RangeAddress.LastAddress.ColumnNumber) cf.Ranges.Add(newRange); } if (!cf.Ranges.Any()) ConditionalFormats.Remove(f => f == cf); } } internal override void WorksheetRangeShiftedRows(XLRange range, int rowsShifted) { if (!range.IsEntireRow()) { var model = new XLRangeAddress( range.RangeAddress.FirstAddress, new XLAddress(XLHelper.MaxRowNumber, range.RangeAddress.LastAddress.ColumnNumber, false, false)); var rangesToSplit = Worksheet.MergedRanges .GetIntersectedRanges(model) .Where(r => r.RangeAddress.FirstAddress.ColumnNumber < range.RangeAddress.FirstAddress.ColumnNumber || r.RangeAddress.LastAddress.ColumnNumber > range.RangeAddress.LastAddress.ColumnNumber) .ToList(); foreach (var rangeToSplit in rangesToSplit) { Worksheet.MergedRanges.Remove(rangeToSplit); } } Workbook.Worksheets.ForEach(ws => MoveNamedRangesRows(range, rowsShifted, ws.NamedRanges)); MoveNamedRangesRows(range, rowsShifted, Workbook.NamedRanges); ShiftConditionalFormattingRows(range, rowsShifted); ShiftPageBreaksRows(range, rowsShifted); } private void ShiftPageBreaksRows(XLRange range, int rowsShifted) { for (var i = 0; i < PageSetup.RowBreaks.Count; i++) { int br = PageSetup.RowBreaks[i]; if (range.RangeAddress.FirstAddress.RowNumber <= br) { PageSetup.RowBreaks[i] = br + rowsShifted; } } } private void ShiftConditionalFormattingRows(XLRange range, int rowsShifted) { if (!ConditionalFormats.Any()) return; Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber; if (firstRow == 1) return; int rowNum = rowsShifted > 0 ? firstRow - 1 : firstRow; var model = Row(rowNum).AsRange(); foreach (var cf in ConditionalFormats.ToList()) { var cfRanges = cf.Ranges.ToList(); cf.Ranges.RemoveAll(); foreach (var cfRange in cfRanges) { var cfAddress = cfRange.RangeAddress; IXLRange newRange; if (cfRange.Intersects(model)) { newRange = Range(cfAddress.FirstAddress.RowNumber, cfAddress.FirstAddress.ColumnNumber, cfAddress.LastAddress.RowNumber + rowsShifted, cfAddress.LastAddress.ColumnNumber); } else if (cfAddress.FirstAddress.RowNumber >= firstRow) { newRange = Range(Math.Max(cfAddress.FirstAddress.RowNumber + rowsShifted, firstRow), cfAddress.FirstAddress.ColumnNumber, cfAddress.LastAddress.RowNumber + rowsShifted, cfAddress.LastAddress.ColumnNumber); } else newRange = cfRange; if (newRange.RangeAddress.IsValid && newRange.RangeAddress.FirstAddress.RowNumber <= newRange.RangeAddress.LastAddress.RowNumber) cf.Ranges.Add(newRange); } if (!cf.Ranges.Any()) ConditionalFormats.Remove(f => f == cf); } } private void MoveNamedRangesRows(XLRange range, int rowsShifted, IXLNamedRanges namedRanges) { foreach (XLNamedRange nr in namedRanges) { var newRangeList = nr.RangeList.Select(r => XLCell.ShiftFormulaRows(r, this, range, rowsShifted)).Where( newReference => newReference.Length > 0).ToList(); nr.RangeList = newRangeList; } } private void MoveNamedRangesColumns(XLRange range, int columnsShifted, IXLNamedRanges namedRanges) { foreach (XLNamedRange nr in namedRanges) { var newRangeList = nr.RangeList.Select(r => XLCell.ShiftFormulaColumns(r, this, range, columnsShifted)).Where( newReference => newReference.Length > 0).ToList(); nr.RangeList = newRangeList; } } public void NotifyRangeShiftedRows(XLRange range, Int32 rowsShifted) { try { SuspendEvents(); var rangesToShift = _rangeRepository.ToList(); WorksheetRangeShiftedRows(range, rowsShifted); foreach (var storedRange in rangesToShift) { if (!ReferenceEquals(range, storedRange)) storedRange.WorksheetRangeShiftedRows(range, rowsShifted); } range.WorksheetRangeShiftedRows(range, rowsShifted); } finally { ResumeEvents(); } } public void NotifyRangeShiftedColumns(XLRange range, Int32 columnsShifted) { try { SuspendEvents(); var rangesToShift = _rangeRepository.ToList(); WorksheetRangeShiftedColumns(range, columnsShifted); foreach (var storedRange in rangesToShift) { var addr = storedRange.RangeAddress; if (!ReferenceEquals(range, storedRange)) storedRange.WorksheetRangeShiftedColumns(range, columnsShifted); } range.WorksheetRangeShiftedColumns(range, columnsShifted); } finally { ResumeEvents(); } } public XLRow Row(Int32 rowNumber, Boolean pingCells) { if (rowNumber <= 0 || rowNumber > XLHelper.MaxRowNumber) throw new IndexOutOfRangeException(String.Format("Row number must be between 1 and {0}", XLHelper.MaxRowNumber)); XLRow row; if (Internals.RowsCollection.TryGetValue(rowNumber, out row)) return row; else { if (pingCells) { // This is a new row so we're going to reference all // cells in columns of this row to preserve their formatting var usedColumns = from c in Internals.ColumnsCollection join dc in Internals.CellsCollection.ColumnsUsed.Keys on c.Key equals dc where !Internals.CellsCollection.Contains(rowNumber, dc) select dc; usedColumns.ForEach(c => Cell(rowNumber, c)); } row = RangeFactory.CreateRow(rowNumber); Internals.RowsCollection.Add(rowNumber, row); } return row; } public IXLTable Table(XLRange range, Boolean addToTables, Boolean setAutofilter = true) { return Table(range, GetNewTableName("Table"), addToTables, setAutofilter); } public IXLTable Table(XLRange range, String name, Boolean addToTables, Boolean setAutofilter = true) { CheckRangeNotInTable(range); XLRangeAddress rangeAddress; if (range.Rows().Count() == 1) { rangeAddress = new XLRangeAddress(range.FirstCell().Address, range.LastCell().CellBelow().Address); range.InsertRowsBelow(1); } else rangeAddress = range.RangeAddress; var table = (XLTable) _rangeRepository.GetOrCreate(new XLRangeKey(XLRangeType.Table, rangeAddress)); if (table.Name != name) table.Name = name; if (addToTables && !Tables.Contains(table)) { Tables.Add(table); } if (setAutofilter && !table.ShowAutoFilter) table.InitializeAutoFilter(); return table; } private void CheckRangeNotInTable(XLRange range) { var overlappingTables = Tables.Where(t => t.RangeUsed().Intersects(range)); if (overlappingTables.Any()) throw new ArgumentException(nameof(range), $"The range {range.RangeAddress.ToStringRelative(true)} is already part of table '{overlappingTables.First().Name}'"); } private string GetNewTableName(string baseName) { var i = 1; string tableName; do { tableName = baseName + i.ToString(); i++; } while (Tables.Any(t => t.Name == tableName)); return tableName; } private IXLRange GetRangeForSort() { var range = RangeUsed(); SortColumns.ForEach(e => range.SortColumns.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase)); SortRows.ForEach(e => range.SortRows.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase)); return range; } public XLPivotTable PivotTable(String name) { return (XLPivotTable)PivotTables.PivotTable(name); } public new IXLCells Cells() { return Cells(true, true); } public new IXLCells Cells(Boolean usedCellsOnly) { if (usedCellsOnly) return Cells(true, true); else return Range(FirstCellUsed(), LastCellUsed()).Cells(false, true); } public new XLCell Cell(String cellAddressInRange) { if (XLHelper.IsValidA1Address(cellAddressInRange)) return Cell(XLAddress.Create(this, cellAddressInRange)); if (NamedRanges.Any(n => String.Compare(n.Name, cellAddressInRange, true) == 0)) return (XLCell)NamedRange(cellAddressInRange).Ranges.First().FirstCell(); var namedRanges = Workbook.NamedRanges.FirstOrDefault(n => String.Compare(n.Name, cellAddressInRange, true) == 0 && n.Ranges.Count == 1); return (XLCell)namedRanges?.Ranges?.FirstOrDefault()?.FirstCell(); } internal XLCell CellFast(String cellAddressInRange) { return Cell(XLAddress.Create(this, cellAddressInRange)); } public override XLRange Range(String rangeAddressStr) { if (XLHelper.IsValidRangeAddress(rangeAddressStr)) return Range(new XLRangeAddress(Worksheet, rangeAddressStr)); if (rangeAddressStr.Contains("[")) return Table(rangeAddressStr.Substring(0, rangeAddressStr.IndexOf("["))) as XLRange; if (NamedRanges.Any(n => String.Compare(n.Name, rangeAddressStr, true) == 0)) return (XLRange)NamedRange(rangeAddressStr).Ranges.First(); var namedRanges = Workbook.NamedRanges.FirstOrDefault(n => String.Compare(n.Name, rangeAddressStr, true) == 0 && n.Ranges.Count == 1 ); if (namedRanges == null || !namedRanges.Ranges.Any()) return null; return (XLRange)namedRanges.Ranges.First(); } public IXLRanges MergedRanges { get { return Internals.MergedRanges; } } public IXLConditionalFormats ConditionalFormats { get; private set; } private Boolean _eventTracking; public void SuspendEvents() { _eventTracking = EventTrackingEnabled; EventTrackingEnabled = false; } public void ResumeEvents() { EventTrackingEnabled = _eventTracking; } public IXLRanges SelectedRanges { get; internal set; } public IXLCell ActiveCell { get; set; } private XLCalcEngine _calcEngine; internal XLCalcEngine CalcEngine { get { return _calcEngine ?? (_calcEngine = new XLCalcEngine(this)); } } public Object Evaluate(String expression) { return CalcEngine.Evaluate(expression); } /// <summary> /// Force recalculation of all cell formulas. /// </summary> public void RecalculateAllFormulas() { CellsUsed().Cast<XLCell>().ForEach(cell => cell.Evaluate(true)); } public String Author { get; set; } public override string ToString() { return this.Name; } public IXLPictures Pictures { get; private set; } public IXLPicture Picture(string pictureName) { return Pictures.Picture(pictureName); } public IXLPicture AddPicture(Stream stream) { return Pictures.Add(stream); } public IXLPicture AddPicture(Stream stream, string name) { return Pictures.Add(stream, name); } internal IXLPicture AddPicture(Stream stream, string name, int Id) { return (Pictures as XLPictures).Add(stream, name, Id); } public IXLPicture AddPicture(Stream stream, XLPictureFormat format) { return Pictures.Add(stream, format); } public IXLPicture AddPicture(Stream stream, XLPictureFormat format, string name) { return Pictures.Add(stream, format, name); } public IXLPicture AddPicture(Bitmap bitmap) { return Pictures.Add(bitmap); } public IXLPicture AddPicture(Bitmap bitmap, string name) { return Pictures.Add(bitmap, name); } public IXLPicture AddPicture(string imageFile) { return Pictures.Add(imageFile); } public IXLPicture AddPicture(string imageFile, string name) { return Pictures.Add(imageFile, name); } public override Boolean IsEntireRow() { return true; } public override Boolean IsEntireColumn() { return true; } internal void SetValue<T>(T value, int ro, int co) where T : class { if (value == null) this.Cell(ro, co).SetValue(String.Empty); else if (value is IConvertible) this.Cell(ro, co).SetValue((T)Convert.ChangeType(value, typeof(T))); else this.Cell(ro, co).SetValue(value); } /// <summary> /// Get a cell value not initializing it if it has not been initialized yet. /// </summary> /// <param name="ro">Row number</param> /// <param name="co">Column number</param> /// <returns>Current value of the specified cell. Empty string for non-initialized cells.</returns> internal object GetCellValue(int ro, int co) { if (Internals.CellsCollection.MaxRowUsed < ro || Internals.CellsCollection.MaxColumnUsed < co || !Internals.CellsCollection.Contains(ro, co)) return string.Empty; var cell = Worksheet.Internals.CellsCollection.GetCell(ro, co); if (cell.IsEvaluating) return string.Empty; return cell.Value; } public XLRange GetOrCreateRange(XLRangeParameters xlRangeParameters) { var range = _rangeRepository.GetOrCreate(new XLRangeKey(XLRangeType.Range, xlRangeParameters.RangeAddress)); if (xlRangeParameters.DefaultStyle != null && range.StyleValue == StyleValue) range.InnerStyle = xlRangeParameters.DefaultStyle; return range as XLRange; } /// <summary> /// Get a range row from the shared repository or create a new one. /// </summary> /// <param name="address">Address of range row.</param> /// <param name="defaultStyle">Style to apply. If null the worksheet's style is applied.</param> /// <returns>Range row with the specified address.</returns> public XLRangeRow RangeRow(XLRangeAddress address, IXLStyle defaultStyle = null) { var rangeRow = (XLRangeRow)_rangeRepository.GetOrCreate(new XLRangeKey(XLRangeType.RangeRow, address)); if (defaultStyle != null && rangeRow.StyleValue == StyleValue) rangeRow.InnerStyle = defaultStyle; return rangeRow; } /// <summary> /// Get a range column from the shared repository or create a new one. /// </summary> /// <param name="address">Address of range column.</param> /// <param name="defaultStyle">Style to apply. If null the worksheet's style is applied.</param> /// <returns>Range column with the specified address.</returns> public XLRangeColumn RangeColumn(XLRangeAddress address, IXLStyle defaultStyle = null) { var rangeColumn = (XLRangeColumn)_rangeRepository.GetOrCreate(new XLRangeKey(XLRangeType.RangeColumn, address)); if (defaultStyle != null && rangeColumn.StyleValue == StyleValue) rangeColumn.InnerStyle = defaultStyle; return rangeColumn; } protected override void OnRangeAddressChanged(XLRangeAddress oldAddress, XLRangeAddress newAddress) { } public void RellocateRange(XLRangeType rangeType, XLRangeAddress oldAddress, XLRangeAddress newAddress) { if (_rangeRepository == null) return; var range = _rangeRepository.Replace(new XLRangeKey(rangeType, oldAddress), new XLRangeKey(rangeType, newAddress)); foreach (var rangeIndex in _rangeIndices) { if (rangeIndex.Remove(range)) rangeIndex.Add(range); } } internal void DeleteColumn(int columnNumber) { Internals.ColumnsCollection.Remove(columnNumber); var columnsToMove = new List<Int32>(); columnsToMove.AddRange( Internals.ColumnsCollection.Where(c => c.Key > columnNumber).Select(c => c.Key)); foreach (int column in columnsToMove.OrderBy(c => c)) { Internals.ColumnsCollection.Add(column - 1, Internals.ColumnsCollection[column]); Internals.ColumnsCollection.Remove(column); Internals.ColumnsCollection[column - 1].SetColumnNumber(column - 1); } } internal void DeleteRow(int rowNumber) { Internals.RowsCollection.Remove(rowNumber); var rowsToMove = new List<Int32>(); rowsToMove.AddRange(Internals.RowsCollection.Where(c => c.Key > rowNumber).Select(c => c.Key)); foreach (int row in rowsToMove.OrderBy(r => r)) { Internals.RowsCollection.Add(row - 1, Worksheet.Internals.RowsCollection[row]); Internals.RowsCollection.Remove(row); Internals.RowsCollection[row - 1].SetRowNumber(row - 1); } } internal void DeleteRange(XLRangeAddress rangeAddress) { _rangeRepository.Remove(new XLRangeKey(XLRangeType.Range, rangeAddress)); } } }
using System; using Avalonia.Collections; using Avalonia.Controls.Metadata; using Avalonia.Controls.Mixins; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.Utilities; namespace Avalonia.Controls { /// <summary> /// Enum which describes how to position the ticks in a <see cref="Slider"/>. /// </summary> public enum TickPlacement { /// <summary> /// No tick marks will appear. /// </summary> None, /// <summary> /// Tick marks will appear above the track for a horizontal <see cref="Slider"/>, or to the left of the track for a vertical <see cref="Slider"/>. /// </summary> TopLeft, /// <summary> /// Tick marks will appear below the track for a horizontal <see cref="Slider"/>, or to the right of the track for a vertical <see cref="Slider"/>. /// </summary> BottomRight, /// <summary> /// Tick marks appear on both sides of either a horizontal or vertical <see cref="Slider"/>. /// </summary> Outside } /// <summary> /// A control that lets the user select from a range of values by moving a Thumb control along a Track. /// </summary> [PseudoClasses(":vertical", ":horizontal", ":pressed")] public class Slider : RangeBase { /// <summary> /// Defines the <see cref="Orientation"/> property. /// </summary> public static readonly StyledProperty<Orientation> OrientationProperty = ScrollBar.OrientationProperty.AddOwner<Slider>(); /// <summary> /// Defines the <see cref="IsDirectionReversed"/> property. /// </summary> public static readonly StyledProperty<bool> IsDirectionReversedProperty = Track.IsDirectionReversedProperty.AddOwner<Slider>(); /// <summary> /// Defines the <see cref="IsSnapToTickEnabled"/> property. /// </summary> public static readonly StyledProperty<bool> IsSnapToTickEnabledProperty = AvaloniaProperty.Register<Slider, bool>(nameof(IsSnapToTickEnabled), false); /// <summary> /// Defines the <see cref="TickFrequency"/> property. /// </summary> public static readonly StyledProperty<double> TickFrequencyProperty = AvaloniaProperty.Register<Slider, double>(nameof(TickFrequency), 0.0); /// <summary> /// Defines the <see cref="TickPlacement"/> property. /// </summary> public static readonly StyledProperty<TickPlacement> TickPlacementProperty = AvaloniaProperty.Register<TickBar, TickPlacement>(nameof(TickPlacement), 0d); /// <summary> /// Defines the <see cref="TicksProperty"/> property. /// </summary> public static readonly StyledProperty<AvaloniaList<double>> TicksProperty = TickBar.TicksProperty.AddOwner<Slider>(); // Slider required parts private bool _isDragging = false; private Track _track; private Button _decreaseButton; private Button _increaseButton; private IDisposable _decreaseButtonPressDispose; private IDisposable _decreaseButtonReleaseDispose; private IDisposable _increaseButtonSubscription; private IDisposable _increaseButtonReleaseDispose; private IDisposable _pointerMovedDispose; private const double Tolerance = 0.0001; /// <summary> /// Initializes static members of the <see cref="Slider"/> class. /// </summary> static Slider() { PressedMixin.Attach<Slider>(); FocusableProperty.OverrideDefaultValue<Slider>(true); OrientationProperty.OverrideDefaultValue(typeof(Slider), Orientation.Horizontal); Thumb.DragStartedEvent.AddClassHandler<Slider>((x, e) => x.OnThumbDragStarted(e), RoutingStrategies.Bubble); Thumb.DragCompletedEvent.AddClassHandler<Slider>((x, e) => x.OnThumbDragCompleted(e), RoutingStrategies.Bubble); ValueProperty.OverrideMetadata<Slider>(new DirectPropertyMetadata<double>(enableDataValidation: true)); } /// <summary> /// Instantiates a new instance of the <see cref="Slider"/> class. /// </summary> public Slider() { UpdatePseudoClasses(Orientation); } /// <summary> /// Defines the ticks to be drawn on the tick bar. /// </summary> public AvaloniaList<double> Ticks { get => GetValue(TicksProperty); set => SetValue(TicksProperty, value); } /// <summary> /// Gets or sets the orientation of a <see cref="Slider"/>. /// </summary> public Orientation Orientation { get { return GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } /// <summary> /// Gets or sets the direction of increasing value. /// </summary> /// <value> /// true if the direction of increasing value is to the left for a horizontal slider or /// down for a vertical slider; otherwise, false. The default is false. /// </value> public bool IsDirectionReversed { get { return GetValue(IsDirectionReversedProperty); } set { SetValue(IsDirectionReversedProperty, value); } } /// <summary> /// Gets or sets a value that indicates whether the <see cref="Slider"/> automatically moves the <see cref="Thumb"/> to the closest tick mark. /// </summary> public bool IsSnapToTickEnabled { get { return GetValue(IsSnapToTickEnabledProperty); } set { SetValue(IsSnapToTickEnabledProperty, value); } } /// <summary> /// Gets or sets the interval between tick marks. /// </summary> public double TickFrequency { get { return GetValue(TickFrequencyProperty); } set { SetValue(TickFrequencyProperty, value); } } /// <summary> /// Gets or sets a value that indicates where to draw /// tick marks in relation to the track. /// </summary> public TickPlacement TickPlacement { get { return GetValue(TickPlacementProperty); } set { SetValue(TickPlacementProperty, value); } } /// <inheritdoc/> protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _decreaseButtonPressDispose?.Dispose(); _decreaseButtonReleaseDispose?.Dispose(); _increaseButtonSubscription?.Dispose(); _increaseButtonReleaseDispose?.Dispose(); _pointerMovedDispose?.Dispose(); _decreaseButton = e.NameScope.Find<Button>("PART_DecreaseButton"); _track = e.NameScope.Find<Track>("PART_Track"); _increaseButton = e.NameScope.Find<Button>("PART_IncreaseButton"); if (_track != null) { _track.IsThumbDragHandled = true; } if (_decreaseButton != null) { _decreaseButtonPressDispose = _decreaseButton.AddDisposableHandler(PointerPressedEvent, TrackPressed, RoutingStrategies.Tunnel); _decreaseButtonReleaseDispose = _decreaseButton.AddDisposableHandler(PointerReleasedEvent, TrackReleased, RoutingStrategies.Tunnel); } if (_increaseButton != null) { _increaseButtonSubscription = _increaseButton.AddDisposableHandler(PointerPressedEvent, TrackPressed, RoutingStrategies.Tunnel); _increaseButtonReleaseDispose = _increaseButton.AddDisposableHandler(PointerReleasedEvent, TrackReleased, RoutingStrategies.Tunnel); } _pointerMovedDispose = this.AddDisposableHandler(PointerMovedEvent, TrackMoved, RoutingStrategies.Tunnel); } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Handled || e.KeyModifiers != KeyModifiers.None) return; var handled = true; switch (e.Key) { case Key.Down: case Key.Left: MoveToNextTick(IsDirectionReversed ? SmallChange : -SmallChange); break; case Key.Up: case Key.Right: MoveToNextTick(IsDirectionReversed ? -SmallChange : SmallChange); break; case Key.PageUp: MoveToNextTick(IsDirectionReversed ? -LargeChange : LargeChange); break; case Key.PageDown: MoveToNextTick(IsDirectionReversed ? LargeChange : -LargeChange); break; case Key.Home: Value = Minimum; break; case Key.End: Value = Maximum; break; default: handled = false; break; } e.Handled = handled; } private void MoveToNextTick(double direction) { if (direction == 0.0) return; var value = Value; // Find the next value by snapping var next = SnapToTick(Math.Max(Minimum, Math.Min(Maximum, value + direction))); var greaterThan = direction > 0; //search for the next tick greater than value? // If the snapping brought us back to value, find the next tick point if (Math.Abs(next - value) < Tolerance && !(greaterThan && Math.Abs(value - Maximum) < Tolerance) // Stop if searching up if already at Max && !(!greaterThan && Math.Abs(value - Minimum) < Tolerance)) // Stop if searching down if already at Min { var ticks = Ticks; // If ticks collection is available, use it. // Note that ticks may be unsorted. if (ticks != null && ticks.Count > 0) { foreach (var tick in ticks) { // Find the smallest tick greater than value or the largest tick less than value if (greaterThan && MathUtilities.GreaterThan(tick, value) && (MathUtilities.LessThan(tick, next) || Math.Abs(next - value) < Tolerance) || !greaterThan && MathUtilities.LessThan(tick, value) && (MathUtilities.GreaterThan(tick, next) || Math.Abs(next - value) < Tolerance)) { next = tick; } } } else if (MathUtilities.GreaterThan(TickFrequency, 0.0)) { // Find the current tick we are at var tickNumber = Math.Round((value - Minimum) / TickFrequency); if (greaterThan) tickNumber += 1.0; else tickNumber -= 1.0; next = Minimum + tickNumber * TickFrequency; } } // Update if we've found a better value if (Math.Abs(next - value) > Tolerance) { Value = next; } } private void TrackMoved(object sender, PointerEventArgs e) { if (_isDragging) { MoveToPoint(e.GetCurrentPoint(_track)); } } private void TrackReleased(object sender, PointerReleasedEventArgs e) { _isDragging = false; } private void TrackPressed(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) { MoveToPoint(e.GetCurrentPoint(_track)); _isDragging = true; } } private void MoveToPoint(PointerPoint posOnTrack) { var orient = Orientation == Orientation.Horizontal; var thumbLength = (orient ? _track.Thumb.Bounds.Width : _track.Thumb.Bounds.Height) + double.Epsilon; var trackLength = (orient ? _track.Bounds.Width : _track.Bounds.Height) - thumbLength; var trackPos = orient ? posOnTrack.Position.X : posOnTrack.Position.Y; var logicalPos = MathUtilities.Clamp((trackPos - thumbLength * 0.5) / trackLength, 0.0d, 1.0d); var invert = orient ? IsDirectionReversed ? 1 : 0 : IsDirectionReversed ? 0 : 1; var calcVal = Math.Abs(invert - logicalPos); var range = Maximum - Minimum; var finalValue = calcVal * range + Minimum; Value = IsSnapToTickEnabled ? SnapToTick(finalValue) : finalValue; } protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value) { if (property == ValueProperty) { DataValidationErrors.SetError(this, value.Error); } } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); if (change.Property == OrientationProperty) { UpdatePseudoClasses(change.NewValue.GetValueOrDefault<Orientation>()); } } /// <summary> /// Called when user start dragging the <see cref="Thumb"/>. /// </summary> /// <param name="e"></param> protected virtual void OnThumbDragStarted(VectorEventArgs e) { _isDragging = true; } /// <summary> /// Called when user stop dragging the <see cref="Thumb"/>. /// </summary> /// <param name="e"></param> protected virtual void OnThumbDragCompleted(VectorEventArgs e) { _isDragging = false; } /// <summary> /// Snap the input 'value' to the closest tick. /// </summary> /// <param name="value">Value that want to snap to closest Tick.</param> private double SnapToTick(double value) { if (IsSnapToTickEnabled) { var previous = Minimum; var next = Maximum; // This property is rarely set so let's try to avoid the GetValue var ticks = Ticks; // If ticks collection is available, use it. // Note that ticks may be unsorted. if (ticks != null && ticks.Count > 0) { foreach (var tick in ticks) { if (MathUtilities.AreClose(tick, value)) { return value; } if (MathUtilities.LessThan(tick, value) && MathUtilities.GreaterThan(tick, previous)) { previous = tick; } else if (MathUtilities.GreaterThan(tick, value) && MathUtilities.LessThan(tick, next)) { next = tick; } } } else if (MathUtilities.GreaterThan(TickFrequency, 0.0)) { previous = Minimum + Math.Round((value - Minimum) / TickFrequency) * TickFrequency; next = Math.Min(Maximum, previous + TickFrequency); } // Choose the closest value between previous and next. If tie, snap to 'next'. value = MathUtilities.GreaterThanOrClose(value, (previous + next) * 0.5) ? next : previous; } return value; } private void UpdatePseudoClasses(Orientation o) { PseudoClasses.Set(":vertical", o == Orientation.Vertical); PseudoClasses.Set(":horizontal", o == Orientation.Horizontal); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- // Code for the main Gui Editor tree view that shows the hierarchy of the // current GUI being edited. //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::init(%this) { } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::update( %this ) { %obj = GuiEditorContent.getObject( 0 ); if( !isObject( %obj ) ) GuiEditorTreeView.clear(); else { // Open inspector tree. GuiEditorTreeView.open( %obj ); // Sync selection with GuiEditor. GuiEditorTreeView.clearSelection(); %selection = GuiEditor.getSelection(); %count = %selection.getCount(); for( %i = 0; %i < %count; %i ++ ) GuiEditorTreeView.addSelection( %selection.getObject( %i ) ); } } //============================================================================================= // Event Handlers. //============================================================================================= //--------------------------------------------------------------------------------------------- /// Defines the icons to be used in the tree view control. /// Provide the paths to each icon minus the file extension. /// Seperate them with ':'. /// The order of the icons must correspond to the bit array defined /// in the GuiTreeViewCtrl.h. function GuiEditorTreeView::onDefineIcons(%this) { %icons = ":" @ // Default1 ":" @ // SimGroup1 ":" @ // SimGroup2 ":" @ // SimGroup3 ":" @ // SimGroup4 "tools/gui/images/treeview/hidden:" @ "tools/worldEditor/images/lockedHandle"; GuiEditorTreeView.buildIconTable( %icons ); } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::onRightMouseDown( %this, %item, %pts, %obj ) { if( %this.getSelectedItemsCount() > 1 ) { %popup = new PopupMenu() { superClass = "MenuBuilder"; isPopup = true; object = -1; }; %popup.item[ 0 ] = "Delete" TAB "" TAB "GuiEditor.deleteSelection();"; %popup.reloadItems(); %popup.showPopup( Canvas ); } else if( %obj ) { %popup = new PopupMenu() { superClass = "MenuBuilder"; isPopup = true; object = %obj; }; %popup.item[ 0 ] = "Rename" TAB "" TAB "GuiEditorTreeView.showItemRenameCtrl( GuiEditorTreeView.findItemByObjectId(" @ %popup.object @ ") );"; %popup.item[ 1 ] = "Delete" TAB "" TAB "GuiEditor.deleteControl(" @ %popup.object @ ");"; %popup.item[ 2 ] = "-"; %popup.item[ 3 ] = "Locked" TAB "" TAB "%this.object.setLocked( !" @ %popup.object @ ".locked); GuiEditorTreeView.update();"; %popup.item[ 4 ] = "Hidden" TAB "" TAB "%this.object.setVisible( !" @ %popup.object @ ".isVisible() ); GuiEditorTreeView.update();"; %popup.item[ 5 ] = "-"; %popup.item[ 6 ] = "Add New Controls Here" TAB "" TAB "GuiEditor.setCurrentAddSet( " @ %popup.object @ ");"; %popup.item[ 7 ] = "Add Child Controls to Selection" TAB "" TAB "GuiEditor.selectAllControlsInSet( " @ %popup.object @ ", false );"; %popup.item[ 8 ] = "Remove Child Controls from Selection" TAB "" TAB "GuiEditor.selectAllControlsInSet( " @ %popup.object @ ", true );"; %popup.checkItem( 3, %obj.locked ); %popup.checkItem( 4, !%obj.isVisible() ); %popup.enableItem( 6, %obj.isContainer ); %popup.enableItem( 7, %obj.getCount() > 0 ); %popup.enableItem( 8, %obj.getCount() > 0 ); %popup.reloadItems(); %popup.showPopup( Canvas ); } } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::onAddSelection(%this,%ctrl) { GuiEditor.dontSyncTreeViewSelection = true; GuiEditor.addSelection( %ctrl ); GuiEditor.dontSyncTreeViewSelection = false; GuiEditor.setFirstResponder(); } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::onRemoveSelection( %this, %ctrl ) { GuiEditor.dontSyncTreeViewSelection = true; GuiEditor.removeSelection( %ctrl ); GuiEditor.dontSyncTreeViewSelection = false; } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::onDeleteSelection(%this) { GuiEditor.clearSelection(); } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::onSelect( %this, %obj ) { if( isObject( %obj ) ) { GuiEditor.dontSyncTreeViewSelection = true; GuiEditor.select( %obj ); GuiEditor.dontSyncTreeViewSelection = false; GuiEditorInspectFields.update( %obj ); } } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::isValidDragTarget( %this, %id, %obj ) { return ( %obj.isContainer || %obj.getCount() > 0 ); } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::onBeginReparenting( %this ) { if( isObject( %this.reparentUndoAction ) ) %this.reparentUndoAction.delete(); %action = UndoActionReparentObjects::create( %this ); %this.reparentUndoAction = %action; } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::onReparent( %this, %obj, %oldParent, %newParent ) { %this.reparentUndoAction.add( %obj, %oldParent, %newParent ); } //--------------------------------------------------------------------------------------------- function GuiEditorTreeView::onEndReparenting( %this ) { %action = %this.reparentUndoAction; %this.reparentUndoAction = ""; if( %action.numObjects > 0 ) { if( %action.numObjects == 1 ) %action.actionName = "Reparent Control"; else %action.actionName = "Reparent Controls"; %action.addToManager( GuiEditor.getUndoManager() ); GuiEditor.updateUndoMenu(); } else %action.delete(); }
// *********************************************************************** // Copyright (c) 2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData.TestCaseAttributeFixture; using NUnit.TestUtilities; #if ASYNC using System.Threading.Tasks; #endif #if NET_4_0 using Task = System.Threading.Tasks.TaskEx; #endif namespace NUnit.Framework.Attributes { [TestFixture] public class TestCaseAttributeTests { [TestCase(12, 3, 4)] [TestCase(12, 2, 6)] [TestCase(12, 4, 3)] public void IntegerDivisionWithResultPassedToTest(int n, int d, int q) { Assert.AreEqual(q, n / d); } [TestCase(12, 3, ExpectedResult = 4)] [TestCase(12, 2, ExpectedResult = 6)] [TestCase(12, 4, ExpectedResult = 3)] public int IntegerDivisionWithResultCheckedByNUnit(int n, int d) { return n / d; } [TestCase(2, 2, ExpectedResult=4)] public double CanConvertIntToDouble(double x, double y) { return x + y; } [TestCase("2.2", "3.3", ExpectedResult = 5.5)] public decimal CanConvertStringToDecimal(decimal x, decimal y) { return x + y; } [TestCase(2.2, 3.3, ExpectedResult = 5.5)] public decimal CanConvertDoubleToDecimal(decimal x, decimal y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public decimal CanConvertIntToDecimal(decimal x, decimal y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public short CanConvertSmallIntsToShort(short x, short y) { return (short)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public byte CanConvertSmallIntsToByte(byte x, byte y) { return (byte)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public sbyte CanConvertSmallIntsToSByte(sbyte x, sbyte y) { return (sbyte)(x + y); } [TestCase("MethodCausesConversionOverflow", RunState.NotRunnable)] [TestCase("VoidTestCaseWithExpectedResult", RunState.NotRunnable)] [TestCase("TestCaseWithNullableReturnValueAndNullExpectedResult", RunState.Runnable)] public void TestCaseRunnableState(string methodName, RunState expectedState) { var test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), methodName).Tests[0]; Assert.AreEqual(expectedState, test.RunState); } [TestCase("12-October-1942")] public void CanConvertStringToDateTime(DateTime dt) { Assert.AreEqual(1942, dt.Year); } [TestCase("4:44:15")] public void CanConvertStringToTimeSpan(TimeSpan ts) { Assert.AreEqual(4, ts.Hours); Assert.AreEqual(44, ts.Minutes); Assert.AreEqual(15, ts.Seconds); } [TestCase(null)] public void CanPassNullAsFirstArgument(object a) { Assert.IsNull(a); } [TestCase(new object[] { 1, "two", 3.0 })] [TestCase(new object[] { "zip" })] public void CanPassObjectArrayAsFirstArgument(object[] a) { } [TestCase(new object[] { "a", "b" })] public void CanPassArrayAsArgument(object[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase("a", "b")] public void ArgumentsAreCoalescedInObjectArray(object[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase(1, "b")] public void ArgumentsOfDifferentTypeAreCoalescedInObjectArray(object[] array) { Assert.AreEqual(1, array[0]); Assert.AreEqual("b", array[1]); } [TestCase(ExpectedResult = null)] public object ResultCanBeNull() { return null; } [TestCase("a", "b")] public void HandlesParamsArrayAsSoleArgument(params string[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase("a")] public void HandlesParamsArrayWithOneItemAsSoleArgument(params string[] array) { Assert.AreEqual("a", array[0]); } [TestCase("a", "b", "c", "d")] public void HandlesParamsArrayAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual("c", array[0]); Assert.AreEqual("d", array[1]); } [TestCase("a", "b")] public void HandlesParamsArrayWithNoItemsAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual(0, array.Length); } [TestCase("a", "b", "c")] public void HandlesParamsArrayWithOneItemAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual("c", array[0]); } [TestCase("x", ExpectedResult = new []{"x", "b", "c"})] [TestCase("x", "y", ExpectedResult = new[] { "x", "y", "c" })] [TestCase("x", "y", "z", ExpectedResult = new[] { "x", "y", "z" })] public string[] HandlesOptionalArguments(string s1, string s2 = "b", string s3 = "c") { return new[] {s1, s2, s3}; } [TestCase(ExpectedResult = new []{"a", "b"})] [TestCase("x", ExpectedResult = new[] { "x", "b" })] [TestCase("x", "y", ExpectedResult = new[] { "x", "y" })] public string[] HandlesAllOptionalArguments(string s1 = "a", string s2 = "b") { return new[] {s1, s2}; } [TestCase("a", "b", Explicit = true)] public void ShouldNotRunAndShouldNotFailInConsoleRunner() { Assert.Fail(); } [Test] public void CanSpecifyDescription() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasDescriptionSpecified").Tests[0]; Assert.AreEqual("My Description", test.Properties.Get(PropertyNames.Description)); } [Test] public void CanSpecifyTestName_FixedText() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified_FixedText").Tests[0]; Assert.AreEqual("XYZ", test.Name); Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture.XYZ", test.FullName); } [Test] public void CanSpecifyTestName_WithMethodName() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified_WithMethodName").Tests[0]; var expectedName = "MethodHasTestNameSpecified_WithMethodName+XYZ"; Assert.AreEqual(expectedName, test.Name); Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture." + expectedName, test.FullName); } [Test] public void CanSpecifyCategory() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasSingleCategory").Tests[0]; IList categories = test.Properties["Category"]; Assert.AreEqual(new string[] { "XYZ" }, categories); } [Test] public void CanSpecifyMultipleCategories() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasMultipleCategories").Tests[0]; IList categories = test.Properties["Category"]; Assert.AreEqual(new string[] { "X", "Y", "Z" }, categories); } [Test] public void CanIgnoreIndividualTestCases() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithIgnoredTestCases"); Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); testCase = TestFinder.Find("MethodWithIgnoredTestCases(3)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!")); } [Test] public void CanMarkIndividualTestCasesExplicit() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithExplicitTestCases"); Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing")); } #if !PORTABLE && !NETSTANDARD1_6 [Test] public void CanIncludePlatform() { bool isLinux = OSPlatform.CurrentPlatform.IsUnix; bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX; TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithIncludePlatform"); Test testCase1 = TestFinder.Find("MethodWithIncludePlatform(1)", suite, false); Test testCase2 = TestFinder.Find("MethodWithIncludePlatform(2)", suite, false); Test testCase3 = TestFinder.Find("MethodWithIncludePlatform(3)", suite, false); Test testCase4 = TestFinder.Find("MethodWithIncludePlatform(4)", suite, false); if (isLinux) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped)); } else if (isMacOSX) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped)); } else { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped)); } } [Test] public void CanExcludePlatform() { bool isLinux = OSPlatform.CurrentPlatform.IsUnix; bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX; TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWitExcludePlatform"); Test testCase1 = TestFinder.Find("MethodWitExcludePlatform(1)", suite, false); Test testCase2 = TestFinder.Find("MethodWitExcludePlatform(2)", suite, false); Test testCase3 = TestFinder.Find("MethodWitExcludePlatform(3)", suite, false); Test testCase4 = TestFinder.Find("MethodWitExcludePlatform(4)", suite, false); if (isLinux) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } else if (isMacOSX) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } else { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } } #endif #region Nullable<> tests [TestCase(12, 3, 4)] [TestCase(12, 2, 6)] [TestCase(12, 4, 3)] public void NullableIntegerDivisionWithResultPassedToTest(int? n, int? d, int? q) { Assert.AreEqual(q, n / d); } [TestCase(12, 3, ExpectedResult = 4)] [TestCase(12, 2, ExpectedResult = 6)] [TestCase(12, 4, ExpectedResult = 3)] public int? NullableIntegerDivisionWithResultCheckedByNUnit(int? n, int? d) { return n / d; } [TestCase(2, 2, ExpectedResult = 4)] public double? CanConvertIntToNullableDouble(double? x, double? y) { return x + y; } [TestCase(1)] public void CanConvertIntToNullableShort(short? x) { Assert.That(x.HasValue); Assert.That(x.Value, Is.EqualTo(1)); } [TestCase(1)] public void CanConvertIntToNullableByte(byte? x) { Assert.That(x.HasValue); Assert.That(x.Value, Is.EqualTo(1)); } [TestCase(1)] public void CanConvertIntToNullableSByte(sbyte? x) { Assert.That(x.HasValue); Assert.That(x.Value, Is.EqualTo(1)); } [TestCase("2.2", "3.3", ExpectedResult = 5.5)] public decimal? CanConvertStringToNullableDecimal(decimal? x, decimal? y) { Assert.That(x.HasValue); Assert.That(y.HasValue); return x.Value + y.Value; } [TestCase(null)] public void SupportsNullableDecimal(decimal? x) { Assert.That(x.HasValue, Is.False); } [TestCase(2.2, 3.3, ExpectedResult = 5.5)] public decimal? CanConvertDoubleToNullableDecimal(decimal? x, decimal? y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public decimal? CanConvertIntToNullableDecimal(decimal? x, decimal? y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public short? CanConvertSmallIntsToNullableShort(short? x, short? y) { return (short)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public byte? CanConvertSmallIntsToNullableByte(byte? x, byte? y) { return (byte)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public sbyte? CanConvertSmallIntsToNullableSByte(sbyte? x, sbyte? y) { return (sbyte)(x + y); } [TestCase("12-October-1942")] public void CanConvertStringToNullableDateTime(DateTime? dt) { Assert.That(dt.HasValue); Assert.AreEqual(1942, dt.Value.Year); } [TestCase(null)] public void SupportsNullableDateTime(DateTime? dt) { Assert.That(dt.HasValue, Is.False); } [TestCase("4:44:15")] public void CanConvertStringToNullableTimeSpan(TimeSpan? ts) { Assert.That(ts.HasValue); Assert.AreEqual(4, ts.Value.Hours); Assert.AreEqual(44, ts.Value.Minutes); Assert.AreEqual(15, ts.Value.Seconds); } [TestCase(null)] public void SupportsNullableTimeSpan(TimeSpan? dt) { Assert.That(dt.HasValue, Is.False); } [TestCase(1)] public void NullableSimpleFormalParametersWithArgument(int? a) { Assert.AreEqual(1, a); } [TestCase(null)] public void NullableSimpleFormalParametersWithNullArgument(int? a) { Assert.IsNull(a); } [TestCase(null, ExpectedResult = null)] [TestCase(1, ExpectedResult = 1)] public int? TestCaseWithNullableReturnValue(int? a) { return a; } [TestCase(1, ExpectedResult = 1)] public T TestWithGenericReturnType<T>(T arg1) { return arg1; } #if ASYNC [TestCase(1, ExpectedResult = 1)] public async Task<T> TestWithAsyncGenericReturnType<T>(T arg1) { return await Task.Run(() => arg1); } #endif #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.PortableExecutable { public class ManagedPEBuilder : PEBuilder { public const int ManagedResourcesDataAlignment = ManagedTextSection.ManagedResourcesDataAlignment; public const int MappedFieldDataAlignment = ManagedTextSection.MappedFieldDataAlignment; private const int DefaultStrongNameSignatureSize = 128; private const string TextSectionName = ".text"; private const string ResourceSectionName = ".rsrc"; private const string RelocationSectionName = ".reloc"; private readonly PEDirectoriesBuilder _peDirectoriesBuilder; private readonly TypeSystemMetadataSerializer _metadataSerializer; private readonly BlobBuilder _ilStream; private readonly BlobBuilder _mappedFieldDataOpt; private readonly BlobBuilder _managedResourcesOpt; private readonly ResourceSectionBuilder _nativeResourcesOpt; private readonly int _strongNameSignatureSize; private readonly MethodDefinitionHandle _entryPointOpt; private readonly DebugDirectoryBuilder _debugDirectoryBuilderOpt; private readonly CorFlags _corFlags; private int _lazyEntryPointAddress; private Blob _lazyStrongNameSignature; public ManagedPEBuilder( PEHeaderBuilder header, TypeSystemMetadataSerializer metadataSerializer, BlobBuilder ilStream, BlobBuilder mappedFieldData = null, BlobBuilder managedResources = null, ResourceSectionBuilder nativeResources = null, DebugDirectoryBuilder debugDirectoryBuilder = null, int strongNameSignatureSize = DefaultStrongNameSignatureSize, MethodDefinitionHandle entryPoint = default(MethodDefinitionHandle), CorFlags flags = CorFlags.ILOnly, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProvider = null) : base(header, deterministicIdProvider) { if (header == null) { Throw.ArgumentNull(nameof(header)); } if (metadataSerializer == null) { Throw.ArgumentNull(nameof(metadataSerializer)); } if (ilStream == null) { Throw.ArgumentNull(nameof(ilStream)); } if (strongNameSignatureSize < 0) { Throw.ArgumentOutOfRange(nameof(strongNameSignatureSize)); } _metadataSerializer = metadataSerializer; _ilStream = ilStream; _mappedFieldDataOpt = mappedFieldData; _managedResourcesOpt = managedResources; _nativeResourcesOpt = nativeResources; _strongNameSignatureSize = strongNameSignatureSize; _entryPointOpt = entryPoint; _debugDirectoryBuilderOpt = debugDirectoryBuilder ?? CreateDefaultDebugDirectoryBuilder(); _corFlags = flags; _peDirectoriesBuilder = new PEDirectoriesBuilder(); } private DebugDirectoryBuilder CreateDefaultDebugDirectoryBuilder() { if (IsDeterministic) { var builder = new DebugDirectoryBuilder(); builder.AddReproducibleEntry(); return builder; } return null; } protected override ImmutableArray<Section> CreateSections() { var builder = ImmutableArray.CreateBuilder<Section>(3); builder.Add(new Section(TextSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemExecute | SectionCharacteristics.ContainsCode)); if (_nativeResourcesOpt != null) { builder.Add(new Section(ResourceSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData)); } if (Header.Machine == Machine.I386 || Header.Machine == 0) { builder.Add(new Section(RelocationSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemDiscardable | SectionCharacteristics.ContainsInitializedData)); } return builder.ToImmutable(); } protected override BlobBuilder SerializeSection(string name, SectionLocation location) { switch (name) { case TextSectionName: return SerializeTextSection(location); case ResourceSectionName: return SerializeResourceSection(location); case RelocationSectionName: return SerializeRelocationSection(location); default: throw new ArgumentException(SR.Format(SR.UnknownSectionName, name), nameof(name)); } } private BlobBuilder SerializeTextSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); var metadataBuilder = new BlobBuilder(); var metadataSizes = _metadataSerializer.MetadataSizes; var textSection = new ManagedTextSection( imageCharacteristics: Header.ImageCharacteristics, machine: Header.Machine, ilStreamSize: _ilStream.Count, metadataSize: metadataSizes.MetadataSize, resourceDataSize: _managedResourcesOpt?.Count ?? 0, strongNameSignatureSize: _strongNameSignatureSize, debugDataSize: _debugDirectoryBuilderOpt?.Size ?? 0, mappedFieldDataSize: _mappedFieldDataOpt?.Count ?? 0); int methodBodyStreamRva = location.RelativeVirtualAddress + textSection.OffsetToILStream; int mappedFieldDataStreamRva = location.RelativeVirtualAddress + textSection.CalculateOffsetToMappedFieldDataStream(); _metadataSerializer.SerializeMetadata(metadataBuilder, methodBodyStreamRva, mappedFieldDataStreamRva); DirectoryEntry debugDirectoryEntry; BlobBuilder debugTableBuilderOpt; if (_debugDirectoryBuilderOpt != null) { int debugDirectoryOffset = textSection.ComputeOffsetToDebugDirectory(); debugTableBuilderOpt = new BlobBuilder(_debugDirectoryBuilderOpt.TableSize); _debugDirectoryBuilderOpt.Serialize(debugTableBuilderOpt, location, debugDirectoryOffset); // Only the size of the fixed part of the debug table goes here. debugDirectoryEntry = new DirectoryEntry( location.RelativeVirtualAddress + debugDirectoryOffset, _debugDirectoryBuilderOpt.TableSize); } else { debugTableBuilderOpt = null; debugDirectoryEntry = default(DirectoryEntry); } _lazyEntryPointAddress = textSection.GetEntryPointAddress(location.RelativeVirtualAddress); textSection.Serialize( sectionBuilder, location.RelativeVirtualAddress, _entryPointOpt.IsNil ? 0 : MetadataTokens.GetToken(_entryPointOpt), _corFlags, Header.ImageBase, metadataBuilder, _ilStream, _mappedFieldDataOpt, _managedResourcesOpt, debugTableBuilderOpt, out _lazyStrongNameSignature); _peDirectoriesBuilder.AddressOfEntryPoint = _lazyEntryPointAddress; _peDirectoriesBuilder.DebugTable = debugDirectoryEntry; _peDirectoriesBuilder.ImportAddressTable = textSection.GetImportAddressTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.ImportTable = textSection.GetImportTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.CorHeaderTable = textSection.GetCorHeaderDirectoryEntry(location.RelativeVirtualAddress); return sectionBuilder; } private BlobBuilder SerializeResourceSection(SectionLocation location) { Debug.Assert(_nativeResourcesOpt != null); var sectionBuilder = new BlobBuilder(); _nativeResourcesOpt.Serialize(sectionBuilder, location); _peDirectoriesBuilder.ResourceTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count); return sectionBuilder; } private BlobBuilder SerializeRelocationSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); WriteRelocationSection(sectionBuilder, Header.Machine, _lazyEntryPointAddress); _peDirectoriesBuilder.BaseRelocationTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count); return sectionBuilder; } private static void WriteRelocationSection(BlobBuilder builder, Machine machine, int entryPointAddress) { Debug.Assert(builder.Count == 0); builder.WriteUInt32((((uint)entryPointAddress + 2) / 0x1000) * 0x1000); builder.WriteUInt32((machine == Machine.IA64) ? 14u : 12u); uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000; uint relocType = (machine == Machine.Amd64 || machine == Machine.IA64) ? 10u : 3u; ushort s = (ushort)((relocType << 12) | offsetWithinPage); builder.WriteUInt16(s); if (machine == Machine.IA64) { builder.WriteUInt32(relocType << 12); } builder.WriteUInt16(0); // next chunk's RVA } protected internal override PEDirectoriesBuilder GetDirectories() { return _peDirectoriesBuilder; } private IEnumerable<Blob> GetContentToSign(BlobBuilder peImage) { // Signed content includes // - PE header without its alignment padding // - all sections including their alignment padding and excluding strong name signature blob int remainingHeader = Header.ComputeSizeOfPeHeaders(GetSections().Length); foreach (var blob in peImage.GetBlobs()) { if (remainingHeader > 0) { int length = Math.Min(remainingHeader, blob.Length); yield return new Blob(blob.Buffer, blob.Start, length); remainingHeader -= length; } else if (blob.Buffer == _lazyStrongNameSignature.Buffer) { yield return new Blob(blob.Buffer, blob.Start, _lazyStrongNameSignature.Start - blob.Start); yield return new Blob(blob.Buffer, _lazyStrongNameSignature.Start + _lazyStrongNameSignature.Length, blob.Length - _lazyStrongNameSignature.Length); } else { yield return new Blob(blob.Buffer, blob.Start, blob.Length); } } } public void Sign(BlobBuilder peImage, Func<IEnumerable<Blob>, byte[]> signatureProvider) { if (peImage == null) { throw new ArgumentNullException(nameof(peImage)); } if (signatureProvider == null) { throw new ArgumentNullException(nameof(signatureProvider)); } var content = GetContentToSign(peImage); byte[] signature = signatureProvider(content); // signature may be shorter (the rest of the reserved space is padding): if (signature == null || signature.Length > _lazyStrongNameSignature.Length) { throw new InvalidOperationException(SR.SignatureProviderReturnedInvalidSignature); } // TODO: Native csc also calculates and fills checksum in the PE header // Using MapFileAndCheckSum() from imagehlp.dll. var writer = new BlobWriter(_lazyStrongNameSignature); writer.WriteBytes(signature); } } }
// Copyright (c) 2007-2012 Andrej Repin aka Gremlin2 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Xml; namespace FB2Fix { internal class Genre { private readonly string name; private readonly Dictionary<string, string> descriptions; public Genre(string name) { this.name = name; this.descriptions = new Dictionary<string, string>(2); } public string Name { get { return this.name; } } public void AddDescription(string lang, string value) { if (String.IsNullOrEmpty(lang)) { throw new ArgumentException("lang"); } if (value == null) { throw new ArgumentNullException("value"); } descriptions[lang] = value; } public string GetDescription(string lang) { if(descriptions.ContainsKey(lang)) { return descriptions[lang]; } return String.Empty; } } internal class GenreTable : IEnumerable<Genre> { private readonly Dictionary<string, Genre> genres; private readonly Dictionary<string, string> genreMap; private static volatile GenreTable instance; private static readonly object genreSync = new object(); private GenreTable() { this.genres = new Dictionary<string, Genre>(); this.genreMap = new Dictionary<string, string>(); } public static GenreTable Table { get { if(instance == null) { lock(genreSync) { if(instance == null) { instance = new GenreTable(); } } } return instance; } } public static void ReadGenreList(XmlReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } lock (genreSync) { if(instance == null) { instance = new GenreTable(); } XmlDocument genreList = new XmlDocument(); genreList.Load(reader); instance.genres.Clear(); instance.genreMap.Clear(); XmlNodeList nodeList = genreList.SelectNodes("//fbgenrestransfer/genre/subgenres/subgenre"); foreach (XmlNode genreNode in nodeList) { XmlElement genreElement = genreNode as XmlElement; if (genreElement != null) { XmlAttribute genreName = genreElement.Attributes["value"]; if (genreName != null && !String.IsNullOrEmpty(genreName.Value)) { Genre genre = new Genre(genreName.Value); foreach (XmlNode childNode in genreElement.ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { XmlElement childElement = childNode as XmlElement; if (childElement == null) { continue; } switch (childElement.LocalName) { case "genre-descr": XmlAttribute langAttribute = childElement.Attributes["lang"]; XmlAttribute titleAttribute = childElement.Attributes["title"]; if (langAttribute != null && !String.IsNullOrEmpty(langAttribute.Value)) { genre.AddDescription(langAttribute.Value, titleAttribute == null ? String.Empty : titleAttribute.Value); } break; case "genre-alt": XmlAttribute valueAttribute = childElement.Attributes["value"]; if (valueAttribute != null && !String.IsNullOrEmpty(valueAttribute.Value)) { instance.genreMap[valueAttribute.Value] = genreName.Value; } break; } } } instance.genres[genreName.Value] = genre; } } } } } public ReadOnlyDictionary<string, string> MapTable { get { return new ReadOnlyDictionary<string, string>(this.genreMap); } } public Genre this[string name] { get { if (name == null) { throw new ArgumentNullException("name"); } if(this.genres.ContainsKey(name)) { return this.genres[name]; } return null; } } IEnumerator<Genre> IEnumerable<Genre>.GetEnumerator() { foreach (Genre genre in genres.Values) { yield return genre; } } public IEnumerator GetEnumerator() { return ((IEnumerable<Genre>) this).GetEnumerator(); } } }
/* * 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; using System.Collections.Generic; using System.Reflection; using System.Threading; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Grid.Framework; namespace OpenSim.Grid.AgentDomain.Modules { public class AvatarCreationModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private UserDataBaseService m_userDataBaseService; // private BaseHttpServer m_httpServer; // TODO: unused: private UserConfig m_config; private string m_inventoryServerUrl; private IInterServiceInventoryServices m_inventoryService; public AvatarCreationModule(UserDataBaseService userDataBaseService, UserConfig config, IInterServiceInventoryServices inventoryService) { // TODO: unused: m_config = config; m_userDataBaseService = userDataBaseService; m_inventoryService = inventoryService; m_inventoryServerUrl = config.InventoryUrl.OriginalString; } public void Initialise(IGridServiceCore core) { CommandConsole console; if (core.TryGet<CommandConsole>(out console)) { console.Commands.AddCommand("userserver", false, "clone avatar", "clone avatar <TemplateAvatarFirstName> <TemplateAvatarLastName> <TargetAvatarFirstName> <TargetAvatarLastName>", "Clone the template avatar's inventory into a target avatar", RunCommand); } } public void PostInitialise() { } public void RegisterHandlers(BaseHttpServer httpServer) { } public void RunCommand(string module, string[] cmd) { if ((cmd.Length == 6) && (cmd[0] == "clone") && (cmd[1] == "avatar")) { try { string tFirst = cmd[2]; string tLast = cmd[3]; string nFirst = cmd[4]; string nLast = cmd[5]; UserProfileData templateAvatar = m_userDataBaseService.GetUserProfile(tFirst, tLast); UserProfileData newAvatar = m_userDataBaseService.GetUserProfile(nFirst, nLast); if (templateAvatar == null) { m_log.ErrorFormat("[AvatarAppearance] Clone Avatar: Could not find template avatar {0} , {1}", tFirst, tLast); return; } if (newAvatar == null) { m_log.ErrorFormat("[AvatarAppearance] Clone Avatar: Could not find target avatar {0} , {1}", nFirst, nLast); return; } Guid avatar = newAvatar.ID.Guid; Guid template = templateAvatar.ID.Guid; CloneAvatar(avatar, template, true, true); } catch (Exception e) { m_log.Error("Error: " + e.ToString()); } } } #region Avatar Appearance Creation public bool CloneAvatar(Guid avatarID, Guid templateID, bool modifyPermissions, bool removeTargetsClothes) { m_log.InfoFormat("[AvatarAppearance] Starting to clone avatar {0} inventory to avatar {1}", templateID.ToString(), avatarID.ToString()); // TODO: unused: Guid bodyFolder = Guid.Empty; // TODO: unused: Guid clothesFolder = Guid.Empty; bool success = false; UUID avID = new UUID(avatarID); List<InventoryFolderBase> avatarInventory = m_inventoryService.GetInventorySkeleton(avID); if ((avatarInventory == null) || (avatarInventory.Count == 0)) { m_log.InfoFormat("[AvatarAppearance] No inventory found for user {0} , so creating it", avID.ToString()); m_inventoryService.CreateNewUserInventory(avID); Thread.Sleep(5000); avatarInventory = m_inventoryService.GetInventorySkeleton(avID); } if ((avatarInventory != null) && (avatarInventory.Count > 0)) { UUID tempOwnID = new UUID(templateID); AvatarAppearance appearance = m_userDataBaseService.GetUserAppearance(tempOwnID); if (removeTargetsClothes) { //remove clothes and attachments from target avatar so that the end result isn't a merger of its existing clothes // and the clothes from the template avatar. RemoveClothesAndAttachments(avID); } List<InventoryFolderBase> templateInventory = m_inventoryService.GetInventorySkeleton(tempOwnID); if ((templateInventory != null) && (templateInventory.Count != 0)) { for (int i = 0; i < templateInventory.Count; i++) { if (templateInventory[i].ParentID == UUID.Zero) { success = CloneFolder(avatarInventory, avID, UUID.Zero, appearance, templateInventory[i], templateInventory, modifyPermissions); break; } } } else { m_log.InfoFormat("[AvatarAppearance] Failed to find the template owner's {0} inventory", tempOwnID); } } m_log.InfoFormat("[AvatarAppearance] finished cloning avatar with result: {0}", success); return success; } private bool CloneFolder(List<InventoryFolderBase> avatarInventory, UUID avID, UUID parentFolder, AvatarAppearance appearance, InventoryFolderBase templateFolder, List<InventoryFolderBase> templateFolders, bool modifyPermissions) { bool success = false; UUID templateFolderId = templateFolder.ID; if (templateFolderId != UUID.Zero) { InventoryFolderBase toFolder = FindFolder(templateFolder.Name, parentFolder.Guid, avatarInventory); if (toFolder == null) { //create new folder toFolder = new InventoryFolderBase(); toFolder.ID = UUID.Random(); toFolder.Name = templateFolder.Name; toFolder.Owner = avID; toFolder.Type = templateFolder.Type; toFolder.Version = 1; toFolder.ParentID = parentFolder; if (!SynchronousRestObjectRequester.MakeRequest<InventoryFolderBase, bool>( "POST", m_inventoryServerUrl + "CreateFolder/", toFolder)) { m_log.InfoFormat("[AvatarApperance] Couldn't make new folder {0} in users inventory", toFolder.Name); return false; } else { // m_log.InfoFormat("made new folder {0} in users inventory", toFolder.Name); } } List<InventoryItemBase> templateItems = SynchronousRestObjectRequester.MakeRequest<Guid, List<InventoryItemBase>>( "POST", m_inventoryServerUrl + "GetItems/", templateFolderId.Guid); if ((templateItems != null) && (templateItems.Count > 0)) { List<ClothesAttachment> wornClothes = new List<ClothesAttachment>(); List<ClothesAttachment> attachedItems = new List<ClothesAttachment>(); foreach (InventoryItemBase item in templateItems) { UUID clonedItemId = CloneInventoryItem(avID, toFolder.ID, item, modifyPermissions); if (clonedItemId != UUID.Zero) { int appearanceType = ItemIsPartOfAppearance(item, appearance); if (appearanceType >= 0) { // UpdateAvatarAppearance(avID, appearanceType, clonedItemId, item.AssetID); wornClothes.Add(new ClothesAttachment(appearanceType, clonedItemId, item.AssetID)); } if (appearance != null) { int attachment = appearance.GetAttachpoint(item.ID); if (attachment > 0) { //UpdateAvatarAttachment(avID, attachment, clonedItemId, item.AssetID); attachedItems.Add(new ClothesAttachment(attachment, clonedItemId, item.AssetID)); } } success = true; } } if ((wornClothes.Count > 0) || (attachedItems.Count > 0)) { //Update the worn clothes and attachments AvatarAppearance targetAppearance = GetAppearance(avID); if (targetAppearance != null) { foreach (ClothesAttachment wornItem in wornClothes) { targetAppearance.Wearables[wornItem.Type].AssetID = wornItem.AssetID; targetAppearance.Wearables[wornItem.Type].ItemID = wornItem.ItemID; } foreach (ClothesAttachment wornItem in attachedItems) { targetAppearance.SetAttachment(wornItem.Type, wornItem.ItemID, wornItem.AssetID); } m_userDataBaseService.UpdateUserAppearance(avID, targetAppearance); wornClothes.Clear(); attachedItems.Clear(); } } } else if ((templateItems != null) && (templateItems.Count == 0)) { // m_log.Info("[AvatarAppearance]Folder being cloned was empty"); success = true; } List<InventoryFolderBase> subFolders = FindSubFolders(templateFolder.ID.Guid, templateFolders); foreach (InventoryFolderBase subFolder in subFolders) { if (subFolder.Name.ToLower() != "trash") { success = CloneFolder(avatarInventory, avID, toFolder.ID, appearance, subFolder, templateFolders, modifyPermissions); } } } else { m_log.Info("[AvatarAppearance] Failed to find the template folder"); } return success; } private UUID CloneInventoryItem(UUID avatarID, UUID avatarFolder, InventoryItemBase item, bool modifyPerms) { if (avatarFolder != UUID.Zero) { InventoryItemBase clonedItem = new InventoryItemBase(); clonedItem.Owner = avatarID; clonedItem.AssetID = item.AssetID; clonedItem.AssetType = item.AssetType; clonedItem.BasePermissions = item.BasePermissions; clonedItem.CreationDate = item.CreationDate; clonedItem.CreatorId = item.CreatorId; clonedItem.CreatorIdAsUuid = item.CreatorIdAsUuid; clonedItem.CurrentPermissions = item.CurrentPermissions; clonedItem.Description = item.Description; clonedItem.EveryOnePermissions = item.EveryOnePermissions; clonedItem.Flags = item.Flags; clonedItem.Folder = avatarFolder; clonedItem.GroupID = item.GroupID; clonedItem.GroupOwned = item.GroupOwned; clonedItem.GroupPermissions = item.GroupPermissions; clonedItem.ID = UUID.Random(); clonedItem.InvType = item.InvType; clonedItem.Name = item.Name; clonedItem.NextPermissions = item.NextPermissions; clonedItem.SalePrice = item.SalePrice; clonedItem.SaleType = item.SaleType; if (modifyPerms) { ModifyPermissions(ref clonedItem); } SynchronousRestObjectRequester.MakeRequest<InventoryItemBase, bool>( "POST", m_inventoryServerUrl + "AddNewItem/", clonedItem); return clonedItem.ID; } return UUID.Zero; } // TODO: unused // private void UpdateAvatarAppearance(UUID avatarID, int wearableType, UUID itemID, UUID assetID) // { // AvatarAppearance appearance = GetAppearance(avatarID); // appearance.Wearables[wearableType].AssetID = assetID; // appearance.Wearables[wearableType].ItemID = itemID; // m_userDataBaseService.UpdateUserAppearance(avatarID, appearance); // } // TODO: unused // private void UpdateAvatarAttachment(UUID avatarID, int attachmentPoint, UUID itemID, UUID assetID) // { // AvatarAppearance appearance = GetAppearance(avatarID); // appearance.SetAttachment(attachmentPoint, itemID, assetID); // m_userDataBaseService.UpdateUserAppearance(avatarID, appearance); // } private void RemoveClothesAndAttachments(UUID avatarID) { AvatarAppearance appearance = GetAppearance(avatarID); appearance.ClearWearables(); appearance.ClearAttachments(); m_userDataBaseService.UpdateUserAppearance(avatarID, appearance); } private AvatarAppearance GetAppearance(UUID avatarID) { AvatarAppearance appearance = m_userDataBaseService.GetUserAppearance(avatarID); if (appearance == null) { appearance = CreateDefaultAppearance(avatarID); } return appearance; } // TODO: unused // private UUID FindFolderID(string name, List<InventoryFolderBase> folders) // { // foreach (InventoryFolderBase folder in folders) // { // if (folder.Name == name) // { // return folder.ID; // } // } // return UUID.Zero; // } // TODO: unused // private InventoryFolderBase FindFolder(string name, List<InventoryFolderBase> folders) // { // foreach (InventoryFolderBase folder in folders) // { // if (folder.Name == name) // { // return folder; // } // } // return null; // } private InventoryFolderBase FindFolder(string name, Guid parentFolderID, List<InventoryFolderBase> folders) { foreach (InventoryFolderBase folder in folders) { if ((folder.Name == name) && (folder.ParentID.Guid == parentFolderID)) { return folder; } } return null; } // TODO: unused // private InventoryItemBase GetItem(string itemName, List<InventoryItemBase> items) // { // foreach (InventoryItemBase item in items) // { // if (item.Name.ToLower() == itemName.ToLower()) // { // return item; // } // } // return null; // } private List<InventoryFolderBase> FindSubFolders(Guid parentFolderID, List<InventoryFolderBase> folders) { List<InventoryFolderBase> subFolders = new List<InventoryFolderBase>(); foreach (InventoryFolderBase folder in folders) { if (folder.ParentID.Guid == parentFolderID) { subFolders.Add(folder); } } return subFolders; } protected virtual void ModifyPermissions(ref InventoryItemBase item) { // Propagate Permissions item.BasePermissions = item.BasePermissions & item.NextPermissions; item.CurrentPermissions = item.BasePermissions; item.EveryOnePermissions = item.EveryOnePermissions & item.NextPermissions; item.GroupPermissions = item.GroupPermissions & item.NextPermissions; } private AvatarAppearance CreateDefaultAppearance(UUID avatarId) { AvatarAppearance appearance = null; AvatarWearable[] wearables; byte[] visualParams; GetDefaultAvatarAppearance(out wearables, out visualParams); appearance = new AvatarAppearance(avatarId, wearables, visualParams); return appearance; } private static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams) { visualParams = GetDefaultVisualParams(); wearables = AvatarWearable.DefaultWearables; } private static byte[] GetDefaultVisualParams() { byte[] visualParams; visualParams = new byte[218]; for (int i = 0; i < 218; i++) { visualParams[i] = 100; } return visualParams; } private int ItemIsPartOfAppearance(InventoryItemBase item, AvatarAppearance appearance) { if (appearance != null) { if (appearance.BodyItem == item.ID) return (int)WearableType.Shape; if (appearance.EyesItem == item.ID) return (int)WearableType.Eyes; if (appearance.GlovesItem == item.ID) return (int)WearableType.Gloves; if (appearance.HairItem == item.ID) return (int)WearableType.Hair; if (appearance.JacketItem == item.ID) return (int)WearableType.Jacket; if (appearance.PantsItem == item.ID) return (int)WearableType.Pants; if (appearance.ShirtItem == item.ID) return (int)WearableType.Shirt; if (appearance.ShoesItem == item.ID) return (int)WearableType.Shoes; if (appearance.SkinItem == item.ID) return (int)WearableType.Skin; if (appearance.SkirtItem == item.ID) return (int)WearableType.Skirt; if (appearance.SocksItem == item.ID) return (int)WearableType.Socks; if (appearance.UnderPantsItem == item.ID) return (int)WearableType.Underpants; if (appearance.UnderShirtItem == item.ID) return (int)WearableType.Undershirt; } return -1; } #endregion public enum PermissionMask { None = 0, Transfer = 8192, Modify = 16384, Copy = 32768, Move = 524288, Damage = 1048576, All = 2147483647, } public enum WearableType { Shape = 0, Skin = 1, Hair = 2, Eyes = 3, Shirt = 4, Pants = 5, Shoes = 6, Socks = 7, Jacket = 8, Gloves = 9, Undershirt = 10, Underpants = 11, Skirt = 12, } public class ClothesAttachment { public int Type; public UUID ItemID; public UUID AssetID; public ClothesAttachment(int type, UUID itemID, UUID assetID) { Type = type; ItemID = itemID; AssetID = assetID; } } } }
using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using DependenciesTracking.Interfaces; namespace DependenciesTracking.Tests.Stubs { public class Order : INotifyPropertyChanged { private OrderProperties _properties; private string _orderLine; private int _totalCost; public OrderProperties Properties { get { return _properties; } set { if (_properties != value) { _properties = value; OnPropertyChanged("Properties"); } } } public int TotalCost { get { return _totalCost; } private set { if (_totalCost != value) { _totalCost = value; OnPropertyChanged("TotalCost"); } } } public string OrderLine { get { return _orderLine; } private set { if (_orderLine != value) { _orderLine = value; OnPropertyChanged("OrderLine"); } } } public string ShortOrderLine { get { return _shortOrderLine; } private set { if (_shortOrderLine != value) { _shortOrderLine = value; OnPropertyChanged("ShortOrderLine"); } } } private static readonly IDependenciesMap<Order> _map = new DependenciesMap<Order>(); private IDisposable _tracker; private string _shortOrderLine; static Order() { _map.AddDependency(o => o.OrderLine, BuildOrderLine, o => o.Properties.Category, o => o.Properties.Price, o => o.Properties.Quantity) .AddDependency(o => o.TotalCost, o => o.Properties != null ? o.Properties.Price * o.Properties.Quantity : -1, o => o.Properties.Price, o => o.Properties.Quantity) .AddDependency(o => o.ShortOrderLine, o => o.TotalCost == -1 ? "ShortOrderLine is empty" : string.Format("Order has total cost = {0}", o.TotalCost), o => o.TotalCost); } public Order() { _tracker = _map.StartTracking(this); } private static string BuildOrderLine(Order order) { return order.Properties == null ? "Order is empty" : string.Format("Order category: {0}, price = {1}, quantity = {2}", order.Properties.Category, order.Properties.Price, order.Properties.Quantity); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } public class OrderProperties : INotifyPropertyChanged { private int _price; private int _quantity; private string _category; public string Category { get { return _category; } set { if (_category != value) { _category = value; OnPropertyChanged("Category"); } } } public int Price { get { return _price; } set { if (_price != value) { _price = value; OnPropertyChanged("Price"); } } } public int Quantity { get { return _quantity; } set { if (_quantity != value) { _quantity = value; OnPropertyChanged("Quantity"); } } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } public sealed class Invoice : INotifyPropertyChanged { private ObservableCollection<FlatOrder> _orders; private int _totalCost; public ObservableCollection<FlatOrder> Orders { get { return _orders; } set { if (_orders != value) { _orders = value; OnPropertyChanged("Orders"); } } } public int TotalCost { get { return _totalCost; } set { if (_totalCost != value) { _totalCost = value; OnPropertyChanged("TotalCost"); } } } private static readonly DependenciesMap<Invoice> _dependenciesMap = new DependenciesMap<Invoice>(); private IDisposable _tracker; static Invoice() { _dependenciesMap.AddDependency(i => i.TotalCost, i => i.Orders == null ? -1 : i.Orders.Sum(o => o.Price * o.Quantity), i => DependenciesTracking.CollectionExtensions.EachElement(i.Orders).Price, i => DependenciesTracking.CollectionExtensions.EachElement(i.Orders).Quantity); } public Invoice() { _tracker = _dependenciesMap.StartTracking(this); } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } }
/** * Copyright(C) 2016 Singapore ETH Centre, Future Cities Laboratory * All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license.See the LICENSE file for details. * * Author: Filip Schramka ([email protected]) * Summary: Class which opens the serial communication. * * Credit: * This piece of software was modified from its original * form which was written by * * SerialCommUnity (Serial Communication for Unity) * Author: Daniel Wilches <[email protected]> * * This work is released under the Creative Commons * Attributions license. * https://creativecommons.org/licenses/by/2.0/ * */ using UnityEngine; using System; using System.IO; using System.IO.Ports; using System.Collections; using System.Threading; using System.Collections.Generic; using SerialFramework; /** * This class contains methods that must be run from inside a thread and others * that must be invoked from Unity. Both types of methods are clearly marked in * the code, although you, the final user of this library, don't need to even * open this file unless you are introducing incompatibilities for upcoming * versions. */ public class SerialIO { // Parameters passed from SerialController, used for connecting to the // serial device as explained in the SerialController documentation. private string portName; private int baudRate; private Parity paritySetting; private int dataBitCount; private StopBits stopBitSetting; private int delayBeforeReconnecting; // received data will be read into this buffer private byte[] rawSerialBuffer; private const int serialBufferSize = 256; private Queue<byte> rawQueue; // Object from the .Net framework used to communicate with serial devices. private SerialPort serialPort; // Amount of milliseconds alloted to a single read or connect. An // exception is thrown when such operations take more than this time // to complete. private const int readTimeout = 100; // Amount of milliseconds alloted to a single write. An exception is thrown // when such operations take more than this time to complete. private const int writeTimeout = 100; // Internal synchronized queues used to send and receive messages from the // serial device. They serve as the point of communication between the // Unity thread and the SerialComm thread. private Queue inputQueue, outputQueue; // Indicates when this thread should stop executing. When SerialController // invokes 'RequestStop()' this variable is set. private bool stopRequested = false; // interprets the data before enqueue them into the outputqueue private AbstractSerialInterpreter interpreter; //- TODO remove // signal counter variables //private const int maxHashCount = 5; //private int hashCount = 0; //private int hashTimeout = readTimeout; //private bool hashTimeoutTrigger = false; /************************************************************************** * Methods intended to be invoked from the Unity thread. *************************************************************************/ // ------------------------------------------------------------------------ // Constructs the thread object. This object is not a thread actually, but // its method 'RunForever' can later be used to create a real Thread. // ------------------------------------------------------------------------ public SerialIO(string portName, int baudRate, Parity paritySetting, int dataBitCount, StopBits stopBitSetting, int delayBeforeReconnecting, AbstractSerialInterpreter interpreter) { Debug.Assert(interpreter != null); this.portName = portName; this.baudRate = baudRate; this.paritySetting = paritySetting; this.dataBitCount = dataBitCount; this.stopBitSetting = stopBitSetting; this.delayBeforeReconnecting = delayBeforeReconnecting; this.interpreter = interpreter; inputQueue = Queue.Synchronized(new Queue()); outputQueue = Queue.Synchronized(new Queue()); rawSerialBuffer = new byte[serialBufferSize]; rawQueue = new Queue<byte>(); } // ------------------------------------------------------------------------ // Returns the count of the bytes in the input queue // ------------------------------------------------------------------------ public int GetInputQueueSize() { return inputQueue.Count; } // ------------------------------------------------------------------------ // Returns the count of byte[] in the output queue // ------------------------------------------------------------------------ public int GetOutputQueueSize() { return outputQueue.Count; } // ------------------------------------------------------------------------ // Dequeues the next value // ------------------------------------------------------------------------ public object GetNextInput() { return inputQueue.Dequeue(); } // ------------------------------------------------------------------------ // Peeks into the queue // ------------------------------------------------------------------------ public object checkNextInput() { return inputQueue.Peek(); } // ------------------------------------------------------------------------ // Enqueues a character for sending // ------------------------------------------------------------------------ public void SendCharacter(char c) { outputQueue.Enqueue(new byte[] { (byte)c }); } // ------------------------------------------------------------------------ // Enqueues the whole buffer for sending // ------------------------------------------------------------------------ public void SendBuffer(byte[] b) { outputQueue.Enqueue(b); } // ------------------------------------------------------------------------ // Invoked to indicate to this thread object that it should stop. // ------------------------------------------------------------------------ public void RequestStop() { interpreter.AddSystemMessage(SystemMessage.Connection_Down); lock (this) { stopRequested = true; } } /************************************************************************** * Methods intended to be invoked from the SerialComm thread (the one * created by the SerialController). *************************************************************************/ // ------------------------------------------------------------------------ // Enters an almost infinite loop of attempting conenction to the serial // device, reading messages and sending messages. This loop can be stopped // by invoking 'RequestStop'. // ------------------------------------------------------------------------ public void RunForever() { // This try is for having a log message in case of an unexpected // exception. try { while (!IsStopRequested()) { try { // Try to connect AttemptConnection(); // Enter the semi-infinite loop of reading/writing to the // device. while (!IsStopRequested()) RunOnce(); // send the finish commands to the device Thread.Sleep(100); RunOnce(); } catch (Exception ioe) { // request stop if port doesnt exist if (ioe.Message.Contains(portName + "' does not exist")) { RequestStop(); Debug.Log(portName + " does not exist"); } else if (ioe.Message.Contains("is not connected")) { Debug.Log("Device on " + portName + " is not connected"); } else Debug.LogWarning("Exception: " + ioe.Message + " StackTrace: " + ioe.StackTrace); Debug.Log("Dissconnected from " + portName); // As I don't know in which stage the SerialPort threw the // exception I call this method that is very safe in // disregard of the port's status CloseDevice(); // Don't attempt to reconnect just yet, wait some // user-defined time. It is OK to sleep here as this is not // Unity's thread, this doesn't affect frame-rate // throughput. Thread.Sleep(delayBeforeReconnecting); } } // Attempt to do a final cleanup. This method doesn't fail even if // the port is in an invalid status. CloseDevice(); } catch (Exception e) { Debug.LogError("Unknown exception: " + e.Message + " " + e.StackTrace); } } // ------------------------------------------------------------------------ // Try to connect to the serial device. May throw IO exceptions. // ------------------------------------------------------------------------ private void AttemptConnection() { serialPort = new SerialPort(portName, baudRate, paritySetting, dataBitCount, stopBitSetting); serialPort.ReadTimeout = readTimeout; serialPort.WriteTimeout = writeTimeout; serialPort.Open(); Debug.Log("Connected to Port " + portName); interpreter.AddSystemMessage(SystemMessage.Connection_Up); } public bool isSerialPortOpen() { return serialPort != null && serialPort.IsOpen; } // ------------------------------------------------------------------------ // Release any resource used, and don't fail in the attempt. // ------------------------------------------------------------------------ private void CloseDevice() { if (serialPort == null) return; try { serialPort.Close(); } catch (IOException) { // Nothing to do, not a big deal, don't try to cleanup any further. } serialPort = null; } // ------------------------------------------------------------------------ // Just checks if 'RequestStop()' has already been called in this object. // ------------------------------------------------------------------------ private bool IsStopRequested() { lock (this) { return stopRequested; } } // ------------------------------------------------------------------------ // A single iteration of the semi-infinite loop. Attempt to read/write to // the serial device. If there are more lines in the queue than we may have // at a given time, then the newly read lines will be discarded. This is a // protection mechanism when the port is faster than the Unity progeram. // If not, we may run out of memory if the queue really fills. // ------------------------------------------------------------------------ private void RunOnce() { try { // Send a byte[] if (outputQueue.Count != 0) { byte[] message = (byte[])outputQueue.Dequeue(); serialPort.Write(message, 0, message.Length); } // receive and interprete data int l = serialPort.Read(rawSerialBuffer, 0, serialBufferSize); for (int i = 0; i < l; ++i) rawQueue.Enqueue(rawSerialBuffer[i]); interpreter.InterpreteAndAdd(rawQueue, inputQueue); } catch (TimeoutException) { // This is normal, not everytime we have a report from the serial device } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } public void LockControllerReleaseMouse(bool state) { if (state) { this.enabled = false; m_MouseLook.SetCursorLock(false); m_MouseLook.UpdateCursorLock(); } else { this.enabled = true; m_MouseLook.SetCursorLock(true); m_MouseLook.UpdateCursorLock(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; using ALinq.Mapping; using ALinq.SqlClient; using FirebirdSql.Data.FirebirdClient; namespace ALinq.Firebird { public class FirebirdProvider : SqlProvider, IProvider, IProviderExtend { private string dbName; private string connectionString; private bool deleted; public FirebirdProvider() : base(ProviderMode.Firebird) { } void IProvider.CreateDatabase() { var connection = ((FbConnection)Connection); var builder = new FbConnectionStringBuilder(connection.ConnectionString); if (File.Exists(builder.Database)) throw SqlClient.Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(services.Model.DatabaseName); FbConnection.CreateDatabase(connection.ConnectionString); connection.Open(); var transaction = connection.BeginTransaction(); var sqlBuilder = FirebirdSqlBuilder.CreateInstance(this); try { if (services.Model.GetTables().Count() == 0) { throw SqlClient.Error.CreateDatabaseFailedBecauseOfContextWithNoTables(services.Model.DatabaseName); } var model = services.Model; //foreach (var table in model.GetTables()) //{ // string createTableCommand = sqlBuilder.GetCreateTableCommand(table); // if (!string.IsNullOrEmpty(createTableCommand)) // Execute(connection, transaction, createTableCommand); //} //Create Generator //foreach (var table in model.GetTables()) //{ // if (table.RowType.DBGeneratedIdentityMember != null) // { // var commandText = "CREATE SEQUENCE " + FirebirdSqlBuilder.GetSequenceName(table.RowType.DBGeneratedIdentityMember); // Execute(connection, transaction, commandText); // } //} //foreach (var table in model.GetTables()) //{ // var commandText = sqlBuilder.GetCreatePrimaryKeyCommand(table); // if (!string.IsNullOrEmpty(commandText)) // Execute(connection, transaction, commandText); //} foreach (var table in model.GetTables()) { var commands = sqlBuilder.GetCreateTableCommands(table); foreach (var command in commands) Execute(connection, transaction, command); } foreach (MetaTable table in model.GetTables()) foreach (string commandText in sqlBuilder.GetCreateForeignKeyCommands(table)) if (!string.IsNullOrEmpty(commandText)) Execute(connection, transaction, commandText); transaction.Commit(); } catch { transaction.Rollback(); throw; } finally { connection.Close(); } } public bool DatabaseExists() { var builder = new FbConnectionStringBuilder(Connection.ConnectionString); if (builder.ServerType == FbServerType.Embedded) { var fileName = builder.Database; return File.Exists(fileName); } var flag = false; try { conManager.UseConnection(this); conManager.Connection.ChangeDatabase(builder.Database); conManager.ReleaseConnection(this); flag = true; } catch (Exception) { } finally { if ((this.conManager.Connection.State == ConnectionState.Closed) && (string.Compare(this.conManager.Connection.ConnectionString, connectionString, StringComparison.Ordinal) != 0)) { //this.conManager.Connection.ConnectionString = connectionString; } } return flag; } public void DeleteDatabase() { if (!deleted) { //File.Delete(dbName); FbConnection.ClearAllPools(); FbConnection.DropDatabase(Connection.ConnectionString); deleted = true; } } private void Execute(IDbConnection connection, IDbTransaction transaction, string commandText) { if (Log != null) { Log.WriteLine(commandText); Log.WriteLine(); } IDbCommand command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = commandText; command.ExecuteNonQuery(); } void IProvider.Initialize(IDataServices dataServices, object connection) { if (dataServices == null) throw SqlClient.Error.ArgumentNull("dataServices"); IDbConnection connection2; if (connection is string) { var constr = ((string)connection); if (constr.EndsWith(".fdb", true, CultureInfo.CurrentCulture)) { var builder = new FbConnectionStringBuilder() { Database = constr, DataSource = "localhost", ServerType = FbServerType.Default, UserID = "SYSDBA", Password = "masterkey" }; connection2 = new FbConnection(builder.ToString()); } else connection2 = new FbConnection(constr); } else if (connection is IDbConnection) { connection2 = (IDbConnection)connection; } else throw SqlClient.Error.InvalidConnectionArgument("connection"); Initialize(dataServices, connection2); } internal override SqlIdentifier SqlIdentifier { [System.Diagnostics.DebuggerStepThrough] get { return FirebirdIdentifier.Instance; } } internal override DbFormatter CreateSqlFormatter() { return new FirebirdFormatter(this); } internal override ITypeSystemProvider CreateTypeSystemProvider() { return new FirebirdDataTypeProvider(); } //internal override void AssignParameters(System.Data.Common.DbCommand cmd, ReadOnlyCollection<SqlParameterInfo> parms, object[] userArguments, object lastResult) //{ // parms = new ReadOnlyCollection<SqlParameterInfo>(parms.Where(o => o.Parameter.Name != "NULL").ToArray()); // base.AssignParameters(cmd, parms, userArguments, lastResult); //} internal override ISqlParameterizer CreateSqlParameterizer(ITypeSystemProvider typeProvider, SqlNodeAnnotations annotations) { return new FirebirdParameterizer(typeProvider, annotations); } private FbPostBindDotNetConverter postBindDotNetConverter; internal override PostBindDotNetConverter PostBindDotNetConverter { get { if (postBindDotNetConverter == null) postBindDotNetConverter = new FbPostBindDotNetConverter(this.sqlFactory); return postBindDotNetConverter; //return FbPostBindDotNetConverter.Instance; } } internal override QueryConverter CreateQueryConverter(SqlFactory sql) { return new FirdbirdQueryConverter(services, typeProvider, translator, sql) { ConverterStrategy = ConverterStrategy.CanUseJoinOn }; } internal override void AssignParameters(System.Data.Common.DbCommand cmd, ReadOnlyCollection<SqlParameterInfo> parms, object[] userArguments, object lastResult) { if (cmd.CommandText.StartsWith("SELECT")) { var list = new List<SqlParameterInfo>(parms); var regex = new Regex(SqlIdentifier.ParameterPrefix + "[x][0-9]+"); cmd.CommandText = regex.Replace(cmd.CommandText, new MatchEvaluator(delegate(Match match) { var pName = match.Value; var parameter = parms.Where(o => o.Parameter.Name == pName).Single(); list.Remove(parameter); var value = parameter.Value; if (value == null) return "''"; if (value is DateTime) return "'" + ((DateTime)value).ToShortDateString() + "'"; else if (value is bool) { return ((bool)value) ? "1" : "0"; } else if (!(value.GetType().IsValueType)) return "'" + value + "'"; else return value.ToString(); })); if (list.Count != parms.Count) { base.AssignParameters(cmd, new ReadOnlyCollection<SqlParameterInfo>(list), userArguments, lastResult); return; } } base.AssignParameters(cmd, parms, userArguments, lastResult); } internal override SqlFactory CreateSqlFactory(ITypeSystemProvider typeProvider, MetaModel metaModel) { return new FirebirdSqlFactory(typeProvider, metaModel); } #region IProviderExtend Members void IProviderExtend.CreateTable(MetaTable metaTable) { //var metaTable = services.Model.GetTable(metaTable); //var sqlBuilder = new FirebirdSqlBuilder(this); //var command = sqlBuilder.GetCreateTableCommand(metaTable); //services.Context.ExecuteCommand(command); var sqlBuilder = new FirebirdSqlBuilder(this); var commands = sqlBuilder.GetCreateTableCommands(metaTable); foreach (var command in commands) { Debug.Assert(command != null); services.Context.ExecuteCommand(command); } } bool IProviderExtend.TableExists(MetaTable metaTable) { // var metaTable = services.Model.GetTable(metaTable); var sql = @"SELECT COUNT(*) FROM RDB$RELATIONS WHERE UPPER(RDB$RELATION_NAME) = {0}"; var count = services.Context.ExecuteQuery<int>(sql, metaTable.TableName.ToUpper()).Single(); return count > 0; } void IProviderExtend.DeleteTable(MetaTable metaTable) { //var metaTable = services.Model.GetTable(metaTable); //var sql = "DROP TABLE {0}"; //sql = string.Format(sql, metaTable.TableName); //services.Context.ExecuteCommand(sql); var commands = new FirebirdSqlBuilder(this).GetDropTableCommands(metaTable); foreach (var command in commands) { Debug.Assert(!string.IsNullOrEmpty(command)); services.Context.ExecuteCommand(command); } } void IProviderExtend.CreateForeignKeys(MetaTable metaTable) { //var metaTable = services.Model.GetTable(metaTable); var sqlBuilder = new FirebirdSqlBuilder(this); var commands = sqlBuilder.GetCreateForeignKeyCommands(metaTable); foreach (var command in commands) services.Context.ExecuteCommand(command); } #endregion } }
// 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.IO; using System.Text; using System.Collections.Generic; using System.Text.RegularExpressions; namespace WebsitePanel.Ecommerce.EnterpriseServer { /* Method template to create a new TLD match * WHOIS server response is read line-by-line so this template works almost for all types of response private static void Parse_REGISTRAR_ID_GOES_HERE(WhoisResult whoisResult, StringReader whoisResponse) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // advance to the next line sLine = whoisResponse.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (Regex.IsMatch(sLine, "RECORD NOT FOUND regex to match goes here...")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (Regex.IsMatch(sLine, @"DOMAIN NAME MATCH (for example - google.com) regex goes here...")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Copy nameservers if (sLine.Equals("DNS SERVERS match goes here...")) { // advance to the next line sLine = whoisResponse.ReadLine(); // while (nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = whoisResponse.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (throwError) throw new WhoisException(errorMessage.ToString()); } */ internal class WhoisParser { public const string UNKNOWN_FORMAT_FAILURE = "Couldn't find any formatters for the specified WHOIS server {0}."; public const string WHOIS_LIMIT_EXCEED_FAILURE = "You've exceeded WHOIS queries limit per minute. Please try later."; public const string WHOIS_EMPTY_QUERY_FAILURE = "WHOIS query may not be an empty string."; // regular expression for nameserver string private static readonly Regex nameServersRegex = new Regex(@"([a-zA-Z0-9\-\.]+\.[a-zA-Z0-9\-]+\.[a-zA-Z\-]+)"); static WhoisParser() { } public static WhoisResult Parse(string domain, string whoisServer, StringReader whoisResponse) { WhoisResult result = new WhoisResult(); result.Domain = domain; string whoisFormat = (string)WhoisSettings.Parsers[whoisServer]; switch (whoisFormat) { case WhoisSettings.UANIC: Parse_UANIC(result, whoisResponse); break; case WhoisSettings.INTERNIC: Parse_INTERNIC(result, whoisResponse); break; case WhoisSettings.AFFILIAS_LTD: case WhoisSettings.PIR: case WhoisSettings.mTLD: Parse_PIR(result, whoisResponse); break; case WhoisSettings.EDUCAUSE: Parse_EDUCAUSE(result, whoisResponse); break; case WhoisSettings.NOMINET: Parse_NOMINET(result, whoisResponse); break; case WhoisSettings.AUREGISTRY: Parse_AUREGISTRY(result, whoisResponse); break; case WhoisSettings.EURID: Parse_EURID(result, whoisResponse); break; case WhoisSettings.ROMANIAN: Parse_ROMANIAN(result, whoisResponse); break; case WhoisSettings.SWITCH: Parse_SWITCH(result, whoisResponse); break; case WhoisSettings.NEULEVEL: case WhoisSettings.NEUSTAR: Parse_NEUSTAR(result, whoisResponse); break; case WhoisSettings.SIDN: Parse_SIDN(result, whoisResponse); break; case WhoisSettings.AFNIC: Parse_AFNIC(result, whoisResponse); break; case WhoisSettings.TIERED_ACCESS: Parse_TIERED_ACCESS(result, whoisResponse); break; case WhoisSettings.INTERNET_NZ: Parse_INTERNET_NZ(result, whoisResponse); break; default: throw new Exception(String.Format(UNKNOWN_FORMAT_FAILURE, whoisServer)); } return result; } private static void Parse_UANIC(WhoisResult whoisResult, StringReader whoisResponse) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); // According to the research it seems // UA WHOIS servers do not throw any errors, so do we. while (sLine != null) { // advance to the next line sLine = whoisResponse.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record found if (Regex.IsMatch(sLine, @"domain\: .*ua")) { // response is ok whoisResult.RecordFound = true; continue; } // 2. Copy nameservers if (sLine.StartsWith("nserver")) { // while (sLine.StartsWith("nserver") && nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = whoisResponse.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); } } } private static void Parse_INTERNET_NZ(WhoisResult whoisResult, StringReader whoisResponse) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // advance to the next line sLine = whoisResponse.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record found if (Regex.IsMatch(sLine, @"domain_name\: .*nz")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 2. Match query status if (Regex.IsMatch(sLine, @"query_status\:")) { // Available if (sLine.Contains("220")) { whoisResult.RecordFound = false; return; // EXIT } // Active if (sLine.Contains("200")) continue; else throwError = true; } // 3. Copy nameservers if (sLine.StartsWith("ns_name_")) { // while (nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = whoisResponse.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_NUDOMAINLTD(WhoisResult whoisResult, StringReader whoisResponse) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // advance to the next line sLine = whoisResponse.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (Regex.IsMatch(sLine, "NO MATCH for domain \\\".*nu\\\" \\(ASCII\\)\\:")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (Regex.IsMatch(sLine, @"Domain Name \(ASCII\)\: .*nu")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Copy nameservers if (sLine.Equals("Domain servers in listed order:")) { // advance to the next line sLine = whoisResponse.ReadLine(); // while (nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = whoisResponse.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_TIERED_ACCESS(WhoisResult whoisResult, StringReader sr) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.Equals("No match.")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (Regex.IsMatch(sLine, "Not available for.*registration")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Copy nameservers if (sLine.StartsWith("Name Server:")) { while (nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_AFNIC(WhoisResult whoisResult, StringReader sr) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.Equals("%% No entries found in the AFNIC Database.")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (sLine.StartsWith("domain:")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Copy nameservers if (sLine.StartsWith("nserver:")) { while (nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_SIDN(WhoisResult whoisResult, StringReader sr) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.Equals(whoisResult.Domain + " is free")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (sLine.StartsWith("Domain name:")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Copy nameservers if (sLine.StartsWith("Domain nameservers:")) { // advance to the next line sLine = sr.ReadLine(); // while (nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_INTERNIC(WhoisResult whoisResult, StringReader sr) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.StartsWith("No match for ")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (sLine.StartsWith("Domain Name:")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Copy nameservers if (sLine.StartsWith("Name Server:")) { while (nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_PIR(WhoisResult whoisResult, StringReader sr) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.StartsWith("NOT FOUND")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (sLine.StartsWith("Domain Name:")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Copy nameservers if (sLine.StartsWith("Name Server:")) { while (sLine != null) { // exit when we finish with nameservers if (!sLine.StartsWith("Name Server:")) break; // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); if (nsMatch.Success) nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); return; } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_EDUCAUSE(WhoisResult whoisResult, StringReader sr) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool throwError = true; while (sLine != null) { // read line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.StartsWith("No Match")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Domain record found if (sLine.StartsWith("Domain Name:")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Found name servers records if (sLine.StartsWith("Name Servers:")) { // advance to the next line sLine = sr.ReadLine(); while (nameServersRegex.IsMatch(sLine)) { // lookup for ns match Match nsMatch = nameServersRegex.Match(sLine); // add name server record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy found ns records whoisResult.NameServers = nameServers.ToArray(); return; // EXIT } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if any if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_NOMINET(WhoisResult whoisResult, StringReader sr) { string sLine = ""; StringBuilder errorMessage = new StringBuilder(); List<string> nameServers = new List<string>(); bool throwError = true; // read while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.StartsWith("No match for")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Check record found if (sLine.StartsWith("Domain name:")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Record found lookup for nameservers if (sLine.StartsWith("Name servers:")) { // advance to the next line sLine = sr.ReadLine(); // loop for name servers records while (nameServersRegex.IsMatch(sLine)) { // lookup for match Match nsMatch = nameServersRegex.Match(sLine); // push nameserver to the list nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); return; // EXIT } // 4. Collect response lines errorMessage.AppendLine(sLine); } // throw an whois error if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_AUREGISTRY(WhoisResult whoisResult, StringReader sr) { string sLine = ""; StringBuilder errorMessage = new StringBuilder(); List<string> nameServers = new List<string>(); bool throwError = true; // read while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.StartsWith("No Data Found")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Check record found if (sLine.StartsWith("Domain Name:")) { // response is ok throwError = false; whoisResult.RecordFound = true; continue; } // 3. Record found lookup for nameservers if (sLine.StartsWith("Name Server:")) { // loop for name servers records while (sLine != null) { // lookup for match Match nsMatch = nameServersRegex.Match(sLine); // check lookup status and push nameserver to the list if (nsMatch.Success) nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); return; // EXIT } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw whois error if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_EURID(WhoisResult whoisResult, StringReader sr) { string sLine = ""; StringBuilder errorMessage = new StringBuilder(); List<string> nameServers = new List<string>(); bool throwError = true; // read while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Check record status if (sLine.StartsWith("Status:")) { // cleanup status sLine = sLine.Replace("Status:", "").Trim(); // 2. Record found switch (sLine) { case "AVAILABLE": whoisResult.RecordFound = false; return; case "REGISTERED": case "RESERVED": // response detected as success throwError = false; whoisResult.RecordFound = true; break; } } if (sLine.StartsWith("Registrant:")) { // cleanup status sLine = sr.ReadLine(); if (!String.IsNullOrEmpty(sLine)) { whoisResult.RecordFound = true; } } // 3. Record found lookup for nameservers if (sLine.StartsWith("Nameservers:")) { // advance to the next line sLine = sr.ReadLine(); // loop for name servers records while (nameServersRegex.IsMatch(sLine)) { // lookup for match Match nsMatch = nameServersRegex.Match(sLine); // push nameserver to the list nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); return; // EXIT } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw whois error if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_ROMANIAN(WhoisResult whoisResult, StringReader sr) { string sLine = ""; StringBuilder errorMessage = new StringBuilder(); List<string> nameServers = new List<string>(); bool throwError = true; // read while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Check record status if (sLine.StartsWith("% No entries found for the selected source(s).")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (sLine.StartsWith("domain-name:")) { // response detected as success throwError = false; whoisResult.RecordFound = true; continue; } // 3. Record found lookup for nameservers if (sLine.StartsWith("nameserver:")) { // loop for name servers records while (nameServersRegex.IsMatch(sLine)) { // lookup for match Match nsMatch = nameServersRegex.Match(sLine); // push nameserver to the list nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); return; // EXIT } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw whois error if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_SWITCH(WhoisResult whoisResult, StringReader sr) { string sLine = ""; StringBuilder errorMessage = new StringBuilder(); List<string> nameServers = new List<string>(); bool throwError = true; // read while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Check record status if (sLine.StartsWith("We do not have an entry in our database matching your query.")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (sLine.StartsWith("Domain name:")) { // response detected as success throwError = false; whoisResult.RecordFound = true; continue; } // 3. Record found lookup for nameservers if (sLine.StartsWith("Name servers:")) { // advance to the next line sLine = sr.ReadLine(); // loop for name servers records while (nameServersRegex.IsMatch(sLine)) { // lookup for match Match nsMatch = nameServersRegex.Match(sLine); // push nameserver to the list nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); return; // EXIT } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw whois error if (throwError) throw new WhoisException(errorMessage.ToString()); } private static void Parse_NEUSTAR(WhoisResult whoisResult, StringReader sr) { string sLine = ""; List<string> nameServers = new List<string>(); StringBuilder errorMessage = new StringBuilder(); bool raiseError = true; while (sLine != null) { // advance to the next line sLine = sr.ReadLine(); // skip empty lines if (String.IsNullOrEmpty(sLine)) continue; // trim whitespaces sLine = sLine.Trim(); // 1. Record not found if (sLine.StartsWith("Not found:")) { whoisResult.RecordFound = false; return; // EXIT } // 2. Record found if (sLine.StartsWith("Domain Name:")) { whoisResult.RecordFound = true; // response detected as success raiseError = false; continue; } // 3. Copy nameservers if (sLine.StartsWith("Name Server:")) { while (nameServersRegex.IsMatch(sLine)) { // lookup for nameserver match Match nsMatch = nameServersRegex.Match(sLine); // add ns record nameServers.Add(nsMatch.Value.ToLower()); // advance to the next line sLine = sr.ReadLine(); } // copy result whoisResult.NameServers = nameServers.ToArray(); return; // EXIT } // 4. Response contains errors errorMessage.AppendLine(sLine); } // throw an error if error message is not empty if (raiseError) throw new WhoisException(errorMessage.ToString()); } } }
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TQVaultAE.GUI { using Microsoft.Extensions.DependencyInjection; using System; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Security.Permissions; using System.Threading; using System.Windows.Forms; using TQVaultAE.Data; using TQVaultAE.Domain.Contracts.Providers; using TQVaultAE.Domain.Contracts.Services; using TQVaultAE.Domain.Entities; using TQVaultAE.Domain.Exceptions; using TQVaultAE.Logs; using TQVaultAE.Presentation; using TQVaultAE.Services; using TQVaultAE.Services.Win32; using Microsoft.Extensions.Logging; /// <summary> /// Main Program class /// </summary> public static class Program { private static ILogger Log; /// <summary> /// Right to left reading options for message boxes /// </summary> private static MessageBoxOptions rightToLeft; internal static ServiceProvider ServiceProvider { get; private set; } private static ILoggerFactory LoggerFactory; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)] public static void Main() { try { // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += new ThreadExceptionEventHandler(MainForm_UIThreadException); // Set the unhandled exception mode to force all Windows Forms errors to go through our handler. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // Add the event handler for handling non-UI thread exceptions to the event. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); #if DEBUG //TQDebug.DebugEnabled = true; #endif // Setup regular Microsoft.Extensions.Logging abstraction manualy LoggerFactory = new LoggerFactory(); LoggerFactory.AddLog4Net(); Log = LoggerFactory.CreateLogger(typeof(Program));// Make static level logger restart: // Configure DI var scol = new ServiceCollection() // Logs .AddSingleton(LoggerFactory) .AddSingleton(typeof(ILogger<>), typeof(Logger<>)) // States .AddSingleton<SessionContext>() // Providers .AddTransient<IRecordInfoProvider, RecordInfoProvider>() .AddTransient<IArcFileProvider, ArcFileProvider>() .AddTransient<IArzFileProvider, ArzFileProvider>() .AddSingleton<IDatabase, Database>() .AddSingleton<IItemProvider, ItemProvider>() .AddTransient<ILootTableCollectionProvider, LootTableCollectionProvider>() .AddTransient<IStashProvider, StashProvider>() .AddTransient<IPlayerCollectionProvider, PlayerCollectionProvider>() .AddTransient<ISackCollectionProvider, SackCollectionProvider>() .AddSingleton<IItemAttributeProvider, ItemAttributeProvider>() .AddTransient<IDBRecordCollectionProvider, DBRecordCollectionProvider>() // Services .AddTransient<IAddFontToOS, AddFontToOSWin>() .AddSingleton<IGamePathService, GamePathServiceWin>() .AddTransient<IPlayerService, PlayerService>() .AddTransient<IStashService, StashService>() .AddTransient<IVaultService, VaultService>() .AddTransient<IFontService, FontService>() .AddTransient<ITranslationService, TranslationService>() .AddSingleton<IUIService, UIService>() .AddSingleton<ITQDataService, TQDataService>() .AddTransient<IBitmapService, BitmapService>() // Forms .AddSingleton<MainForm>() .AddTransient<AboutBox>() .AddTransient<CharacterEditDialog>() .AddTransient<ItemProperties>() .AddTransient<ItemSeedDialog>() .AddTransient<ResultsDialog>() .AddTransient<SearchDialogAdvanced>() .AddTransient<SettingsDialog>() .AddTransient<VaultMaintenanceDialog>() .AddTransient<SplashScreenForm>(); Program.ServiceProvider = scol.BuildServiceProvider(); var gamePathResolver = Program.ServiceProvider.GetService<IGamePathService>(); try { ManageCulture(); SetUILanguage(); SetupGamePaths(gamePathResolver); SetupMapName(gamePathResolver); } catch (ExGamePathNotFound ex) { using (var fbd = new FolderBrowserDialog() { Description = ex.Message, ShowNewFolderButton = false }) { DialogResult result = fbd.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { Config.Settings.Default.ForceGamePath = fbd.SelectedPath; Config.Settings.Default.Save(); goto restart; } else goto exit; } } var mainform = Program.ServiceProvider.GetService<MainForm>(); Application.Run(mainform); } catch (Exception ex) { Log.ErrorException(ex); MessageBox.Show(Log.FormatException(ex), Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); } exit:; } #region Init /// <summary> /// Reads the paths from the config files and sets them. /// </summary> private static void SetupGamePaths(IGamePathService gamePathResolver) { if (Config.Settings.Default.AutoDetectGamePath) { gamePathResolver.TQPath = gamePathResolver.ResolveGamePath(); gamePathResolver.ImmortalThronePath = gamePathResolver.ResolveGamePath(); } else { gamePathResolver.TQPath = Config.Settings.Default.TQPath; gamePathResolver.ImmortalThronePath = Config.Settings.Default.TQITPath; } Log.LogInformation("Selected TQ path {0}", gamePathResolver.TQPath); Log.LogInformation("Selected TQIT path {0}", gamePathResolver.ImmortalThronePath); // Show a message that the default path is going to be used. if (string.IsNullOrEmpty(Config.Settings.Default.VaultPath)) { string folderPath = Path.Combine(gamePathResolver.TQSaveFolder, "TQVaultData"); // Check to see if we are still using a shortcut to specify the vault path and display a message // to use the configuration UI if we are. if (!Directory.Exists(folderPath) && File.Exists(Path.ChangeExtension(folderPath, ".lnk"))) { MessageBox.Show(Resources.DataLinkMsg, Resources.DataLink, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, VaultForm.RightToLeftOptions); } else { MessageBox.Show(Resources.DataDefaultPathMsg, Resources.DataDefaultPath, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, VaultForm.RightToLeftOptions); } } gamePathResolver.TQVaultSaveFolder = Config.Settings.Default.VaultPath; } /// <summary> /// Attempts to read the language from the config file and set the Current Thread's Culture and UICulture. /// Defaults to the OS UI Culture. /// </summary> private static void SetUILanguage() { string settingsCulture = null; if (!string.IsNullOrEmpty(Config.Settings.Default.UILanguage)) { settingsCulture = Config.Settings.Default.UILanguage; } else if (!Config.Settings.Default.AutoDetectLanguage) { settingsCulture = Config.Settings.Default.TQLanguage; } if (!string.IsNullOrEmpty(settingsCulture)) { string myCulture = null; foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) { if (ci.EnglishName.Equals(settingsCulture, StringComparison.InvariantCultureIgnoreCase)) { myCulture = ci.TextInfo.CultureName; break; } } // We found something so we will use it. if (!string.IsNullOrEmpty(myCulture)) { try { // Sets the culture Thread.CurrentThread.CurrentCulture = new CultureInfo(myCulture); // Sets the UI culture Thread.CurrentThread.CurrentUICulture = new CultureInfo(myCulture); } catch (ArgumentNullException e) { Log.LogError(e, "Argument Null Exception when setting the language"); } catch (NotSupportedException e) { Log.LogError(e, "Not Supported Exception when setting the language"); } } // If not then we just default to the OS UI culture. } } /// <summary> /// Sets the name of the game map if a custom map is set in the config file. /// Defaults to Main otherwise. /// </summary> private static void SetupMapName(IGamePathService gamePathResolver) { // Set the map name. Command line argument can override this setting in LoadResources(). string mapName = "main"; if (Config.Settings.Default.ModEnabled) mapName = Config.Settings.Default.CustomMap; gamePathResolver.MapName = mapName; } #endregion private static void ManageCulture() { if (CultureInfo.CurrentCulture.IsNeutralCulture) { // Neutral cultures are not supported. Fallback to application's default. String assemblyCultureName = ((NeutralResourcesLanguageAttribute)Attribute.GetCustomAttribute( Assembly.GetExecutingAssembly(), typeof(NeutralResourcesLanguageAttribute), false)) .CultureName; Thread.CurrentThread.CurrentCulture = new CultureInfo(assemblyCultureName, true); } // Set options for Right to Left reading. rightToLeft = (MessageBoxOptions)0; if (CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft) { rightToLeft = MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading; } } /// <summary> /// Handle the UI exceptions by showing a dialog box, and asking the user whether or not they wish to abort execution. /// </summary> /// <param name="sender">sender object</param> /// <param name="t">ThreadExceptionEventArgs data</param> private static void MainForm_UIThreadException(object sender, ThreadExceptionEventArgs t) { DialogResult result = DialogResult.Cancel; try { Log.LogError(t.Exception, "UI Thread Exception"); result = MessageBox.Show(Log.FormatException(t.Exception), "Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1, rightToLeft); } catch { try { Log.LogCritical(t.Exception, "Fatal Windows Forms Error"); MessageBox.Show(Log.FormatException(t.Exception), "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1, rightToLeft); } finally { Application.Exit(); } } // Exits the program when the user clicks Abort. if (result == DialogResult.Abort) { Application.Exit(); } } /// <summary> /// Handle the UI exceptions by showing a dialog box, and asking the user whether or not they wish to abort execution. /// </summary> /// <remarks>NOTE: This exception cannot be kept from terminating the application - it can only log the event, and inform the user about it.</remarks> /// <param name="sender">sender object</param> /// <param name="e">UnhandledExceptionEventArgs data</param> private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { Exception ex = (Exception)e.ExceptionObject; Log.LogError(ex, "An application error occurred."); } finally { Application.Exit(); } } } }
namespace System.Workflow.ComponentModel.Serialization { using System; using System.IO; using System.CodeDom; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Collections; using System.Xml; using System.Xml.Serialization; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Globalization; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Design; using System.Runtime.Serialization; using System.Security.Permissions; using System.Collections.ObjectModel; using System.Drawing; #region Mapping Support #region Mapping internal sealed class WorkflowMarkupSerializerMapping { private static readonly Dictionary<string, Type> wellKnownTypes; private static readonly List<WorkflowMarkupSerializerMapping> wellKnownMappings; private static readonly WorkflowMarkupSerializerMapping Activities; private static readonly WorkflowMarkupSerializerMapping ComponentModel; private static readonly WorkflowMarkupSerializerMapping Serialization; private static readonly WorkflowMarkupSerializerMapping Rules; private static readonly WorkflowMarkupSerializerMapping ComponentModelDesign; private string xmlns = String.Empty; private string clrns = String.Empty; private string targetAssemblyName = String.Empty; private string prefix = String.Empty; private string unifiedAssemblyName = String.Empty; static WorkflowMarkupSerializerMapping() { WorkflowMarkupSerializerMapping.wellKnownTypes = new Dictionary<string, Type>(); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(ThrowActivity).Name, typeof(ThrowActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(ThrowDesigner).Name, typeof(ThrowDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(SuspendActivity).Name, typeof(SuspendActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(SuspendDesigner).Name, typeof(SuspendDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(CancellationHandlerActivity).Name, typeof(CancellationHandlerActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(CancellationHandlerActivityDesigner).Name, typeof(CancellationHandlerActivityDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(CompensateActivity).Name, typeof(CompensateActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(CompensateDesigner).Name, typeof(CompensateDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(CompensationHandlerActivity).Name, typeof(CompensationHandlerActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(CompensationHandlerActivityDesigner).Name, typeof(CompensationHandlerActivityDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(FaultHandlerActivity).Name, typeof(FaultHandlerActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(FaultHandlerActivityDesigner).Name, typeof(FaultHandlerActivityDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(FaultHandlersActivity).Name, typeof(FaultHandlersActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(FaultHandlersActivityDesigner).Name, typeof(FaultHandlersActivityDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(SynchronizationScopeActivity).Name, typeof(SynchronizationScopeActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(SequenceDesigner).Name, typeof(SequenceDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(TransactionScopeActivity).Name, typeof(TransactionScopeActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(TransactionScopeActivityDesigner).Name, typeof(TransactionScopeActivityDesigner)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(PropertySegment).Name, typeof(PropertySegment)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(CompensatableTransactionScopeActivity).Name, typeof(CompensatableTransactionScopeActivity)); WorkflowMarkupSerializerMapping.wellKnownTypes.Add(typeof(ActivityDesigner).Name, typeof(ActivityDesigner)); //I am hard coding the well known mappings here instead of going through the assemblies as we want the mappings to be in //a specific order for performance optimization when searching for type WorkflowMarkupSerializerMapping.wellKnownMappings = new List<WorkflowMarkupSerializerMapping>(); WorkflowMarkupSerializerMapping.Activities = new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.Activities", AssemblyRef.ActivitiesAssemblyRef); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(WorkflowMarkupSerializerMapping.Activities); WorkflowMarkupSerializerMapping.ComponentModel = new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.ComponentModel", Assembly.GetExecutingAssembly().FullName); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(WorkflowMarkupSerializerMapping.ComponentModel); WorkflowMarkupSerializerMapping.Serialization = new WorkflowMarkupSerializerMapping(StandardXomlKeys.Definitions_XmlNs_Prefix, StandardXomlKeys.Definitions_XmlNs, "System.Workflow.ComponentModel.Serialization", Assembly.GetExecutingAssembly().FullName); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(WorkflowMarkupSerializerMapping.Serialization); WorkflowMarkupSerializerMapping.Rules = new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.Activities.Rules", AssemblyRef.ActivitiesAssemblyRef); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(WorkflowMarkupSerializerMapping.Rules); WorkflowMarkupSerializerMapping.ComponentModelDesign = new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.ComponentModel.Design", Assembly.GetExecutingAssembly().FullName); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(WorkflowMarkupSerializerMapping.ComponentModelDesign); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.Runtime", AssemblyRef.RuntimeAssemblyRef)); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.ComponentModel.Compiler", Assembly.GetExecutingAssembly().FullName)); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.Activities.Rules.Design", AssemblyRef.ActivitiesAssemblyRef)); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.Runtime.Configuration", AssemblyRef.RuntimeAssemblyRef)); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.Runtime.Hosting", AssemblyRef.RuntimeAssemblyRef)); WorkflowMarkupSerializerMapping.wellKnownMappings.Add(new WorkflowMarkupSerializerMapping(StandardXomlKeys.WorkflowPrefix, StandardXomlKeys.WorkflowXmlNs, "System.Workflow.Runtime.Tracking", AssemblyRef.RuntimeAssemblyRef)); } public WorkflowMarkupSerializerMapping(string prefix, string xmlNamespace, string clrNamespace, string assemblyName) { if (prefix == null) throw new ArgumentNullException("prefix"); if (xmlNamespace == null) throw new ArgumentNullException("xmlNamespace"); if (clrNamespace == null) throw new ArgumentNullException("clrNamespace"); if (assemblyName == null) throw new ArgumentNullException("assemblyName"); this.prefix = prefix; this.xmlns = xmlNamespace; this.clrns = clrNamespace; this.targetAssemblyName = assemblyName; this.unifiedAssemblyName = assemblyName; } public WorkflowMarkupSerializerMapping(string prefix, string xmlNamespace, string clrNamespace, string targetAssemblyName, string unifiedAssemblyName) { if (prefix == null) throw new ArgumentNullException("prefix"); if (xmlNamespace == null) throw new ArgumentNullException("xmlNamespace"); if (clrNamespace == null) throw new ArgumentNullException("clrNamespace"); if (targetAssemblyName == null) throw new ArgumentNullException("targetAssemblyName"); if (unifiedAssemblyName == null) throw new ArgumentNullException("unifiedAssemblyName"); this.prefix = prefix; this.xmlns = xmlNamespace; this.clrns = clrNamespace; this.targetAssemblyName = targetAssemblyName; this.unifiedAssemblyName = unifiedAssemblyName; } public override bool Equals(object value) { WorkflowMarkupSerializerMapping mapping = value as WorkflowMarkupSerializerMapping; if (mapping == null) { return false; } // // This class is intended to make MT scenarios easier by holding both the target and the unified (current) // assembly names. They both represent the same type in this container and thus the both need to match to be equal. // This makes it easier to make this classes default (static constructor) work better with MT in the rest of the codebase. if (this.clrns == mapping.clrns && this.targetAssemblyName == mapping.targetAssemblyName && this.unifiedAssemblyName == mapping.unifiedAssemblyName) { return true; } return false; } public override int GetHashCode() { return (ClrNamespace.GetHashCode() ^ this.unifiedAssemblyName.GetHashCode()); } public string ClrNamespace { get { return this.clrns; } } public string XmlNamespace { get { return this.xmlns; } } public string AssemblyName { get { return this.targetAssemblyName; } } public string Prefix { get { return this.prefix; } } #region Namespace Helpers internal static IList<WorkflowMarkupSerializerMapping> WellKnownMappings { get { return WorkflowMarkupSerializerMapping.wellKnownMappings; } } internal static Type ResolveWellKnownTypes(WorkflowMarkupSerializationManager manager, string xmlns, string typeName) { Type resolvedType = null; List<WorkflowMarkupSerializerMapping> knownMappings = new List<WorkflowMarkupSerializerMapping>(); if (xmlns.Equals(StandardXomlKeys.WorkflowXmlNs, StringComparison.Ordinal)) { if (!WorkflowMarkupSerializerMapping.wellKnownTypes.TryGetValue(typeName, out resolvedType)) { if (typeName.EndsWith("Activity", StringComparison.OrdinalIgnoreCase)) { knownMappings.Add(WorkflowMarkupSerializerMapping.Activities); knownMappings.Add(WorkflowMarkupSerializerMapping.ComponentModel); } if (typeName.EndsWith("Designer", StringComparison.OrdinalIgnoreCase)) { knownMappings.Add(WorkflowMarkupSerializerMapping.Activities); knownMappings.Add(WorkflowMarkupSerializerMapping.ComponentModel); knownMappings.Add(WorkflowMarkupSerializerMapping.ComponentModelDesign); } else if (typeName.EndsWith("Theme", StringComparison.OrdinalIgnoreCase)) { knownMappings.Add(WorkflowMarkupSerializerMapping.ComponentModelDesign); knownMappings.Add(WorkflowMarkupSerializerMapping.Activities); } else if (typeName.StartsWith("Rule", StringComparison.OrdinalIgnoreCase) || typeName.EndsWith("Action", StringComparison.OrdinalIgnoreCase)) { knownMappings.Add(WorkflowMarkupSerializerMapping.Rules); } } } else if (xmlns.Equals(StandardXomlKeys.Definitions_XmlNs, StringComparison.Ordinal)) { knownMappings.Add(WorkflowMarkupSerializerMapping.Serialization); } if (resolvedType == null) { foreach (WorkflowMarkupSerializerMapping mapping in knownMappings) { string fullyQualifiedTypeName = mapping.ClrNamespace + "." + typeName + ", " + mapping.AssemblyName; resolvedType = manager.GetType(fullyQualifiedTypeName); if (resolvedType != null) break; } } return resolvedType; } internal static void GetMappingsFromXmlNamespace(WorkflowMarkupSerializationManager serializationManager, string xmlNamespace, out IList<WorkflowMarkupSerializerMapping> matchingMappings, out IList<WorkflowMarkupSerializerMapping> collectedMappings) { matchingMappings = new List<WorkflowMarkupSerializerMapping>(); collectedMappings = new List<WorkflowMarkupSerializerMapping>(); XmlReader reader = serializationManager.WorkflowMarkupStack[typeof(XmlReader)] as XmlReader; if (reader != null) { if (xmlNamespace.StartsWith(StandardXomlKeys.CLRNamespaceQualifier, StringComparison.OrdinalIgnoreCase)) { //Format for the xmlnamespace: clr-namespace:[Namespace][;Assembly=[AssemblyName]] bool invalidXmlnsFormat = false; string clrNamespace = xmlNamespace.Substring(StandardXomlKeys.CLRNamespaceQualifier.Length).Trim(); string assemblyName = String.Empty; int index = clrNamespace.IndexOf(';'); if (index != -1) { assemblyName = (index + 1 < clrNamespace.Length) ? clrNamespace.Substring(index + 1).Trim() : String.Empty; clrNamespace = clrNamespace.Substring(0, index).Trim(); if (!assemblyName.StartsWith(StandardXomlKeys.AssemblyNameQualifier, StringComparison.OrdinalIgnoreCase)) invalidXmlnsFormat = true; assemblyName = assemblyName.Substring(StandardXomlKeys.AssemblyNameQualifier.Length); } if (!invalidXmlnsFormat) { if (clrNamespace.Equals(StandardXomlKeys.GlobalNamespace, StringComparison.OrdinalIgnoreCase)) clrNamespace = String.Empty; matchingMappings.Add(new WorkflowMarkupSerializerMapping(reader.Prefix, xmlNamespace, clrNamespace, assemblyName)); } } else { List<Assembly> referencedAssemblies = new List<Assembly>(); if (serializationManager.LocalAssembly != null) referencedAssemblies.Add(serializationManager.LocalAssembly); ITypeProvider typeProvider = serializationManager.GetService(typeof(ITypeProvider)) as ITypeProvider; if (typeProvider != null) referencedAssemblies.AddRange(typeProvider.ReferencedAssemblies); foreach (Assembly assembly in referencedAssemblies) { object[] xmlnsDefinitions = assembly.GetCustomAttributes(typeof(XmlnsDefinitionAttribute), true); if (xmlnsDefinitions != null) { foreach (XmlnsDefinitionAttribute xmlnsDefinition in xmlnsDefinitions) { string assemblyName = String.Empty; if (serializationManager.LocalAssembly != assembly) { if (xmlnsDefinition.AssemblyName != null && xmlnsDefinition.AssemblyName.Trim().Length > 0) assemblyName = xmlnsDefinition.AssemblyName; else assemblyName = assembly.FullName; } if (xmlnsDefinition.XmlNamespace.Equals(xmlNamespace, StringComparison.Ordinal)) matchingMappings.Add(new WorkflowMarkupSerializerMapping(reader.Prefix, xmlNamespace, xmlnsDefinition.ClrNamespace, assemblyName)); else collectedMappings.Add(new WorkflowMarkupSerializerMapping(reader.Prefix, xmlNamespace, xmlnsDefinition.ClrNamespace, assemblyName)); } } } } } } internal static void GetMappingFromType(WorkflowMarkupSerializationManager manager, Type type, out WorkflowMarkupSerializerMapping matchingMapping, out IList<WorkflowMarkupSerializerMapping> collectedMappings) { matchingMapping = null; collectedMappings = new List<WorkflowMarkupSerializerMapping>(); string clrNamespace = (type.Namespace != null) ? type.Namespace : String.Empty; string xmlNamespace = String.Empty; string assemblyName = String.Empty; string prefix = String.Empty; assemblyName = GetAssemblyName(type, manager); if (type.Assembly.FullName.Equals(AssemblyRef.RuntimeAssemblyRef, StringComparison.Ordinal)) { xmlNamespace = StandardXomlKeys.WorkflowXmlNs; prefix = StandardXomlKeys.WorkflowPrefix; } if (type.Assembly.FullName.Equals(AssemblyRef.ActivitiesAssemblyRef, StringComparison.Ordinal)) { xmlNamespace = StandardXomlKeys.WorkflowXmlNs; prefix = StandardXomlKeys.WorkflowPrefix; } else if (type.Assembly == Assembly.GetExecutingAssembly()) { xmlNamespace = StandardXomlKeys.WorkflowXmlNs; prefix = StandardXomlKeys.WorkflowPrefix; } if (xmlNamespace.Length == 0) { //First lookup the type's assembly for XmlNsDefinitionAttribute object[] xmlnsDefinitions = type.Assembly.GetCustomAttributes(typeof(XmlnsDefinitionAttribute), true); foreach (XmlnsDefinitionAttribute xmlnsDefinition in xmlnsDefinitions) { xmlNamespace = xmlnsDefinition.XmlNamespace; assemblyName = xmlnsDefinition.AssemblyName; if (type.Assembly == manager.LocalAssembly) assemblyName = String.Empty; else if (String.IsNullOrEmpty(assemblyName)) assemblyName = GetAssemblyName(type, manager); if (String.IsNullOrEmpty(xmlNamespace)) xmlNamespace = GetFormatedXmlNamespace(clrNamespace, assemblyName); prefix = GetPrefix(manager, type.Assembly, xmlNamespace); WorkflowMarkupSerializerMapping mapping = new WorkflowMarkupSerializerMapping(prefix, xmlNamespace, clrNamespace, assemblyName, type.Assembly.FullName); if (xmlnsDefinition.ClrNamespace.Equals(clrNamespace, StringComparison.Ordinal) && matchingMapping == null) matchingMapping = mapping; else collectedMappings.Add(mapping); } } if (matchingMapping == null) { if (type.Assembly == manager.LocalAssembly) assemblyName = String.Empty; else if (String.IsNullOrEmpty(assemblyName)) assemblyName = GetAssemblyName(type, manager); xmlNamespace = GetFormatedXmlNamespace(clrNamespace, assemblyName); if (String.IsNullOrEmpty(prefix)) prefix = GetPrefix(manager, type.Assembly, xmlNamespace); matchingMapping = new WorkflowMarkupSerializerMapping(prefix, xmlNamespace, clrNamespace, assemblyName, type.Assembly.FullName); } } private static string GetAssemblyName(Type type, WorkflowMarkupSerializationManager manager) { TypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as TypeProvider; if (typeProvider != null) { return typeProvider.GetAssemblyName(type); } // // Handle DesignTimeType if (type.Assembly == null) { return string.Empty; } else { return type.Assembly.FullName; } } //Format for the xmlnamespace: clr-namespace:[Namespace][;Assembly=[AssemblyName]] private static string GetFormatedXmlNamespace(string clrNamespace, string assemblyName) { string xmlNamespace = StandardXomlKeys.CLRNamespaceQualifier; xmlNamespace += (String.IsNullOrEmpty(clrNamespace)) ? StandardXomlKeys.GlobalNamespace : clrNamespace; if (!String.IsNullOrEmpty(assemblyName)) xmlNamespace += ";" + StandardXomlKeys.AssemblyNameQualifier + assemblyName; return xmlNamespace; } private static string GetPrefix(WorkflowMarkupSerializationManager manager, Assembly assembly, string xmlNamespace) { string prefix = String.Empty; object[] xmlnsPrefixes = assembly.GetCustomAttributes(typeof(XmlnsPrefixAttribute), true); if (xmlnsPrefixes != null) { foreach (XmlnsPrefixAttribute xmlnsPrefix in xmlnsPrefixes) { if (xmlnsPrefix.XmlNamespace.Equals(xmlNamespace, StringComparison.Ordinal)) { prefix = xmlnsPrefix.Prefix; break; } } } if (String.IsNullOrEmpty(prefix) || !IsNamespacePrefixUnique(prefix, manager.PrefixBasedMappings.Keys)) { string basePrefix = (String.IsNullOrEmpty(prefix)) ? "ns" : prefix; int index = 0; prefix = basePrefix + string.Format(CultureInfo.InvariantCulture, "{0}", index++); while (!IsNamespacePrefixUnique(prefix, manager.PrefixBasedMappings.Keys)) prefix = basePrefix + string.Format(CultureInfo.InvariantCulture, "{0}", index++); } return prefix; } private static bool IsNamespacePrefixUnique(string prefix, ICollection existingPrefixes) { bool isUnique = true; foreach (string existingPrefix in existingPrefixes) { if (existingPrefix.Equals(prefix, StringComparison.Ordinal)) { isUnique = false; break; } } return isUnique; } #endregion } #endregion #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Threading; using SocketHttpListener.Net; using SocketHttpListener.Net.WebSockets; namespace SocketHttpListener { /// <summary> /// Implements the WebSocket interface. /// </summary> /// <remarks> /// The WebSocket class provides a set of methods and properties for two-way communication using /// the WebSocket protocol (<see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>). /// </remarks> public class WebSocket : IDisposable { #region Private Fields private string _base64Key; private RemoteCertificateValidationCallback _certValidationCallback; private Action _closeContext; private CompressionMethod _compression; private WebSocketContext _context; private CookieCollection _cookies; private NetworkCredential _credentials; private string _extensions; private AutoResetEvent _exitReceiving; private object _forConn; private object _forEvent; private object _forMessageEventQueue; private object _forSend; private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private Func<WebSocketContext, string> _handshakeRequestChecker; private Queue<MessageEventArgs> _messageEventQueue; private uint _nonceCount; private string _origin; private bool _preAuth; private string _protocol; private string[] _protocols; private NetworkCredential _proxyCredentials; private Uri _proxyUri; private volatile WebSocketState _readyState; private AutoResetEvent _receivePong; private bool _secure; private Stream _stream; private TcpClient _tcpClient; private Uri _uri; private const string _version = "13"; #endregion #region Internal Fields internal const int FragmentLength = 1016; // Max value is int.MaxValue - 14. #endregion #region Internal Constructors // As server internal WebSocket(HttpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _secure = context.IsSecureConnection; _stream = context.Stream; init(); } #endregion // As server internal Func<WebSocketContext, string> CustomHandshakeRequestChecker { get { return _handshakeRequestChecker ?? (context => null); } set { _handshakeRequestChecker = value; } } internal bool IsConnected { get { return _readyState == WebSocketState.Open || _readyState == WebSocketState.Closing; } } /// <summary> /// Gets the state of the WebSocket connection. /// </summary> /// <value> /// One of the <see cref="WebSocketState"/> enum values, indicates the state of the WebSocket /// connection. The default value is <see cref="WebSocketState.Connecting"/>. /// </value> public WebSocketState ReadyState { get { return _readyState; } } #region Public Events /// <summary> /// Occurs when the WebSocket connection has been closed. /// </summary> public event EventHandler<CloseEventArgs> OnClose; /// <summary> /// Occurs when the <see cref="WebSocket"/> gets an error. /// </summary> public event EventHandler<ErrorEventArgs> OnError; /// <summary> /// Occurs when the <see cref="WebSocket"/> receives a message. /// </summary> public event EventHandler<MessageEventArgs> OnMessage; /// <summary> /// Occurs when the WebSocket connection has been established. /// </summary> public event EventHandler OnOpen; #endregion #region Private Methods // As server private bool acceptHandshake() { var msg = checkIfValidHandshakeRequest(_context); if (msg != null) { error("An error has occurred while connecting: " + msg); Close(HttpStatusCode.BadRequest); return false; } if (_protocol != null && !_context.SecWebSocketProtocols.Contains(protocol => protocol == _protocol)) _protocol = null; var extensions = _context.Headers["Sec-WebSocket-Extensions"]; if (extensions != null && extensions.Length > 0) processSecWebSocketExtensionsHeader(extensions); return sendHttpResponse(createHandshakeResponse()); } // As server private string checkIfValidHandshakeRequest(WebSocketContext context) { var headers = context.Headers; return context.RequestUri == null ? "Invalid request url." : !context.IsWebSocketRequest ? "Not WebSocket connection request." : !validateSecWebSocketKeyHeader(headers["Sec-WebSocket-Key"]) ? "Invalid Sec-WebSocket-Key header." : !validateSecWebSocketVersionClientHeader(headers["Sec-WebSocket-Version"]) ? "Invalid Sec-WebSocket-Version header." : CustomHandshakeRequestChecker(context); } private void close(CloseStatusCode code, string reason, bool wait) { close(new PayloadData(((ushort)code).Append(reason)), !code.IsReserved(), wait); } private void close(PayloadData payload, bool send, bool wait) { lock (_forConn) { if (_readyState == WebSocketState.Closing || _readyState == WebSocketState.Closed) { return; } _readyState = WebSocketState.Closing; } var e = new CloseEventArgs(payload); e.WasClean = closeHandshake( send ? WebSocketFrame.CreateCloseFrame(Mask.Unmask, payload).ToByteArray() : null, wait ? 1000 : 0, closeServerResources); _readyState = WebSocketState.Closed; try { OnClose.Emit(this, e); } catch (Exception ex) { error("An exception has occurred while OnClose.", ex); } } private bool closeHandshake(byte[] frameAsBytes, int millisecondsTimeout, Action release) { var sent = frameAsBytes != null && writeBytes(frameAsBytes); var received = millisecondsTimeout == 0 || (sent && _exitReceiving != null && _exitReceiving.WaitOne(millisecondsTimeout)); release(); if (_receivePong != null) { _receivePong.Close(); _receivePong = null; } if (_exitReceiving != null) { _exitReceiving.Close(); _exitReceiving = null; } var result = sent && received; return result; } // As server private void closeServerResources() { if (_closeContext == null) return; _closeContext(); _closeContext = null; _stream = null; _context = null; } private bool concatenateFragmentsInto(Stream dest) { while (true) { var frame = WebSocketFrame.Read(_stream, true); if (frame.IsFinal) { /* FINAL */ // CONT if (frame.IsContinuation) { dest.WriteBytes(frame.PayloadData.ApplicationData); break; } // PING if (frame.IsPing) { processPingFrame(frame); continue; } // PONG if (frame.IsPong) { processPongFrame(frame); continue; } // CLOSE if (frame.IsClose) return processCloseFrame(frame); } else { /* MORE */ // CONT if (frame.IsContinuation) { dest.WriteBytes(frame.PayloadData.ApplicationData); continue; } } // ? return processUnsupportedFrame( frame, CloseStatusCode.IncorrectData, "An incorrect data has been received while receiving fragmented data."); } return true; } // As server private HttpResponse createHandshakeCloseResponse(HttpStatusCode code) { var res = HttpResponse.CreateCloseResponse(code); res.Headers["Sec-WebSocket-Version"] = _version; return res; } // As server private HttpResponse createHandshakeResponse() { var res = HttpResponse.CreateWebSocketResponse(); var headers = res.Headers; headers["Sec-WebSocket-Accept"] = CreateResponseKey(_base64Key); if (_protocol != null) headers["Sec-WebSocket-Protocol"] = _protocol; if (_extensions != null) headers["Sec-WebSocket-Extensions"] = _extensions; if (_cookies.Count > 0) res.SetCookies(_cookies); return res; } private MessageEventArgs dequeueFromMessageEventQueue() { lock (_forMessageEventQueue) return _messageEventQueue.Count > 0 ? _messageEventQueue.Dequeue() : null; } private void enqueueToMessageEventQueue(MessageEventArgs e) { lock (_forMessageEventQueue) _messageEventQueue.Enqueue(e); } private void error(string message, Exception exception) { try { if (exception != null) { message += ". Exception.Message: " + exception.Message; } OnError.Emit(this, new ErrorEventArgs(message)); } catch (Exception ex) { } } private void error(string message) { try { OnError.Emit(this, new ErrorEventArgs(message)); } catch (Exception ex) { } } private void init() { _compression = CompressionMethod.None; _cookies = new CookieCollection(); _forConn = new object(); _forEvent = new object(); _forSend = new object(); _messageEventQueue = new Queue<MessageEventArgs>(); _forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot; _readyState = WebSocketState.Connecting; } private void open() { try { startReceiving(); lock (_forEvent) { try { OnOpen.Emit(this, EventArgs.Empty); } catch (Exception ex) { processException(ex, "An exception has occurred while OnOpen."); } } } catch (Exception ex) { processException(ex, "An exception has occurred while opening."); } } private bool processCloseFrame(WebSocketFrame frame) { var payload = frame.PayloadData; close(payload, !payload.ContainsReservedCloseStatusCode, false); return false; } private bool processDataFrame(WebSocketFrame frame) { var e = frame.IsCompressed ? new MessageEventArgs( frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression)) : new MessageEventArgs(frame.Opcode, frame.PayloadData); enqueueToMessageEventQueue(e); return true; } private void processException(Exception exception, string message) { var code = CloseStatusCode.Abnormal; var reason = message; if (exception is WebSocketException) { var wsex = (WebSocketException)exception; code = wsex.Code; reason = wsex.Message; } error(message ?? code.GetMessage(), exception); if (_readyState == WebSocketState.Connecting) Close(HttpStatusCode.BadRequest); else close(code, reason ?? code.GetMessage(), false); } private bool processFragmentedFrame(WebSocketFrame frame) { return frame.IsContinuation // Not first fragment ? true : processFragments(frame); } private bool processFragments(WebSocketFrame first) { using (var buff = new MemoryStream()) { buff.WriteBytes(first.PayloadData.ApplicationData); if (!concatenateFragmentsInto(buff)) return false; byte[] data; if (_compression != CompressionMethod.None) { data = buff.DecompressToArray(_compression); } else { buff.Close(); data = buff.ToArray(); } enqueueToMessageEventQueue(new MessageEventArgs(first.Opcode, data)); return true; } } private bool processPingFrame(WebSocketFrame frame) { var mask = Mask.Unmask; return true; } private bool processPongFrame(WebSocketFrame frame) { _receivePong.Set(); return true; } // As server private void processSecWebSocketExtensionsHeader(string value) { var buff = new StringBuilder(32); var compress = false; foreach (var extension in value.SplitHeaderValue(',')) { var trimed = extension.Trim(); var unprefixed = trimed.RemovePrefix("x-webkit-"); if (!compress && unprefixed.IsCompressionExtension()) { var method = unprefixed.ToCompressionMethod(); if (method != CompressionMethod.None) { _compression = method; compress = true; buff.Append(trimed + ", "); } } } var len = buff.Length; if (len > 0) { buff.Length = len - 2; _extensions = buff.ToString(); } } private bool processUnsupportedFrame(WebSocketFrame frame, CloseStatusCode code, string reason) { processException(new WebSocketException(code, reason), null); return false; } private bool processWebSocketFrame(WebSocketFrame frame) { return frame.IsCompressed && _compression == CompressionMethod.None ? processUnsupportedFrame( frame, CloseStatusCode.IncorrectData, "A compressed data has been received without available decompression method.") : frame.IsFragmented ? processFragmentedFrame(frame) : frame.IsData ? processDataFrame(frame) : frame.IsPing ? processPingFrame(frame) : frame.IsPong ? processPongFrame(frame) : frame.IsClose ? processCloseFrame(frame) : processUnsupportedFrame(frame, CloseStatusCode.PolicyViolation, null); } private bool send(Opcode opcode, Stream stream) { lock (_forSend) { var src = stream; var compressed = false; var sent = false; try { if (_compression != CompressionMethod.None) { stream = stream.Compress(_compression); compressed = true; } sent = send(opcode, Mask.Unmask, stream, compressed); if (!sent) error("Sending a data has been interrupted."); } catch (Exception ex) { error("An exception has occurred while sending a data.", ex); } finally { if (compressed) stream.Dispose(); src.Dispose(); } return sent; } } private bool send(Opcode opcode, Mask mask, Stream stream, bool compressed) { var len = stream.Length; /* Not fragmented */ if (len == 0) return send(Fin.Final, opcode, mask, new byte[0], compressed); var quo = len / FragmentLength; var rem = (int)(len % FragmentLength); byte[] buff = null; if (quo == 0) { buff = new byte[rem]; return stream.Read(buff, 0, rem) == rem && send(Fin.Final, opcode, mask, buff, compressed); } buff = new byte[FragmentLength]; if (quo == 1 && rem == 0) return stream.Read(buff, 0, FragmentLength) == FragmentLength && send(Fin.Final, opcode, mask, buff, compressed); /* Send fragmented */ // Begin if (stream.Read(buff, 0, FragmentLength) != FragmentLength || !send(Fin.More, opcode, mask, buff, compressed)) return false; var n = rem == 0 ? quo - 2 : quo - 1; for (long i = 0; i < n; i++) if (stream.Read(buff, 0, FragmentLength) != FragmentLength || !send(Fin.More, Opcode.Cont, mask, buff, compressed)) return false; // End if (rem == 0) rem = FragmentLength; else buff = new byte[rem]; return stream.Read(buff, 0, rem) == rem && send(Fin.Final, Opcode.Cont, mask, buff, compressed); } private bool send(Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed) { lock (_forConn) { if (_readyState != WebSocketState.Open) { return false; } return writeBytes( WebSocketFrame.CreateWebSocketFrame(fin, opcode, mask, data, compressed).ToByteArray()); } } private void sendAsync(Opcode opcode, Stream stream, Action<bool> completed) { Func<Opcode, Stream, bool> sender = send; sender.BeginInvoke( opcode, stream, ar => { try { var sent = sender.EndInvoke(ar); if (completed != null) completed(sent); } catch (Exception ex) { error("An exception has occurred while callback.", ex); } }, null); } // As server private bool sendHttpResponse(HttpResponse response) { return writeBytes(response.ToByteArray()); } private void startReceiving() { if (_messageEventQueue.Count > 0) _messageEventQueue.Clear(); _exitReceiving = new AutoResetEvent(false); _receivePong = new AutoResetEvent(false); Action receive = null; receive = () => WebSocketFrame.ReadAsync( _stream, true, frame => { if (processWebSocketFrame(frame) && _readyState != WebSocketState.Closed) { receive(); if (!frame.IsData) return; lock (_forEvent) { try { var e = dequeueFromMessageEventQueue(); if (e != null && _readyState == WebSocketState.Open) OnMessage.Emit(this, e); } catch (Exception ex) { processException(ex, "An exception has occurred while OnMessage."); } } } else if (_exitReceiving != null) { _exitReceiving.Set(); } }, ex => processException(ex, "An exception has occurred while receiving a message.")); receive(); } // As client private bool validateSecWebSocketAcceptHeader(string value) { return value != null && value == CreateResponseKey(_base64Key); } // As client private bool validateSecWebSocketExtensionsHeader(string value) { var compress = _compression != CompressionMethod.None; if (value == null || value.Length == 0) { if (compress) _compression = CompressionMethod.None; return true; } if (!compress) return false; var extensions = value.SplitHeaderValue(','); if (extensions.Contains( extension => extension.Trim() != _compression.ToExtensionString())) return false; _extensions = value; return true; } // As server private bool validateSecWebSocketKeyHeader(string value) { if (value == null || value.Length == 0) return false; _base64Key = value; return true; } // As client private bool validateSecWebSocketProtocolHeader(string value) { if (value == null) return _protocols == null; if (_protocols == null || !_protocols.Contains(protocol => protocol == value)) return false; _protocol = value; return true; } // As server private bool validateSecWebSocketVersionClientHeader(string value) { return value != null && value == _version; } // As client private bool validateSecWebSocketVersionServerHeader(string value) { return value == null || value == _version; } private bool writeBytes(byte[] data) { try { _stream.Write(data, 0, data.Length); return true; } catch (Exception ex) { return false; } } #endregion #region Internal Methods // As server internal void Close(HttpResponse response) { _readyState = WebSocketState.Closing; sendHttpResponse(response); closeServerResources(); _readyState = WebSocketState.Closed; } // As server internal void Close(HttpStatusCode code) { Close(createHandshakeCloseResponse(code)); } // As server public void ConnectAsServer() { try { if (acceptHandshake()) { _readyState = WebSocketState.Open; open(); } } catch (Exception ex) { processException(ex, "An exception has occurred while connecting."); } } internal static string CreateResponseKey(string base64Key) { var buff = new StringBuilder(base64Key, 64); buff.Append(_guid); SHA1 sha1 = new SHA1CryptoServiceProvider(); var src = sha1.ComputeHash(Encoding.UTF8.GetBytes(buff.ToString())); return Convert.ToBase64String(src); } #endregion #region Public Methods /// <summary> /// Closes the WebSocket connection, and releases all associated resources. /// </summary> public void Close() { var msg = _readyState.CheckIfClosable(); if (msg != null) { error(msg); return; } var send = _readyState == WebSocketState.Open; close(new PayloadData(), send, send); } /// <summary> /// Closes the WebSocket connection with the specified <see cref="CloseStatusCode"/> /// and <see cref="string"/>, and releases all associated resources. /// </summary> /// <remarks> /// This method emits a <see cref="OnError"/> event if the size /// of <paramref name="reason"/> is greater than 123 bytes. /// </remarks> /// <param name="code"> /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code /// indicating the reason for the close. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the close. /// </param> public void Close(CloseStatusCode code, string reason) { byte[] data = null; var msg = _readyState.CheckIfClosable() ?? (data = ((ushort)code).Append(reason)).CheckIfValidControlData("reason"); if (msg != null) { error(msg); return; } var send = _readyState == WebSocketState.Open && !code.IsReserved(); close(new PayloadData(data), send, send); } /// <summary> /// Sends a binary <paramref name="data"/> asynchronously using the WebSocket connection. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="completed"> /// An Action&lt;bool&gt; delegate that references the method(s) called when the send is /// complete. A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is /// complete successfully; otherwise, <c>false</c>. /// </param> public void SendAsync(byte[] data, Action<bool> completed) { var msg = _readyState.CheckIfOpen() ?? data.CheckIfValidSendData(); if (msg != null) { error(msg); return; } sendAsync(Opcode.Binary, new MemoryStream(data), completed); } /// <summary> /// Sends a text <paramref name="data"/> asynchronously using the WebSocket connection. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="completed"> /// An Action&lt;bool&gt; delegate that references the method(s) called when the send is /// complete. A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is /// complete successfully; otherwise, <c>false</c>. /// </param> public void SendAsync(string data, Action<bool> completed) { var msg = _readyState.CheckIfOpen() ?? data.CheckIfValidSendData(); if (msg != null) { error(msg); return; } sendAsync(Opcode.Text, new MemoryStream(Encoding.UTF8.GetBytes(data)), completed); } #endregion #region Explicit Interface Implementation /// <summary> /// Closes the WebSocket connection, and releases all associated resources. /// </summary> /// <remarks> /// This method closes the WebSocket connection with <see cref="CloseStatusCode.Away"/>. /// </remarks> void IDisposable.Dispose() { Close(CloseStatusCode.Away, null); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="PrologCompiler.cs" company="Axiom"> // // Copyright (c) 2006 Axiom, Inc. All rights reserved. // // The use and distribution terms for this source code are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // </copyright> //------------------------------------------------------------------------------ using System; using System.IO; using System.Reflection; using System.Collections; using System.CodeDom; using System.CodeDom.Compiler; using Axiom.Runtime; using Axiom.Runtime.Instructions; using Axiom.Compiler.CodeObjectModel; namespace Axiom.Compiler.Framework { public abstract class PrologCompiler : PrologCodeGenerator, IPrologCompiler { PrologCompilerResults IPrologCompiler.CompileAbstractCodeFromUnit(PrologCompilerParameters p, PrologCodeUnit unit) { PrologCompilerResults results = new PrologCompilerResults(); results.AbstractInstructions = new ArrayList(); GenerateCodeFromUnit(unit, results.AbstractInstructions); /* patch predicates */ //PatchPredicates(results.AbstractInstructions, GetPredicateAddresses(results.AbstractInstructions)); /* save foreign methods */ //results.ForeignMethods = GetForeignMethods(unit.Methods); /* save namespaces */ results.Namespaces = unit.Namespaces; /* save assembly files */ results.AssemblyFiles = unit.AssemblyFiles; /* return results */ return results; } PrologCompilerResults IPrologCompiler.CompileAbstractCodeFromFile(PrologCompilerParameters p, string fileName) { PrologCompilerResults results = new PrologCompilerResults(); PrologCodeParser parser = new PrologCodeParser(); PrologCodeUnit unit = new PrologCodeUnit(); try { StreamReader reader = new StreamReader(fileName); unit = parser.Parse(reader); /* Get errors after parsing */ results.Errors = parser.Errors; } catch (FileNotFoundException) { results.Errors.Add(new PrologCompilerError("P0008", "Input file not found.", fileName, false, 0, 0)); return results; } results.AbstractInstructions = new ArrayList(); GenerateCodeFromUnit(unit, results.AbstractInstructions); /* patch predicates */ //PatchPredicates(results.AbstractInstructions, GetPredicateAddresses(results.AbstractInstructions)); /* Save foreign methods */ //results.ForeignMethods = GetForeignMethods(unit.Methods); /* save namespaces */ results.Namespaces = unit.Namespaces; /* save assembly files */ results.AssemblyFiles = unit.AssemblyFiles; /* return results */ return results; } PrologCompilerResults IPrologCompiler.CompileAssemblyFromUnit (PrologCompilerParameters options, PrologCodeUnit e) { return FromUnit(options, e); } PrologCompilerResults IPrologCompiler.CompileAssemblyFromFile (PrologCompilerParameters options, string fileName) { return FromFile(options, fileName); } protected virtual PrologCompilerResults FromUnit (PrologCompilerParameters options, PrologCodeUnit e) { ArrayList instructions = new ArrayList(); PrologCompilerResults results = new PrologCompilerResults(); /* Generate abstract machine instructions */ GenerateCodeFromUnit(e, instructions); /* Determine assembly name and type to generate */ if (options.GenerateExecutable) { results.CompiledAssembly = GenerateExecutableAssembly(options, instructions); } else { results.CompiledAssembly = GenerateDllAssembly(options, instructions, e); } return results; } private Assembly GenerateDllAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions, PrologCodeUnit unit) { CodeCompileUnit compileUnit = new CodeCompileUnit(); // Declare namespace, default is Prolog.Assembly CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly"); plNamespace.Imports.Add(new CodeNamespaceImport("System")); plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections")); plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime")); compileUnit.Namespaces.Add(plNamespace); // Declare class type CodeTypeDeclaration classType = new CodeTypeDeclaration(unit.Class); plNamespace.Types.Add(classType); classType.TypeAttributes = TypeAttributes.Public; // Declare private members CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine"); CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more"); classType.Members.Add(machineField); classType.Members.Add(moreField); // Generate constructor method CodeConstructor cons = new CodeConstructor(); cons.Attributes = MemberAttributes.Public; cons.Statements.Add(new CodeSnippetExpression("Init()")); classType.Members.Add(cons); // Generate the 'More' property CodeMemberProperty moreProperty = new CodeMemberProperty(); moreProperty.Attributes = MemberAttributes.Public; moreProperty.Name = "More"; moreProperty.HasGet = true; moreProperty.HasSet = false; moreProperty.Type = new CodeTypeReference("System.Boolean"); string getStmt1 = "if (machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\")) { _more = false; } "; string getStmt2 = "return !(machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\"));"; moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt1)); moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt2)); classType.Members.Add(moreProperty); // Generate Redo() method CodeMemberMethod redoMethod = new CodeMemberMethod(); redoMethod.Name = "Redo"; redoMethod.Statements.Add(new CodeSnippetStatement("machine.Backtrack();")); redoMethod.Statements.Add(new CodeSnippetStatement("_more = true;")); redoMethod.Attributes = MemberAttributes.Public; classType.Members.Add(redoMethod); // Generate Init() method GenerateInitMethod(classType, instructions); // Generate method signatures GenerateMethodSignatures(classType, instructions); // Compile the file into a DLL CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" }); compparams.GenerateInMemory = false; compparams.OutputAssembly = compilerParameters.OutputAssembly; compparams.TempFiles.KeepFiles = true; Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider(); ICodeCompiler cscompiler = csharp.CreateCompiler(); CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit); if (compresult.Errors.Count > 0) { foreach(CompilerError err in compresult.Errors) { Console.WriteLine(err); } return null; } return compresult.CompiledAssembly; } private void GenerateMethodSignatures(CodeTypeDeclaration classType, ArrayList instructions) { Hashtable procedures = new Hashtable(); // Get all predicate names foreach (AbstractInstruction i in instructions) { if (i.Name() == "procedure") { ProcedureInstruction pi = (ProcedureInstruction)i; if (!procedures.ContainsKey(pi.ProcedureName)) { procedures.Add(pi.ProcedureName, pi); } } } foreach (DictionaryEntry entry in procedures) { ProcedureInstruction pi = (ProcedureInstruction)entry.Value; GenerateMethod(classType, pi); } } private void GenerateMethod(CodeTypeDeclaration classType, ProcedureInstruction pi) { CodeMemberMethod method = new CodeMemberMethod(); method.Name = pi.ProcedureName; method.ReturnType = new CodeTypeReference("System.Boolean"); method.Attributes = MemberAttributes.Public; string objectStatement = "new object [] { "; for (int i = 0; i < pi.Arity; i++) { method.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "arg" + (i + 1))); objectStatement += "arg" + (i + 1); if (i == pi.Arity - 1) { objectStatement += " }"; } else { objectStatement += ", "; } } method.Statements.Add(new CodeSnippetStatement("return machine.Call(\"" + pi.ProcedureName + "\", " + pi.Arity + ", " + objectStatement + ", _more);")); classType.Members.Add(method); } private void GenerateInitMethod(CodeTypeDeclaration classType, ArrayList instructions) { CodeMemberMethod initMethod = new CodeMemberMethod(); initMethod.Attributes = MemberAttributes.Private; initMethod.Name = "Init"; initMethod.Statements.Add(new CodeSnippetStatement("ArrayList program = new ArrayList();")); initMethod.Statements.Add(new CodeSnippetStatement("machine = new AbstractMachineState(new AMFactory());")); initMethod.Statements.Add(new CodeSnippetStatement("AMInstructionSet iset = new AMInstructionSet();")); initMethod.Statements.Add(new CodeSnippetStatement("_more = false;")); // generate instructions here... foreach (AbstractInstruction inst in instructions) { string statement = GetInstructionStatement(inst); initMethod.Statements.Add(new CodeSnippetStatement(statement)); } initMethod.Statements.Add(new CodeSnippetStatement("machine.Initialize(program);")); classType.Members.Add(initMethod); } private string GetInstructionStatement(AbstractInstruction inst) { string statement = "program.Add(iset.CreateInstruction("; if (inst.Name() == "procedure") { ProcedureInstruction pi = (ProcedureInstruction)inst; statement += "\"procedure\", \"" + pi.ProcedureName + "\", \"" + pi.Arity + "\""; } else { if (inst._arguments == null || inst._arguments.Length == 0) { statement += "\"" + inst.Name() + "\""; } else { statement += "\"" + inst.Name() + "\", "; for (int i = 0; i < inst._arguments.Length; i++) { statement += "\"" + inst._arguments[i] + "\""; if (i != (inst._arguments.Length - 1)) { statement += ", "; } } } } statement += "));"; return statement; } private Assembly GenerateExecutableAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions) { CodeCompileUnit compileUnit = new CodeCompileUnit(); // Declare namespace, default is Prolog.Assembly CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly"); plNamespace.Imports.Add(new CodeNamespaceImport("System")); plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections")); plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime")); compileUnit.Namespaces.Add(plNamespace); // Declare class type CodeTypeDeclaration classType = new CodeTypeDeclaration("PrologApp"); plNamespace.Types.Add(classType); classType.TypeAttributes = TypeAttributes.Public; // Declare private members CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine"); CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more"); classType.Members.Add(machineField); classType.Members.Add(moreField); // Generate constructor method CodeConstructor cons = new CodeConstructor(); cons.Attributes = MemberAttributes.Public; cons.Statements.Add(new CodeSnippetExpression("Init()")); classType.Members.Add(cons); // Generate Init() method GenerateInitMethod(classType, instructions); // Generate main method CodeEntryPointMethod mainMethod = new CodeEntryPointMethod(); mainMethod.Name = "Main"; mainMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public; mainMethod.Statements.Add(new CodeSnippetStatement("PrologApp app = new PrologApp();")); mainMethod.Statements.Add(new CodeSnippetStatement("app.Run();")); classType.Members.Add(mainMethod); CodeMemberMethod runMethod = new CodeMemberMethod(); runMethod.Name = "Run"; runMethod.Attributes = MemberAttributes.Public; runMethod.Statements.Add(new CodeSnippetStatement("machine.Call(\"main\");")); classType.Members.Add(runMethod); // Compile the file into a DLL CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" }); compparams.GenerateInMemory = false; compparams.GenerateExecutable = true; compparams.OutputAssembly = compilerParameters.OutputAssembly; compparams.TempFiles.KeepFiles = true; Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider(); ICodeCompiler cscompiler = csharp.CreateCompiler(); CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit); if (compresult.Errors.Count > 0) { foreach (CompilerError err in compresult.Errors) { Console.WriteLine(err); } return null; } return compresult.CompiledAssembly; } protected virtual PrologCompilerResults FromFile (PrologCompilerParameters options, string fileName) { PrologCompilerResults results = new PrologCompilerResults(); PrologCodeParser parser = new PrologCodeParser(); PrologCodeUnit unit = new PrologCodeUnit(); try { StreamReader reader = new StreamReader(fileName); unit = parser.Parse(reader); } catch (FileNotFoundException) { results.Errors.Add(new PrologCompilerError("P0008", "Input file not found.", fileName, false, 0, 0)); return results; } return FromUnit(options, unit); } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kodestruct.Analysis.BeamForces.PinnedFixed { public class UniformlyDistributedLoad : ISingleLoadCaseBeam, ISingleLoadCaseDeflectionBeam { const string CASE = "C3B_1"; BeamPinnedFixed beam; double L, w, R1, R2; bool ReactionsWereCalculated; public UniformlyDistributedLoad (BeamPinnedFixed beam, double w) { this.beam = beam; L = beam.Length; this.w = w; } public double Moment(double X) { beam.EvaluateX(X); if (ReactionsWereCalculated==false) { CalculateReactions(); } double M = R1 * X - w * X * X / 2.0; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 1, new Dictionary<string, double>() { {"R1",R1}, {"w",w}, {"L",L}, {"X",X } }, CASE, beam); return M; } public ForceDataPoint MomentMax() { if (w>=0.0) { BeamEntryFactory.CreateEntry("Mx", M1, BeamTemplateType.Mmax, 2, new Dictionary<string, double>() { {"L",L }, {"X",M1Location }, {"w",w } }, CASE, beam, true); return new ForceDataPoint(M1Location,M1); } else { BeamEntryFactory.CreateEntry("Mx", MSupport, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"L",L }, {"X",L }, {"w",w } }, CASE, beam, true); return new ForceDataPoint(L, MSupport); } } public ForceDataPoint MomentMin() { if (w <= 0.0) { BeamEntryFactory.CreateEntry("Mx", M1, BeamTemplateType.Mmax, 2, new Dictionary<string, double>() { {"L",L }, {"X",M1Location }, {"w",w } }, CASE, beam, false, true); return new ForceDataPoint(M1Location, M1); } else { BeamEntryFactory.CreateEntry("Mx", MSupport, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"L",L }, {"X",L }, {"w",w } }, CASE, beam, false, true); return new ForceDataPoint(L, MSupport); } throw new NotImplementedException(); } public double Shear(double X) { beam.EvaluateX(X); if (ReactionsWereCalculated == false) { CalculateReactions(); } double V = R1 - w * X; BeamEntryFactory.CreateEntry("Vx", V, BeamTemplateType.Vx, 1, new Dictionary<string, double>() { {"R1",R1 }, {"L",L }, {"X",X }, {"w",w } }, CASE, beam); return V; } public ForceDataPoint ShearMax() { double Vmax = R2; BeamEntryFactory.CreateEntry("Vx", Vmax, BeamTemplateType.Vmax, 1, new Dictionary<string, double>() { {"L",L }, {"X",L }, {"w",w } }, CASE, beam, true); return new ForceDataPoint(L, Vmax); } void CalculateReactions() { Dictionary<string, double> valDic = new Dictionary<string, double>() { {"L",L }, {"w",w } }; R1 = 3.0/8.0*w*L; BeamEntryFactory.CreateEntry("R1", R1, BeamTemplateType.R, 1, valDic, CASE, beam); R2 = 5.0 / 8.0 * w * L; BeamEntryFactory.CreateEntry("R2", R2, BeamTemplateType.R, 2, valDic, CASE, beam); ReactionsWereCalculated = true; } public double M1Location { get { double X = 3.0/8.0* L; return X; } } public double M1 { get { double M = 9.0 / 128.0 * w * L * L; return M; } } public double MSupport { get { double M =- w * L * L / 8.0; return M; } } public double MaximumDeflection() { double E = beam.ModulusOfElasticity; double I = beam.MomentOfInertia; double delta_Maximum = ((w * Math.Pow(L, 4)) / (185.0 * E * I)); return delta_Maximum; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Multiple Day Absences Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class STRADataSet : EduHubDataSet<STRA> { /// <inheritdoc /> public override string Name { get { return "STRA"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal STRADataSet(EduHubContext Context) : base(Context) { Index_ABS_TYPE = new Lazy<NullDictionary<short?, IReadOnlyList<STRA>>>(() => this.ToGroupedNullDictionary(i => i.ABS_TYPE)); Index_STKEY = new Lazy<Dictionary<string, IReadOnlyList<STRA>>>(() => this.ToGroupedDictionary(i => i.STKEY)); Index_TID = new Lazy<Dictionary<int, STRA>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="STRA" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="STRA" /> fields for each CSV column header</returns> internal override Action<STRA, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<STRA, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "STKEY": mapper[i] = (e, v) => e.STKEY = v; break; case "START_DATE": mapper[i] = (e, v) => e.START_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "START_AM_PM": mapper[i] = (e, v) => e.START_AM_PM = v; break; case "END_DATE": mapper[i] = (e, v) => e.END_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "END_AM_PM": mapper[i] = (e, v) => e.END_AM_PM = v; break; case "COMMENTS": mapper[i] = (e, v) => e.COMMENTS = v; break; case "ABS_TYPE": mapper[i] = (e, v) => e.ABS_TYPE = v == null ? (short?)null : short.Parse(v); break; case "START_PERIOD": mapper[i] = (e, v) => e.START_PERIOD = v == null ? (short?)null : short.Parse(v); break; case "END_PERIOD": mapper[i] = (e, v) => e.END_PERIOD = v == null ? (short?)null : short.Parse(v); break; case "FREQUENCY": mapper[i] = (e, v) => e.FREQUENCY = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="STRA" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="STRA" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="STRA" /> entities</param> /// <returns>A merged <see cref="IEnumerable{STRA}"/> of entities</returns> internal override IEnumerable<STRA> ApplyDeltaEntities(IEnumerable<STRA> Entities, List<STRA> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.STKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.STKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<short?, IReadOnlyList<STRA>>> Index_ABS_TYPE; private Lazy<Dictionary<string, IReadOnlyList<STRA>>> Index_STKEY; private Lazy<Dictionary<int, STRA>> Index_TID; #endregion #region Index Methods /// <summary> /// Find STRA by ABS_TYPE field /// </summary> /// <param name="ABS_TYPE">ABS_TYPE value used to find STRA</param> /// <returns>List of related STRA entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STRA> FindByABS_TYPE(short? ABS_TYPE) { return Index_ABS_TYPE.Value[ABS_TYPE]; } /// <summary> /// Attempt to find STRA by ABS_TYPE field /// </summary> /// <param name="ABS_TYPE">ABS_TYPE value used to find STRA</param> /// <param name="Value">List of related STRA entities</param> /// <returns>True if the list of related STRA entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByABS_TYPE(short? ABS_TYPE, out IReadOnlyList<STRA> Value) { return Index_ABS_TYPE.Value.TryGetValue(ABS_TYPE, out Value); } /// <summary> /// Attempt to find STRA by ABS_TYPE field /// </summary> /// <param name="ABS_TYPE">ABS_TYPE value used to find STRA</param> /// <returns>List of related STRA entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STRA> TryFindByABS_TYPE(short? ABS_TYPE) { IReadOnlyList<STRA> value; if (Index_ABS_TYPE.Value.TryGetValue(ABS_TYPE, out value)) { return value; } else { return null; } } /// <summary> /// Find STRA by STKEY field /// </summary> /// <param name="STKEY">STKEY value used to find STRA</param> /// <returns>List of related STRA entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STRA> FindBySTKEY(string STKEY) { return Index_STKEY.Value[STKEY]; } /// <summary> /// Attempt to find STRA by STKEY field /// </summary> /// <param name="STKEY">STKEY value used to find STRA</param> /// <param name="Value">List of related STRA entities</param> /// <returns>True if the list of related STRA entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTKEY(string STKEY, out IReadOnlyList<STRA> Value) { return Index_STKEY.Value.TryGetValue(STKEY, out Value); } /// <summary> /// Attempt to find STRA by STKEY field /// </summary> /// <param name="STKEY">STKEY value used to find STRA</param> /// <returns>List of related STRA entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STRA> TryFindBySTKEY(string STKEY) { IReadOnlyList<STRA> value; if (Index_STKEY.Value.TryGetValue(STKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find STRA by TID field /// </summary> /// <param name="TID">TID value used to find STRA</param> /// <returns>Related STRA entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STRA FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find STRA by TID field /// </summary> /// <param name="TID">TID value used to find STRA</param> /// <param name="Value">Related STRA entity</param> /// <returns>True if the related STRA entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out STRA Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find STRA by TID field /// </summary> /// <param name="TID">TID value used to find STRA</param> /// <returns>Related STRA entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STRA TryFindByTID(int TID) { STRA value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a STRA table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STRA]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[STRA]( [TID] int IDENTITY NOT NULL, [STKEY] varchar(10) NOT NULL, [START_DATE] datetime NULL, [START_AM_PM] varchar(1) NULL, [END_DATE] datetime NULL, [END_AM_PM] varchar(1) NULL, [COMMENTS] varchar(30) NULL, [ABS_TYPE] smallint NULL, [START_PERIOD] smallint NULL, [END_PERIOD] smallint NULL, [FREQUENCY] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [STRA_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [STRA_Index_ABS_TYPE] ON [dbo].[STRA] ( [ABS_TYPE] ASC ); CREATE CLUSTERED INDEX [STRA_Index_STKEY] ON [dbo].[STRA] ( [STKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STRA]') AND name = N'STRA_Index_ABS_TYPE') ALTER INDEX [STRA_Index_ABS_TYPE] ON [dbo].[STRA] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STRA]') AND name = N'STRA_Index_TID') ALTER INDEX [STRA_Index_TID] ON [dbo].[STRA] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STRA]') AND name = N'STRA_Index_ABS_TYPE') ALTER INDEX [STRA_Index_ABS_TYPE] ON [dbo].[STRA] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STRA]') AND name = N'STRA_Index_TID') ALTER INDEX [STRA_Index_TID] ON [dbo].[STRA] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STRA"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="STRA"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STRA> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[STRA] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the STRA data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STRA data set</returns> public override EduHubDataSetDataReader<STRA> GetDataSetDataReader() { return new STRADataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the STRA data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STRA data set</returns> public override EduHubDataSetDataReader<STRA> GetDataSetDataReader(List<STRA> Entities) { return new STRADataReader(new EduHubDataSetLoadedReader<STRA>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class STRADataReader : EduHubDataSetDataReader<STRA> { public STRADataReader(IEduHubDataSetReader<STRA> Reader) : base (Reader) { } public override int FieldCount { get { return 14; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // STKEY return Current.STKEY; case 2: // START_DATE return Current.START_DATE; case 3: // START_AM_PM return Current.START_AM_PM; case 4: // END_DATE return Current.END_DATE; case 5: // END_AM_PM return Current.END_AM_PM; case 6: // COMMENTS return Current.COMMENTS; case 7: // ABS_TYPE return Current.ABS_TYPE; case 8: // START_PERIOD return Current.START_PERIOD; case 9: // END_PERIOD return Current.END_PERIOD; case 10: // FREQUENCY return Current.FREQUENCY; case 11: // LW_DATE return Current.LW_DATE; case 12: // LW_TIME return Current.LW_TIME; case 13: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // START_DATE return Current.START_DATE == null; case 3: // START_AM_PM return Current.START_AM_PM == null; case 4: // END_DATE return Current.END_DATE == null; case 5: // END_AM_PM return Current.END_AM_PM == null; case 6: // COMMENTS return Current.COMMENTS == null; case 7: // ABS_TYPE return Current.ABS_TYPE == null; case 8: // START_PERIOD return Current.START_PERIOD == null; case 9: // END_PERIOD return Current.END_PERIOD == null; case 10: // FREQUENCY return Current.FREQUENCY == null; case 11: // LW_DATE return Current.LW_DATE == null; case 12: // LW_TIME return Current.LW_TIME == null; case 13: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // STKEY return "STKEY"; case 2: // START_DATE return "START_DATE"; case 3: // START_AM_PM return "START_AM_PM"; case 4: // END_DATE return "END_DATE"; case 5: // END_AM_PM return "END_AM_PM"; case 6: // COMMENTS return "COMMENTS"; case 7: // ABS_TYPE return "ABS_TYPE"; case 8: // START_PERIOD return "START_PERIOD"; case 9: // END_PERIOD return "END_PERIOD"; case 10: // FREQUENCY return "FREQUENCY"; case 11: // LW_DATE return "LW_DATE"; case 12: // LW_TIME return "LW_TIME"; case 13: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "STKEY": return 1; case "START_DATE": return 2; case "START_AM_PM": return 3; case "END_DATE": return 4; case "END_AM_PM": return 5; case "COMMENTS": return 6; case "ABS_TYPE": return 7; case "START_PERIOD": return 8; case "END_PERIOD": return 9; case "FREQUENCY": return 10; case "LW_DATE": return 11; case "LW_TIME": return 12; case "LW_USER": return 13; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Glimpse.Core.Extensibility; using Glimpse.Core.Extensions; using Glimpse.Core.Message; using Glimpse.Core.ResourceResult; using Glimpse.Core.Tab.Assist; using Tavis.UriTemplates; #if NET35 using Glimpse.Core.Backport; #endif namespace Glimpse.Core.Framework { /// <summary> /// The heart and soul of Glimpse. The runtime coordinate all input from a <see cref="IFrameworkProvider" />, persists collected runtime information and writes responses out to the <see cref="IFrameworkProvider" />. /// </summary> public class GlimpseRuntime : IGlimpseRuntime { private static readonly MethodInfo MethodInfoBeginRequest = typeof(GlimpseRuntime).GetMethod("BeginRequest", BindingFlags.Public | BindingFlags.Instance); private static readonly MethodInfo MethodInfoEndRequest = typeof(GlimpseRuntime).GetMethod("EndRequest", BindingFlags.Public | BindingFlags.Instance); private static readonly object LockObj = new object(); /// <summary> /// Initializes static members of the <see cref="GlimpseRuntime" /> class. /// </summary> /// <exception cref="System.NullReferenceException">BeginRequest method not found</exception> static GlimpseRuntime() { // Version is in major.minor.build format to support http://semver.org/ // TODO: Consider adding configuration hash to version Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(3); if (MethodInfoBeginRequest == null) { throw new NullReferenceException("BeginRequest method not found"); } if (MethodInfoEndRequest == null) { throw new NullReferenceException("EndRequest method not found"); } } /// <summary> /// Initializes a new instance of the <see cref="GlimpseRuntime" /> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <exception cref="System.ArgumentNullException">Throws an exception if <paramref name="configuration"/> is <c>null</c>.</exception> public GlimpseRuntime(IGlimpseConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException("configuration"); } Configuration = configuration; } /// <summary> /// Gets the executing version of Glimpse. /// </summary> /// <value> /// The version of Glimpse. /// </value> /// <remarks>Glimpse versioning follows the rules of <see href="http://semver.org/">Semantic Versioning</see>.</remarks> public static string Version { get; private set; } /// <summary> /// Gets or sets the configuration. /// </summary> /// <value> /// The configuration. /// </value> public IGlimpseConfiguration Configuration { get; set; } /// <summary> /// Gets a value indicating whether this instance has been initialized. /// </summary> /// <value> /// <c>true</c> if this instance is initialized; otherwise, <c>false</c>. /// </value> public bool IsInitialized { get; private set; } private IDictionary<string, TabResult> TabResultsStore { get { var requestStore = Configuration.FrameworkProvider.HttpRequestStore; var result = requestStore.Get<IDictionary<string, TabResult>>(Constants.TabResultsDataStoreKey); if (result == null) { result = new Dictionary<string, TabResult>(); requestStore.Set(Constants.TabResultsDataStoreKey, result); } return result; } } private IDictionary<string, TabResult> DisplayResultsStore { get { var requestStore = Configuration.FrameworkProvider.HttpRequestStore; var result = requestStore.Get<IDictionary<string, TabResult>>(Constants.DisplayResultsDataStoreKey); if (result == null) { result = new Dictionary<string, TabResult>(); requestStore.Set(Constants.DisplayResultsDataStoreKey, result); } return result; } } /// <summary> /// Begins Glimpse's processing of a Http request. /// </summary> /// <exception cref="Glimpse.Core.Framework.GlimpseException">Throws an exception if <see cref="GlimpseRuntime"/> is not yet initialized.</exception> public void BeginRequest() { if (!IsInitialized) { throw new GlimpseException(Resources.BeginRequestOutOfOrderRuntimeMethodCall); } if (HasOffRuntimePolicy(RuntimeEvent.BeginRequest)) { return; } ExecuteTabs(RuntimeEvent.BeginRequest); var requestStore = Configuration.FrameworkProvider.HttpRequestStore; // Give Request an ID var requestId = Guid.NewGuid(); requestStore.Set(Constants.RequestIdKey, requestId); Func<Guid?, string> generateClientScripts = (rId) => rId.HasValue ? GenerateScriptTags(rId.Value) : GenerateScriptTags(requestId); requestStore.Set(Constants.ClientScriptsStrategy, generateClientScripts); var executionTimer = CreateAndStartGlobalExecutionTimer(requestStore); Configuration.MessageBroker.Publish(new RuntimeMessage().AsSourceMessage(typeof(GlimpseRuntime), MethodInfoBeginRequest).AsTimelineMessage("Start Request", TimelineCategory.Request).AsTimedMessage(executionTimer.Point())); } private bool HasOffRuntimePolicy(RuntimeEvent policyName) { var policy = DetermineAndStoreAccumulatedRuntimePolicy(policyName); return policy.HasFlag(RuntimePolicy.Off); } /// <summary> /// Ends Glimpse's processing a Http request. /// </summary> /// <exception cref="Glimpse.Core.Framework.GlimpseException">Throws an exception if <c>BeginRequest</c> has not yet been called on a given request.</exception> public void EndRequest() // TODO: Add PRG support { if (HasOffRuntimePolicy(RuntimeEvent.EndRequest)) { return; } var frameworkProvider = Configuration.FrameworkProvider; var requestStore = frameworkProvider.HttpRequestStore; var executionTimer = requestStore.Get<ExecutionTimer>(Constants.GlobalTimerKey); if (executionTimer != null) { Configuration.MessageBroker.Publish(new RuntimeMessage().AsSourceMessage(typeof(GlimpseRuntime), MethodInfoBeginRequest).AsTimelineMessage("End Request", TimelineCategory.Request).AsTimedMessage(executionTimer.Point())); } ExecuteTabs(RuntimeEvent.EndRequest); ExecuteDisplays(); Guid requestId; Stopwatch stopwatch; try { requestId = requestStore.Get<Guid>(Constants.RequestIdKey); stopwatch = requestStore.Get<Stopwatch>(Constants.GlobalStopwatchKey); stopwatch.Stop(); } catch (NullReferenceException ex) { throw new GlimpseException(Resources.EndRequestOutOfOrderRuntimeMethodCall, ex); } var requestMetadata = frameworkProvider.RequestMetadata; var policy = DetermineAndStoreAccumulatedRuntimePolicy(RuntimeEvent.EndRequest); if (policy.HasFlag(RuntimePolicy.PersistResults)) { var persistenceStore = Configuration.PersistenceStore; var metadata = new GlimpseRequest(requestId, requestMetadata, TabResultsStore, DisplayResultsStore, stopwatch.Elapsed); try { persistenceStore.Save(metadata); } catch (Exception exception) { Configuration.Logger.Error(Resources.GlimpseRuntimeEndRequesPersistError, exception, persistenceStore.GetType()); } } if (policy.HasFlag(RuntimePolicy.ModifyResponseHeaders)) { frameworkProvider.SetHttpResponseHeader(Constants.HttpResponseHeader, requestId.ToString()); if (requestMetadata.GetCookie(Constants.ClientIdCookieName) == null) { frameworkProvider.SetCookie(Constants.ClientIdCookieName, requestMetadata.ClientId); } } if (policy.HasFlag(RuntimePolicy.DisplayGlimpseClient)) { var html = GenerateScriptTags(requestId); frameworkProvider.InjectHttpResponseBody(html); } } /// <summary> /// Executes the default resource. /// </summary> public void ExecuteDefaultResource() { ExecuteResource(Configuration.DefaultResource.Name, ResourceParameters.None()); } /// <summary> /// Begins access to session data. /// </summary> public void BeginSessionAccess() { if (HasOffRuntimePolicy(RuntimeEvent.BeginSessionAccess)) { return; } ExecuteTabs(RuntimeEvent.BeginSessionAccess); } /// <summary> /// Ends access to session data. /// </summary> public void EndSessionAccess() { if (HasOffRuntimePolicy(RuntimeEvent.EndSessionAccess)) { return; } ExecuteTabs(RuntimeEvent.EndSessionAccess); } /// <summary> /// Executes the resource. /// </summary> /// <param name="resourceName">Name of the resource.</param> /// <param name="parameters">The parameters.</param> /// <exception cref="System.ArgumentNullException">Throws an exception if either parameter is <c>null</c>.</exception> public void ExecuteResource(string resourceName, ResourceParameters parameters) { if (string.IsNullOrEmpty(resourceName)) { throw new ArgumentNullException("resourceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } string message; var logger = Configuration.Logger; var context = new ResourceResultContext(logger, Configuration.FrameworkProvider, Configuration.Serializer, Configuration.HtmlEncoder); // First we determine the current policy as it has been processed so far RuntimePolicy policy = DetermineAndStoreAccumulatedRuntimePolicy(RuntimeEvent.ExecuteResource); // It is possible that the policy now says Off, but if the requested resource is the default resource or one of it dependent resources, // then we need to make sure there is a good reason for not executing that resource, since the default resource (or one of it dependencies) // is the one we most likely need to set Glimpse On with in the first place. IDependOnResources defaultResourceDependsOnResources = Configuration.DefaultResource as IDependOnResources; if (resourceName.Equals(Configuration.DefaultResource.Name) || (defaultResourceDependsOnResources != null && defaultResourceDependsOnResources.DependsOn(resourceName))) { // To be clear we only do this for the default resource (or its dependencies), and we do this because it allows us to secure the default resource // the same way as any other resource, but for this we only rely on runtime policies that handle ExecuteResource runtime events and we ignore // ignore previously executed runtime policies (most likely during BeginRequest). // Either way, the default runtime policy is still our starting point and when it says Off, it remains Off policy = DetermineRuntimePolicy(RuntimeEvent.ExecuteResource, Configuration.DefaultRuntimePolicy); } if (policy == RuntimePolicy.Off) { string errorMessage = string.Format(Resources.ExecuteResourceInsufficientPolicy, resourceName); logger.Info(errorMessage); new StatusCodeResourceResult(403, errorMessage).Execute(context); return; } var resources = Configuration.Resources.Where( r => r.Name.Equals(resourceName, StringComparison.InvariantCultureIgnoreCase)); IResourceResult result; switch (resources.Count()) { case 1: // 200 - OK try { var resource = resources.First(); var resourceContext = new ResourceContext(parameters.GetParametersFor(resource), Configuration.PersistenceStore, logger); var privilegedResource = resource as IPrivilegedResource; if (privilegedResource != null) { result = privilegedResource.Execute(resourceContext, Configuration); } else { result = resource.Execute(resourceContext); } } catch (Exception ex) { logger.Error(Resources.GlimpseRuntimeExecuteResourceError, ex, resourceName); result = new ExceptionResourceResult(ex); } break; case 0: // 404 - File Not Found message = string.Format(Resources.ExecuteResourceMissingError, resourceName); logger.Warn(message); result = new StatusCodeResourceResult(404, message); break; default: // 500 - Server Error message = string.Format(Resources.ExecuteResourceDuplicateError, resourceName); logger.Warn(message); result = new StatusCodeResourceResult(500, message); break; } try { result.Execute(context); } catch (Exception exception) { logger.Fatal(Resources.GlimpseRuntimeExecuteResourceResultError, exception, result.GetType()); } } /// <summary> /// Initializes this instance of the Glimpse runtime. /// </summary> /// <returns> /// <c>true</c> if system initialized successfully, <c>false</c> otherwise /// </returns> public bool Initialize() { var policy = RuntimePolicy.Off; // Double checked lock to ensure thread safety. http://en.wikipedia.org/wiki/Double_checked_locking_pattern if (!IsInitialized) { lock (LockObj) { if (!IsInitialized) { var logger = Configuration.Logger; policy = DetermineAndStoreAccumulatedRuntimePolicy(RuntimeEvent.Initialize); if (policy != RuntimePolicy.Off) { CreateAndStartGlobalExecutionTimer(Configuration.FrameworkProvider.HttpRequestStore); var messageBroker = Configuration.MessageBroker; // TODO: Fix this to IDisplay no longer uses I*Tab*Setup var displaysThatRequireSetup = Configuration.Displays.Where(display => display is ITabSetup).Select(display => display); foreach (ITabSetup display in displaysThatRequireSetup) { var key = CreateKey(display); try { var setupContext = new TabSetupContext(logger, messageBroker, () => GetTabStore(key)); display.Setup(setupContext); } catch (Exception exception) { logger.Error(Resources.InitializeTabError, exception, key); } } var tabsThatRequireSetup = Configuration.Tabs.Where(tab => tab is ITabSetup).Select(tab => tab); foreach (ITabSetup tab in tabsThatRequireSetup) { var key = CreateKey(tab); try { var setupContext = new TabSetupContext(logger, messageBroker, () => GetTabStore(key)); tab.Setup(setupContext); } catch (Exception exception) { logger.Error(Resources.InitializeTabError, exception, key); } } var inspectorContext = new InspectorContext(logger, Configuration.ProxyFactory, messageBroker, Configuration.TimerStrategy, Configuration.RuntimePolicyStrategy); foreach (var inspector in Configuration.Inspectors) { try { inspector.Setup(inspectorContext); logger.Debug(Resources.GlimpseRuntimeInitializeSetupInspector, inspector.GetType()); } catch (Exception exception) { logger.Error(Resources.InitializeInspectorError, exception, inspector.GetType()); } } PersistMetadata(); } IsInitialized = true; } } } return policy != RuntimePolicy.Off; } private static UriTemplate SetParameters(UriTemplate template, IEnumerable<KeyValuePair<string, string>> nameValues) { if (nameValues == null) { return template; } foreach (var pair in nameValues) { template.SetParameter(pair.Key, pair.Value); } return template; } private static ExecutionTimer CreateAndStartGlobalExecutionTimer(IDataStore requestStore) { if (requestStore.Contains(Constants.GlobalStopwatchKey) && requestStore.Contains(Constants.GlobalTimerKey)) { return requestStore.Get<ExecutionTimer>(Constants.GlobalTimerKey); } // Create and start global stopwatch var stopwatch = Stopwatch.StartNew(); var executionTimer = new ExecutionTimer(stopwatch); requestStore.Set(Constants.GlobalStopwatchKey, stopwatch); requestStore.Set(Constants.GlobalTimerKey, executionTimer); return executionTimer; } private static string CreateKey(object obj) { string result; var keyProvider = obj as IKey; if (keyProvider != null) { result = keyProvider.Key; } else { result = obj.GetType().FullName; } return result .Replace('.', '_') .Replace(' ', '_') .ToLower(); } private IDataStore GetTabStore(string tabName) { var requestStore = Configuration.FrameworkProvider.HttpRequestStore; if (!requestStore.Contains(Constants.TabStorageKey)) { requestStore.Set(Constants.TabStorageKey, new Dictionary<string, IDataStore>()); } var tabStorage = requestStore.Get<IDictionary<string, IDataStore>>(Constants.TabStorageKey); if (!tabStorage.ContainsKey(tabName)) { tabStorage.Add(tabName, new DictionaryDataStoreAdapter(new Dictionary<string, object>())); } return tabStorage[tabName]; } private void ExecuteTabs(RuntimeEvent runtimeEvent) { var runtimeContext = Configuration.FrameworkProvider.RuntimeContext; var frameworkProviderRuntimeContextType = runtimeContext.GetType(); var messageBroker = Configuration.MessageBroker; // Only use tabs that either don't specify a specific context type, or have a context type that matches the current framework provider's. var runtimeTabs = Configuration.Tabs.Where( tab => tab.RequestContextType == null || frameworkProviderRuntimeContextType.IsSubclassOf(tab.RequestContextType) || tab.RequestContextType == frameworkProviderRuntimeContextType); var supportedRuntimeTabs = runtimeTabs.Where(p => p.ExecuteOn.HasFlag(runtimeEvent)); var tabResultsStore = TabResultsStore; var logger = Configuration.Logger; foreach (var tab in supportedRuntimeTabs) { TabResult result; var key = CreateKey(tab); try { var tabContext = new TabContext(runtimeContext, GetTabStore(key), logger, messageBroker); var tabData = tab.GetData(tabContext); var tabSection = tabData as TabSection; if (tabSection != null) { tabData = tabSection.Build(); } result = new TabResult(tab.Name, tabData); } catch (Exception exception) { result = new TabResult(tab.Name, exception.ToString()); logger.Error(Resources.ExecuteTabError, exception, key); } if (tabResultsStore.ContainsKey(key)) { tabResultsStore[key] = result; } else { tabResultsStore.Add(key, result); } } } private void ExecuteDisplays() { var runtimeContext = Configuration.FrameworkProvider.RuntimeContext; var messageBroker = Configuration.MessageBroker; var displayResultsStore = DisplayResultsStore; var logger = Configuration.Logger; foreach (var display in Configuration.Displays) { TabResult result; // TODO: Rename now that it is no longer *just* tab results var key = CreateKey(display); try { var displayContext = new TabContext(runtimeContext, GetTabStore(key), logger, messageBroker); // TODO: Do we need a DisplayContext? var displayData = display.GetData(displayContext); result = new TabResult(display.Name, displayData); } catch (Exception exception) { result = new TabResult(display.Name, exception.ToString()); logger.Error(Resources.ExecuteTabError, exception, key); } if (displayResultsStore.ContainsKey(key)) { displayResultsStore[key] = result; } else { displayResultsStore.Add(key, result); } } } private void PersistMetadata() { var metadata = new GlimpseMetadata { Version = Version, Hash = Configuration.Hash }; var tabMetadata = metadata.Tabs; foreach (var tab in Configuration.Tabs) { var metadataInstance = new TabMetadata(); var documentationTab = tab as IDocumentation; if (documentationTab != null) { metadataInstance.DocumentationUri = documentationTab.DocumentationUri; } var layoutControlTab = tab as ILayoutControl; if (layoutControlTab != null) { metadataInstance.KeysHeadings = layoutControlTab.KeysHeadings; } var layoutTab = tab as ITabLayout; if (layoutTab != null) { metadataInstance.Layout = layoutTab.GetLayout(); } if (metadataInstance.HasMetadata) { tabMetadata[CreateKey(tab)] = metadataInstance; } } var resources = metadata.Resources; var endpoint = Configuration.ResourceEndpoint; var logger = Configuration.Logger; foreach (var resource in Configuration.Resources) { var resourceKey = CreateKey(resource); if (resources.ContainsKey(resourceKey)) { logger.Warn(Resources.GlimpseRuntimePersistMetadataMultipleResourceWarning, resource.Name); } resources[resourceKey] = endpoint.GenerateUriTemplate(resource, Configuration.EndpointBaseUri, logger); } Configuration.PersistenceStore.Save(metadata); } private RuntimePolicy DetermineRuntimePolicy(RuntimeEvent runtimeEvent, RuntimePolicy maximumAllowedPolicy) { if (maximumAllowedPolicy == RuntimePolicy.Off) { return maximumAllowedPolicy; } var frameworkProvider = Configuration.FrameworkProvider; var logger = Configuration.Logger; // only run policies for this runtimeEvent var policies = Configuration.RuntimePolicies.Where( policy => policy.ExecuteOn.HasFlag(runtimeEvent)); var policyContext = new RuntimePolicyContext(frameworkProvider.RequestMetadata, Configuration.Logger, frameworkProvider.RuntimeContext); foreach (var policy in policies) { var policyResult = RuntimePolicy.Off; try { policyResult = policy.Execute(policyContext); if (policyResult != RuntimePolicy.On) { logger.Debug("RuntimePolicy set to '{0}' by IRuntimePolicy of type '{1}' during RuntimeEvent '{2}'.", policyResult, policy.GetType(), runtimeEvent); } } catch (Exception exception) { logger.Warn("Exception when executing IRuntimePolicy of type '{0}'. RuntimePolicy is now set to 'Off'.", exception, policy.GetType()); } // Only use the lowest policy allowed for the request if (policyResult < maximumAllowedPolicy) { maximumAllowedPolicy = policyResult; } // If the policy indicates Glimpse is Off, then we stop processing any other runtime policy if (maximumAllowedPolicy == RuntimePolicy.Off) { break; } } return maximumAllowedPolicy; } private RuntimePolicy DetermineAndStoreAccumulatedRuntimePolicy(RuntimeEvent runtimeEvent) { var frameworkProvider = Configuration.FrameworkProvider; var requestStore = frameworkProvider.HttpRequestStore; // First determine the maximum allowed policy to start from. This is or the current stored runtime policy for this // request, or if none can be found, the default runtime policy set in the configuration var maximumAllowedPolicy = requestStore.Contains(Constants.RuntimePolicyKey) ? requestStore.Get<RuntimePolicy>(Constants.RuntimePolicyKey) : Configuration.DefaultRuntimePolicy; maximumAllowedPolicy = DetermineRuntimePolicy(runtimeEvent, maximumAllowedPolicy); // store result for request requestStore.Set(Constants.RuntimePolicyKey, maximumAllowedPolicy); return maximumAllowedPolicy; } private string GenerateScriptTags(Guid requestId) { var requestStore = Configuration.FrameworkProvider.HttpRequestStore; var runtimePolicy = requestStore.Get<RuntimePolicy>(Constants.RuntimePolicyKey); var hasRendered = false; if (requestStore.Contains(Constants.ScriptsHaveRenderedKey)) { hasRendered = requestStore.Get<bool>(Constants.ScriptsHaveRenderedKey); } if (hasRendered) { return string.Empty; } var encoder = Configuration.HtmlEncoder; var resourceEndpoint = Configuration.ResourceEndpoint; var clientScripts = Configuration.ClientScripts; var logger = Configuration.Logger; var resources = Configuration.Resources; var stringBuilder = new StringBuilder(); foreach (var clientScript in clientScripts.OrderBy(cs => cs.Order)) { var dynamicScript = clientScript as IDynamicClientScript; if (dynamicScript != null) { try { var requestTokenValues = new Dictionary<string, string> { { ResourceParameter.RequestId.Name, requestId.ToString() }, { ResourceParameter.VersionNumber.Name, Version }, { ResourceParameter.Hash.Name, Configuration.Hash } }; var resourceName = dynamicScript.GetResourceName(); var resource = resources.FirstOrDefault(r => r.Name.Equals(resourceName, StringComparison.InvariantCultureIgnoreCase)); if (resource == null) { logger.Warn(Resources.RenderClientScriptMissingResourceWarning, clientScript.GetType(), resourceName); continue; } var uriTemplate = resourceEndpoint.GenerateUriTemplate(resource, Configuration.EndpointBaseUri, logger); var resourceParameterProvider = dynamicScript as IParameterValueProvider; if (resourceParameterProvider != null) { resourceParameterProvider.OverrideParameterValues(requestTokenValues); } var template = SetParameters(new UriTemplate(uriTemplate), requestTokenValues); var uri = encoder.HtmlAttributeEncode(template.Resolve()); if (!string.IsNullOrEmpty(uri)) { stringBuilder.AppendFormat(@"<script type='text/javascript' src='{0}'></script>", uri); } continue; } catch (Exception exception) { logger.Error(Core.Resources.GenerateScriptTagsDynamicException, exception, dynamicScript.GetType()); } } var staticScript = clientScript as IStaticClientScript; if (staticScript != null) { try { var uri = encoder.HtmlAttributeEncode(staticScript.GetUri(Version)); if (!string.IsNullOrEmpty(uri)) { stringBuilder.AppendFormat(@"<script type='text/javascript' src='{0}'></script>", uri); } continue; } catch (Exception exception) { logger.Error(Core.Resources.GenerateScriptTagsStaticException, exception, staticScript.GetType()); } } logger.Warn(Core.Resources.RenderClientScriptImproperImplementationWarning, clientScript.GetType()); } requestStore.Set(Constants.ScriptsHaveRenderedKey, true); return stringBuilder.ToString(); } /// <summary> /// The message used to to track the beginning and end of Http requests. /// </summary> protected class RuntimeMessage : ITimelineMessage, ISourceMessage { /// <summary> /// Gets the id of the request. /// </summary> /// <value> /// The id. /// </value> public Guid Id { get; private set; } /// <summary> /// Gets or sets the name of the event. /// </summary> /// <value> /// The name of the event. /// </value> public string EventName { get; set; } /// <summary> /// Gets or sets the event category. /// </summary> /// <value> /// The event category. /// </value> public TimelineCategoryItem EventCategory { get; set; } /// <summary> /// Gets or sets the event sub text. /// </summary> /// <value> /// The event sub text. /// </value> public string EventSubText { get; set; } /// <summary> /// Gets or sets the type of the executed. /// </summary> /// <value> /// The type of the executed. /// </value> public Type ExecutedType { get; set; } /// <summary> /// Gets or sets the executed method. /// </summary> /// <value> /// The executed method. /// </value> public MethodInfo ExecutedMethod { get; set; } /// <summary> /// Gets or sets the offset. /// </summary> /// <value> /// The offset. /// </value> public TimeSpan Offset { get; set; } /// <summary> /// Gets or sets the duration. /// </summary> /// <value> /// The duration. /// </value> public TimeSpan Duration { get; set; } /// <summary> /// Gets or sets the start time. /// </summary> /// <value> /// The start time. /// </value> public DateTime StartTime { get; set; } } } }
using System; using System.Reflection; using NMock2.Matchers; using NMock2.Syntax; namespace NMock2.Internal { public class ExpectationBuilder : IReceiverSyntax, IMethodSyntax, IArgumentSyntax, IMatchSyntax, IActionSyntax { protected BuildableExpectation expectation; protected IMockObject mockObject = null; public ExpectationBuilder(string description, Matcher requiredCountMatcher, Matcher acceptedCountMatcher) { expectation = new BuildableExpectation(description, requiredCountMatcher, acceptedCountMatcher); } virtual public IMethodSyntax On(object receiver) { if (receiver is IMockObject) { mockObject = (IMockObject) receiver; expectation.ReceiverMatcher = new DescriptionOverride(receiver.ToString(), Is.Same(receiver)); mockObject.AddExpectation(expectation); } else { throw new ArgumentException("not a mock object", "receiver"); } return this; } public IArgumentSyntax Method(string methodName) { return Method(new MethodNameMatcher(methodName)); } public IArgumentSyntax Method(MethodInfo method) { return Method(new DescriptionOverride(method.Name, Is.Same(method))); } public IArgumentSyntax Method(Matcher methodMatcher) { if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have a method matching " + methodMatcher); } expectation.MethodMatcher = methodMatcher; return this; } public IMatchSyntax GetProperty(string propertyName) { Matcher methodMatcher = NewMethodNameMatcher(propertyName, "get_"+propertyName); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have a getter for property " + propertyName); } expectation.MethodMatcher = methodMatcher; expectation.ArgumentsMatcher = new DescriptionOverride("", new ArgumentsMatcher()); return this; } public IValueSyntax SetProperty(string propertyName) { Matcher methodMatcher = NewMethodNameMatcher(propertyName+" = ", "set_"+propertyName); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have a setter for property " + propertyName); } expectation.MethodMatcher = methodMatcher; return new PropertyValueBuilder(this); } private class PropertyValueBuilder : IValueSyntax { private readonly ExpectationBuilder builder; public PropertyValueBuilder(ExpectationBuilder builder) { this.builder = builder; } public IMatchSyntax To(Matcher valueMatcher) { return builder.With(valueMatcher); } public IMatchSyntax To(object equalValue) { return To(Is.EqualTo(equalValue)); } } public IGetIndexerSyntax Get { get { Matcher methodMatcher = NewMethodNameMatcher("", "get_Item"); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have an indexed setter"); } expectation.DescribeAsIndexer(); expectation.MethodMatcher = methodMatcher; return new IndexGetterBuilder(expectation, this); } } private class IndexGetterBuilder : IGetIndexerSyntax { private readonly BuildableExpectation expectation; private readonly ExpectationBuilder builder; public IndexGetterBuilder(BuildableExpectation expectation, ExpectationBuilder builder) { this.expectation = expectation; this.builder = builder; } public IMatchSyntax this[params object[] expectedArguments] { get { expectation.ArgumentsMatcher = new IndexGetterArgumentsMatcher(ArgumentMatchers(expectedArguments)); return builder; } } } public ISetIndexerSyntax Set { get { Matcher methodMatcher = NewMethodNameMatcher("", "set_Item"); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have an indexed setter"); } expectation.DescribeAsIndexer(); expectation.MethodMatcher = methodMatcher; return new IndexSetterBuilder(expectation, this); } } private class IndexSetterBuilder : ISetIndexerSyntax, IValueSyntax { private readonly BuildableExpectation expectation; private readonly ExpectationBuilder builder; private Matcher[] matchers; public IndexSetterBuilder(BuildableExpectation expectation, ExpectationBuilder builder) { this.expectation = expectation; this.builder = builder; } public IValueSyntax this[params object[] expectedArguments] { get { Matcher[] indexMatchers = ArgumentMatchers(expectedArguments); matchers = new Matcher[indexMatchers.Length + 1]; Array.Copy(indexMatchers, matchers, indexMatchers.Length); SetValueMatcher(Is.Anything); return this; } } public IMatchSyntax To(Matcher matcher) { SetValueMatcher(matcher); return builder; } public IMatchSyntax To(object equalValue) { return To(Is.EqualTo(equalValue)); } private void SetValueMatcher(Matcher matcher) { matchers[matchers.Length - 1] = matcher; expectation.ArgumentsMatcher = new IndexSetterArgumentsMatcher(matchers); } } public IMatchSyntax EventAdd(string eventName, Matcher listenerMatcher) { Matcher methodMatcher = NewMethodNameMatcher(eventName + " += ", "add_"+eventName); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have an event named " + eventName); } expectation.MethodMatcher = methodMatcher; expectation.ArgumentsMatcher = new ArgumentsMatcher(listenerMatcher); return this; } public IMatchSyntax EventAdd(string eventName, Delegate equalListener) { return EventAdd(eventName, Is.EqualTo(equalListener)); } public IMatchSyntax EventRemove(string eventName, Matcher listenerMatcher) { Matcher methodMatcher = NewMethodNameMatcher(eventName + " -= ", "remove_"+eventName); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have an event named " + eventName); } expectation.MethodMatcher = methodMatcher; expectation.ArgumentsMatcher = new ArgumentsMatcher(listenerMatcher); return this; } public IMatchSyntax EventRemove(string eventName, Delegate equalListener) { return EventRemove(eventName, Is.EqualTo(equalListener)); } public IMatchSyntax With(params object[] expectedArguments) { expectation.ArgumentsMatcher = new ArgumentsMatcher(ArgumentMatchers(expectedArguments)); return this; } private static Matcher[] ArgumentMatchers(object[] expectedArguments) { Matcher[] matchers = new Matcher[expectedArguments.Length]; for (int i = 0; i < matchers.Length; i++) { object o = expectedArguments[i]; matchers[i] = (o is Matcher) ? (Matcher) o : new EqualMatcher(o); } return matchers; } public IMatchSyntax WithNoArguments() { return With(new Matcher[0]); } public IMatchSyntax WithAnyArguments() { expectation.ArgumentsMatcher = new AlwaysMatcher(true, "(any arguments)"); return this; } public IActionSyntax Matching(Matcher matcher) { expectation.AddInvocationMatcher(matcher); return this; } public void Will(params IAction[] actions) { foreach (IAction action in actions) { expectation.AddAction(action); } } private static Matcher NewMethodNameMatcher(string description, string methodName) { return new DescriptionOverride(description, new MethodNameMatcher(methodName)); } } }
// 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.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Windows.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { public partial class TestWorkspaceFactory { /// <summary> /// This place-holder value is used to set a project's file path to be null. It was explicitly chosen to be /// convoluted to avoid any accidental usage (e.g., what if I really wanted FilePath to be the string "null"?), /// obvious to anybody debugging that it is a special value, and invalid as an actual file path. /// </summary> public const string NullFilePath = "NullFilePath::{AFA13775-BB7D-4020-9E58-C68CF43D8A68}"; private class TestDocumentationProvider : DocumentationProvider { protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) { return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID); } public override bool Equals(object obj) { return ReferenceEquals(this, obj); } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } public static TestWorkspace CreateWorkspace(string xmlDefinition, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null) { return CreateWorkspace(XElement.Parse(xmlDefinition), completed, openDocuments, exportProvider); } public static TestWorkspace CreateWorkspace( XElement workspaceElement, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null, string workspaceKind = null) { SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); if (workspaceElement.Name != WorkspaceElementName) { throw new ArgumentException(); } exportProvider = exportProvider ?? TestExportProvider.ExportProviderWithCSharpAndVisualBasic; var workspace = new TestWorkspace(exportProvider, workspaceKind); var projectMap = new Dictionary<string, TestHostProject>(); var documentElementToFilePath = new Dictionary<XElement, string>(); var projectElementToAssemblyName = new Dictionary<XElement, string>(); var filePathToTextBufferMap = new Dictionary<string, ITextBuffer>(); int projectIdentifier = 0; int documentIdentifier = 0; foreach (var projectElement in workspaceElement.Elements(ProjectElementName)) { var project = CreateProject( workspaceElement, projectElement, exportProvider, workspace, projectElementToAssemblyName, documentElementToFilePath, filePathToTextBufferMap, ref projectIdentifier, ref documentIdentifier); Assert.False(projectMap.ContainsKey(project.AssemblyName)); projectMap.Add(project.AssemblyName, project); workspace.Projects.Add(project); } var documentFilePaths = new HashSet<string>(); foreach (var project in projectMap.Values) { foreach (var document in project.Documents) { Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath)); } } var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider); foreach (var submission in submissions) { projectMap.Add(submission.AssemblyName, submission); } var solution = new TestHostSolution(projectMap.Values.ToArray()); workspace.AddTestSolution(solution); foreach (var projectElement in workspaceElement.Elements(ProjectElementName)) { foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName)) { var fromName = projectElementToAssemblyName[projectElement]; var toName = projectReference.Value; var fromProject = projectMap[fromName]; var toProject = projectMap[toName]; var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray(); workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default(ImmutableArray<string>))); } } for (int i = 1; i < submissions.Count; i++) { workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[i - 1].Id)); } foreach (var project in projectMap.Values) { foreach (var document in project.Documents) { if (openDocuments) { workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile); } workspace.Documents.Add(document); } } return workspace; } private static IList<TestHostProject> CreateSubmissions( TestWorkspace workspace, IEnumerable<XElement> submissionElements, ExportProvider exportProvider) { var submissions = new List<TestHostProject>(); var submissionIndex = 0; foreach (var submissionElement in submissionElements) { var submissionName = "Submission" + (submissionIndex++); var languageName = GetLanguage(workspace, submissionElement); // The document var markupCode = submissionElement.NormalizedValue(); string code; int? cursorPosition; IDictionary<string, IList<TextSpan>> spans; MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans); var languageServices = workspace.Services.GetLanguageServices(languageName); var contentTypeLanguageService = languageServices.GetService<IContentTypeLanguageService>(); var contentType = contentTypeLanguageService.GetDefaultContentType(); var textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code); // The project var document = new TestHostDocument(exportProvider, languageServices, textBuffer, submissionName, cursorPosition, spans, SourceCodeKind.Interactive); var syntaxFactory = languageServices.GetService<ISyntaxTreeFactoryService>(); var compilationFactory = languageServices.GetService<ICompilationFactoryService>(); var compilationOptions = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var parseOptions = syntaxFactory.GetDefaultParseOptions().WithKind(SourceCodeKind.Interactive); var references = CreateCommonReferences(workspace, submissionElement); var project = new TestHostProject( languageServices, compilationOptions, parseOptions, submissionName, references, new List<TestHostDocument> { document }, isSubmission: true); submissions.Add(project); } return submissions; } private static TestHostProject CreateProject( XElement workspaceElement, XElement projectElement, ExportProvider exportProvider, TestWorkspace workspace, Dictionary<XElement, string> projectElementToAssemblyName, Dictionary<XElement, string> documentElementToFilePath, Dictionary<string, ITextBuffer> filePathToTextBufferMap, ref int projectId, ref int documentId) { var language = GetLanguage(workspace, projectElement); var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId); projectElementToAssemblyName.Add(projectElement, assemblyName); string filePath; if (projectElement.Attribute(FilePathAttributeName) != null) { filePath = projectElement.Attribute(FilePathAttributeName).Value; if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0) { // allow explicit null file path filePath = null; } } else { filePath = assemblyName + (language == LanguageNames.CSharp ? ".csproj" : language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language)); } var contentTypeRegistryService = exportProvider.GetExportedValue<IContentTypeRegistryService>(); var languageServices = workspace.Services.GetLanguageServices(language); var compilationOptions = CreateCompilationOptions(workspace, projectElement, language); var parseOptions = GetParseOptions(projectElement, language, languageServices); var references = CreateReferenceList(workspace, projectElement); var analyzers = CreateAnalyzerList(workspace, projectElement); var documents = new List<TestHostDocument>(); var documentElements = projectElement.Elements(DocumentElementName).ToList(); foreach (var documentElement in documentElements) { var document = CreateDocument( workspace, workspaceElement, documentElement, language, exportProvider, languageServices, filePathToTextBufferMap, ref documentId); documents.Add(document); documentElementToFilePath.Add(documentElement, document.FilePath); } return new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, references, documents, filePath: filePath, analyzerReferences: analyzers); } private static ParseOptions GetParseOptions(XElement projectElement, string language, HostLanguageServices languageServices) { return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic ? GetParseOptionsWorker(projectElement, language, languageServices) : null; } private static ParseOptions GetParseOptionsWorker(XElement projectElement, string language, HostLanguageServices languageServices) { ParseOptions parseOptions; var preprocessorSymbolsAttribute = projectElement.Attribute(PreprocessorSymbolsAttributeName); if (preprocessorSymbolsAttribute != null) { parseOptions = GetPreProcessorParseOptions(language, preprocessorSymbolsAttribute); } else { parseOptions = languageServices.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions(); } var languageVersionAttribute = projectElement.Attribute(LanguageVersionAttributeName); if (languageVersionAttribute != null) { parseOptions = GetParseOptionsWithLanguageVersion(language, parseOptions, languageVersionAttribute); } var documentationMode = GetDocumentationMode(projectElement); if (documentationMode != null) { parseOptions = parseOptions.WithDocumentationMode(documentationMode.Value); } return parseOptions; } private static ParseOptions GetPreProcessorParseOptions(string language, XAttribute preprocessorSymbolsAttribute) { if (language == LanguageNames.CSharp) { return new CSharpParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value.Split(',')); } else if (language == LanguageNames.VisualBasic) { return new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value .Split(',').Select(v => KeyValuePair.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray()); } else { throw new ArgumentException("Unexpected language '{0}' for generating custom parse options.", language); } } private static ParseOptions GetParseOptionsWithLanguageVersion(string language, ParseOptions parseOptions, XAttribute languageVersionAttribute) { if (language == LanguageNames.CSharp) { var languageVersion = (CodeAnalysis.CSharp.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.CSharp.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion); } else if (language == LanguageNames.VisualBasic) { var languageVersion = (CodeAnalysis.VisualBasic.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.VisualBasic.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((VisualBasicParseOptions)parseOptions).WithLanguageVersion(languageVersion); } return parseOptions; } private static DocumentationMode? GetDocumentationMode(XElement projectElement) { var documentationModeAttribute = projectElement.Attribute(DocumentationModeAttributeName); if (documentationModeAttribute != null) { return (DocumentationMode)Enum.Parse(typeof(DocumentationMode), documentationModeAttribute.Value); } else { return null; } } private static string GetAssemblyName(TestWorkspace workspace, XElement projectElement, ref int projectId) { var assemblyNameAttribute = projectElement.Attribute(AssemblyNameAttributeName); if (assemblyNameAttribute != null) { return assemblyNameAttribute.Value; } var language = GetLanguage(workspace, projectElement); projectId++; return language == LanguageNames.CSharp ? "CSharpAssembly" + projectId : language == LanguageNames.VisualBasic ? "VisualBasicAssembly" + projectId : language + "Assembly" + projectId; } private static string GetLanguage(TestWorkspace workspace, XElement projectElement) { string languageName = projectElement.Attribute(LanguageAttributeName).Value; if (!workspace.Services.SupportedLanguages.Contains(languageName)) { throw new ArgumentException(string.Format("Language should be one of '{0}' and it is {1}", string.Join(", ", workspace.Services.SupportedLanguages), languageName)); } return languageName; } private static CompilationOptions CreateCompilationOptions( TestWorkspace workspace, XElement projectElement, string language) { var compilationOptionsElement = projectElement.Element(CompilationOptionsElementName); return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic ? CreateCompilationOptions(workspace, language, compilationOptionsElement) : null; } private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement) { var rootNamespace = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace; var globalImports = new List<GlobalImport>(); var reportDiagnostic = ReportDiagnostic.Default; if (compilationOptionsElement != null) { globalImports = compilationOptionsElement.Elements(GlobalImportElementName) .Select(x => GlobalImport.Parse(x.Value)).ToList(); var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName); if (rootNamespaceAttribute != null) { rootNamespace = rootNamespaceAttribute.Value; } var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName); if (reportDiagnosticAttribute != null) { reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute); } var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName); if (outputTypeAttribute != null && outputTypeAttribute.Value == "WindowsRuntimeMetadata") { if (rootNamespaceAttribute == null) { rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace; } return language == LanguageNames.CSharp ? (CompilationOptions)new CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata) : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports) .WithRootNamespace(rootNamespace); } } else { // Add some common global imports by default for VB globalImports.Add(GlobalImport.Parse("System")); globalImports.Add(GlobalImport.Parse("System.Collections.Generic")); globalImports.Add(GlobalImport.Parse("System.Linq")); } // TODO: Allow these to be specified. var languageServices = workspace.Services.GetLanguageServices(language); var compilationOptions = languageServices.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions(); compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary) .WithGeneralDiagnosticOption(reportDiagnostic) .WithSourceReferenceResolver(SourceFileResolver.Default) .WithXmlReferenceResolver(XmlFileResolver.Default) .WithMetadataReferenceResolver(new AssemblyReferenceResolver(MetadataFileReferenceResolver.Default, MetadataFileReferenceProvider.Default)) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (language == LanguageNames.VisualBasic) { compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace) .WithGlobalImports(globalImports); } return compilationOptions; } private static TestHostDocument CreateDocument( TestWorkspace workspace, XElement workspaceElement, XElement documentElement, string language, ExportProvider exportProvider, HostLanguageServices languageServiceProvider, Dictionary<string, ITextBuffer> filePathToTextBufferMap, ref int documentId) { string markupCode; string filePath; var isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName); bool isLinkFile = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value; if (isLinkFile) { // This is a linked file. Use the filePath and markup from the referenced document. var originalProjectName = documentElement.Attribute(LinkAssemblyNameAttributeName); var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName); if (originalProjectName == null || originalDocumentPath == null) { throw new ArgumentException("Linked file specified without LinkAssemblyName or LinkFilePath."); } var originalProjectNameStr = originalProjectName.Value; var originalDocumentPathStr = originalDocumentPath.Value; var originalProject = workspaceElement.Elements(ProjectElementName).First(p => { var assemblyName = p.Attribute(AssemblyNameAttributeName); return assemblyName != null && assemblyName.Value == originalProjectNameStr; }); if (originalProject == null) { throw new ArgumentException("Linked file's LinkAssemblyName '{0}' project not found.", originalProjectNameStr); } var originalDocument = originalProject.Elements(DocumentElementName).First(d => { var documentPath = d.Attribute(FilePathAttributeName); return documentPath != null && documentPath.Value == originalDocumentPathStr; }); if (originalDocument == null) { throw new ArgumentException("Linked file's LinkFilePath '{0}' file not found.", originalDocumentPathStr); } markupCode = originalDocument.NormalizedValue(); filePath = GetFilePath(workspace, originalDocument, ref documentId); } else { markupCode = documentElement.NormalizedValue(); filePath = GetFilePath(workspace, documentElement, ref documentId); } var folders = GetFolders(documentElement); var optionsElement = documentElement.Element(ParseOptionsElementName); // TODO: Allow these to be specified. var codeKind = SourceCodeKind.Regular; if (optionsElement != null) { var attr = optionsElement.Attribute(KindAttributeName); codeKind = attr == null ? SourceCodeKind.Regular : (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value); } var contentTypeLanguageService = languageServiceProvider.GetService<IContentTypeLanguageService>(); var contentType = contentTypeLanguageService.GetDefaultContentType(); string code; int? cursorPosition; IDictionary<string, IList<TextSpan>> spans; MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans); // For linked files, use the same ITextBuffer for all linked documents ITextBuffer textBuffer; if (!filePathToTextBufferMap.TryGetValue(filePath, out textBuffer)) { textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code); filePathToTextBufferMap.Add(filePath, textBuffer); } return new TestHostDocument(exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile); } private static string GetFilePath( TestWorkspace workspace, XElement documentElement, ref int documentId) { var filePathAttribute = documentElement.Attribute(FilePathAttributeName); if (filePathAttribute != null) { return filePathAttribute.Value; } var language = GetLanguage(workspace, documentElement.Ancestors(ProjectElementName).Single()); documentId++; var name = "Test" + documentId; return language == LanguageNames.CSharp ? name + ".cs" : name + ".vb"; } private static IReadOnlyList<string> GetFolders(XElement documentElement) { var folderAttribute = documentElement.Attribute(FoldersAttributeName); if (folderAttribute == null) { return null; } var folderContainers = folderAttribute.Value.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); return new ReadOnlyCollection<string>(folderContainers.ToList()); } /// <summary> /// Takes completely valid code, compiles it, and emits it to a MetadataReference without using /// the file system /// </summary> private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace workspace, XElement referencedSource) { var compilation = CreateCompilation(workspace, referencedSource); var aliasElement = referencedSource.Attribute("Aliases") != null ? referencedSource.Attribute("Aliases").Value : null; var aliases = aliasElement != null ? aliasElement.Split(',').Select(s => s.Trim()).ToImmutableArray() : default(ImmutableArray<string>); bool includeXmlDocComments = false; var includeXmlDocCommentsAttribute = referencedSource.Attribute(IncludeXmlDocCommentsAttributeName); if (includeXmlDocCommentsAttribute != null && ((bool?)includeXmlDocCommentsAttribute).HasValue && ((bool?)includeXmlDocCommentsAttribute).Value) { includeXmlDocComments = true; } return MetadataReference.CreateFromImage(compilation.EmitToArray(), new MetadataReferenceProperties(aliases: aliases), includeXmlDocComments ? new DeferredDocumentationProvider(compilation) : null); } private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource) { string languageName = GetLanguage(workspace, referencedSource); string assemblyName = "ReferencedAssembly"; var assemblyNameAttribute = referencedSource.Attribute(AssemblyNameAttributeName); if (assemblyNameAttribute != null) { assemblyName = assemblyNameAttribute.Value; } var languageServices = workspace.Services.GetLanguageServices(languageName); var compilationFactory = languageServices.GetService<ICompilationFactoryService>(); var options = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var compilation = compilationFactory.CreateCompilation(assemblyName, options); var documentElements = referencedSource.Elements(DocumentElementName).ToList(); foreach (var documentElement in documentElements) { compilation = compilation.AddSyntaxTrees(CreateSyntaxTree(languageName, documentElement.Value)); } foreach (var reference in CreateReferenceList(workspace, referencedSource)) { compilation = compilation.AddReferences(reference); } return compilation; } private static SyntaxTree CreateSyntaxTree(string languageName, string referencedCode) { if (LanguageNames.CSharp == languageName) { return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(referencedCode); } else { return Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(referencedCode); } } private static IList<MetadataReference> CreateReferenceList(TestWorkspace workspace, XElement element) { var references = CreateCommonReferences(workspace, element); foreach (var reference in element.Elements(MetadataReferenceElementName)) { references.Add(MetadataReference.CreateFromFile(reference.Value)); } foreach (var metadataReferenceFromSource in element.Elements(MetadataReferenceFromSourceElementName)) { references.Add(CreateMetadataReferenceFromSource(workspace, metadataReferenceFromSource)); } return references; } private static IList<AnalyzerReference> CreateAnalyzerList(TestWorkspace workspace, XElement projectElement) { var analyzers = new List<AnalyzerReference>(); foreach (var analyzer in projectElement.Elements(AnalyzerElementName)) { analyzers.Add( new AnalyzerImageReference( ImmutableArray<DiagnosticAnalyzer>.Empty, display: (string)analyzer.Attribute(AnalyzerDisplayAttributeName), fullPath: (string)analyzer.Attribute(AnalyzerFullPathAttributeName))); } return analyzers; } private static IList<MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element) { var references = new List<MetadataReference>(); var net45 = element.Attribute(CommonReferencesNet45AttributeName); if (net45 != null && ((bool?)net45).HasValue && ((bool?)net45).Value) { references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName); if (commonReferencesAttribute != null && ((bool?)commonReferencesAttribute).HasValue && ((bool?)commonReferencesAttribute).Value) { references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var winRT = element.Attribute(CommonReferencesWinRTAttributeName); if (winRT != null && ((bool?)winRT).HasValue && ((bool?)winRT).Value) { references = new List<MetadataReference>(TestBase.WinRtRefs.Length); references.AddRange(TestBase.WinRtRefs); if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var portable = element.Attribute(CommonReferencesPortableAttributeName); if (portable != null && ((bool?)portable).HasValue && ((bool?)portable).Value) { references = new List<MetadataReference>(TestBase.PortableRefsMinimal.Length); references.AddRange(TestBase.PortableRefsMinimal); } var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName); if (systemRuntimeFacade != null && ((bool?)systemRuntimeFacade).HasValue && ((bool?)systemRuntimeFacade).Value) { references.Add(TestBase.SystemRuntimeFacadeRef); } return references; } } }
using System; using System.CodeDom; using System.Xml; using System.Collections; using Stetic.Editor; namespace Stetic.Wrapper { public class ActionToolbarWrapper: Container { ActionTree actionTree; XmlElement toolbarInfo; ToolbarStyle toolbarStyle; bool treeChanged; static Gtk.ToolbarStyle defaultStyle; static bool gotDefault; public enum ToolbarStyle { Icons, Text, Both, BothHoriz, Default } public ActionToolbarWrapper() { } public override void Dispose () { DisposeTree (); base.Dispose (); } public static new Gtk.Toolbar CreateInstance () { ActionToolbar t = new ActionToolbar (); return t; } ActionToolbar toolbar { get { return (ActionToolbar) Wrapped; } } protected override bool AllowPlaceholders { get { return false; } } public override void Wrap (object obj, bool initialized) { base.Wrap (obj, initialized); CreateTree (); toolbar.FillMenu (actionTree); } public override bool HExpandable { get { return toolbar.Orientation == Gtk.Orientation.Horizontal; } } public override bool VExpandable { get { return toolbar.Orientation == Gtk.Orientation.Vertical; } } public Gtk.Orientation Orientation { get { return toolbar.Orientation; } set { toolbar.Orientation = value; EmitContentsChanged (); } } public Gtk.IconSize IconSize { get { return toolbar.IconSize; } set { toolbar.IconSize = value; EmitNotify ("IconSize"); } } public ToolbarStyle ButtonStyle { get { return toolbarStyle; } set { toolbarStyle = value; if (value == ToolbarStyle.Default) { if (!gotDefault) { // Is there a better way of getting the default? Gtk.Window d = new Gtk.Window (""); Gtk.Toolbar t = new Gtk.Toolbar (); d.Add (t); defaultStyle = t.ToolbarStyle; d.Destroy (); } toolbar.ToolbarStyle = defaultStyle; } else { toolbar.ToolbarStyle = (Gtk.ToolbarStyle) ((int)value); } EmitNotify ("ButtonStyle"); } } internal protected override void OnSelected () { Loading = true; toolbar.ShowInsertPlaceholder = true; Loading = false; } internal protected override void OnUnselected () { base.OnUnselected (); Loading = true; toolbar.ShowInsertPlaceholder = false; toolbar.Unselect (); Loading = false; } protected override XmlElement WriteProperties (ObjectWriter writer) { XmlElement elem = base.WriteProperties (writer); if (writer.Format == FileFormat.Native) { // The style is already stored in ButtonStyle GladeUtils.ExtractProperty (elem, "ToolbarStyle", ""); if (toolbarInfo != null) elem.AppendChild (writer.XmlDocument.ImportNode (toolbarInfo, true)); else elem.AppendChild (actionTree.Write (writer.XmlDocument, writer.Format)); } return elem; } protected override void ReadProperties (ObjectReader reader, XmlElement elem) { base.ReadProperties (reader, elem); toolbarInfo = elem ["node"]; } protected override void OnNameChanged (WidgetNameChangedArgs args) { base.OnNameChanged (args); if (actionTree != null) actionTree.Name = Wrapped.Name; } internal protected override CodeExpression GenerateObjectCreation (GeneratorContext ctx) { BuildTree (); actionTree.Type = Gtk.UIManagerItemType.Toolbar; actionTree.Name = Wrapped.Name; CodeExpression exp = GenerateUiManagerElement (ctx, actionTree); if (exp != null) return new CodeCastExpression (typeof(Gtk.Toolbar), exp); else return base.GenerateObjectCreation (ctx); } protected override void GeneratePropertySet (GeneratorContext ctx, CodeExpression var, PropertyDescriptor prop) { if (toolbarStyle == ToolbarStyle.Default && prop.Name == "ToolbarStyle") return; else base.GeneratePropertySet (ctx, var, prop); } internal protected override void OnDesignerAttach (IDesignArea designer) { base.OnDesignerAttach (designer); BuildTree (); Loading = true; toolbar.FillMenu (actionTree); Loading = false; if (LocalActionGroups.Count == 0) LocalActionGroups.Add (new ActionGroup ("Default")); } protected override void EmitNotify (string propertyName) { base.EmitNotify (propertyName); toolbar.FillMenu (actionTree); } public override object GetUndoDiff () { XmlElement oldElem = treeChanged ? UndoManager.GetObjectStatus (this) ["node"] : null; if (oldElem != null) oldElem = (XmlElement) oldElem.CloneNode (true); treeChanged = false; object baseDiff = base.GetUndoDiff (); if (oldElem != null) { XmlElement newElem = UndoManager.GetObjectStatus (this) ["node"]; if (newElem != null && oldElem.OuterXml == newElem.OuterXml) oldElem = null; } if (baseDiff == null && oldElem == null) return null; else { object stat = toolbar.SaveStatus (); return new object[] { baseDiff, oldElem, stat }; } } public override object ApplyUndoRedoDiff (object diff) { object[] data = (object[]) diff; object retBaseDiff; XmlElement oldNode = null; if (actionTree != null) { XmlElement status = UndoManager.GetObjectStatus (this); oldNode = status ["node"]; if (oldNode != null) oldNode = (XmlElement) oldNode.CloneNode (true); } object oldStat = toolbar.SaveStatus (); if (data [0] != null) retBaseDiff = base.ApplyUndoRedoDiff (data [0]); else retBaseDiff = null; XmlElement xdiff = (XmlElement) data [1]; if (xdiff != null) { XmlElement status = UndoManager.GetObjectStatus (this); XmlElement prevNode = status ["node"]; if (prevNode != null) status.RemoveChild (prevNode); status.AppendChild (xdiff); if (actionTree != null) { Loading = true; DisposeTree (); CreateTree (); actionTree.Read (this, xdiff); toolbar.FillMenu (actionTree); Loading = false; } } // Restore the status after all menu structure has been properly built GLib.Timeout.Add (50, delegate { toolbar.RestoreStatus (data[2]); return false; }); return new object [] { retBaseDiff, oldNode, oldStat }; } void BuildTree () { if (toolbarInfo != null) { DisposeTree (); CreateTree (); actionTree.Read (this, toolbarInfo); toolbarInfo = null; } } void CreateTree () { actionTree = new ActionTree (); actionTree.Name = Wrapped.Name; actionTree.Type = Gtk.UIManagerItemType.Toolbar; actionTree.Changed += OnTreeChanged; } void DisposeTree () { if (actionTree != null) { actionTree.Dispose (); actionTree.Changed -= OnTreeChanged; actionTree = null; } } void OnTreeChanged (object s, EventArgs a) { treeChanged = true; NotifyChanged (); } } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 2.3.1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IRetrieveAllSignedDeedsApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Retrieves ALL-SIGNED deed(s). /// </summary> /// <remarks> /// The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>string</returns> string DeedRetrieveSignedGet (); /// <summary> /// Retrieves ALL-SIGNED deed(s). /// </summary> /// <remarks> /// The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of string</returns> ApiResponse<string> DeedRetrieveSignedGetWithHttpInfo (); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Retrieves ALL-SIGNED deed(s). /// </summary> /// <remarks> /// The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> DeedRetrieveSignedGetAsync (); /// <summary> /// Retrieves ALL-SIGNED deed(s). /// </summary> /// <remarks> /// The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> DeedRetrieveSignedGetAsyncWithHttpInfo (); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class RetrieveAllSignedDeedsApi : IRetrieveAllSignedDeedsApi { private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="RetrieveAllSignedDeedsApi"/> class. /// </summary> /// <returns></returns> public RetrieveAllSignedDeedsApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // 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="RetrieveAllSignedDeedsApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public RetrieveAllSignedDeedsApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // 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 'Configuration.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> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Swagger.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <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> /// Retrieves ALL-SIGNED deed(s). The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>string</returns> public string DeedRetrieveSignedGet () { ApiResponse<string> localVarResponse = DeedRetrieveSignedGetWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Retrieves ALL-SIGNED deed(s). The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of string</returns> public ApiResponse< string > DeedRetrieveSignedGetWithHttpInfo () { var localVarPath = "/deed/retrieve-signed"; 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[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; 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"); // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeedRetrieveSignedGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } /// <summary> /// Retrieves ALL-SIGNED deed(s). The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> DeedRetrieveSignedGetAsync () { ApiResponse<string> localVarResponse = await DeedRetrieveSignedGetAsyncWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Retrieves ALL-SIGNED deed(s). The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<ApiResponse<string>> DeedRetrieveSignedGetAsyncWithHttpInfo () { var localVarPath = "/deed/retrieve-signed"; 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[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; 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"); // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeedRetrieveSignedGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } } }
/* ==================================================================== 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 TestCases.HSSF.Record { using System; using NUnit.Framework; using NPOI.HSSF.Record; using NPOI.HSSF.UserModel; using NPOI.SS; using NPOI.SS.Formula; using NPOI.SS.Formula.PTG; using NPOI.SS.UserModel; using NPOI.Util; using TestCases.Exceptions; using TestCases.HSSF; using TestCases.HSSF.UserModel; /** * @author Josh Micich */ [TestFixture] public class TestSharedFormulaRecord { /** * A sample spreadsheet known to have one sheet with 4 shared formula ranges */ private static String SHARED_FORMULA_TEST_XLS = "SharedFormulaTest.xls"; /** * Binary data for an encoded formula. Taken from attachment 22062 (bugzilla 45123/45421). * The shared formula is in Sheet1!C6:C21, with text "SUMPRODUCT(--(End_Acct=$C6),--(End_Bal))" * This data is found at offset 0x1A4A (within the shared formula record). * The critical thing about this formula is that it Contains shared formula tokens (tRefN*, * tAreaN*) with operand class 'array'. */ private static byte[] SHARED_FORMULA_WITH_REF_ARRAYS_DATA = { 0x1A, 0x00, 0x63, 0x02, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x02, (byte)0x80, // tRefNA 0x0B, 0x15, 0x13, 0x13, 0x63, 0x03, 0x00, 0x00, 0x00, 0x15, 0x13, 0x13, 0x42, 0x02, (byte)0xE4, 0x00, }; /** * The method <tt>SharedFormulaRecord.ConvertSharedFormulas()</tt> Converts formulas from * 'shared formula' to 'single cell formula' format. It is important that token operand * classes are preserved during this transformation, because Excel may not tolerate the * incorrect encoding. The formula here is one such example (Excel displays #VALUE!). */ [Test] public void TestConvertSharedFormulasOperandClasses_bug45123() { ILittleEndianInput in1 = TestcaseRecordInputStream.CreateLittleEndian(SHARED_FORMULA_WITH_REF_ARRAYS_DATA); int encodedLen = in1.ReadUShort(); Ptg[] sharedFormula = Ptg.ReadTokens(encodedLen, in1); SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97); Ptg[] ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 100, 200); RefPtg refPtg = (RefPtg)ConvertedFormula[1]; Assert.AreEqual("$C101", refPtg.ToFormulaString()); if (refPtg.PtgClass == Ptg.CLASS_REF) { throw new AssertionException("Identified bug 45123"); } ConfirmOperandClasses(sharedFormula, ConvertedFormula); } private static void ConfirmOperandClasses(Ptg[] originalPtgs, Ptg[] convertedPtg) { Assert.AreEqual(originalPtgs.Length, convertedPtg.Length); for (int i = 0; i < convertedPtg.Length; i++) { Ptg originalPtg = originalPtgs[i]; Ptg ConvertedPtg = convertedPtg[i]; if (originalPtg.PtgClass != ConvertedPtg.PtgClass) { throw new ComparisonFailure("Different operand class for token[" + i + "]", originalPtg.PtgClass.ToString(), ConvertedPtg.PtgClass.ToString()); } } } [Test] public void TestConvertSharedFormulas() { IWorkbook wb = new HSSFWorkbook(); HSSFEvaluationWorkbook fpb = HSSFEvaluationWorkbook.Create(wb); Ptg[] sharedFormula, ConvertedFormula; SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97); sharedFormula = FormulaParser.Parse("A2", fpb, FormulaType.Cell, -1, -1); ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 0, 0); ConfirmOperandClasses(sharedFormula, ConvertedFormula); //conversion relative to [0,0] should return the original formula Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "A2"); ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 0); ConfirmOperandClasses(sharedFormula, ConvertedFormula); //one row down Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "A3"); ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 1); ConfirmOperandClasses(sharedFormula, ConvertedFormula); //one row down and one cell right Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "B3"); sharedFormula = FormulaParser.Parse("SUM(A1:C1)", fpb, FormulaType.Cell, -1, -1); ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 0, 0); ConfirmOperandClasses(sharedFormula, ConvertedFormula); Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(A1:C1)"); ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 0); ConfirmOperandClasses(sharedFormula, ConvertedFormula); Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(A2:C2)"); ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 1); ConfirmOperandClasses(sharedFormula, ConvertedFormula); Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(B2:D2)"); } /** * Make sure that POI preserves {@link SharedFormulaRecord}s */ [Test] public void TestPreserveOnReSerialize() { HSSFWorkbook wb; ISheet sheet; ICell cellB32769; ICell cellC32769; // Reading directly from XLS file wb = HSSFTestDataSamples.OpenSampleWorkbook(SHARED_FORMULA_TEST_XLS); sheet = wb.GetSheetAt(0); cellB32769 = sheet.GetRow(32768).GetCell(1); cellC32769 = sheet.GetRow(32768).GetCell(2); // check Reading of formulas which are shared (two cells from a 1R x 8C range) Assert.AreEqual("B32770*2", cellB32769.CellFormula); Assert.AreEqual("C32770*2", cellC32769.CellFormula); ConfirmCellEvaluation(wb, cellB32769, 4); ConfirmCellEvaluation(wb, cellC32769, 6); // Confirm this example really does have SharedFormulas. // there are 3 others besides the one at A32769:H32769 Assert.AreEqual(4, countSharedFormulas(sheet)); // Re-serialize and check again wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); cellB32769 = sheet.GetRow(32768).GetCell(1); cellC32769 = sheet.GetRow(32768).GetCell(2); Assert.AreEqual("B32770*2", cellB32769.CellFormula); ConfirmCellEvaluation(wb, cellB32769, 4); Assert.AreEqual(4, countSharedFormulas(sheet)); } [Test] public void TestUnshareFormulaDueToChangeFormula() { HSSFWorkbook wb; ISheet sheet; ICell cellB32769; ICell cellC32769; wb = HSSFTestDataSamples.OpenSampleWorkbook(SHARED_FORMULA_TEST_XLS); sheet = wb.GetSheetAt(0); cellB32769 = sheet.GetRow(32768).GetCell(1); cellC32769 = sheet.GetRow(32768).GetCell(2); // Updating cell formula, causing it to become unshared cellB32769.CellFormula = (/*setter*/"1+1"); ConfirmCellEvaluation(wb, cellB32769, 2); // currently (Oct 2008) POI handles this by exploding the whole shared formula group Assert.AreEqual(3, countSharedFormulas(sheet)); // one less now // check that nearby cell of the same group still has the same formula Assert.AreEqual("C32770*2", cellC32769.CellFormula); ConfirmCellEvaluation(wb, cellC32769, 6); } [Test] public void TestUnshareFormulaDueToDelete() { HSSFWorkbook wb; ISheet sheet; ICell cell; int ROW_IX = 2; // changing shared formula cell to blank wb = HSSFTestDataSamples.OpenSampleWorkbook(SHARED_FORMULA_TEST_XLS); sheet = wb.GetSheetAt(0); Assert.AreEqual("A$1*2", sheet.GetRow(ROW_IX).GetCell(1).CellFormula); cell = sheet.GetRow(ROW_IX).GetCell(1); cell.SetCellType(CellType.Blank); Assert.AreEqual(3, countSharedFormulas(sheet)); wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); Assert.AreEqual("A$1*2", sheet.GetRow(ROW_IX + 1).GetCell(1).CellFormula); // deleting shared formula cell wb = HSSFTestDataSamples.OpenSampleWorkbook(SHARED_FORMULA_TEST_XLS); sheet = wb.GetSheetAt(0); Assert.AreEqual("A$1*2", sheet.GetRow(ROW_IX).GetCell(1).CellFormula); cell = sheet.GetRow(ROW_IX).GetCell(1); sheet.GetRow(ROW_IX).RemoveCell(cell); Assert.AreEqual(3, countSharedFormulas(sheet)); wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); Assert.AreEqual("A$1*2", sheet.GetRow(ROW_IX + 1).GetCell(1).CellFormula); } private static void ConfirmCellEvaluation(IWorkbook wb, ICell cell, double expectedValue) { HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); CellValue cv = fe.Evaluate(cell); Assert.AreEqual(CellType.Numeric, cv.CellType); Assert.AreEqual(expectedValue, cv.NumberValue, 0.0); } /** * @return the number of {@link SharedFormulaRecord}s encoded for the specified sheet */ private static int countSharedFormulas(ISheet sheet) { NPOI.HSSF.Record.Record[] records = RecordInspector.GetRecords(sheet, 0); int count = 0; for (int i = 0; i < records.Length; i++) { NPOI.HSSF.Record.Record rec = records[i]; if (rec is SharedFormulaRecord) { count++; } } return count; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using System.Diagnostics; namespace System.Collections.Generic { [TypeDependency("System.Collections.Generic.ObjectEqualityComparer`1")] public abstract partial class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T> { // To minimize generic instantiation overhead of creating the comparer per type, we keep the generic portion of the code as small // as possible and define most of the creation logic in a non-generic class. public static EqualityComparer<T> Default { [Intrinsic] get; } = (EqualityComparer<T>)ComparerHelpers.CreateDefaultEqualityComparer(typeof(T)); internal virtual int IndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { if (Equals(array[i], value)) return i; } return -1; } internal virtual int LastIndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex - count + 1; for (int i = startIndex; i >= endIndex; i--) { if (Equals(array[i], value)) return i; } return -1; } } public sealed partial class GenericEqualityComparer<T> : EqualityComparer<T> #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { internal override int IndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex + count; if (value == null) { for (int i = startIndex; i < endIndex; i++) { if (array[i] == null) return i; } } else { for (int i = startIndex; i < endIndex; i++) { if (array[i] != null && array[i].Equals(value)) return i; } } return -1; } internal override int LastIndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex - count + 1; if (value == null) { for (int i = startIndex; i >= endIndex; i--) { if (array[i] == null) return i; } } else { for (int i = startIndex; i >= endIndex; i--) { if (array[i] != null && array[i].Equals(value)) return i; } } return -1; } } public sealed partial class NullableEqualityComparer<T> : EqualityComparer<T?> where T : struct, #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant IEquatable<T> #nullable restore { internal override int IndexOf(T?[] array, T? value, int startIndex, int count) { int endIndex = startIndex + count; if (!value.HasValue) { for (int i = startIndex; i < endIndex; i++) { if (!array[i].HasValue) return i; } } else { for (int i = startIndex; i < endIndex; i++) { if (array[i].HasValue && array[i].value.Equals(value.value)) return i; } } return -1; } internal override int LastIndexOf(T?[] array, T? value, int startIndex, int count) { int endIndex = startIndex - count + 1; if (!value.HasValue) { for (int i = startIndex; i >= endIndex; i--) { if (!array[i].HasValue) return i; } } else { for (int i = startIndex; i >= endIndex; i--) { if (array[i].HasValue && array[i].value.Equals(value.value)) return i; } } return -1; } } public sealed partial class ObjectEqualityComparer<T> : EqualityComparer<T> { internal override int IndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex + count; if (value == null) { for (int i = startIndex; i < endIndex; i++) { if (array[i] == null) return i; } } else { for (int i = startIndex; i < endIndex; i++) { if (array[i] != null && array[i]!.Equals(value)) return i; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } } return -1; } internal override int LastIndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex - count + 1; if (value == null) { for (int i = startIndex; i >= endIndex; i--) { if (array[i] == null) return i; } } else { for (int i = startIndex; i >= endIndex; i--) { if (array[i] != null && array[i]!.Equals(value)) return i; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } } return -1; } } public sealed partial class ByteEqualityComparer : EqualityComparer<byte> { #if DEBUG internal override int IndexOf(byte[] array, byte value, int startIndex, int count) { Debug.Fail("Should not get here."); return -1; } internal override int LastIndexOf(byte[] array, byte value, int startIndex, int count) { Debug.Fail("Should not get here."); return -1; } #endif } public sealed partial class EnumEqualityComparer<T> : EqualityComparer<T> where T : struct, Enum { [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(T x, T y) { return System.Runtime.CompilerServices.RuntimeHelpers.EnumEquals(x, y); } internal override int IndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { if (System.Runtime.CompilerServices.RuntimeHelpers.EnumEquals(array[i], value)) return i; } return -1; } internal override int LastIndexOf(T[] array, T value, int startIndex, int count) { int endIndex = startIndex - count + 1; for (int i = startIndex; i >= endIndex; i--) { if (System.Runtime.CompilerServices.RuntimeHelpers.EnumEquals(array[i], value)) return i; } return -1; } } }
using J2N.Text; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Standard; using Lucene.Net.Attributes; using Lucene.Net.Documents.Extensions; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Util; using NUnit.Framework; using System; using System.IO; using System.Text; using Assert = Lucene.Net.TestFramework.Assert; using Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Documents { /* * 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 CannedTokenStream = Lucene.Net.Analysis.CannedTokenStream; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using Token = Lucene.Net.Analysis.Token; // sanity check some basics of fields [TestFixture] public class TestField : LuceneTestCase { [Test] public virtual void TestDoubleField() { Field[] fields = new Field[] { new DoubleField("foo", 5d, Field.Store.NO), new DoubleField("foo", 5d, Field.Store.YES) }; foreach (Field field in fields) { TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); field.SetDoubleValue(6d); // ok TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(6d, field.GetDoubleValue().Value, 0.0d); } } [Test] public virtual void TestDoubleDocValuesField() { DoubleDocValuesField field = new DoubleDocValuesField("foo", 5d); TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); field.SetDoubleValue(6d); // ok TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(6d, J2N.BitConversion.Int64BitsToDouble(field.GetInt64Value().Value), 0.0d); } [Test] public virtual void TestFloatDocValuesField() { SingleDocValuesField field = new SingleDocValuesField("foo", 5f); TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); field.SetSingleValue(6f); // ok TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(6f, J2N.BitConversion.Int32BitsToSingle(field.GetInt32Value().Value), 0.0f); } [Test] public virtual void TestFloatField() { Field[] fields = new Field[] { new SingleField("foo", 5f, Field.Store.NO), new SingleField("foo", 5f, Field.Store.YES) }; foreach (Field field in fields) { TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); field.SetSingleValue(6f); // ok TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(6f, field.GetSingleValue().Value, 0.0f); } } [Test] public virtual void TestIntField() { Field[] fields = new Field[] { new Int32Field("foo", 5, Field.Store.NO), new Int32Field("foo", 5, Field.Store.YES) }; foreach (Field field in fields) { TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); field.SetInt32Value(6); // ok TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(6, field.GetInt32Value().Value); } } [Test] public virtual void TestNumericDocValuesField() { NumericDocValuesField field = new NumericDocValuesField("foo", 5L); TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); field.SetInt64Value(6); // ok TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(6L, field.GetInt64Value().Value); } [Test] public virtual void TestLongField() { Field[] fields = new Field[] { new Int64Field("foo", 5L, Field.Store.NO), new Int64Field("foo", 5L, Field.Store.YES) }; foreach (Field field in fields) { TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); field.SetInt64Value(6); // ok TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(6L, field.GetInt64Value().Value); } } [Test] public virtual void TestSortedBytesDocValuesField() { SortedDocValuesField field = new SortedDocValuesField("foo", new BytesRef("bar")); TrySetBoost(field); TrySetByteValue(field); field.SetBytesValue("fubar".GetBytes(Encoding.UTF8)); field.SetBytesValue(new BytesRef("baz")); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(new BytesRef("baz"), field.GetBinaryValue()); } [Test] public virtual void TestBinaryDocValuesField() { BinaryDocValuesField field = new BinaryDocValuesField("foo", new BytesRef("bar")); TrySetBoost(field); TrySetByteValue(field); field.SetBytesValue("fubar".GetBytes(Encoding.UTF8)); field.SetBytesValue(new BytesRef("baz")); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(new BytesRef("baz"), field.GetBinaryValue()); } [Test] public virtual void TestStringField() { Field[] fields = new Field[] { new StringField("foo", "bar", Field.Store.NO), new StringField("foo", "bar", Field.Store.YES) }; foreach (Field field in fields) { TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); field.SetStringValue("baz"); TrySetTokenStreamValue(field); Assert.AreEqual("baz", field.GetStringValue()); } } [Test] public virtual void TestTextFieldString() { Field[] fields = new Field[] { new TextField("foo", "bar", Field.Store.NO), new TextField("foo", "bar", Field.Store.YES) }; foreach (Field field in fields) { field.Boost = 5f; TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); field.SetStringValue("baz"); field.SetTokenStream(new CannedTokenStream(new Token("foo", 0, 3))); Assert.AreEqual("baz", field.GetStringValue()); Assert.AreEqual(5f, field.Boost, 0f); } } [Test] public virtual void TestTextFieldReader() { Field field = new TextField("foo", new StringReader("bar")); field.Boost = 5f; TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); field.SetReaderValue(new StringReader("foobar")); TrySetShortValue(field); TrySetStringValue(field); field.SetTokenStream(new CannedTokenStream(new Token("foo", 0, 3))); Assert.IsNotNull(field.GetReaderValue()); Assert.AreEqual(5f, field.Boost, 0f); } /* TODO: this is pretty expert and crazy * see if we can fix it up later public void testTextFieldTokenStream() throws Exception { } */ [Test] public virtual void TestStoredFieldBytes() { Field[] fields = new Field[] { new StoredField("foo", "bar".GetBytes(Encoding.UTF8)), new StoredField("foo", "bar".GetBytes(Encoding.UTF8), 0, 3), new StoredField("foo", new BytesRef("bar")) }; foreach (Field field in fields) { TrySetBoost(field); TrySetByteValue(field); field.SetBytesValue("baz".GetBytes(Encoding.UTF8)); field.SetBytesValue(new BytesRef("baz")); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(new BytesRef("baz"), field.GetBinaryValue()); } } [Test] public virtual void TestStoredFieldString() { Field field = new StoredField("foo", "bar"); TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); field.SetStringValue("baz"); TrySetTokenStreamValue(field); Assert.AreEqual("baz", field.GetStringValue()); } [Test] public virtual void TestStoredFieldInt() { Field field = new StoredField("foo", 1); TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); field.SetInt32Value(5); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(5, field.GetInt32Value()); } [Test] public virtual void TestStoredFieldDouble() { Field field = new StoredField("foo", 1D); TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); field.SetDoubleValue(5D); TrySetIntValue(field); TrySetFloatValue(field); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(5D, field.GetDoubleValue().Value, 0.0D); } [Test] public virtual void TestStoredFieldFloat() { Field field = new StoredField("foo", 1F); TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); field.SetSingleValue(5f); TrySetLongValue(field); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(5f, field.GetSingleValue().Value, 0.0f); } [Test] public virtual void TestStoredFieldLong() { Field field = new StoredField("foo", 1L); TrySetBoost(field); TrySetByteValue(field); TrySetBytesValue(field); TrySetBytesRefValue(field); TrySetDoubleValue(field); TrySetIntValue(field); TrySetFloatValue(field); field.SetInt64Value(5); TrySetReaderValue(field); TrySetShortValue(field); TrySetStringValue(field); TrySetTokenStreamValue(field); Assert.AreEqual(5L, field.GetInt64Value().Value); } private void TrySetByteValue(Field f) { try { f.SetByteValue((byte)10); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetBytesValue(Field f) { try { f.SetBytesValue(new byte[] { 5, 5 }); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetBytesRefValue(Field f) { try { f.SetBytesValue(new BytesRef("bogus")); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetDoubleValue(Field f) { try { f.SetDoubleValue(double.MaxValue); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetIntValue(Field f) { try { f.SetInt32Value(int.MaxValue); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetLongValue(Field f) { try { f.SetInt64Value(long.MaxValue); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetFloatValue(Field f) { try { f.SetSingleValue(float.MaxValue); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetReaderValue(Field f) { try { f.SetReaderValue(new StringReader("BOO!")); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetShortValue(Field f) { try { f.SetInt16Value(short.MaxValue); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetStringValue(Field f) { try { f.SetStringValue("BOO!"); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetTokenStreamValue(Field f) { try { f.SetTokenStream(new CannedTokenStream(new Token("foo", 0, 3))); Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } private void TrySetBoost(Field f) { try { f.Boost = 5.0f; Assert.Fail(); } #pragma warning disable 168 catch (ArgumentException expected) #pragma warning restore 168 { // expected } } // Possible issue reported via dev maling list: http://apache.markmail.org/search/?q=lucenenet+issue+with+doublefield#query:lucenenet%20issue%20with%20doublefield+page:1+mid:4ewxqrsg2nl3en5d+state:results // As it turns out this is the correct behavior, as confirmed in Lucene using the following tests [Test, LuceneNetSpecific] public void TestStoreAndRetrieveFieldType() { Directory dir = new RAMDirectory(); Analyzer analyzer = new StandardAnalyzer(LuceneVersion.LUCENE_48); IndexWriterConfig iwc = new IndexWriterConfig(LuceneVersion.LUCENE_48, analyzer); double value = double.MaxValue; string fieldName = "DoubleField"; FieldType type = new FieldType(); type.IsIndexed = true; type.IsStored = true; type.IsTokenized = false; type.NumericType = NumericType.DOUBLE; using (IndexWriter writer = new IndexWriter(dir, iwc)) { Document doc = new Document(); Field field = new DoubleField(fieldName, value, type); FieldType fieldType = field.FieldType; assertEquals(true, fieldType.IsIndexed); assertEquals(true, fieldType.IsStored); assertEquals(false, fieldType.IsTokenized); assertEquals(NumericType.DOUBLE, fieldType.NumericType); doc.Add(field); writer.AddDocument(doc); writer.Commit(); } using (IndexReader reader = DirectoryReader.Open(dir)) { IndexSearcher searcher = new IndexSearcher(reader); var hits = searcher.Search(new MatchAllDocsQuery(), 10).ScoreDocs; Document doc = searcher.Doc(hits[0].Doc); Field field = doc.GetField<Field>(fieldName); FieldType fieldType = field.FieldType; assertEquals(false, fieldType.IsIndexed); assertEquals(true, fieldType.IsStored); assertEquals(true, fieldType.IsTokenized); assertEquals(NumericType.NONE, fieldType.NumericType); } dir.Dispose(); } // In Java, the corresponding test is: //public void testStoreAndRetrieveFieldType() throws java.io.IOException //{ // org.apache.lucene.store.Directory dir = new org.apache.lucene.store.RAMDirectory(); // org.apache.lucene.analysis.Analyzer analyzer = new org.apache.lucene.analysis.standard.StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_48); // org.apache.lucene.index.IndexWriterConfig iwc = new org.apache.lucene.index.IndexWriterConfig(org.apache.lucene.util.Version.LUCENE_48, analyzer); // double value = Double.MAX_VALUE; // String fieldName = "DoubleField"; // FieldType type = new FieldType(); // type.setIndexed(true); // type.setStored(true); // type.setTokenized(false); // type.setNumericType(FieldType.NumericType.DOUBLE); // org.apache.lucene.index.IndexWriter writer = new org.apache.lucene.index.IndexWriter(dir, iwc); // { // Document doc = new Document(); // Field field = new DoubleField(fieldName, value, type); // FieldType fieldType = field.fieldType(); // assertEquals(true, fieldType.indexed()); // assertEquals(true, fieldType.stored()); // assertEquals(false, fieldType.tokenized()); // assertEquals(FieldType.NumericType.DOUBLE, fieldType.numericType()); // doc.add(field); // writer.addDocument(doc); // writer.commit(); // } // writer.close(); // org.apache.lucene.index.IndexReader reader = org.apache.lucene.index.DirectoryReader.open(dir); // { // org.apache.lucene.search.IndexSearcher searcher = new org.apache.lucene.search.IndexSearcher(reader); // org.apache.lucene.search.ScoreDoc[] hits = searcher.search(new org.apache.lucene.search.MatchAllDocsQuery(), 10).scoreDocs; // Document doc = searcher.doc(hits[0].doc); // Field field = (Field)doc.getField(fieldName); // FieldType fieldType = field.fieldType(); // assertEquals(false, fieldType.indexed()); // assertEquals(true, fieldType.stored()); // assertEquals(true, fieldType.tokenized()); // assertEquals(null, fieldType.numericType()); // } // reader.close(); // dir.close(); //} } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Windows.Forms; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.PostEditor.Video.VideoService; using OpenLiveWriter.PostEditor.Video.YouTube; namespace OpenLiveWriter.PostEditor.Video.VideoListBox { internal class VideoListBoxControl : ListBox { #region Private Members private VideoThumbNailManager _thumbnailManager; #endregion #region Initialization and Cleanup public void Initialize() { // set options for list box DrawMode = DrawMode.OwnerDrawFixed; SelectionMode = SelectionMode.One; HorizontalScrollbar = false; IntegralHeight = false; // create the thumbnail manager _thumbnailManager = new VideoThumbNailManager(this); _thumbnailManager.ThumbnailDownloadCompleted += _thumbnailManager_ThumbnailDownloadCompleted; } protected override void Dispose(bool disposing) { if (disposing) { if (_thumbnailManager != null) { _thumbnailManager.ThumbnailDownloadCompleted -= _thumbnailManager_ThumbnailDownloadCompleted; _thumbnailManager.Dispose(); } } base.Dispose(disposing); } #endregion #region Public Interface public void DisplayVideos(IVideo[] videos) { Items.Clear(); ItemHeight = CalculateItemHeight(); // clear all pending downloads _thumbnailManager.ClearPendingDownloads(); // initiate a download for each video foreach (IVideo video in videos) _thumbnailManager.DownloadThumbnail(video); // add the videos to the list foreach (IVideo video in videos) Items.Add(video); // update status text if (Items.Count == 0) DisplayNoVideosFound(); else QueryStatusText = null; } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string QueryStatusText { get { return QueryStatusLabel.Text; } set { if (value != null) { QueryStatusLabel.Text = value; QueryStatusLabel.Width = Width - 5; LayoutHelper.NaturalizeHeight(QueryStatusLabel); QueryStatusLabel.Left = Left + Width / 2 - QueryStatusLabel.Width / 2; QueryStatusLabel.Top = Top + (Height / 2); QueryStatusLabel.Visible = true; QueryStatusLabel.BringToFront(); QueryStatusLabel.Update(); } else { QueryStatusLabel.Text = String.Empty; QueryStatusLabel.Visible = false; QueryStatusLabel.SendToBack(); QueryStatusLabel.Update(); } } } public void DisplayGetVideosError() { QueryStatusText = Res.Get(StringId.VideoGetVideosError); } public void DisplayLoggingIn() { QueryStatusText = Res.Get(StringId.Plugin_Video_Soapbox_LoggingIn); } public void DisplayNoVideosFound() { QueryStatusText = Res.Get(StringId.Plugin_Video_Soapbox_None_Found); } public void DisplayWebError() { QueryStatusText = Res.Get(StringId.Plugin_Video_Soapbox_Web_Error); } public void DisplaySearchError() { QueryStatusText = Res.Get(StringId.Plugin_Video_Soapbox_Soap_Error); } #endregion #region Hyperlink Mouse Handling protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); Cursor = Cursors.Default; _preventSelectionPainting = false; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); _lastMouseLocation = new PointF(e.X, e.Y); if (MouseInHyperlink) { Cursor = Cursors.Hand; _preventSelectionPainting = true; } else { Cursor = Cursors.Default; _preventSelectionPainting = false; } } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); _preventSelectionPainting = false; } private bool MouseInHyperlink { get { return GetMouseOverVideo() != null; } } private IVideo GetMouseOverVideo() { // handle no videos displayed if (Items.Count == 0) return null; using (Graphics g = CreateGraphics()) { const int LEFT_MARGIN = HORIZONTAL_INSET + THUMBNAIL_IMAGE_WIDTH + HORIZONTAL_INSET; int maxItemsDisplayed = Height / ItemHeight; int itemsDisplayed = Math.Min(maxItemsDisplayed, Items.Count - TopIndex); for (int i = 0; i < itemsDisplayed; i++) { // get the current video IVideo currentVideo = Items[TopIndex + i] as IVideo; // see if the mouse lies in the video's title range PointF titleLocation = new Point(LEFT_MARGIN, (i * ItemHeight) + VERTICAL_INSET); SizeF titleSize = g.MeasureString(currentVideo.Title, Font, Width - Convert.ToInt32(titleLocation.X)); RectangleF titleRectangle = new RectangleF(titleLocation, titleSize); if (titleRectangle.Contains(_lastMouseLocation)) { return currentVideo; } }; // wasn't in hyperlink return null; } } private PointF _lastMouseLocation = Point.Empty; private bool _preventSelectionPainting = false; #endregion #region Painting protected override void OnDrawItem(DrawItemEventArgs e) { // screen invalid drawing states if (DesignMode || e.Index == -1) return; // get video we are rendering IVideo video = Items[e.Index] as IVideo; // determine state bool selected = ((e.State & DrawItemState.Selected) > 0) && !_preventSelectionPainting; // calculate colors Color textColor; if (selected) { if (Focused) { textColor = SystemColors.HighlightText; } else { textColor = SystemColors.ControlText; } } else { textColor = SystemColors.ControlText; } Color previewColor = Color.FromArgb(200, textColor); BidiGraphics g = new BidiGraphics(e.Graphics, e.Bounds); // setup standard string format TextFormatFlags ellipsesStringFormat = TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl | TextFormatFlags.ExpandTabs | TextFormatFlags.WordEllipsis; // draw background e.DrawBackground(); //using (SolidBrush solidBrush = new SolidBrush(backColor)) // g.FillRectangle(solidBrush, e.Bounds); // draw the thumbnail image Rectangle thumbnailRect = new Rectangle(e.Bounds.Left + ScaleX(HORIZONTAL_INSET), e.Bounds.Top + ScaleY(VERTICAL_INSET), THUMBNAIL_IMAGE_WIDTH, THUMBNAIL_IMAGE_HEIGHT); VideoThumbnail thumbnail = _thumbnailManager.GetThumbnail(video); thumbnail.Draw(g, e.Font, thumbnailRect); // calculate standard text drawing metrics int leftMargin = ScaleX(HORIZONTAL_INSET) + THUMBNAIL_IMAGE_WIDTH + ScaleX(HORIZONTAL_INSET); int topMargin = e.Bounds.Top + ScaleY(VERTICAL_INSET); int fontHeight = g.MeasureText(video.Title, e.Font).Height; // draw title and duration int titleWidth; Rectangle durationRectangle; using (Font hyperlinkFont = new Font(e.Font, FontStyle.Underline)) { titleWidth = e.Bounds.Right - ScaleX(HORIZONTAL_INSET) - leftMargin; Rectangle titleRectangle = new Rectangle(leftMargin, topMargin, titleWidth, fontHeight); string title = video.Title ?? ""; g.DrawText(title, hyperlinkFont, titleRectangle, selected ? textColor : SystemColors.HotTrack, ellipsesStringFormat); } using (Font durationFont = new Font(e.Font, FontStyle.Regular)) // was bold { durationRectangle = new Rectangle(leftMargin, topMargin + fontHeight + 3, titleWidth, fontHeight); string duration = String.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}", video.LengthSeconds / 60, video.LengthSeconds % 60); g.DrawText( duration, durationFont, durationRectangle, textColor, ellipsesStringFormat); } // draw description // calculate layout rectangle Rectangle layoutRectangle = new Rectangle( leftMargin, durationRectangle.Bottom + ScaleY(VERTICAL_INSET), e.Bounds.Width - leftMargin - ScaleX(HORIZONTAL_INSET), e.Bounds.Bottom - ScaleY(VERTICAL_INSET) - durationRectangle.Bottom - ScaleY(VERTICAL_INSET)); // draw description g.DrawText( video.Description, e.Font, layoutRectangle, previewColor, ellipsesStringFormat); // draw bottom-line if necessary if (!selected) { using (Pen pen = new Pen(SystemColors.ControlLight)) g.DrawLine(pen, e.Bounds.Left, e.Bounds.Bottom - ScaleY(1), e.Bounds.Right, e.Bounds.Bottom - ScaleY(1)); } // focus rectange if necessary e.DrawFocusRectangle(); } #region High DPI Scaling protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { SaveScale(factor.Width, factor.Height); base.ScaleControl(factor, specified); } protected override void ScaleCore(float dx, float dy) { SaveScale(dx, dy); base.ScaleCore(dx, dy); } private void SaveScale(float dx, float dy) { scale = new PointF(scale.X * dx, scale.Y * dy); } private PointF scale = new PointF(1f, 1f); protected int ScaleX(int x) { return (int)(x * scale.X); } protected int ScaleY(int y) { return (int)(y * scale.Y); } #endregion private int CalculateItemHeight() { return ScaleY(VERTICAL_INSET) + THUMBNAIL_IMAGE_HEIGHT + ScaleY(VERTICAL_INSET); } private void _thumbnailManager_ThumbnailDownloadCompleted(IVideo listBoxVideo) { // if the listBoxVideo whose download completed is visible then invalidate its rectangle int maxItemsDisplayed = Height / ItemHeight; int itemsDisplayed = Math.Min(maxItemsDisplayed, Items.Count - TopIndex); for (int i = 0; i < itemsDisplayed; i++) { // get the current listBoxVideo IVideo currentListBoxVideo = Items[TopIndex + i] as IVideo; if (listBoxVideo == currentListBoxVideo) { // invalidate just the rectangle containing the listBoxVideo Rectangle invalidateRect = new Rectangle( HORIZONTAL_INSET, (i * ItemHeight) + VERTICAL_INSET, THUMBNAIL_IMAGE_WIDTH, THUMBNAIL_IMAGE_HEIGHT); Invalidate(invalidateRect); break; } }; } private Label QueryStatusLabel { get { if (_queryStatusLabel == null) { Label label = new Label(); label.Size = new Size(Width - 5, 4 * Convert.ToInt32(Font.GetHeight())); label.TextAlign = ContentAlignment.MiddleCenter; label.BackColor = BackColor; label.ForeColor = SystemColors.ControlDarkDark; label.Font = Res.GetFont(FontSize.XLarge, FontStyle.Regular); label.Text = String.Empty; label.Visible = false; //label.FlatStyle = FlatStyle.System; label.TabStop = false; label.Location = new Point( Left + (Width / 2) - (label.Width / 2), Top + (Height / 2) - (label.Height / 2) - 30); Parent.Controls.Add(label); _queryStatusLabel = label; } return _queryStatusLabel; } } private Label _queryStatusLabel; // item metrics private const int VERTICAL_INSET = 5; private const int HORIZONTAL_INSET = 5; private const int THUMBNAIL_IMAGE_WIDTH = 130; private const int THUMBNAIL_IMAGE_HEIGHT = 100; #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer { public class InventoryTransferModule : IInventoryTransferModule, IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> private List<Scene> m_Scenelist = new List<Scene>(); private Dictionary<UUID, Scene> m_AgentRegions = new Dictionary<UUID, Scene>(); private IMessageTransferModule m_TransferModule = null; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { if (config.Configs["Messaging"] != null) { // Allow disabling this module in config // if (config.Configs["Messaging"].GetString( "InventoryTransferModule", "InventoryTransferModule") != "InventoryTransferModule") return; } if (!m_Scenelist.Contains(scene)) { if (m_Scenelist.Count == 0) { m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); if (m_TransferModule == null) m_log.Error("[INVENTORY TRANSFER]: No Message transfer module found, transfers will be local only"); } m_Scenelist.Add(scene); scene.RegisterModuleInterface<IInventoryTransferModule>(this); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClientClosed += ClientLoggedOut; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); } } public void PostInitialise() { } public void Close() { } public string Name { get { return "InventoryModule"; } } public bool IsSharedModule { get { return true; } } #endregion private void OnNewClient(IClientAPI client) { // Inventory giving is conducted via instant message client.OnInstantMessage += OnInstantMessage; } //////////////////////////////////////////////// // Utility functions for inventory offer/accept/decline private Scene FindScene(UUID agentId) { lock (m_Scenelist) { foreach (Scene scene in m_Scenelist) { if (scene.GetScenePresence(agentId) != null) return scene; } } return null; } private ScenePresence FindAgent(UUID agentId) { ScenePresence presence = null; lock (m_Scenelist) { foreach (Scene scene in m_Scenelist) { presence = scene.GetScenePresence(agentId); if (presence != null) break; } } return presence; } private void RelayInventoryOfferIM(Scene scene, ScenePresence user, GridInstantMessage im) { if (user != null) // Local (root agent or child agent) { // m_log.WarnFormat("[INVENTORY_OFFER]: Relaying IM {0} locally to {1}", im.dialog, im.toAgentID); user.ControllingClient.SendInstantMessage(im); } else { // m_log.WarnFormat("[INVENTORY_OFFER]: Relaying IM {0} remotely to {1}", im.dialog, im.toAgentID); if (m_TransferModule == null) m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im, delegate(bool success) { }); else m_log.ErrorFormat("[INVENTORY_OFFER]: Could not relay IM {0} remotely to {1}", im.dialog, im.toAgentID); } } private void RelayInventoryOfferIM(Scene scene, GridInstantMessage im) { UUID agentId = new UUID(im.toAgentID); ScenePresence user = FindAgent(agentId); RelayInventoryOfferIM(scene, user, im); } //////////////////////////////////////////////// // User-to-user inventory offers private void UserInventoryOffer(IClientAPI client, Scene scene, GridInstantMessage im) { InventoryFolderBase folder = null; InventoryItemBase item = null; UUID toAgentID = new UUID(im.toAgentID); IMuteListModule m_muteListModule = scene.RequestModuleInterface<IMuteListModule>(); if (m_muteListModule != null) { if (m_muteListModule.IsMuted(client.AgentId, toAgentID)) { client.SendAgentAlertMessage("Inventory offer was automatically declined.", false); return; // recipient has sender muted } } // Unpack the binary bucket AssetType assetType = (AssetType)im.binaryBucket[0]; UUID destID = new UUID(im.binaryBucket, 1); UUID copyID; bool isFolder = (assetType == AssetType.Folder); ScenePresence recipient = scene.GetScenePresence(toAgentID); if (recipient != null && recipient.IsBot) { client.SendAgentAlertMessage("Can't give inventory to bots.", false); return;//can't give objects to bots } if (assetType == AssetType.Folder) { folder = scene.GiveInventoryFolder(toAgentID, client.AgentId, destID, UUID.Zero); if (folder == null) { client.SendAgentAlertMessage("Can't find folder to give. Nothing given.", false); return; } copyID = folder.ID; } else { item = scene.GiveInventoryItem(toAgentID, client.AgentId, destID); if (item == null) { client.SendAgentAlertMessage("Can't find item to give. Nothing given.", false); return; } copyID = item.ID; } // m_log.InfoFormat("[AGENT INVENTORY]: Offering {0} {1} to user {2} inventory as {3}", isFolder ? "folder" : "item", destID, toAgentID, copyID); // Update the asset type and destination ID into the outgoing IM. im.binaryBucket = new byte[17]; im.binaryBucket[0] = (byte)assetType; Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16); // Also stuff the destination ID into the session ID field for retrieval in accept/decline im.imSessionID = copyID.Guid; CachedUserInfo recipientInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(toAgentID); if (recipientInfo != null && recipient != null) { if ((!isFolder) && (item != null)) { // item offer? recipient.ControllingClient.SendInventoryItemCreateUpdate(item, 0); } if (isFolder && (folder != null)) { // folder offer? folder = recipientInfo.GetFolder(folder.ID); if (folder != null) { recipient.ControllingClient.SendBulkUpdateInventory(folder); recipientInfo.SendInventoryDecendents(recipient.ControllingClient, folder.ID, false, true); } } } // Send the IM to the recipient. The item is already in their inventory, so // it will not be lost if they are offline. Transaction ID is the item ID. // We get that same ID back on the reply so we know what to act on. RelayInventoryOfferIM(scene, recipient, im); } private void UserInventoryOfferAccept(IClientAPI client, Scene scene, GridInstantMessage im) { // No extra work to do here. RelayInventoryOfferIM(scene, im); } private void UserInventoryOfferDecline(IClientAPI client, Scene scene, GridInstantMessage im) { // No extra work to do here. RelayInventoryOfferIM(scene, im); } //////////////////////////////////////////////// // Object-to-user inventory offers private void TaskInventoryOffer(IClientAPI client, Scene scene, GridInstantMessage im) { IMuteListModule m_muteListModule = scene.RequestModuleInterface<IMuteListModule>(); if (m_muteListModule != null) { UUID sender = new UUID(im.fromAgentID); UUID recipient = new UUID(im.toAgentID); if (m_muteListModule.IsMuted(sender, recipient)) { return; // recipient has sender muted } } RelayInventoryOfferIM(scene, im); } private void TaskInventoryOfferAccept(IClientAPI client, Scene scene, GridInstantMessage im) { InventoryFolderBase folder = null; InventoryItemBase item = null; // The inventory item/folder, back from it's trip UUID inventoryEntityID = new UUID(im.imSessionID); UUID toAgentID = new UUID(im.toAgentID); UUID bucketID = new UUID(im.binaryBucket, 0); // Here, the recipient is local and we can assume that the inventory is loaded. // Courtesy of the above bulk update, it will have been pushed to the client, too. CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(client.AgentId); if (userInfo != null) { // Is it a folder or an item? if (userInfo.QueryItem(inventoryEntityID)) { // It's an item. item = userInfo.FindItem(inventoryEntityID); if (item == null) { client.SendAgentAlertMessage("Unable to accept received inventory: item/folder not found.", false); return; } client.SendInventoryItemCreateUpdate(item, 0); } else { // It's a folder. folder = userInfo.GetFolder(inventoryEntityID); if (folder != null) { client.SendBulkUpdateInventory(folder); // If we don't send the descendents, viewer shows "Loading..." on the trash item. userInfo.SendInventoryDecendents(client, folder.ID, false, true); } } } // RelayInventoryOfferIM(scene, im); // we don't need to notify a box that the user accepted this } private void TaskInventoryOfferDecline(IClientAPI client, Scene scene, GridInstantMessage im) { // The inventory item/folder, back from it's trip UUID inventoryEntityID = new UUID(im.imSessionID); // Here, the recipient is local and we can assume that the inventory is loaded. // Courtesy of the above bulk update, it will have been pushed to the client, too. CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(client.AgentId); if (userInfo != null) { InventoryFolderBase trashFolder = userInfo.FindFolderForType((int)AssetType.TrashFolder); if (null == trashFolder) { client.SendAgentAlertMessage("Unable to decline received inventory: Trash folder not found.", false); return; } // Is it a folder or an item? if (userInfo.QueryItem(inventoryEntityID)) { // It's an item. InventoryItemBase item = userInfo.FindItem(inventoryEntityID); if (item == null) { client.SendAgentAlertMessage("Unable to decline received inventory: item/folder not found.", false); return; } userInfo.MoveItemToTrash(item, trashFolder); scene.AddInventoryItem(client, item); client.SendInventoryItemCreateUpdate(item, 0); } else { // It's a folder. InventoryFolderBase folder = userInfo.GetFolderAttributes(inventoryEntityID); userInfo.MoveFolder(inventoryEntityID, trashFolder.ID); folder = userInfo.GetFolder(inventoryEntityID); if (folder != null) { client.SendBulkUpdateInventory(folder); // If we don't send the descendents, viewer shows "Loading..." on the trash item. userInfo.SendInventoryDecendents(client, folder.ID, false, true); } } } } //////////////////////////////////////////////// // Incoming IM handlers /// I believe this is an IM from a local agent or object, rather than one from the grid somewhere. private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { Scene scene = FindScene(client.AgentId); if (scene == null) // Something seriously wrong here. return; if (im.dialog == (byte)InstantMessageDialog.InventoryOffered) { UserInventoryOffer(client, scene, im); } else if (im.dialog == (byte)InstantMessageDialog.InventoryAccepted) { UserInventoryOfferAccept(client, scene, im); } else if (im.dialog == (byte)InstantMessageDialog.InventoryDeclined) { UserInventoryOfferDecline(client, scene, im); } else if (im.dialog == (byte)InstantMessageDialog.TaskInventoryOffered) { TaskInventoryOffer(client, scene, im); } else if (im.dialog == (byte)InstantMessageDialog.TaskInventoryAccepted) { TaskInventoryOfferAccept(client, scene, im); } else if (im.dialog == (byte)InstantMessageDialog.TaskInventoryDeclined) { TaskInventoryOfferDecline(client, scene, im); } } private void GridInventoryOffer(GridInstantMessage im) { if (im.binaryBucket.Length < 1) // Invalid { m_log.WarnFormat("[INVENTORY TRANSFER]: Invalid IM (binary bucket length {0}).", im.binaryBucket.Length); return; } Scene scene = FindScene(new UUID(im.toAgentID)); ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); if (user == null) // Shouldn't happen { m_log.Warn("[INVENTORY TRANSFER]: Can't find recipient"); return; } CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService. GetUserDetails(user.ControllingClient.AgentId); if (userInfo == null) { m_log.Warn("[INVENTORY TRANSFER]: Can't find user info of recipient"); return; } AssetType assetType = (AssetType)im.binaryBucket[0]; UUID inventoryEntityID = UUID.Zero; if (im.binaryBucket.Length >= 17) // includes UUID inventoryEntityID = new UUID(im.binaryBucket, 1); if (AssetType.Folder == assetType) { if (inventoryEntityID != UUID.Zero) { // Get folder info InventoryFolderBase folder = userInfo.GetFolder(inventoryEntityID); if (folder == null) { m_log.WarnFormat("[INVENTORY TRANSFER]: Can't retrieve folder {0} to give.", inventoryEntityID); return; } // Update folder to viewer (makes it appear to user) user.ControllingClient.SendBulkUpdateInventory(folder); userInfo.SendInventoryDecendents(user.ControllingClient, folder.ID, false, true); } // Deliver message user.ControllingClient.SendInstantMessage(im); } else { if (inventoryEntityID != UUID.Zero) { // Get item info InventoryItemBase item = userInfo.FindItem(inventoryEntityID); if (item == null) { m_log.WarnFormat("[INVENTORY TRANSFER]: Can't retrieve item {0} to give.", inventoryEntityID); return; } // Update item to viewer (makes it appear in proper folder) user.ControllingClient.SendInventoryItemCreateUpdate(item, 0); } // Deliver message user.ControllingClient.SendInstantMessage(im); } } // When we arrive here from a grid message, all the hard lifting has already been done. // All that is left is to notify the result to the sender of the offer. private void GridInventoryOfferAcceptDecline(GridInstantMessage im) { UUID agentId = new UUID(im.toAgentID); Scene scene = FindScene(agentId); if (scene == null) return; // recipient is not here ScenePresence user = scene.GetScenePresence(agentId); RelayInventoryOfferIM(scene, user, im); } /// <summary> /// This is an IM from the grid, as opposed to an IM from a local agent or object. /// </summary> /// <param name="msg"></param> private void OnGridInstantMessage(GridInstantMessage im) { if (im.dialog == (byte)InstantMessageDialog.InventoryOffered) { GridInventoryOffer(im); } else if (im.dialog == (byte)InstantMessageDialog.InventoryAccepted) { // m_log.Warn("[INVENTORY TRANSFER]: InventoryAccepted"); GridInventoryOfferAcceptDecline(im); } else if (im.dialog == (byte)InstantMessageDialog.InventoryDeclined) { // m_log.Warn("[INVENTORY TRANSFER]: InventoryDeclined"); GridInventoryOfferAcceptDecline(im); } else if (im.dialog == (byte)InstantMessageDialog.TaskInventoryOffered) { // m_log.Info("[INVENTORY TRANSFER]: TaskInventoryOffered"); GridInventoryOffer(im); } else if (im.dialog == (byte)InstantMessageDialog.TaskInventoryAccepted) { // m_log.Info("[INVENTORY TRANSFER]: TaskInventoryAccepted"); GridInventoryOfferAcceptDecline(im); } else if (im.dialog == (byte)InstantMessageDialog.TaskInventoryDeclined) { // m_log.Info("[INVENTORY TRANSFER]: TaskInventoryDeclined"); GridInventoryOfferAcceptDecline(im); } } //////////////////////////////////////////////// public void SetRootAgentScene(UUID agentID, Scene scene) { lock (m_AgentRegions) { m_AgentRegions[agentID] = scene; } } public bool NeedSceneCacheClear(UUID agentID, Scene scene) { bool haveAgent; lock (m_AgentRegions) { haveAgent = m_AgentRegions.ContainsKey(agentID); } if (!haveAgent) { // Since we can get here two ways, we need to scan // the scenes here. This is somewhat more expensive // but helps avoid a nasty bug // foreach (Scene s in m_Scenelist) { ScenePresence presence; if (s.TryGetAvatar(agentID, out presence)) { // If the agent is in this scene, then we // are being called twice in a single // teleport. This is wasteful of cycles // but harmless due to this 2nd level check // // If the agent is found in another scene // then the list wasn't current // // If the agent is totally unknown, then what // are we even doing here?? // if (s == scene) { //m_log.Debug("[INVTRANSFERMOD]: s == scene. Returning true in " + scene.RegionInfo.RegionName); return true; } else { //m_log.Debug("[INVTRANSFERMOD]: s != scene. Returning false in " + scene.RegionInfo.RegionName); return false; } } } //m_log.Debug("[INVTRANSFERMOD]: agent not in scene. Returning true in " + scene.RegionInfo.RegionName); return true; } // The agent is left in current Scene, so we must be // going to another instance // lock (m_AgentRegions) { if (m_AgentRegions[agentID] == scene) { //m_log.Debug("[INVTRANSFERMOD]: m_AgentRegions[agentID] == scene. Returning true in " + scene.RegionInfo.RegionName); m_AgentRegions.Remove(agentID); return true; } } // Another region has claimed the agent // //m_log.Debug("[INVTRANSFERMOD]: last resort. Returning false in " + scene.RegionInfo.RegionName); return false; } public void ClientLoggedOut(UUID agentID, Scene scene) { lock (m_AgentRegions) { if (m_AgentRegions.ContainsKey(agentID)) m_AgentRegions.Remove(agentID); } } } }
// // XPathEditableNavigatorTests.cs // // Author: // Atsushi Enomoto <[email protected]> // // Copyright (C) 2005 Novell, Inc. http://www.novell.com // #if NET_2_0 using System; using System.Xml; using System.Xml.XPath; using NUnit.Framework; namespace MonoTests.System.Xml.XPath { [TestFixture] public class XPathEditableNavigatorTests { private XPathNavigator GetInstance (string xml) { XmlDocument doc = new XmlDocument (); doc.LoadXml (xml); return doc.CreateNavigator (); } private static void AssertNavigator (string label, XPathNavigator nav, XPathNodeType type, string prefix, string localName, string ns, string name, string value, bool hasAttributes, bool hasChildren, bool isEmptyElement) { label += nav.GetType (); Assert.AreEqual (type, nav.NodeType, label + "NodeType"); Assert.AreEqual (prefix, nav.Prefix, label + "Prefix"); Assert.AreEqual (localName, nav.LocalName, label + "LocalName"); Assert.AreEqual (ns, nav.NamespaceURI, label + "Namespace"); Assert.AreEqual (name, nav.Name, label + "Name"); Assert.AreEqual (value, nav.Value, label + "Value"); Assert.AreEqual (hasAttributes, nav.HasAttributes, label + "HasAttributes"); Assert.AreEqual (hasChildren, nav.HasChildren, label + "HasChildren"); Assert.AreEqual (isEmptyElement, nav.IsEmptyElement, label + "IsEmptyElement"); } [Test] [ExpectedException (typeof (XmlException))] public void AppendChildStartDocumentInvalid () { XPathNavigator nav = GetInstance (String.Empty); XmlWriter w = nav.AppendChild (); w.WriteStartDocument (); w.Close (); } [Test] [ExpectedException (typeof (XmlException))] public void AppendChildStartAttributeInvalid () { XPathNavigator nav = GetInstance (String.Empty); XmlWriter w = nav.AppendChild (); // Seems like it is just ignored. w.WriteStartAttribute ("test"); w.WriteEndAttribute (); w.Close (); Assert.AreEqual (XPathNodeType.Root, nav.NodeType, "#1"); Assert.IsFalse (nav.MoveToFirstChild (), "#2"); } [Test] [ExpectedException (typeof (XmlException))] public void AppendChildElementIncomplete () { XPathNavigator nav = GetInstance (String.Empty); XmlWriter w = nav.AppendChild (); w.WriteStartElement ("foo"); w.Close (); } [Test] // empty content is allowed. public void AppendChildEmptyString () { XPathNavigator nav = GetInstance ("<root/>"); nav.MoveToFirstChild (); // root nav.AppendChild (String.Empty); } [Test] public void AppendChildElement () { XPathNavigator nav = GetInstance ("<root/>"); nav.MoveToFirstChild (); XmlWriter w = nav.AppendChild (); w.WriteStartElement ("foo"); w.WriteEndElement (); w.Close (); Assert.IsTrue (nav.MoveToFirstChild ()); AssertNavigator ("#1", nav, XPathNodeType.Element, String.Empty, // Prefix "foo", // LocalName String.Empty, // NamespaceURI "foo", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement } [Test] public void AppendChildStringFragment () { // check that the input string inherits // namespace context. XPathNavigator nav = GetInstance ("<root xmlns='urn:foo'/>"); nav.MoveToFirstChild (); nav.AppendChild ("<child/>fragment<child></child>"); Assert.IsTrue (nav.MoveToFirstChild (), "#1-1"); AssertNavigator ("#1-2", nav, XPathNodeType.Element, String.Empty, // Prefix "child", // LocalName "urn:foo", // NamespaceURI "child", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement Assert.IsFalse (nav.MoveToFirstChild (), "#2-1"); Assert.IsTrue (nav.MoveToNext (), "#2-2"); AssertNavigator ("#2-3", nav, XPathNodeType.Text, String.Empty, // Prefix String.Empty, // LocalName String.Empty, // NamespaceURI String.Empty, // Name "fragment", // Value false, // HasAttributes false, // HasChildren false); // IsEmptyElement Assert.IsTrue (nav.MoveToNext (), "#3-1"); AssertNavigator ("#3-2", nav, XPathNodeType.Element, String.Empty, // Prefix "child", // LocalName "urn:foo", // NamespaceURI "child", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren false); // IsEmptyElement } [Test] public void AppendChildStringInvalidFragment () { XPathNavigator nav = GetInstance ("<root xmlns='urn:foo'/>"); nav.MoveToFirstChild (); nav.AppendChild ("<?xml version='1.0'?><root/>"); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void AppendChildToTextNode () { XPathNavigator nav = GetInstance ("<root>text</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); XmlWriter w = nav.AppendChild (); } [Test] public void InsertAfter () { XPathNavigator nav = GetInstance ("<root>test</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); nav.InsertAfter ("<blah/><doh>sample</doh>"); AssertNavigator ("#1", nav, XPathNodeType.Text, String.Empty, // Prefix String.Empty, // LocalName String.Empty, // NamespaceURI String.Empty, // Name "test", // Value false, // HasAttributes false, // HasChildren false); // IsEmptyElement Assert.IsTrue (nav.MoveToNext (), "#2"); AssertNavigator ("#2-2", nav, XPathNodeType.Element, String.Empty, // Prefix "blah", // LocalName String.Empty, // NamespaceURI "blah", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement Assert.IsTrue (nav.MoveToNext (), "#3"); AssertNavigator ("#3-2", nav, XPathNodeType.Element, String.Empty, // Prefix "doh", // LocalName String.Empty, // NamespaceURI "doh", // Name "sample", // Value false, // HasAttributes true, // HasChildren false); // IsEmptyElement } [Test] [ExpectedException (typeof (InvalidOperationException))] public void InsertAfterRoot () { XPathNavigator nav = GetInstance ("<root/>"); nav.InsertAfter (); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void InsertAfterAttribute () { XPathNavigator nav = GetInstance ("<root a='b'/>"); nav.MoveToFirstChild (); nav.MoveToFirstAttribute (); nav.InsertAfter (); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void InsertAfterNamespace () { XPathNavigator nav = GetInstance ("<root xmlns='urn:foo'/>"); nav.MoveToFirstChild (); nav.MoveToFirstNamespace (); nav.InsertAfter (); } [Test] [ExpectedException (typeof (InvalidOperationException))] // xmlns:xml='...', which is likely to have XmlElement or XmlDocument as its node. public void InsertAfterNamespace2 () { XPathNavigator nav = GetInstance ("<root />"); nav.MoveToFirstChild (); nav.MoveToFirstNamespace (); nav.InsertAfter (); } [Test] // empty content is allowed. public void InsertAfterEmptyString () { XPathNavigator nav = GetInstance ("<root/>"); nav.MoveToFirstChild (); // root nav.InsertAfter (String.Empty); } [Test] public void InsertBefore () { XPathNavigator nav = GetInstance ("<root>test</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); nav.InsertBefore ("<blah/><doh>sample</doh>"); AssertNavigator ("#1", nav, XPathNodeType.Text, String.Empty, // Prefix String.Empty, // LocalName String.Empty, // NamespaceURI String.Empty, // Name "test", // Value false, // HasAttributes false, // HasChildren false); // IsEmptyElement Assert.IsTrue (nav.MoveToFirst (), "#2-1"); AssertNavigator ("#2-2", nav, XPathNodeType.Element, String.Empty, // Prefix "blah", // LocalName String.Empty, // NamespaceURI "blah", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement Assert.IsTrue (nav.MoveToNext (), "#3"); AssertNavigator ("#3-2", nav, XPathNodeType.Element, String.Empty, // Prefix "doh", // LocalName String.Empty, // NamespaceURI "doh", // Name "sample", // Value false, // HasAttributes true, // HasChildren false); // IsEmptyElement } [Test] [ExpectedException (typeof (InvalidOperationException))] public void InsertBeforeRoot () { XPathNavigator nav = GetInstance ("<root/>"); nav.InsertBefore (); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void InsertBeforeAttribute () { XPathNavigator nav = GetInstance ("<root a='b'/>"); nav.MoveToFirstChild (); nav.MoveToFirstAttribute (); nav.InsertBefore (); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void InsertBeforeNamespace () { XPathNavigator nav = GetInstance ("<root xmlns='urn:foo'/>"); nav.MoveToFirstChild (); nav.MoveToFirstNamespace (); nav.InsertBefore (); } [Test] [ExpectedException (typeof (InvalidOperationException))] // xmlns:xml='...', which is likely to have XmlElement or XmlDocument as its node. public void InsertBeforeNamespace2 () { XPathNavigator nav = GetInstance ("<root />"); nav.MoveToFirstChild (); nav.MoveToFirstNamespace (); nav.InsertBefore (); } [Test] // empty content is allowed. public void InsertBeforeEmptyString () { XPathNavigator nav = GetInstance ("<root/>"); nav.MoveToFirstChild (); // root nav.InsertBefore (String.Empty); } [Test] public void DeleteRange () { XPathNavigator nav = GetInstance ("<root><foo><bar/><baz/></foo><next>child<tmp/></next>final</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // <foo> XPathNavigator end = nav.Clone (); end.MoveToNext (); // <next> end.MoveToNext (); // final nav.DeleteRange (end); AssertNavigator ("#1", nav, XPathNodeType.Element, String.Empty, // Prefix "root", // LocalName String.Empty, // NamespaceURI "root", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren false); // IsEmptyElement } [Test] [ExpectedException (typeof (ArgumentNullException))] public void DeleteRangeNullArg () { XPathNavigator nav = GetInstance ("<root><foo><bar/><baz/></foo><next>child<tmp/></next>final</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // <foo> nav.DeleteRange (null); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void DeleteRangeInvalidArg () { XPathNavigator nav = GetInstance ("<root><foo><bar/><baz/></foo><next>child<tmp/></next>final</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // <foo> XPathNavigator end = nav.Clone (); end.MoveToNext (); // <next> end.MoveToFirstChild (); // child nav.DeleteRange (end); } [Test] public void ReplaceRange () { XPathNavigator nav = GetInstance ("<root><foo><bar/><baz/></foo><next>child<tmp/></next>final</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // <foo> XPathNavigator end = nav.Clone (); end.MoveToNext (); // <next> XmlWriter w = nav.ReplaceRange (end); AssertNavigator ("#1", nav, XPathNodeType.Element, String.Empty, // Prefix "foo", // LocalName String.Empty, // NamespaceURI "foo", // Name String.Empty, // Value false, // HasAttributes true, // HasChildren false); // IsEmptyElement Assert.IsTrue (nav.MoveToParent (), "#1-2"); w.WriteStartElement ("whoa"); w.WriteEndElement (); w.Close (); AssertNavigator ("#2", nav, XPathNodeType.Element, String.Empty, // Prefix "whoa", // LocalName String.Empty, // NamespaceURI "whoa", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement Assert.IsTrue (nav.MoveToNext (), "#2-1"); AssertNavigator ("#3", nav, XPathNodeType.Text, String.Empty, // Prefix String.Empty, // LocalName String.Empty, // NamespaceURI String.Empty, // Name "final", // Value false, // HasAttributes false, // HasChildren false); // IsEmptyElement } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ReplaceRangeNullArg () { XPathNavigator nav = GetInstance ("<root><foo><bar/><baz/></foo><next>child<tmp/></next>final</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // <foo> nav.ReplaceRange (null); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void ReplaceRangeInvalidArg () { XPathNavigator nav = GetInstance ("<root><foo><bar/><baz/></foo><next>child<tmp/></next>final</root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // <foo> XPathNavigator end = nav.Clone (); end.MoveToNext (); // <next> end.MoveToFirstChild (); // child nav.ReplaceRange (end); } [Test] public void PrependChildXmlReader () { XPathNavigator nav = GetInstance ("<root><foo>existing_child</foo></root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo XmlReader reader = new XmlTextReader ( "<child>text</child><next_sibling/>", XmlNodeType.Element, null); nav.PrependChild (reader); XmlAssert.AssertNode ("#0", reader, XmlNodeType.None, 0, // Depth false, // IsEmptyElement String.Empty, // Name String.Empty, // Prefix String.Empty, // LocalName String.Empty, // NamespaceURI String.Empty, // Value false, // HasValue 0, // AttributeCount false); // HasAttributes AssertNavigator ("#1", nav, XPathNodeType.Element, String.Empty, // Prefix "foo", // LocalName String.Empty, // NamespaceURI "foo", // Name "textexisting_child", // Value false, // HasAttributes true, // HasChildren false); // IsEmptyElement Assert.IsTrue (nav.MoveToFirstChild (), "#1-2"); AssertNavigator ("#2", nav, XPathNodeType.Element, String.Empty, // Prefix "child", // LocalName String.Empty, // NamespaceURI "child", // Name "text", // Value false, // HasAttributes true, // HasChildren false); // IsEmptyElement Assert.IsTrue (nav.MoveToNext (), "#2-2"); AssertNavigator ("#3", nav, XPathNodeType.Element, String.Empty, // Prefix "next_sibling", // LocalName String.Empty, // NamespaceURI "next_sibling", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement Assert.IsTrue (nav.MoveToNext (), "#3-2"); AssertNavigator ("#4", nav, XPathNodeType.Text, String.Empty, // Prefix String.Empty, // LocalName String.Empty, // NamespaceURI String.Empty, // Name "existing_child",// Value false, // HasAttributes false, // HasChildren false); // IsEmptyElement } [Test] [ExpectedException (typeof (InvalidOperationException))] public void PrependChildInvalid () { XPathNavigator nav = GetInstance ("<root><foo>existing_child</foo></root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo XmlWriter w = nav.PrependChild (); w.WriteStartAttribute ("whoa"); w.WriteEndAttribute (); w.Close (); } [Test] // empty content is allowed. public void PrependChildEmptyString () { XPathNavigator nav = GetInstance ("<root><foo/><bar/><baz/></root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo nav.MoveToNext (); // bar nav.PrependChild (String.Empty); AssertNavigator ("#1", nav, XPathNodeType.Element, String.Empty, // Prefix "bar", // LocalName String.Empty, // NamespaceURI "bar", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement Assert.IsTrue (nav.MoveToFirst (), "#1-2"); AssertNavigator ("#2", nav, XPathNodeType.Element, String.Empty, // Prefix "foo", // LocalName String.Empty, // NamespaceURI "foo", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement } [Test] public void ReplaceSelf () { XPathNavigator nav = GetInstance ("<root><foo>existing_child</foo></root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo nav.ReplaceSelf ("<hijacker>hah, hah</hijacker><next/>"); AssertNavigator ("#1", nav, XPathNodeType.Element, String.Empty, // Prefix "hijacker", // LocalName String.Empty, // NamespaceURI "hijacker", // Name "hah, hah", // Value false, // HasAttributes true, // HasChildren false); // IsEmptyElement Assert.IsTrue (nav.MoveToNext (), "#1-2"); AssertNavigator ("#2", nav, XPathNodeType.Element, String.Empty, // Prefix "next", // LocalName String.Empty, // NamespaceURI "next", // Name String.Empty, // Value false, // HasAttributes false, // HasChildren true); // IsEmptyElement } [Test] // possible internal behavior difference e.g. due to ReadNode() public void ReplaceSelfXmlReaderInteractive () { XPathNavigator nav = GetInstance ("<root><foo>existing_child</foo></root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo XmlReader xr = new XmlTextReader ( "<hijacker>hah, hah</hijacker><next/>", XmlNodeType.Element, null); xr.MoveToContent (); nav.ReplaceSelf (xr); AssertNavigator ("#1", nav, XPathNodeType.Element, String.Empty, // Prefix "hijacker", // LocalName String.Empty, // NamespaceURI "hijacker", // Name "hah, hah", // Value false, // HasAttributes true, // HasChildren false); // IsEmptyElement Assert.IsFalse (nav.MoveToNext (), "#1-2"); } [Test] [ExpectedException (typeof (InvalidOperationException))] // empty content is not allowed public void ReplaceSelfEmptyString () { XPathNavigator nav = GetInstance ("<root><foo>existing_child</foo></root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo nav.ReplaceSelf (String.Empty); } [Test] public void SetValueEmptyString () { XPathNavigator nav = GetInstance ("<root><foo>existing_child</foo></root>"); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo nav.SetValue (String.Empty); AssertNavigator ("#1", nav, XPathNodeType.Element, String.Empty, // Prefix "foo", // LocalName String.Empty, // NamespaceURI "foo", // Name String.Empty, // Value false, // HasAttributes true, // HasChildren false); // IsEmptyElement } [Test] public void MoveToFollowing () { XPathNavigator end; XPathNavigator nav = GetInstance ("<root><bar><foo attr='v1'><baz><foo attr='v2'/></baz></foo></bar><dummy/><foo attr='v3'></foo></root>"); Assert.IsTrue (nav.MoveToFollowing ("foo", String.Empty), "#1"); Assert.AreEqual ("v1", nav.GetAttribute ("attr", String.Empty), "#2"); Assert.IsTrue (nav.MoveToFollowing ("foo", String.Empty), "#3"); Assert.AreEqual ("v2", nav.GetAttribute ("attr", String.Empty), "#4"); Assert.IsTrue (nav.MoveToFollowing ("foo", String.Empty), "#5"); Assert.AreEqual ("v3", nav.GetAttribute ("attr", String.Empty), "#6"); // round 2 end = nav.Clone (); nav.MoveToRoot (); Assert.IsTrue (nav.MoveToFollowing ("foo", String.Empty, end), "#7"); Assert.AreEqual ("v1", nav.GetAttribute ("attr", String.Empty), "#8"); Assert.IsTrue (nav.MoveToFollowing ("foo", String.Empty, end), "#9"); Assert.AreEqual ("v2", nav.GetAttribute ("attr", String.Empty), "#10"); // end is exclusive Assert.IsFalse (nav.MoveToFollowing ("foo", String.Empty, end), "#11"); // in this case it never moves to somewhere else. Assert.AreEqual ("v2", nav.GetAttribute ("attr", String.Empty), "#12"); } [Test] public void MoveToFollowingFromAttribute () { XPathNavigator nav = GetInstance ("<root a='b'><foo/></root>"); nav.MoveToFirstChild (); nav.MoveToFirstAttribute (); // should first move to owner element and go on. Assert.IsTrue (nav.MoveToFollowing ("foo", String.Empty)); } [Test] public void AppendChildInDocumentFragment () { XmlDocumentFragment f = new XmlDocument ().CreateDocumentFragment (); XmlWriter w = f.CreateNavigator ().AppendChild (); w.WriteStartElement ("foo"); w.WriteEndElement (); w.Close (); Assert.IsNotNull (f.FirstChild as XmlElement); } [Test] public void CanEdit () { XmlDocument doc = new XmlDocument (); Assert.IsTrue (doc.CreateNavigator ().CanEdit); Assert.IsTrue (GetInstance ("<root/>").CanEdit); } [Test] public void DeleteSelfAttribute () { // bug #376210. XmlDocument document = new XmlDocument (); document.LoadXml ("<test><node date='2000-12-23'>z</node></test>"); XPathNavigator navigator = document.CreateNavigator (); XPathNavigator nodeElement = navigator.SelectSingleNode ("//node"); nodeElement.MoveToAttribute ("date", String.Empty); nodeElement.DeleteSelf (); Assert.AreEqual ("<test><node>z</node></test>", document.OuterXml); } [Test] public void WriteAttributeOnAppendedChild () { XmlDocument x = new XmlDocument (); XmlElement y = x.CreateElement ("test"); using (XmlWriter w = y.CreateNavigator ().AppendChild ()) w.WriteAttributeString ("test", "test1"); } [Test] // bug #1558 public void CreateNavigatorReturnsEdidable () { var document = new XmlDocument(); document.LoadXml ("<div>hello world</div>"); XPathNavigator navigator = document.CreateNavigator ().CreateNavigator (); navigator.SelectSingleNode ("//div").SetValue ("hello world 2"); } } } #endif
/* * CID0025.cs - et culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "et.txt". namespace I18N.Other { using System; using System.Globalization; using I18N.Common; public class CID0025 : RootCulture { public CID0025() : base(0x0025) {} public CID0025(int culture) : base(culture) {} public override String Name { get { return "et"; } } public override String ThreeLetterISOLanguageName { get { return "est"; } } public override String ThreeLetterWindowsLanguageName { get { return "ETI"; } } public override String TwoLetterISOLanguageName { get { return "et"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AbbreviatedDayNames = new String[] {"P", "E", "T", "K", "N", "R", "L"}; dfi.DayNames = new String[] {"p\u00FChap\u00E4ev", "esmasp\u00E4ev", "teisip\u00E4ev", "kolmap\u00E4ev", "neljap\u00E4ev", "reede", "laup\u00E4ev"}; dfi.AbbreviatedMonthNames = new String[] {"jaan", "veebr", "m\u00E4rts", "apr", "mai", "juuni", "juuli", "aug", "sept", "okt", "nov", "dets", ""}; dfi.MonthNames = new String[] {"jaanuar", "veebruar", "m\u00E4rts", "aprill", "mai", "juuni", "juuli", "august", "september", "oktoober", "november", "detsember", ""}; dfi.DateSeparator = "."; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "dddd, d, MMMM yyyy"; dfi.LongTimePattern = "H:mm:ss z"; dfi.ShortDatePattern = "dd.MM.yy"; dfi.ShortTimePattern = "H:mm"; dfi.FullDateTimePattern = "dddd, d, MMMM yyyy H:mm:ss z"; dfi.I18NSetDateTimePatterns(new String[] { "d:dd.MM.yy", "D:dddd, d, MMMM yyyy", "f:dddd, d, MMMM yyyy H:mm:ss z", "f:dddd, d, MMMM yyyy H:mm:ss z", "f:dddd, d, MMMM yyyy H:mm:ss", "f:dddd, d, MMMM yyyy H:mm", "F:dddd, d, MMMM yyyy HH:mm:ss", "g:dd.MM.yy H:mm:ss z", "g:dd.MM.yy H:mm:ss z", "g:dd.MM.yy H:mm:ss", "g:dd.MM.yy H:mm", "G:dd.MM.yy HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:H:mm:ss z", "t:H:mm:ss z", "t:H:mm:ss", "t:H:mm", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override NumberFormatInfo NumberFormat { get { NumberFormatInfo nfi = base.NumberFormat; nfi.CurrencyDecimalSeparator = ","; nfi.CurrencyGroupSeparator = "\u00A0"; nfi.NumberGroupSeparator = "\u00A0"; nfi.PercentGroupSeparator = "\u00A0"; nfi.NegativeSign = "-"; nfi.NumberDecimalSeparator = ","; nfi.PercentDecimalSeparator = ","; nfi.PercentSymbol = "%"; nfi.PerMilleSymbol = "\u2030"; return nfi; } set { base.NumberFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "et": return "Eesti"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "EE": return "Eesti"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int ANSICodePage { get { return 1257; } } public override int EBCDICCodePage { get { return 500; } } public override int MacCodePage { get { return 10029; } } public override int OEMCodePage { get { return 775; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID0025 public class CNet : CID0025 { public CNet() : base() {} }; // class CNet }; // namespace I18N.Other
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; namespace System.Runtime.Serialization { public class SurrogateSelector : ISurrogateSelector { internal readonly SurrogateHashtable _surrogates = new SurrogateHashtable(32); internal ISurrogateSelector _nextSelector; public virtual void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (surrogate == null) { throw new ArgumentNullException(nameof(surrogate)); } var key = new SurrogateKey(type, context); _surrogates.Add(key, surrogate); // Hashtable does duplicate checking. } private static bool HasCycle(ISurrogateSelector selector) { Debug.Assert(selector != null, "[HasCycle]selector!=null"); ISurrogateSelector head = selector, tail = selector; while (head != null) { head = head.GetNextSelector(); if (head == null) { return true; } if (head == tail) { return false; } head = head.GetNextSelector(); tail = tail.GetNextSelector(); if (head == tail) { return false; } } return true; } // Adds another selector to check if we don't have match within this selector. // The logic is:"Add this onto the list as the first thing that you check after yourself." public virtual void ChainSelector(ISurrogateSelector selector) { if (selector == null) { throw new ArgumentNullException(nameof(selector)); } // Verify that we don't try and add ourself twice. if (selector == this) { throw new SerializationException(SR.Serialization_DuplicateSelector); } // Verify that the argument doesn't contain a cycle. if (!HasCycle(selector)) { throw new ArgumentException(SR.Serialization_SurrogateCycleInArgument, nameof(selector)); } // Check for a cycle that would lead back to this. We find the end of the list that we're being asked to // insert for use later. ISurrogateSelector tempCurr = selector.GetNextSelector(); ISurrogateSelector tempEnd = selector; while (tempCurr != null && tempCurr != this) { tempEnd = tempCurr; tempCurr = tempCurr.GetNextSelector(); } if (tempCurr == this) { throw new ArgumentException(SR.Serialization_SurrogateCycle, nameof(selector)); } // Check for a cycle later in the list which would be introduced by this insertion. tempCurr = selector; ISurrogateSelector tempPrev = selector; while (tempCurr != null) { if (tempCurr == tempEnd) { tempCurr = GetNextSelector(); } else { tempCurr = tempCurr.GetNextSelector(); } if (tempCurr == null) { break; } if (tempCurr == tempPrev) { throw new ArgumentException(SR.Serialization_SurrogateCycle, nameof(selector)); } if (tempCurr == tempEnd) { tempCurr = GetNextSelector(); } else { tempCurr = tempCurr.GetNextSelector(); } if (tempPrev == tempEnd) { tempPrev = GetNextSelector(); } else { tempPrev = tempPrev.GetNextSelector(); } if (tempCurr == tempPrev) { throw new ArgumentException(SR.Serialization_SurrogateCycle, nameof(selector)); } } // Add the new selector and it's entire chain of selectors as the next thing that we check. ISurrogateSelector temp = _nextSelector; _nextSelector = selector; if (temp != null) { tempEnd.ChainSelector(temp); } } // Get the next selector on the chain of selectors. public virtual ISurrogateSelector GetNextSelector() => _nextSelector; // Gets the surrogate for a particular type. If this selector can't // provide a surrogate, it checks with all of it's children before returning null. public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) { if (type == null) { throw new ArgumentNullException(nameof(type)); } selector = this; SurrogateKey key = new SurrogateKey(type, context); ISerializationSurrogate temp = (ISerializationSurrogate)_surrogates[key]; if (temp != null) { return temp; } if (_nextSelector != null) { return _nextSelector.GetSurrogate(type, context, out selector); } return null; } // Removes the surrogate associated with a given type. Does not // check chained surrogates. public virtual void RemoveSurrogate(Type type, StreamingContext context) { if (type == null) { throw new ArgumentNullException(nameof(type)); } SurrogateKey key = new SurrogateKey(type, context); _surrogates.Remove(key); } } [Serializable] internal sealed class SurrogateKey { internal readonly Type _type; internal readonly StreamingContext _context; internal SurrogateKey(Type type, StreamingContext context) { Debug.Assert(type != null); _type = type; _context = context; } public override int GetHashCode() => _type.GetHashCode(); } // Subclass to override KeyEquals. internal sealed class SurrogateHashtable : Hashtable { internal SurrogateHashtable(int size) : base(size) { } // Must return true if the context to serialize for (givenContext) // is a subset of the context for which the serialization selector is provided (presentContext) // Note: This is done by overriding KeyEquals rather than overriding Equals() in the SurrogateKey // class because Equals() method must be commutative. protected override bool KeyEquals(object key, object item) { SurrogateKey givenValue = (SurrogateKey)item; SurrogateKey presentValue = (SurrogateKey)key; return presentValue._type == givenValue._type && (presentValue._context.State & givenValue._context.State) == givenValue._context.State && presentValue._context.Context == givenValue._context.Context; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Threading; namespace System.Diagnostics { internal sealed class PerformanceCounterLib { private static volatile string s_computerName; private PerformanceMonitor _performanceMonitor; private string _machineName; private string _perfLcid; private static volatile Dictionary<String, PerformanceCounterLib> s_libraryTable; private Dictionary<int, string> _nameTable; private readonly object _nameTableLock = new Object(); private static Object s_internalSyncObject; private static Object InternalSyncObject { get { if (s_internalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_internalSyncObject, o, null); } return s_internalSyncObject; } } internal PerformanceCounterLib(string machineName, string lcid) { _machineName = machineName; _perfLcid = lcid; } /// <internalonly/> internal static string ComputerName { get { if (s_computerName == null) { lock (InternalSyncObject) { if (s_computerName == null) { s_computerName = Interop.mincore.GetComputerName(); } } } return s_computerName; } } internal Dictionary<int, string> NameTable { get { if (_nameTable == null) { lock (_nameTableLock) { if (_nameTable == null) _nameTable = GetStringTable(false); } } return _nameTable; } } internal string GetCounterName(int index) { string result; return NameTable.TryGetValue(index, out result) ? result : ""; } internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) { string lcidString = culture.Name.ToLowerInvariant(); if (machineName.CompareTo(".") == 0) machineName = ComputerName.ToLowerInvariant(); else machineName = machineName.ToLowerInvariant(); if (PerformanceCounterLib.s_libraryTable == null) { lock (InternalSyncObject) { if (PerformanceCounterLib.s_libraryTable == null) PerformanceCounterLib.s_libraryTable = new Dictionary<string, PerformanceCounterLib>(); } } string libraryKey = machineName + ":" + lcidString; PerformanceCounterLib library; if (!PerformanceCounterLib.s_libraryTable.TryGetValue(libraryKey, out library)) { library = new PerformanceCounterLib(machineName, lcidString); PerformanceCounterLib.s_libraryTable[libraryKey] = library; } return library; } internal byte[] GetPerformanceData(string item) { if (_performanceMonitor == null) { lock (InternalSyncObject) { if (_performanceMonitor == null) _performanceMonitor = new PerformanceMonitor(_machineName); } } return _performanceMonitor.GetData(item); } private Dictionary<int, string> GetStringTable(bool isHelp) { Dictionary<int, string> stringTable; RegistryKey libraryKey; libraryKey = Registry.PerformanceData; try { string[] names = null; int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // In some stress situations, querying counter values from // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009 // often returns null/empty data back. We should build fault-tolerance logic to // make it more reliable because getting null back once doesn't necessarily mean // that the data is corrupted, most of the time we would get the data just fine // in subsequent tries. while (waitRetries > 0) { try { if (!isHelp) names = (string[])libraryKey.GetValue("Counter " + _perfLcid); else names = (string[])libraryKey.GetValue("Explain " + _perfLcid); if ((names == null) || (names.Length == 0)) { --waitRetries; if (waitSleep == 0) waitSleep = 10; else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } } else break; } catch (IOException) { // RegistryKey throws if it can't find the value. We want to return an empty table // and throw a different exception higher up the stack. names = null; break; } catch (InvalidCastException) { // Unable to cast object of type 'System.Byte[]' to type 'System.String[]'. // this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ names = null; break; } } if (names == null) stringTable = new Dictionary<int, string>(); else { stringTable = new Dictionary<int, string>(names.Length / 2); for (int index = 0; index < (names.Length / 2); ++index) { string nameString = names[(index * 2) + 1]; if (nameString == null) nameString = String.Empty; int key; if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) { if (isHelp) { // Category Help Table throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2])); } else { // Counter Name Table throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2])); } } stringTable[key] = nameString; } } } finally { libraryKey.Dispose(); } return stringTable; } internal class PerformanceMonitor { private RegistryKey _perfDataKey = null; private string _machineName; internal PerformanceMonitor(string machineName) { _machineName = machineName; Init(); } private void Init() { _perfDataKey = Registry.PerformanceData; } // Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some // scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY, // ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the // wait loop and switch case below). We want to wait most certainly more than a 2min window. // The curent wait time of up to 10mins takes care of the known stress deadlock issues. In most // cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time // we wait may not be sufficient if the Win32 code keeps running into this deadlock again // and again. A condition very rare but possible in theory. We would get back to the user // in this case with InvalidOperationException after the wait time expires. internal byte[] GetData(string item) { int waitRetries = 17; //2^16*10ms == approximately 10mins int waitSleep = 0; byte[] data = null; int error = 0; while (waitRetries > 0) { try { data = (byte[])_perfDataKey.GetValue(item); return data; } catch (IOException e) { error = Marshal.GetHRForException(e); switch (error) { case Interop.mincore.RPCStatus.RPC_S_CALL_FAILED: case Interop.mincore.Errors.ERROR_INVALID_HANDLE: case Interop.mincore.RPCStatus.RPC_S_SERVER_UNAVAILABLE: Init(); goto case Interop.mincore.WaitOptions.WAIT_TIMEOUT; case Interop.mincore.WaitOptions.WAIT_TIMEOUT: case Interop.mincore.Errors.ERROR_NOT_READY: case Interop.mincore.Errors.ERROR_LOCK_FAILED: case Interop.mincore.Errors.ERROR_BUSY: --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } break; default: throw new Win32Exception(error); } } catch (InvalidCastException e) { throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, _perfDataKey.ToString()), e); } } throw new Win32Exception(error); } } } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; using qx.ui.mobile.core; namespace qx.ui.mobile.page { /// <summary> /// <para>A page is a widget which provides a screen with which users /// can interact in order to do something. Most times a page provides a single task /// or a group of related tasks.</para> /// <para>A qooxdoo mobile application is usually composed of one or more loosely bound /// pages. Typically there is one page that presents the &#8220;main&#8221; view.</para> /// <para>Pages can have one or more child widgets from the <see cref="qx.ui.mobile"/> /// namespace. Normally a page provides a <see cref="qx.ui.mobile.navigationbar.NavigationBar"/> /// for the navigation between pages.</para> /// <para>To navigate between two pages, just call the <see cref="Show"/> method of the page /// that should be shown. Depending on the used page manager a page transition will be animated. /// There are several animations available. Have /// a look at the <see cref="qx.ui.mobile.page.Manager"/> manager or <see cref="qx.ui.mobile.layout.Card"/> card layout for more information.</para> /// <para>A page has predefined lifecycle methods that get called by the used page manager /// when a page gets shown. Each time another page is requested to be shown the currently shown page /// is stopped. The other page, will be, if shown for the first time, initialized and started /// afterwards. For all called lifecycle methods an event is fired.</para> /// <para>Call of the <see cref="Show"/> method triggers the following lifecycle methods:</para> /// <list type="bullet"> /// <item>initialize: Initializes the page to show</item> /// <item>start: Gets called when the page to show is started</item> /// <item>stop: Stops the current page</item> /// </list> /// <para>IMPORTANT: Define all child widgets of a page when the <see cref="Initialize"/> lifecycle /// method is called, either by listening to the <see cref="Initialize"/> event or overriding /// the <see cref="#_initialize"/> method. This is because a page can be instanced during /// application startup and would then decrease performance when the widgets would be /// added during constructor call. The initialize event and the /// <see cref="#_initialize"/> lifecycle method are only called when the page is shown /// for the first time.</para> /// </summary> [JsType(JsMode.Prototype, Name = "qx.ui.mobile.page.Page", OmitOptionalParameters = true, Export = false)] public partial class Page : qx.ui.mobile.container.Composite { #region Events /// <summary> /// <para>Fired when the method <see cref="Back"/> is called. Data indicating /// whether the action was triggered by a key event or not.</para> /// </summary> public event Action<qx.eventx.type.Data> OnBack; /// <summary> /// <para>Fired when the lifecycle method <see cref="Initialize"/> is called</para> /// </summary> public event Action<qx.eventx.type.Event> OnInitialize; /// <summary> /// <para>Fired when the method <see cref="Menu"/> is called</para> /// </summary> public event Action<qx.eventx.type.Event> OnMenu; /// <summary> /// <para>Fired when the lifecycle method <see cref="Pause"/> is called</para> /// </summary> public event Action<qx.eventx.type.Event> OnPause; /// <summary> /// <para>Fired when the lifecycle method <see cref="Resume"/> is called</para> /// </summary> public event Action<qx.eventx.type.Event> OnResume; /// <summary> /// <para>Fired when the lifecycle method <see cref="Start"/> is called</para> /// </summary> public event Action<qx.eventx.type.Event> OnStart; /// <summary> /// <para>Fired when the lifecycle method <see cref="Stop"/> is called</para> /// </summary> public event Action<qx.eventx.type.Event> OnStop; #endregion Events #region Properties /// <summary> /// <para>The default CSS class used for this widget. The default CSS class /// should contain the common appearance of the widget. /// It is set to the container element of the widget. Use <see cref="AddCssClass"/> /// to enhance the default appearance of the widget.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "defaultCssClass", NativeField = true)] public string DefaultCssClass { get; set; } /// <summary> /// <para>Whether the resize should fire the &#8220;domupdated&#8221; event. Set this to &#8220;true&#8221; /// whenever other elements should react on this size change (e.g. when the size /// change does not infect the size of the application, but other widgets should /// react).</para> /// </summary> [JsProperty(Name = "fireDomUpdatedOnResize", NativeField = true)] public bool FireDomUpdatedOnResize { get; set; } #endregion Properties #region Methods public Page() { throw new NotImplementedException(); } public Page(object layout) { throw new NotImplementedException(); } /// <summary> /// <para>Fires the back event. Call this method if you want to request /// a back action. For Android PhoneGap applications this method gets called /// by the used page manager when the back button was pressed. Return true /// to exit the application.</para> /// </summary> /// <param name="triggeredByKeyEvent">Whether the back action was triggered by a key event.</param> /// <returns>Whether the exit should be exit or not. Return true</returns> [JsMethod(Name = "back")] public bool Back(bool triggeredByKeyEvent) { throw new NotImplementedException(); } /// <summary> /// <para>Hide this widget and exclude it from the underlying layout.</para> /// </summary> /// <param name="properties">The animation properties to set. Key / value pairs.</param> [JsMethod(Name = "exclude")] public void Exclude(object properties) { throw new NotImplementedException(); } /// <summary> /// <para>Lifecycle method. Called by the page manager when the page is shown. /// Fires the initialize event. You should create and add all your /// child widgets of the view, either by listening to the <see cref="Initialize"/> event or overriding /// the <see cref="#_initialize"/> method. This is because a page can be instanced during /// application startup and would then decrease performance when the widgets would be /// added during constructor call. The <see cref="#_initialize"/> lifecycle method and the /// initialize are only called once when the page is shown for the first time.</para> /// </summary> [JsMethod(Name = "initialize")] public void Initialize() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the status of the initialization of the page.</para> /// </summary> /// <returns>Whether the page is already initialized or not</returns> [JsMethod(Name = "isInitialized")] public bool IsInitialized() { throw new NotImplementedException(); } /// <summary> /// <para>Only used by Android PhoneGap applications. Called by the used page manager /// when the menu button was pressed. Fires the menu event.</para> /// </summary> [JsMethod(Name = "menu")] public void Menu() { throw new NotImplementedException(); } /// <summary> /// <para>Lifecycle method. Not used right now. Should be called when the current page /// is interrupted, e.g. by a dialog, so that page view updates can be interrupted. /// Fires the pause event.</para> /// </summary> [JsMethod(Name = "pause")] public void Pause() { throw new NotImplementedException(); } /// <summary> /// <para>Lifecycle method. Not used right now. Should be called when the current page /// is resuming from a interruption, e.g. when a dialog is closed, so that page /// can resume updating the view. /// Fires the resume event.</para> /// </summary> [JsMethod(Name = "resume")] public void Resume() { throw new NotImplementedException(); } /// <summary> /// <para>Make this widget visible.</para> /// </summary> /// <param name="properties">The animation properties to set. Key / value pairs.</param> [JsMethod(Name = "show")] public void Show(object properties) { throw new NotImplementedException(); } /// <summary> /// <para>Lifecycle method. Called by the page manager after the <see cref="Initialize"/> /// method when the page is shown. Fires the start event. You should /// register all your event listener when this event occurs, so that no page /// updates are down when page is not shown.</para> /// </summary> [JsMethod(Name = "start")] public void Start() { throw new NotImplementedException(); } /// <summary> /// <para>Lifecycle method. Called by the page manager when another page is shown. /// Fires the stop event. You should unregister all your event /// listener when this event occurs, so that no page updates are down when page is not shown.</para> /// </summary> [JsMethod(Name = "stop")] public void Stop() { throw new NotImplementedException(); } /// <summary> /// <para>Resizes the container element to the height of the parent element.</para> /// </summary> [JsMethod(Name = "fixSize")] public void FixSize() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property fireDomUpdatedOnResize.</para> /// </summary> [JsMethod(Name = "getFireDomUpdatedOnResize")] public bool GetFireDomUpdatedOnResize() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property fireDomUpdatedOnResize /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property fireDomUpdatedOnResize.</param> [JsMethod(Name = "initFireDomUpdatedOnResize")] public void InitFireDomUpdatedOnResize(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property fireDomUpdatedOnResize equals true.</para> /// </summary> [JsMethod(Name = "isFireDomUpdatedOnResize")] public void IsFireDomUpdatedOnResize() { throw new NotImplementedException(); } /// <summary> /// <para>Removes fixed size from container.</para> /// </summary> [JsMethod(Name = "releaseFixedSize")] public void ReleaseFixedSize() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property fireDomUpdatedOnResize.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetFireDomUpdatedOnResize")] public void ResetFireDomUpdatedOnResize() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property fireDomUpdatedOnResize.</para> /// </summary> /// <param name="value">New value for property fireDomUpdatedOnResize.</param> [JsMethod(Name = "setFireDomUpdatedOnResize")] public void SetFireDomUpdatedOnResize(bool value) { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property fireDomUpdatedOnResize.</para> /// </summary> [JsMethod(Name = "toggleFireDomUpdatedOnResize")] public void ToggleFireDomUpdatedOnResize() { throw new NotImplementedException(); } #endregion Methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Text.Tests { public class UTF8EncodingTests { [Fact] public void Ctor_Empty() { UTF8Encoding encoding = new UTF8Encoding(); VerifyUtf8Encoding(encoding, encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_Bool(bool encoderShouldEmitUTF8Identifier) { UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier); VerifyUtf8Encoding(encoding, encoderShouldEmitUTF8Identifier, throwOnInvalidBytes: false); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public void Ctor_Bool_Bool(bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes) { UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes); VerifyUtf8Encoding(encoding, encoderShouldEmitUTF8Identifier, throwOnInvalidBytes); } private static void VerifyUtf8Encoding(UTF8Encoding encoding, bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes) { if (encoderShouldEmitUTF8Identifier) { Assert.Equal(new byte[] { 0xEF, 0xBB, 0xBF }, encoding.GetPreamble()); } else { Assert.Empty(encoding.GetPreamble()); } if (throwOnInvalidBytes) { Assert.Equal(EncoderFallback.ExceptionFallback, encoding.EncoderFallback); Assert.Equal(DecoderFallback.ExceptionFallback, encoding.DecoderFallback); } else { Assert.Equal(new EncoderReplacementFallback("\uFFFD"), encoding.EncoderFallback); Assert.Equal(new DecoderReplacementFallback("\uFFFD"), encoding.DecoderFallback); } } public static IEnumerable<object[]> Encodings_TestData() { yield return new object[] { Encoding.UTF8 }; yield return new object[] { new UTF8Encoding(true, true) }; yield return new object[] { new UTF8Encoding(true, false) }; yield return new object[] { new UTF8Encoding(false, true) }; yield return new object[] { new UTF8Encoding(false, false) }; yield return new object[] { Encoding.GetEncoding("utf-8") }; } [Theory] [MemberData(nameof(Encodings_TestData))] public void WebName(UTF8Encoding encoding) { Assert.Equal("utf-8", encoding.WebName); } [Theory] [MemberData(nameof(Encodings_TestData))] public void CodePage(UTF8Encoding encoding) { Assert.Equal(65001, encoding.CodePage); } [Theory] [MemberData(nameof(Encodings_TestData))] public void EncodingName(UTF8Encoding encoding) { Assert.NotEmpty(encoding.EncodingName); // Unicode (UTF-8) in en-US } [Theory] [MemberData(nameof(Encodings_TestData))] public void IsSingleByte(UTF8Encoding encoding) { Assert.False(encoding.IsSingleByte); } [Theory] [MemberData(nameof(Encodings_TestData))] public void Clone(UTF8Encoding encoding) { UTF8Encoding clone = (UTF8Encoding)encoding.Clone(); Assert.False(clone.IsReadOnly); Assert.NotSame(encoding, clone); Assert.Equal(encoding, clone); } [Fact] public void Clone_CanCloneUtf8SingletonAndSetFallbacks() { // The Encoding.UTF8 singleton is a sealed subclass of UTF8Encoding that has // its own internal fast-track logic that might make assumptions about any // configured replacement behavior. This test clones the singleton instance // to ensure that we can properly set custom fallbacks and that they're // honored by the Encoding. UTF8Encoding clone = (UTF8Encoding)Encoding.UTF8.Clone(); clone.DecoderFallback = new DecoderReplacementFallback("[BAD]"); clone.EncoderFallback = new EncoderReplacementFallback("?"); Assert.Equal("ab[BAD]xy", clone.GetString(new byte[] { (byte)'a', (byte)'b', 0xC0, (byte)'x', (byte)'y' })); Assert.Equal(new byte[] { (byte)'a', (byte)'?', (byte)'c' }, clone.GetBytes("a\ud800c")); } public static IEnumerable<object[]> Equals_TestData() { UTF8Encoding encoding = new UTF8Encoding(); yield return new object[] { encoding, encoding, true }; yield return new object[] { new UTF8Encoding(), new UTF8Encoding(), true }; yield return new object[] { new UTF8Encoding(), new UTF8Encoding(false), true }; yield return new object[] { new UTF8Encoding(), new UTF8Encoding(true), false }; yield return new object[] { new UTF8Encoding(false), new UTF8Encoding(false), true }; yield return new object[] { new UTF8Encoding(true), new UTF8Encoding(true), true }; yield return new object[] { new UTF8Encoding(true), new UTF8Encoding(false), false }; yield return new object[] { new UTF8Encoding(), new UTF8Encoding(false, false), true }; yield return new object[] { new UTF8Encoding(), new UTF8Encoding(false, true), false }; yield return new object[] { new UTF8Encoding(false), new UTF8Encoding(false, false), true }; yield return new object[] { new UTF8Encoding(true), new UTF8Encoding(true, false), true }; yield return new object[] { new UTF8Encoding(false), new UTF8Encoding(false, true), false }; yield return new object[] { new UTF8Encoding(true, true), new UTF8Encoding(true, true), true }; yield return new object[] { new UTF8Encoding(false, false), new UTF8Encoding(false, false), true }; yield return new object[] { new UTF8Encoding(true, false), new UTF8Encoding(true, false), true }; yield return new object[] { new UTF8Encoding(true, false), new UTF8Encoding(false, true), false }; yield return new object[] { Encoding.UTF8, Encoding.UTF8, true }; yield return new object[] { Encoding.GetEncoding("utf-8"), Encoding.UTF8, true }; yield return new object[] { Encoding.UTF8, new UTF8Encoding(true), true }; yield return new object[] { Encoding.UTF8, new UTF8Encoding(false), false }; yield return new object[] { new UTF8Encoding(), new TimeSpan(), false }; yield return new object[] { new UTF8Encoding(), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(UTF8Encoding encoding, object value, bool expected) { Assert.Equal(expected, encoding.Equals(value)); if (value is UTF8Encoding) { Assert.Equal(expected, encoding.GetHashCode().Equals(value.GetHashCode())); } } [Fact] public void CustomSubclassMethodOverrides() { // Ensures that we don't inadvertently implement methods like UTF8Encoding.GetBytes(string) // without accounting for the fact that a subclassed type may have overridden GetBytes(char[], int, int). UTF8Encoding encoding = new CustomUTF8Encoding(); Assert.Equal(new byte[] { (byte)'!', (byte)'a', (byte)'!', (byte)'b', (byte)'!', (byte)'c', (byte)'!' }, encoding.GetBytes("abc")); Assert.Equal("*a*b*c*".ToCharArray(), encoding.GetChars(new byte[] { (byte)'a', (byte)'b', (byte)'c' })); Assert.Equal("~a~b~c~", encoding.GetString(new byte[] { (byte)'a', (byte)'b', (byte)'c' })); } /// <summary> /// An Encoding which is not actually legitimate UTF-8, but which nevertheless /// subclasses UTF8Encoding. A realistic scenario where one might do this would be to /// support "wobbly" data (where the code points U+D800..DFFF are round-trippable). /// </summary> private class CustomUTF8Encoding : UTF8Encoding { public override int GetByteCount(string chars) { return chars.Length * 2 + 1; } public override int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // We'll narrow chars to bytes and surround each char with an exclamation point. List<byte> builder = new List<byte>() { (byte)'!' }; foreach (char ch in chars.AsSpan(charIndex, charCount)) { builder.Add((byte)ch); builder.Add((byte)'!'); } builder.CopyTo(bytes, byteIndex); return builder.Count; } public override int GetCharCount(byte[] bytes, int index, int count) { return count * 2 + 1; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // We'll widen bytes to chars and surround each char with an asterisk. List<char> builder = new List<char>() { '*' }; foreach (byte b in bytes.AsSpan(byteIndex, byteCount)) { builder.Add((char)b); builder.Add('*'); } builder.CopyTo(chars, charIndex); return builder.Count; } public override string GetString(byte[] bytes, int byteIndex, int byteCount) { // We'll widen bytes to chars and surround each char with a tilde. StringBuilder builder = new StringBuilder("~"); foreach (byte b in bytes.AsSpan(byteIndex, byteCount)) { builder.Append((char)b); builder.Append('~'); } return builder.ToString(); } public override int GetMaxByteCount(int charCount) { return charCount * 2 + 1; } public override int GetMaxCharCount(int byteCount) { return byteCount * 2 + 1; } } } }
// Copyright 2007 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.IO; using System.Text; using Google.MailClientInterfaces; using System.Globalization; namespace Google.Thunderbird { internal class ThunderbirdFolder : IFolder { string folderPath; string name; uint messageCount; FolderKind folderKind; IFolder parentFolder; IStore store; ArrayList subFolders; internal ThunderbirdFolder(FolderKind folderKind, string name, string folderPath, IFolder parentFolder, IStore clientStore) { this.folderKind = folderKind; this.name = name; this.folderPath = folderPath; this.parentFolder = parentFolder; this.store = clientStore; this.messageCount = this.CountEmails(); this.subFolders = new ArrayList(); this.PopulateFolder(); } public FolderKind Kind { get { return this.folderKind; } } public uint MailCount { get { return this.messageCount; } } public string Name { get { return this.name; } } public IFolder ParentFolder { get { return this.parentFolder; } } public IStore Store { get { return this.store; } } public IEnumerable SubFolders { get { return this.subFolders; } } public IEnumerable Mails { get { return new ThunderbirdEmailEnumerable(this); } } public string FolderPath { get { return this.folderPath; } } private uint CountEmails() { uint numEmails = 0; try { using (StreamReader fileReader = new StreamReader(folderPath)) { while (fileReader.Peek() != -1) { string line = fileReader.ReadLine(); if (0 == line.IndexOf(ThunderbirdConstants.MboxMailStart)) { ++numEmails; } // Check if the message has been expunged from the mailbox. if (line.StartsWith(ThunderbirdConstants.XMozillaStatus)) { int xMozillaStatusLen = ThunderbirdConstants.XMozillaStatus.Length; string status = line.Substring( xMozillaStatusLen - 1, line.Length - xMozillaStatusLen + 1); int statusNum = 0; try { statusNum = int.Parse(status, NumberStyles.HexNumber); } catch { // The flow should never reach here if the mbox file is correct. // In case it reaches here we will assume that there was an // error here and decrement the count of mail and continue. --numEmails; continue; } int deleted = statusNum & 0x0008; if (deleted > 0) { --numEmails; } } } } } catch (IOException) { // There might be 2 reasons for the program to come here. // 1. The file does not exist. // 2. The file is beign read by some other program. // In both cases we should not do anything. } return numEmails; } // For every folder check whether a correspoding .sbd is present. If it // is present just populate it and add it to subfolder's list. private void PopulateFolder() { string subFoldersPath = Path.GetFullPath( this.folderPath + ThunderbirdConstants.ThunderbirdDir); bool doesSubFolderExist = Directory.Exists(subFoldersPath); if (!doesSubFolderExist) { return; } foreach (string filePath in Directory.GetFiles(subFoldersPath, ThunderbirdConstants.StarDotMSF)) { string fileName = Path.GetFileName(filePath); int msfIndex = fileName.LastIndexOf(ThunderbirdConstants.ThunderbirdMSFExtension); int fileLength = fileName.Length; // Check to see if there is an msf file present. If it is, check to see // if the corresponding msf file is present. This is introduced because // there were cases in which msf files were present but mbox files were // not present which was causing scav to crash. if (msfIndex != -1 && fileLength != ThunderbirdConstants.ThunderbirdMSFLen && (msfIndex + ThunderbirdConstants.ThunderbirdMSFLen == fileLength)) { // Strip out the msf extension and check whether the file exists. string tempFileName = fileName.Substring(0, msfIndex); bool doesFileExist = false; doesFileExist = File.Exists(Path.Combine(subFoldersPath, tempFileName)); if (!doesFileExist) { continue; } FolderKind folderKind = this.GetFolderKind(tempFileName); ThunderbirdFolder folder = new ThunderbirdFolder( folderKind, tempFileName, Path.Combine(subFoldersPath, tempFileName), this, this.store); this.subFolders.Add(folder); } } } private FolderKind GetFolderKind(string folderName) { switch (folderName) { case ThunderbirdConstants.Inbox: return FolderKind.Inbox; case ThunderbirdConstants.Drafts: return FolderKind.Draft; case ThunderbirdConstants.Sent: return FolderKind.Sent; case ThunderbirdConstants.Trash: return FolderKind.Trash; default: return FolderKind.Other; } } } }
namespace Macabresoft.Macabre2D.UI.Editor; using System; using System.ComponentModel; using System.IO; using System.Threading.Tasks; using System.Windows.Input; using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.Media.Imaging; using Macabresoft.AvaloniaEx; using Macabresoft.Macabre2D.Framework; using Macabresoft.Macabre2D.UI.Common; using ReactiveUI; using Unity; public class SpriteReferenceEditor : ValueEditorControl<SpriteReference> { public static readonly DirectProperty<SpriteReferenceEditor, ICommand> ClearSpriteCommandProperty = AvaloniaProperty.RegisterDirect<SpriteReferenceEditor, ICommand>( nameof(ClearSpriteCommand), editor => editor.ClearSpriteCommand); public static readonly DirectProperty<SpriteReferenceEditor, string> ContentPathProperty = AvaloniaProperty.RegisterDirect<SpriteReferenceEditor, string>( nameof(ContentPath), editor => editor.ContentPath); public static readonly DirectProperty<SpriteReferenceEditor, int> MaxIndexProperty = AvaloniaProperty.RegisterDirect<SpriteReferenceEditor, int>( nameof(MaxIndex), editor => editor.MaxIndex); public static readonly DirectProperty<SpriteReferenceEditor, BaseSpriteEntity> RenderEntityProperty = AvaloniaProperty.RegisterDirect<SpriteReferenceEditor, BaseSpriteEntity>( nameof(RenderEntity), editor => editor.RenderEntity); public static readonly DirectProperty<SpriteReferenceEditor, ICommand> SelectSpriteCommandProperty = AvaloniaProperty.RegisterDirect<SpriteReferenceEditor, ICommand>( nameof(SelectSpriteCommand), editor => editor.SelectSpriteCommand); public static readonly DirectProperty<SpriteReferenceEditor, SpriteDisplayModel> SpriteProperty = AvaloniaProperty.RegisterDirect<SpriteReferenceEditor, SpriteDisplayModel>( nameof(Sprite), editor => editor.Sprite); private readonly IAssetManager _assetManager; private readonly ILocalDialogService _dialogService; private readonly IFileSystemService _fileSystem; private readonly IPathService _pathService; private readonly IUndoService _undoService; private ICommand _clearSpriteCommand; private string _contentPath; private int _maxIndex; private SpriteDisplayModel _sprite; public SpriteReferenceEditor() : this( null, Resolver.Resolve<IAssetManager>(), Resolver.Resolve<ILocalDialogService>(), Resolver.Resolve<IFileSystemService>(), Resolver.Resolve<IPathService>(), Resolver.Resolve<IUndoService>()) { } [InjectionConstructor] public SpriteReferenceEditor( ValueControlDependencies dependencies, IAssetManager assetManager, ILocalDialogService dialogService, IFileSystemService fileSystem, IPathService pathService, IUndoService undoService) : base(dependencies) { this._assetManager = assetManager; this._dialogService = dialogService; this._fileSystem = fileSystem; this._pathService = pathService; this._undoService = undoService; this.SelectSpriteCommand = ReactiveCommand.CreateFromTask(this.SelectSprite); this.ResetBitmap(); this.InitializeComponent(); } public BaseSpriteEntity RenderEntity => this.Owner as BaseSpriteEntity; public ICommand SelectSpriteCommand { get; } public ICommand ClearSpriteCommand { get => this._clearSpriteCommand; private set => this.SetAndRaise(ClearSpriteCommandProperty, ref this._clearSpriteCommand, value); } public string ContentPath { get => this._contentPath; private set => this.SetAndRaise(ContentPathProperty, ref this._contentPath, value); } public int MaxIndex { get => this._maxIndex; private set => this.SetAndRaise(MaxIndexProperty, ref this._maxIndex, value); } public SpriteDisplayModel Sprite { get => this._sprite; private set => this.SetAndRaise(SpriteProperty, ref this._sprite, value); } protected override void OnValueChanged() { base.OnValueChanged(); if (this.Value != null) { this.ClearSpriteCommand = ReactiveCommand.Create( this.ClearSprite, this.Value.WhenAny(x => x.ContentId, y => y.Value != Guid.Empty)); this.ResetBitmap(); this.Value.PropertyChanged += this.Value_PropertyChanged; } } protected override void OnValueChanging() { base.OnValueChanging(); if (this.Value != null) { this.Value.PropertyChanged -= this.Value_PropertyChanged; } } private void ClearSprite() { var asset = this.Value.Asset; var spriteIndex = this.Value.SpriteIndex; if (asset != null) { this._undoService.Do( () => this.Value.Clear(), () => { this.Value.SpriteIndex = spriteIndex; this.Value.Initialize(asset); }); } } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void NumericUpDown_OnValueChanged(object sender, NumericUpDownValueChangedEventArgs e) { if (this.Value != null) { var oldValue = (byte)e.OldValue; var newValue = (byte)e.NewValue; if (oldValue != newValue && this.Value.SpriteIndex != newValue) { this._undoService.Do(() => { this.Value.SpriteIndex = newValue; }, () => { this.Value.SpriteIndex = oldValue; }); } } } private void ResetBitmap() { this.ContentPath = null; this.Sprite = null; this.MaxIndex = 0; if (this._assetManager != null && this.Value is SpriteReference { Asset: { } } reference && reference.ContentId != Guid.Empty && this._assetManager.TryGetMetadata(reference.ContentId, out var metadata) && metadata != null) { this.MaxIndex = reference.Asset.MaxIndex; this.ContentPath = $"{metadata.GetContentPath()}{metadata.ContentFileExtension}"; var fullPath = Path.Combine(this._pathService.ContentDirectoryPath, this.ContentPath); if (this._fileSystem.DoesFileExist(fullPath)) { var bitmap = new Bitmap(fullPath); if (bitmap.PixelSize != PixelSize.Empty) { this.Sprite = new SpriteDisplayModel(bitmap, reference.SpriteIndex, reference.Asset); } } } } private async Task SelectSprite() { var (spriteSheet, spriteIndex) = await this._dialogService.OpenSpriteSelectionDialog(); if (spriteSheet != null) { var originalAsset = this.Value.Asset; var originalIndex = this.Value.SpriteIndex; this._undoService.Do( () => { this.Value.SpriteIndex = spriteIndex; this.Value.Initialize(spriteSheet); }, () => { if (originalAsset != null) { this.Value.SpriteIndex = originalIndex; this.Value.Initialize(originalAsset); } else { this.Value.Clear(); } }); } } private void Value_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName is nameof(SpriteReference.ContentId) or nameof(SpriteReference.SpriteIndex) or nameof(SpriteSheetAsset.Rows) or nameof(SpriteSheetAsset.Columns)) { this.ResetBitmap(); } } }