context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Project: Membership Log (application using WhaTBI?) * Filename: BaseForm.cs * Description: Common form code */ using System; using System.Collections; using System.ComponentModel; using System.Reflection; using System.Windows.Forms; using Pdbartlett.Whatbi; namespace Pdbartlett.MembershipLog { public class BaseForm : Form { // Custom events public event CancelEventHandler Submit; // Enumerated data types public enum RecordAction { None, View, Update, Create, Delete }; [Flags] protected enum ValueBoxFlags { None = 0x00 , ReadOnly = 0x01 , InitOnly = 0x02 , Multiline = 0x04 , DontAlign = 0x08 , BindComboText = 0x10 , IsBoolean = 0x20 }; protected bool FlagSet(ValueBoxFlags flags, ValueBoxFlags reqd) { return ((flags & reqd) == reqd); } // String constants (should be moved out for globalisation) protected const string MENU_RECORD = "&Record"; protected const string MENU_RECORD_NEW = "&New..."; protected const string MENU_RECORD_VIEW = "&View..."; protected const string MENU_RECORD_UPDATE = "&Update..."; protected const string MENU_RECORD_DELETE = "&Delete"; // Numerical constants (some refactoring needed here!) protected const int BORDER_SIZE = 3; private const int COLUMN_TWO = 100; private const int MULTILINE_HEIGHT_FACTOR = 3; // Member variables private object m_object; private RecordAction m_action; // Controls (may or may not be created) private Button m_Ok; // Accessor properties protected object Subject { get { return m_object; } } protected RecordAction Action { get { return m_action; } } protected bool OkEnabled { get { return m_Ok != null && m_Ok.Enabled; } set { if (m_Ok == null) throw new InvalidOperationException(); m_Ok.Enabled = value; } } // Construction protected BaseForm() : this(null, RecordAction.None, false) {} protected BaseForm(object obj, RecordAction action, bool disallowNullNone) { if (!Enum.IsDefined(typeof(RecordAction), action)) throw new ArgumentException(); if (disallowNullNone && (obj == null || action == RecordAction.None)) throw new ArgumentException(); m_object = obj; m_action = action; } // Methods protected void OK_Click(object sender, EventArgs ea) { CancelEventArgs cea = new CancelEventArgs(); OnSubmit(cea); if (cea.Cancel) return; DialogResult = DialogResult.OK; CompleteEdit(); Hide(); } protected void Cancel_Click(object sender, EventArgs ea) { DialogResult = DialogResult.Cancel; CancelEdit(); Hide(); } protected virtual void OnSubmit(CancelEventArgs cea) { if (Submit != null) Submit(this, cea); } private void CompleteEdit() { if (Subject != null) GetSubjectBindingManager().EndCurrentEdit(); } private void CancelEdit() { if (Subject != null) GetSubjectBindingManager().CancelCurrentEdit(); } private BindingManagerBase GetSubjectBindingManager() { if (Subject == null) throw new BaseException("No subject set"); BindingManagerBase bm = BindingContext[Subject]; if (bm == null) throw new BaseException("Subject not bound"); return bm; } private void AddSubjectDataBinding(Control ctl, string propName, string dataName, ConvertEventHandler formatter, ConvertEventHandler parser) { Binding binding = new Binding(propName, Subject, dataName); if (formatter != null) binding.Format += formatter; if (parser != null) binding.Parse += parser; ctl.DataBindings.Add(binding); } protected int CreateButtons() { return CreateButtons(-1); } protected int CreateButtons(int fieldsBottom) { m_Ok = new Button(); m_Ok.Text = (Action == RecordAction.View) ? "Close" : "OK"; m_Ok.Left = BORDER_SIZE; int buttonTop = ClientSize.Height - m_Ok.Height - BORDER_SIZE; if (fieldsBottom == -1) { m_Ok.Top = buttonTop; } else { m_Ok.Top = fieldsBottom + BORDER_SIZE; int heightDelta = m_Ok.Top - buttonTop; Height += heightDelta; } m_Ok.Anchor = AnchorStyles.Left | AnchorStyles.Bottom; m_Ok.Click += new EventHandler(OK_Click); Controls.Add(m_Ok); AcceptButton = m_Ok; if (Action == RecordAction.View) { CancelButton = m_Ok; } else { Button cancel = new Button(); cancel.Text = "Cancel"; cancel.Left = m_Ok.Right + BORDER_SIZE; cancel.Top = m_Ok.Top; cancel.Anchor = AnchorStyles.Left | AnchorStyles.Bottom; cancel.Click += new EventHandler(Cancel_Click); Controls.Add(cancel); CancelButton = cancel; } return m_Ok.Top; } protected TabControl CreateTabsAndButtons(params string[] tabNames) { int buttonsTop = CreateButtons(); TabControl tabs = new TabControl(); tabs.Left = BORDER_SIZE; tabs.Top = BORDER_SIZE; tabs.Width = ClientSize.Width - 2 * BORDER_SIZE; tabs.Height = buttonsTop - tabs.Top - BORDER_SIZE; tabs.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom; TabPage[] pages = new TabPage[tabNames.Length]; for (int i = 0; i < tabNames.Length; ++i) pages[i] = new TabPage(tabNames[i]); tabs.TabPages.AddRange(pages); Controls.Add(tabs); tabs.BringToFront(); return tabs; } protected int AddLabelledControl(int top, string displayName, string dataName) { return AddLabelledControl(this, top, displayName, dataName); } protected int AddLabelledControl(Control container, int top, string displayName, string dataName) { return AddLabelledControl(container, top, displayName, dataName, ValueBoxFlags.None, null, null, null); } protected int AddLabelledControl(Control container, int top, string displayName, string dataName, ValueBoxFlags flags, ICollection values, ConvertEventHandler formatter, ConvertEventHandler parser) { // Label Label lbl = null; bool isBoolean = FlagSet(flags, ValueBoxFlags.IsBoolean); if (!isBoolean) { lbl = new Label(); lbl.Text = String.Format("{0}:", displayName); lbl.AutoSize = true; lbl.Left = BORDER_SIZE; lbl.Top = top; // for now lbl.Visible = false; // likewise container.Controls.Add(lbl); } // Control Control ctl = null; ComboBox cb = null; string propName; bool isReadOnly = m_action == RecordAction.View || FlagSet(flags, ValueBoxFlags.ReadOnly) || (m_action != RecordAction.Create && FlagSet(flags, ValueBoxFlags.InitOnly)); if (isBoolean) { CheckBox chk = new CheckBox(); chk.Text = displayName; chk.Enabled = !isReadOnly; ctl = chk; propName = "Checked"; } else { if (isReadOnly || values == null || values.Count == 0) { TextBox tb = new TextBox(); tb.ReadOnly = isReadOnly; if (FlagSet(flags, ValueBoxFlags.Multiline)) { tb.Multiline = true; tb.AcceptsReturn = true; tb.ScrollBars = ScrollBars.Both; tb.Height *= MULTILINE_HEIGHT_FACTOR; } ctl = tb; propName = "Text"; } else { cb = new ComboBox(); cb.DropDownStyle = ComboBoxStyle.DropDownList; foreach (object o in values) cb.Items.Add(o); ctl = cb; propName = "SelectedItem"; } } ctl.Top = top; ctl.Left = FlagSet(flags, ValueBoxFlags.DontAlign) ? (lbl.Right + BORDER_SIZE) : COLUMN_TWO; ctl.Width = container.ClientSize.Width - (ctl.Left + BORDER_SIZE); ctl.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right; ctl.Tag = dataName; container.Controls.Add(ctl); if (dataName != null) AddSubjectDataBinding(ctl, propName, dataName, formatter, parser); if (cb != null && FlagSet(flags, ValueBoxFlags.BindComboText)) { IExpression valExpr = Expr.GetProperty(dataName); object value = valExpr.Evaluate(Subject); if (value != null) { string textValue = value.ToString(); foreach (object o in cb.Items) { if (o.ToString() == textValue) { cb.SelectedItem = o; break; } } if (cb.SelectedIndex == -1 && cb.Items.Count > 0) cb.SelectedIndex = 0; } } if (lbl != null) { // can now calculate "correct" top position for label, and make visible lbl.Top = (ctl.Top + ctl.Bottom - lbl.Height) / 2; lbl.Visible = true; } return ctl.Bottom; } protected void DateOnlyFormatter(object sender, ConvertEventArgs cea) { if (cea.DesiredType == typeof(string) && cea.Value.GetType() == typeof(DateTime)) { DateTime dt = (DateTime)cea.Value; cea.Value = dt.ToShortDateString(); } } protected void MultilineFormatter(object sender, ConvertEventArgs cea) { if (cea.DesiredType == typeof(string) && cea.Value.GetType() == typeof(string)) { string s = (string)cea.Value; s = s.Replace("\r\n", "\n"); // normalize cea.Value = s.Replace("\n", "\r\n"); // format } } } }
#region Header /** * JsonMockWrapper.cs * Mock object implementing IJsonWrapper, to facilitate actions like * skipping data more efficiently. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion Header using System; using System.Collections; using System.Collections.Specialized; namespace CrowSerialization.LitJson { public class JsonMockWrapper : IJsonWrapper { public bool IsArray { get { return false; } } public bool IsBoolean { get { return false; } } public bool IsDouble { get { return false; } } public bool IsInt { get { return false; } } public bool IsLong { get { return false; } } public bool IsObject { get { return false; } } public bool IsString { get { return false; } } public bool GetBoolean () { return false; } public double GetDouble () { return 0.0; } public int GetInt () { return 0; } public JsonType GetJsonType () { return JsonType.None; } public long GetLong () { return 0L; } public string GetString () { return ""; } public void SetBoolean ( bool val ) { } public void SetDouble ( double val ) { } public void SetInt ( int val ) { } public void SetJsonType ( JsonType type ) { } public void SetLong ( long val ) { } public void SetString ( string val ) { } public string ToJson () { return ""; } public void ToJson ( JsonWriter writer ) { } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } object IList.this[int index] { get { return null; } set { } } int IList.Add ( object value ) { return 0; } void IList.Clear () { } bool IList.Contains ( object value ) { return false; } int IList.IndexOf ( object value ) { return -1; } void IList.Insert ( int i, object v ) { } void IList.Remove ( object value ) { } void IList.RemoveAt ( int index ) { } int ICollection.Count { get { return 0; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return null; } } void ICollection.CopyTo ( Array array, int index ) { } IEnumerator IEnumerable.GetEnumerator () { return null; } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { return null; } } ICollection IDictionary.Values { get { return null; } } object IDictionary.this[object key] { get { return null; } set { } } void IDictionary.Add ( object k, object v ) { } void IDictionary.Clear () { } bool IDictionary.Contains ( object key ) { return false; } void IDictionary.Remove ( object key ) { } IDictionaryEnumerator IDictionary.GetEnumerator () { return null; } object IOrderedDictionary.this[int idx] { get { return null; } set { } } IDictionaryEnumerator IOrderedDictionary.GetEnumerator () { return null; } void IOrderedDictionary.Insert ( int i, object k, object v ) { } void IOrderedDictionary.RemoveAt ( int i ) { } } }
// /* // * Copyright (c) 2016, Alachisoft. 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. // */ #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 Alachisoft.NosDB.Common.Protobuf { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class ReadQueryResponse { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_ReadQueryResponse__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse, global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_ReadQueryResponse__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static ReadQueryResponse() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChdSZWFkUXVlcnlSZXNwb25zZS5wcm90bxIgQWxhY2hpc29mdC5Ob3NEQi5D", "b21tb24uUHJvdG9idWYaD0RhdGFDaHVuay5wcm90byJTChFSZWFkUXVlcnlS", "ZXNwb25zZRI+CglkYXRhQ2h1bmsYASABKAsyKy5BbGFjaGlzb2Z0Lk5vc0RC", "LkNvbW1vbi5Qcm90b2J1Zi5EYXRhQ2h1bmtCQQokY29tLmFsYWNoaXNvZnQu", "bm9zZGIuY29tbW9uLnByb3RvYnVmQhlSZWFkUXVlcnlSZXNwb25zZVByb3Rv", "Y29s")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NosDB_Common_Protobuf_ReadQueryResponse__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NosDB_Common_Protobuf_ReadQueryResponse__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse, global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_ReadQueryResponse__Descriptor, new string[] { "DataChunk", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Alachisoft.NosDB.Common.Protobuf.Proto.DataChunk.Descriptor, }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ReadQueryResponse : pb::GeneratedMessage<ReadQueryResponse, ReadQueryResponse.Builder> { private ReadQueryResponse() { } private static readonly ReadQueryResponse defaultInstance = new ReadQueryResponse().MakeReadOnly(); private static readonly string[] _readQueryResponseFieldNames = new string[] { "dataChunk" }; private static readonly uint[] _readQueryResponseFieldTags = new uint[] { 10 }; public static ReadQueryResponse DefaultInstance { get { return defaultInstance; } } public override ReadQueryResponse DefaultInstanceForType { get { return DefaultInstance; } } protected override ReadQueryResponse ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.ReadQueryResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_ReadQueryResponse__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<ReadQueryResponse, ReadQueryResponse.Builder> InternalFieldAccessors { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.ReadQueryResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_ReadQueryResponse__FieldAccessorTable; } } public const int DataChunkFieldNumber = 1; private bool hasDataChunk; private global::Alachisoft.NosDB.Common.Protobuf.DataChunk dataChunk_; public bool HasDataChunk { get { return hasDataChunk; } } public global::Alachisoft.NosDB.Common.Protobuf.DataChunk DataChunk { get { return dataChunk_ ?? global::Alachisoft.NosDB.Common.Protobuf.DataChunk.DefaultInstance; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _readQueryResponseFieldNames; if (hasDataChunk) { output.WriteMessage(1, field_names[0], DataChunk); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasDataChunk) { size += pb::CodedOutputStream.ComputeMessageSize(1, DataChunk); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static ReadQueryResponse ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ReadQueryResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ReadQueryResponse ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ReadQueryResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ReadQueryResponse ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ReadQueryResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static ReadQueryResponse ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static ReadQueryResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static ReadQueryResponse ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ReadQueryResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private ReadQueryResponse 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(ReadQueryResponse prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<ReadQueryResponse, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(ReadQueryResponse cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private ReadQueryResponse result; private ReadQueryResponse PrepareBuilder() { if (resultIsReadOnly) { ReadQueryResponse original = result; result = new ReadQueryResponse(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override ReadQueryResponse 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::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.Descriptor; } } public override ReadQueryResponse DefaultInstanceForType { get { return global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.DefaultInstance; } } public override ReadQueryResponse BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is ReadQueryResponse) { return MergeFrom((ReadQueryResponse) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(ReadQueryResponse other) { if (other == global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.DefaultInstance) return this; PrepareBuilder(); if (other.HasDataChunk) { MergeDataChunk(other.DataChunk); } 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(_readQueryResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _readQueryResponseFieldTags[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 10: { global::Alachisoft.NosDB.Common.Protobuf.DataChunk.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.DataChunk.CreateBuilder(); if (result.hasDataChunk) { subBuilder.MergeFrom(DataChunk); } input.ReadMessage(subBuilder, extensionRegistry); DataChunk = subBuilder.BuildPartial(); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasDataChunk { get { return result.hasDataChunk; } } public global::Alachisoft.NosDB.Common.Protobuf.DataChunk DataChunk { get { return result.DataChunk; } set { SetDataChunk(value); } } public Builder SetDataChunk(global::Alachisoft.NosDB.Common.Protobuf.DataChunk value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasDataChunk = true; result.dataChunk_ = value; return this; } public Builder SetDataChunk(global::Alachisoft.NosDB.Common.Protobuf.DataChunk.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasDataChunk = true; result.dataChunk_ = builderForValue.Build(); return this; } public Builder MergeDataChunk(global::Alachisoft.NosDB.Common.Protobuf.DataChunk value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasDataChunk && result.dataChunk_ != global::Alachisoft.NosDB.Common.Protobuf.DataChunk.DefaultInstance) { result.dataChunk_ = global::Alachisoft.NosDB.Common.Protobuf.DataChunk.CreateBuilder(result.dataChunk_).MergeFrom(value).BuildPartial(); } else { result.dataChunk_ = value; } result.hasDataChunk = true; return this; } public Builder ClearDataChunk() { PrepareBuilder(); result.hasDataChunk = false; result.dataChunk_ = null; return this; } } static ReadQueryResponse() { object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.ReadQueryResponse.Descriptor, null); } } #endregion } #endregion Designer generated code
using System; using System.Net; using NUnit.Framework; using SevenDigital.Api.Schema; using SevenDigital.Api.Wrapper.Exceptions; using SevenDigital.Api.Wrapper.Responses; using SevenDigital.Api.Wrapper.Responses.Parsing; namespace SevenDigital.Api.Wrapper.Unit.Tests.Responses.Parsing { [TestFixture] public class ResponseParserTests { [Test] public void Should_throw_argument_null_exception_when_reponse_is_null() { var apiXmlDeserializer = new ResponseParser<TestObject>(new ApiResponseDetector()); Assert.Throws<ArgumentNullException>(() => apiXmlDeserializer.Parse(null)); } [Test] public void Can_deserialize_object() { //success case with well formed response const string xml = "<?xml version=\"1.0\"?><response xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" status=\"ok\"><testObject id=\"1\"> <name>A big test object</name><listOfThings><string>one</string><string>two</string><string>three</string></listOfThings><listOfInnerObjects><InnerObject id=\"1\"><Name>Trevor</Name></InnerObject><InnerObject id=\"2\"><Name>Bill</Name></InnerObject></listOfInnerObjects></testObject></response>"; var stubResponse = new Response(HttpStatusCode.OK, xml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); Assert.DoesNotThrow(() => xmlParser.Parse(stubResponse)); TestObject testObject = xmlParser.Parse(stubResponse); Assert.That(testObject.Id, Is.EqualTo(1)); } [Test] public void Should_throw_input_parameter_exception_for_1001_error_code_with_error_http_status_code() { const string errorXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"1001\"><errorMessage>Test error</errorMessage></error></response>"; var response = new Response(HttpStatusCode.InternalServerError, errorXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<InputParameterException>(() => xmlParser.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.EqualTo(errorXml)); Assert.That(ex.Message, Is.EqualTo("Test error")); Assert.That(ex.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing)); } [Test] public void Should_throw_input_parameter_exception_for_1001_error_code_with_ok_http_status_code() { const string errorXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"1001\"><errorMessage>Test error</errorMessage></error></response>"; var response = new Response(HttpStatusCode.OK, errorXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<InputParameterException>(() => xmlParser.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.EqualTo(errorXml)); Assert.That(ex.Message, Is.EqualTo("Test error")); Assert.That(ex.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing)); } [Test] public void Should_throw_invalid_resource_exception_for_2001_error_code_with_ok_http_status_code() { const string errorXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"2001\"><errorMessage>Test error</errorMessage></error></response>"; var response = new Response(HttpStatusCode.OK, errorXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<InvalidResourceException>(() => xmlParser.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.EqualTo(errorXml)); Assert.That(ex.Message, Is.EqualTo("Test error")); Assert.That(ex.ErrorCode, Is.EqualTo(ErrorCode.ResourceNotFound)); } [Test] public void Should_throw_user_card_exception_for_3001_error_code_with_ok_http_status_code() { const string errorXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"3001\"><errorMessage>Test error</errorMessage></error></response>"; var response = new Response(HttpStatusCode.OK, errorXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<UserCardException>(() => xmlParser.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.EqualTo(errorXml)); Assert.That(ex.Message, Is.EqualTo("Test error")); Assert.That(ex.ErrorCode, Is.EqualTo(ErrorCode.UserCardHasExpired)); } [Test] public void Should_throw_remote_api_exception_for_9001_error_code_with_ok_http_status_code() { const string errorXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"9001\"><errorMessage>Test error</errorMessage></error></response>"; var response = new Response(HttpStatusCode.OK, errorXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<RemoteApiException>(() => xmlParser.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.EqualTo(errorXml)); Assert.That(ex.Message, Is.EqualTo("Test error")); Assert.That(ex.ErrorCode, Is.EqualTo(ErrorCode.UnexpectedInternalServerError)); } [Test] public void Should_throw_unrecognised_error_exception_for_error_code_out_of_range_with_ok_http_status_code() { const string errorXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"42\"><errorMessage>Test error</errorMessage></error></response>"; var response = new Response(HttpStatusCode.OK, errorXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<UnrecognisedErrorException>(() => xmlParser.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.EqualTo(errorXml)); Assert.That(ex.Message, Is.EqualTo("Test error")); } //badly formed xmls / response [Test] public void Should_not_fail_if_xml_is_a_malformed_api_error() { const string badError = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error><errorme></errorme></error></response>"; var response = new Response(HttpStatusCode.OK, badError); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<UnrecognisedErrorException>(() => xmlParser.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.EqualTo(response.Body)); Assert.That(ex.Message, Is.EqualTo(UnrecognisedErrorException.DEFAULT_ERROR_MESSAGE)); } [Test] public void Should_throw_non_xml_response_exception_when_response_body_is_null() { var response = new Response(HttpStatusCode.OK, null); var xmlSerializer = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<NonXmlResponseException>(() => xmlSerializer.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.Null); } [Test] public void Should_throw_non_xml_response_exception_when_response_body_is_empty() { var response = new Response(HttpStatusCode.OK, string.Empty); var xmlSerializer = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<NonXmlResponseException>(() => xmlSerializer.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.Empty); } [Test] public void Should_throw_unrecognised_error_exception_if_xml_is_missing_error_code() { const string validXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error><errorMessage>An error</errorMessage></error></response>"; var response = new Response(HttpStatusCode.OK, validXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<UnrecognisedErrorException>(() => xmlParser.Parse(response)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); Assert.That(ex.ResponseBody, Is.EqualTo(response.Body)); Assert.That(ex.Message, Is.EqualTo(UnrecognisedErrorException.DEFAULT_ERROR_MESSAGE)); } [Test] public void Should_throw_unrecognised_error_exception_if_xml_is_missing_error_message() { const string validXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"123\"></error></response>"; var response = new Response(HttpStatusCode.OK, validXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<UnrecognisedErrorException>(() => xmlParser.Parse(response)); Assert.That(ex.ResponseBody, Is.EqualTo(response.Body)); Assert.That(ex.Message, Is.EqualTo(UnrecognisedErrorException.DEFAULT_ERROR_MESSAGE)); } [Test] public void Error_captures_http_status_code_from_html() { const string badXml = "<html><head>Error</head><body>It did not work<br><hr></body></html>"; var response = new Response(HttpStatusCode.InternalServerError, badXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<NonXmlResponseException>(() => xmlParser.Parse(response)); Assert.That(ex, Is.Not.Null); Assert.That(ex.Message, Is.EqualTo("Response is not xml")); Assert.That(ex.ResponseBody, Is.EqualTo(badXml)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); } [Test] public void Should_throw_non_xml_response_exception_for_html_ok_response() { const string badXml = "<html><head>Error</head><body>Some random html page<br><hr></body></html>"; var response = new Response(HttpStatusCode.OK, badXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<NonXmlResponseException>(() => xmlParser.Parse(response)); Assert.That(ex, Is.Not.Null); Assert.That(ex.Message, Is.EqualTo("Response is not xml")); Assert.That(ex.ResponseBody, Is.EqualTo(badXml)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); } [Test] public void Should_throw_non_xml_response_exception_for_content_that_appears_XML_but_is_not() { const string badXml = @"<?xml version=""1.0"" encoding=""utf-8"" ?><response status=""ok"">LOL!</hah>"; var response = new Response(HttpStatusCode.OK, badXml); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<NonXmlResponseException>(() => xmlParser.Parse(response)); Assert.That(ex, Is.Not.Null); Assert.That(ex.Message, Is.EqualTo("Response is not xml")); Assert.That(ex.ResponseBody, Is.EqualTo(badXml)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); } [Test] public void Should_handle_plaintext_oauth_fail() { const string ErrorText = "OAuth authentication error: Not authorised - no user credentials provided"; var response = new Response(HttpStatusCode.Unauthorized, ErrorText); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<OAuthException>(() => xmlParser.Parse(response)); Assert.That(ex, Is.Not.Null); Assert.That(ex.Message, Is.EqualTo(ErrorText)); Assert.That(ex.ResponseBody, Is.EqualTo(response.Body)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); } [Test] public void Should_handle_plaintext_oauth_fail_with_ok_status() { const string ErrorText = "OAuth authentication error: Not found"; var response = new Response(HttpStatusCode.OK, ErrorText); var xmlParser = new ResponseParser<TestObject>(new ApiResponseDetector()); var ex = Assert.Throws<OAuthException>(() => xmlParser.Parse(response)); Assert.That(ex, Is.Not.Null); Assert.That(ex.Message, Is.EqualTo(ErrorText)); Assert.That(ex.ResponseBody, Is.EqualTo(response.Body)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); } [Test] public void Should_throw_unrecognised_status_exception_when_deserializing_with_invalid_status() { const string InvalidStatusXmlResponse = "<?xml version=\"1.0\"?><response status=\"fish\" version=\"1.2\"></response>"; var response = new Response(HttpStatusCode.OK, InvalidStatusXmlResponse); var xmlParser = new ResponseParser<TestEmptyObject>(new ApiResponseDetector()); var ex = Assert.Throws<UnrecognisedStatusException>(() => xmlParser.Parse(response)); Assert.That(ex, Is.Not.Null); Assert.That(ex.Message, Is.EqualTo(UnrecognisedStatusException.DEFAULT_ERROR_MESSAGE)); Assert.That(ex.ResponseBody, Is.EqualTo(InvalidStatusXmlResponse)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); } [Test] public void Should_throw_exception_when_deserialize_with_missing_status() { const string MissingStatusXmlResponse = "<?xml version=\"1.0\"?><response version=\"1.2\"></response>"; var response = new Response(HttpStatusCode.OK, MissingStatusXmlResponse); var xmlParser = new ResponseParser<TestEmptyObject>(new ApiResponseDetector()); var ex = Assert.Throws<UnrecognisedStatusException>(() => xmlParser.Parse(response)); Assert.That(ex, Is.Not.Null); Assert.That(ex.Message, Is.EqualTo(UnrecognisedStatusException.DEFAULT_ERROR_MESSAGE)); Assert.That(ex.ResponseBody, Is.EqualTo(MissingStatusXmlResponse)); Assert.That(ex.StatusCode, Is.EqualTo(response.StatusCode)); } } }
/* 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.Windows.Forms; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS; namespace MapTips { public class Form1 : System.Windows.Forms.Form { public System.Windows.Forms.CheckBox chkShowTips; public System.Windows.Forms.Button cmdLoadData; public System.Windows.Forms.ComboBox cboDataField; public System.Windows.Forms.ComboBox cboDataLayer; public System.Windows.Forms.Label Label2; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Button cmdFullExtent; public System.Windows.Forms.Label Label3; private System.Windows.Forms.OpenFileDialog openFileDialog1; private ESRI.ArcGIS.Controls.AxMapControl axMapControl1; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; internal CheckBox chkTransparent; private System.ComponentModel.IContainer components; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } protected override void Dispose( bool disposing ) { //Release COM objects ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.chkShowTips = new System.Windows.Forms.CheckBox(); this.cmdLoadData = new System.Windows.Forms.Button(); this.cboDataField = new System.Windows.Forms.ComboBox(); this.cboDataLayer = new System.Windows.Forms.ComboBox(); this.Label2 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.cmdFullExtent = new System.Windows.Forms.Button(); this.Label3 = new System.Windows.Forms.Label(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); this.chkTransparent = new System.Windows.Forms.CheckBox(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.SuspendLayout(); // // chkShowTips // this.chkShowTips.BackColor = System.Drawing.SystemColors.Control; this.chkShowTips.Cursor = System.Windows.Forms.Cursors.Default; this.chkShowTips.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.chkShowTips.ForeColor = System.Drawing.SystemColors.ControlText; this.chkShowTips.Location = new System.Drawing.Point(8, 40); this.chkShowTips.Name = "chkShowTips"; this.chkShowTips.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkShowTips.Size = new System.Drawing.Size(129, 25); this.chkShowTips.TabIndex = 10; this.chkShowTips.Text = "Show Map Tips"; this.chkShowTips.UseVisualStyleBackColor = false; this.chkShowTips.CheckedChanged += new System.EventHandler(this.chkShowTips_CheckedChanged); this.chkShowTips.CheckStateChanged += new System.EventHandler(this.chkShowTips_CheckStateChanged); // // cmdLoadData // this.cmdLoadData.BackColor = System.Drawing.SystemColors.Control; this.cmdLoadData.Cursor = System.Windows.Forms.Cursors.Default; this.cmdLoadData.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmdLoadData.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdLoadData.Location = new System.Drawing.Point(8, 8); this.cmdLoadData.Name = "cmdLoadData"; this.cmdLoadData.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdLoadData.Size = new System.Drawing.Size(113, 25); this.cmdLoadData.TabIndex = 9; this.cmdLoadData.Text = "Load Document..."; this.cmdLoadData.UseVisualStyleBackColor = false; this.cmdLoadData.Click += new System.EventHandler(this.cmdLoadData_Click); // // cboDataField // this.cboDataField.BackColor = System.Drawing.SystemColors.Window; this.cboDataField.Cursor = System.Windows.Forms.Cursors.Default; this.cboDataField.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cboDataField.ForeColor = System.Drawing.SystemColors.WindowText; this.cboDataField.Location = new System.Drawing.Point(176, 40); this.cboDataField.Name = "cboDataField"; this.cboDataField.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cboDataField.Size = new System.Drawing.Size(161, 22); this.cboDataField.TabIndex = 8; this.cboDataField.SelectedIndexChanged += new System.EventHandler(this.cboDataField_SelectedIndexChanged); // // cboDataLayer // this.cboDataLayer.BackColor = System.Drawing.SystemColors.Window; this.cboDataLayer.Cursor = System.Windows.Forms.Cursors.Default; this.cboDataLayer.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cboDataLayer.ForeColor = System.Drawing.SystemColors.WindowText; this.cboDataLayer.Location = new System.Drawing.Point(176, 16); this.cboDataLayer.Name = "cboDataLayer"; this.cboDataLayer.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cboDataLayer.Size = new System.Drawing.Size(161, 22); this.cboDataLayer.TabIndex = 7; this.cboDataLayer.SelectedIndexChanged += new System.EventHandler(this.cboDataLayer_SelectedIndexChanged); // // Label2 // this.Label2.BackColor = System.Drawing.SystemColors.Control; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Location = new System.Drawing.Point(136, 40); this.Label2.Name = "Label2"; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.Size = new System.Drawing.Size(33, 17); this.Label2.TabIndex = 12; this.Label2.Text = "Fields:"; // // Label1 // this.Label1.BackColor = System.Drawing.SystemColors.Control; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Location = new System.Drawing.Point(136, 16); this.Label1.Name = "Label1"; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.Size = new System.Drawing.Size(41, 17); this.Label1.TabIndex = 11; this.Label1.Text = "Layers:"; // // cmdFullExtent // this.cmdFullExtent.BackColor = System.Drawing.SystemColors.Control; this.cmdFullExtent.Cursor = System.Windows.Forms.Cursors.Default; this.cmdFullExtent.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmdFullExtent.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdFullExtent.Location = new System.Drawing.Point(224, 365); this.cmdFullExtent.Name = "cmdFullExtent"; this.cmdFullExtent.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdFullExtent.Size = new System.Drawing.Size(113, 25); this.cmdFullExtent.TabIndex = 13; this.cmdFullExtent.Text = "Zoom to Full Extent"; this.cmdFullExtent.UseVisualStyleBackColor = false; this.cmdFullExtent.Click += new System.EventHandler(this.cmdFullExtent_Click); // // Label3 // this.Label3.BackColor = System.Drawing.SystemColors.Control; this.Label3.Cursor = System.Windows.Forms.Cursors.Default; this.Label3.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Label3.ForeColor = System.Drawing.SystemColors.ControlText; this.Label3.Location = new System.Drawing.Point(8, 373); this.Label3.Name = "Label3"; this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label3.Size = new System.Drawing.Size(209, 17); this.Label3.TabIndex = 14; this.Label3.Text = "Left mouse button to zoomin, right to pan"; // // axMapControl1 // this.axMapControl1.Location = new System.Drawing.Point(8, 88); this.axMapControl1.Name = "axMapControl1"; this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState"))); this.axMapControl1.Size = new System.Drawing.Size(328, 272); this.axMapControl1.TabIndex = 15; this.axMapControl1.OnMouseDown += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMouseDownEventHandler(this.axMapControl1_OnMouseDown); // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(300, 68); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(32, 32); this.axLicenseControl1.TabIndex = 16; // // chkTransparent // this.chkTransparent.AutoSize = true; this.chkTransparent.Location = new System.Drawing.Point(8, 65); this.chkTransparent.Name = "chkTransparent"; this.chkTransparent.Size = new System.Drawing.Size(106, 17); this.chkTransparent.TabIndex = 17; this.chkTransparent.Text = "Transparent Tips"; this.chkTransparent.UseVisualStyleBackColor = true; this.chkTransparent.CheckedChanged += new System.EventHandler(this.chkTransparent_CheckedChanged); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(344, 400); this.Controls.Add(this.chkTransparent); this.Controls.Add(this.axLicenseControl1); this.Controls.Add(this.axMapControl1); this.Controls.Add(this.cmdFullExtent); this.Controls.Add(this.Label3); this.Controls.Add(this.chkShowTips); this.Controls.Add(this.cmdLoadData); this.Controls.Add(this.cboDataField); this.Controls.Add(this.cboDataLayer); this.Controls.Add(this.Label2); this.Controls.Add(this.Label1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion [STAThread] static void Main() { if (!RuntimeManager.Bind(ProductCode.Engine)) { if (!RuntimeManager.Bind(ProductCode.Desktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { //Disable controls chkShowTips.Enabled = false; chkTransparent.Enabled = false; cboDataLayer.Enabled = false; cboDataField.Enabled = false; } private void cboDataLayer_SelectedIndexChanged(object sender, System.EventArgs e) { //Disable field combo if feature layer is not selected and exit if (axMapControl1.get_Layer(cboDataLayer.SelectedIndex) is IFeatureLayer == false) { cboDataField.Items.Clear(); cboDataField.Enabled = false; return; } //Get IFeatureLayer interface IFeatureLayer featureLayer = (IFeatureLayer) axMapControl1.get_Layer(cboDataLayer.SelectedIndex); //Query interface for ILayerFields ILayerFields layerFields = (ILayerFields) featureLayer; int j = 0; cboDataField.Items.Clear(); cboDataField.Enabled = true; //Loop through the fields for (int i = 0; i <= layerFields.FieldCount - 1; i++) { //Get IField interface IField field = layerFields.get_Field(i); //If the field is not the shape field if (field.Type != esriFieldType.esriFieldTypeGeometry) { //Add field name to the control cboDataField.Items.Insert(j, field.Name); //If the field name is the display field if (field.Name == featureLayer.DisplayField) { //Select the field name in the control cboDataField.SelectedIndex = j; } j = j + 1; } } ShowLayerTips(); } private void chkShowTips_CheckStateChanged(object sender, System.EventArgs e) { ShowLayerTips(); } private void cmdFullExtent_Click(object sender, System.EventArgs e) { //Zoom to full extent of data axMapControl1.Extent = axMapControl1.FullExtent; } private void cmdLoadData_Click(object sender, System.EventArgs e) { openFileDialog1.Title = "Browse Map Document"; openFileDialog1.Filter = "Map Documents (*.mxd)|*.mxd"; openFileDialog1.ShowDialog(); //Exit if no map document is selected string sFilePath = openFileDialog1.FileName; if (sFilePath == "") { return; } //Validate and load map document if (axMapControl1.CheckMxFile(sFilePath)== true) { axMapControl1.LoadMxFile(sFilePath,Type.Missing,""); //Enabled MapControl axMapControl1.Enabled = true; } else { MessageBox.Show(sFilePath + " is not a valid ArcMap document"); return; } //Add the layer names to combo cboDataLayer.Items.Clear(); for (int i = 0; i <= axMapControl1.LayerCount - 1; i++) { cboDataLayer.Items.Insert(i, axMapControl1.get_Layer(i).Name); } //Select first layer in control cboDataLayer.SelectedIndex = 0; //Enable controls if disabled if (chkShowTips.Enabled == false) chkShowTips.Enabled = true; if (chkTransparent.Enabled == false) chkTransparent.Enabled = true; if (cboDataLayer.Enabled == false) cboDataLayer.Enabled = true; if (cboDataField.Enabled == false) cboDataField.Enabled = true; } private void ShowLayerTips() { //Loop through the maps layers for (int i = 0; i <= axMapControl1.LayerCount - 1; i++) { //Get ILayer interface ILayer layer = axMapControl1.get_Layer(i); //If is the layer selected in the control if (cboDataLayer.SelectedIndex == i) { //If want to show map tips if (chkShowTips.CheckState == CheckState.Checked) { layer.ShowTips = true; } else { layer.ShowTips = false; } } else { layer.ShowTips = false; } } } private void cboDataField_SelectedIndexChanged(object sender, System.EventArgs e) { //Get IFeatureLayer interface IFeatureLayer featureLayer = (IFeatureLayer) axMapControl1.get_Layer(cboDataLayer.SelectedIndex); //Query interface for IlayerFields ILayerFields layerFields = (ILayerFields) featureLayer; //Loop through the fields for (int i = 0; i <= layerFields.FieldCount - 1; i++) { //Get IField interface IField field = layerFields.get_Field(i); //If the field name is the name selected in the control if (field.Name == cboDataField.Text) { //Set the field as the display field featureLayer.DisplayField = field.Name; break; } } } private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e) { //If left mouse button zoom in if (e.button == 1) { axMapControl1.Extent = axMapControl1.TrackRectangle(); } //If right mouse button pan else if (e.button == 2) { axMapControl1.Pan(); } } private void chkShowTips_CheckedChanged(object sender, EventArgs e) { if (chkShowTips.CheckState == CheckState.Checked) axMapControl1.ShowMapTips = true; else axMapControl1.ShowMapTips = false; } private void chkTransparent_CheckedChanged(object sender, EventArgs e) { if (chkTransparent.CheckState == CheckState.Checked) axMapControl1.TipStyle = esriTipStyle.esriTipStyleTransparent; else axMapControl1.TipStyle = esriTipStyle.esriTipStyleSolid; } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities { using System; using System.Activities.Runtime; using System.Activities.Validation; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime; using System.Text; using System.Security; [Fx.Tag.XamlVisible(false)] public sealed class RuntimeArgument : LocationReference { static InternalEvaluationOrderComparer evaluationOrderComparer; Argument boundArgument; PropertyDescriptor bindingProperty; object bindingPropertyOwner; List<string> overloadGroupNames; int cacheId; string name; UInt32 nameHash; bool isNameHashSet; Type type; public RuntimeArgument(string name, Type argumentType, ArgumentDirection direction) : this(name, argumentType, direction, false) { } public RuntimeArgument(string name, Type argumentType, ArgumentDirection direction, List<string> overloadGroupNames) : this(name, argumentType, direction, false, overloadGroupNames) { } public RuntimeArgument(string name, Type argumentType, ArgumentDirection direction, bool isRequired) : this(name, argumentType, direction, isRequired, null) { } public RuntimeArgument(string name, Type argumentType, ArgumentDirection direction, bool isRequired, List<string> overloadGroupNames) { if (string.IsNullOrEmpty(name)) { throw FxTrace.Exception.ArgumentNullOrEmpty("name"); } if (argumentType == null) { throw FxTrace.Exception.ArgumentNull("argumentType"); } ArgumentDirectionHelper.Validate(direction, "direction"); this.name = name; this.type = argumentType; this.Direction = direction; this.IsRequired = isRequired; this.overloadGroupNames = overloadGroupNames; } internal RuntimeArgument(string name, Type argumentType, ArgumentDirection direction, bool isRequired, List<string> overloadGroups, PropertyDescriptor bindingProperty, object propertyOwner) : this(name, argumentType, direction, isRequired, overloadGroups) { this.bindingProperty = bindingProperty; this.bindingPropertyOwner = propertyOwner; } internal RuntimeArgument(string name, Type argumentType, ArgumentDirection direction, bool isRequired, List<string> overloadGroups, Argument argument) : this(name, argumentType, direction, isRequired, overloadGroups) { Fx.Assert(argument != null, "This ctor is only for arguments discovered via reflection in an IDictionary and therefore cannot be null."); // Bind straightway since we're not dealing with a property and empty binding isn't an issue. Argument.Bind(argument, this); } internal static IComparer<RuntimeArgument> EvaluationOrderComparer { get { if (RuntimeArgument.evaluationOrderComparer == null) { RuntimeArgument.evaluationOrderComparer = new InternalEvaluationOrderComparer(); } return RuntimeArgument.evaluationOrderComparer; } } protected override string NameCore { get { return this.name; } } protected override Type TypeCore { get { return this.type; } } public ArgumentDirection Direction { get; private set; } public bool IsRequired { get; private set; } public ReadOnlyCollection<string> OverloadGroupNames { get { if (this.overloadGroupNames == null) { this.overloadGroupNames = new List<string>(0); } return new ReadOnlyCollection<string>(this.overloadGroupNames); } } internal Activity Owner { get; private set; } internal bool IsInTree { get { return this.Owner != null; } } internal bool IsBound { get { return this.boundArgument != null; } } internal bool IsEvaluationOrderSpecified { get { return this.IsBound && this.BoundArgument.EvaluationOrder != Argument.UnspecifiedEvaluationOrder; } } internal Argument BoundArgument { get { return this.boundArgument; } set { // We allow this to be set an unlimited number of times. We also allow it // to be set back to null. this.boundArgument = value; } } // returns true if this is the "Result" argument of an Activity<T> internal bool IsResult { get { Fx.Assert(this.Owner != null, "should only be called when argument is bound"); return this.Owner.IsResultArgument(this); } } internal void SetupBinding(Activity owningElement, bool createEmptyBinding) { if (this.bindingProperty != null) { Argument argument = (Argument)this.bindingProperty.GetValue(this.bindingPropertyOwner); if (argument == null) { Fx.Assert(this.bindingProperty.PropertyType.IsGenericType, "We only support arguments that are generic types in our reflection walk."); argument = (Argument) Activator.CreateInstance(this.bindingProperty.PropertyType); argument.WasDesignTimeNull = true; if (createEmptyBinding && !this.bindingProperty.IsReadOnly) { this.bindingProperty.SetValue(this.bindingPropertyOwner, argument); } } Argument.Bind(argument, this); } else if (!this.IsBound) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(owningElement); PropertyDescriptor targetProperty = null; for (int i = 0; i < properties.Count; i++) { PropertyDescriptor property = properties[i]; // We only support auto-setting the property // for generic types. Otherwise we have no // guarantee that the argument returned by the // property still matches the runtime argument's // type. if (property.Name == this.Name && property.PropertyType.IsGenericType) { ArgumentDirection direction; Type argumentType; if (ActivityUtilities.TryGetArgumentDirectionAndType(property.PropertyType, out direction, out argumentType)) { if (this.Type == argumentType && this.Direction == direction) { targetProperty = property; break; } } } } Argument argument = null; if (targetProperty != null) { argument = (Argument)targetProperty.GetValue(owningElement); } if (argument == null) { if (targetProperty != null) { if (targetProperty.PropertyType.IsGenericType) { argument = (Argument)Activator.CreateInstance(targetProperty.PropertyType); } else { argument = ActivityUtilities.CreateArgument(this.Type, this.Direction); } } else { argument = ActivityUtilities.CreateArgument(this.Type, this.Direction); } argument.WasDesignTimeNull = true; if (targetProperty != null && createEmptyBinding && !targetProperty.IsReadOnly) { targetProperty.SetValue(owningElement, argument); } } Argument.Bind(argument, this); } Fx.Assert(this.IsBound, "We should always be bound when exiting this method."); } internal bool InitializeRelationship(Activity parent, ref IList<ValidationError> validationErrors) { if (this.cacheId == parent.CacheId) { // We're part of the same tree walk if (this.Owner == parent) { ActivityUtilities.Add(ref validationErrors, ProcessViolation(parent, SR.ArgumentIsAddedMoreThanOnce(this.Name, this.Owner.DisplayName))); // Get out early since we've already initialized this argument. return false; } Fx.Assert(this.Owner != null, "We must have already assigned an owner."); ActivityUtilities.Add(ref validationErrors, ProcessViolation(parent, SR.ArgumentAlreadyInUse(this.Name, this.Owner.DisplayName, parent.DisplayName))); // Get out early since we've already initialized this argument. return false; } if (this.boundArgument != null && this.boundArgument.RuntimeArgument != this) { ActivityUtilities.Add(ref validationErrors, ProcessViolation(parent, SR.RuntimeArgumentBindingInvalid(this.Name, this.boundArgument.RuntimeArgument.Name))); return false; } this.Owner = parent; this.cacheId = parent.CacheId; if (this.boundArgument != null) { this.boundArgument.Validate(parent, ref validationErrors); if (!this.BoundArgument.IsEmpty) { return this.BoundArgument.Expression.InitializeRelationship(this, ref validationErrors); } } return true; } internal bool TryPopulateValue(LocationEnvironment targetEnvironment, ActivityInstance targetActivityInstance, ActivityExecutor executor, object argumentValueOverride, Location resultLocation, bool skipFastPath) { // We populate values in the following order: // Override // Binding // Default Fx.Assert(this.IsBound, "We should ALWAYS be bound at runtime."); if (argumentValueOverride != null) { Fx.Assert( resultLocation == null, "We should never have both an override and a result location unless some day " + "we decide to allow overrides for argument expressions. If that day comes, we " + "need to deal with potential issues around someone providing and override for " + "a result - with the current code it wouldn't end up in the resultLocation."); Location location = this.boundArgument.CreateDefaultLocation(); targetEnvironment.Declare(this, location, targetActivityInstance); location.Value = argumentValueOverride; return true; } else if (!this.boundArgument.IsEmpty) { if (skipFastPath) { this.BoundArgument.Declare(targetEnvironment, targetActivityInstance); return false; } else { return this.boundArgument.TryPopulateValue(targetEnvironment, targetActivityInstance, executor); } } else if (resultLocation != null && this.IsResult) { targetEnvironment.Declare(this, resultLocation, targetActivityInstance); return true; } else { Location location = this.boundArgument.CreateDefaultLocation(); targetEnvironment.Declare(this, location, targetActivityInstance); return true; } } public override Location GetLocation(ActivityContext context) { if (context == null) { throw FxTrace.Exception.ArgumentNull("context"); } // No need to call context.ThrowIfDisposed explicitly since all // the methods/properties on the context will perform that check. ThrowIfNotInTree(); Location location; if (!context.AllowChainedEnvironmentAccess) { if (!object.ReferenceEquals(this.Owner, context.Activity)) { throw FxTrace.Exception.AsError( new InvalidOperationException(SR.CanOnlyGetOwnedArguments( context.Activity.DisplayName, this.Name, this.Owner.DisplayName))); } if (object.ReferenceEquals(context.Environment.Definition, context.Activity)) { if (!context.Environment.TryGetLocation(this.Id, out location)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ArgumentDoesNotExistInEnvironment(this.Name))); } } else { Fx.Assert(this.Owner.IsFastPath, "If an activity defines an argument, then it should define an environment, unless it's SkipArgumentResolution"); Fx.Assert(this.IsResult, "The only user-accessible argument that a SkipArgumentResolution activity can have is its result"); // We need to give the activity access to its result argument because, if it has // no other arguments, it might have been implicitly opted into SkipArgumentResolution location = context.GetIgnorableResultLocation(this); } } else { Fx.Assert(object.ReferenceEquals(this.Owner, context.Activity) || object.ReferenceEquals(this.Owner, context.Activity.MemberOf.Owner), "This should have been validated by the activity which set AllowChainedEnvironmentAccess."); if (!context.Environment.TryGetLocation(this.Id, this.Owner, out location)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ArgumentDoesNotExistInEnvironment(this.Name))); } } return location; } // Soft-Link: This method is referenced through reflection by // ExpressionUtilities.TryRewriteLambdaExpression. Update that // file if the signature changes. public object Get(ActivityContext context) { return context.GetValue<object>(this); } // Soft-Link: This method is referenced through reflection by // ExpressionUtilities.TryRewriteLambdaExpression. Update that // file if the signature changes. public T Get<T>(ActivityContext context) { return context.GetValue<T>(this); } public void Set(ActivityContext context, object value) { context.SetValue(this, value); } // This method exists for the Debugger internal Location InternalGetLocation(LocationEnvironment environment) { Fx.Assert(this.IsInTree, "Argument must be opened"); Location location; if (!environment.TryGetLocation(this.Id, this.Owner, out location)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ArgumentDoesNotExistInEnvironment(this.Name))); } return location; } ValidationError ProcessViolation(Activity owner, string errorMessage) { return new ValidationError(errorMessage, false, this.Name) { Source = owner, Id = owner.Id }; } internal void ThrowIfNotInTree() { if (!this.IsInTree) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.RuntimeArgumentNotOpen(this.Name))); } } void EnsureHash() { if (!this.isNameHashSet) { this.nameHash = CRCHashCode.Calculate(this.Name); this.isNameHashSet = true; } } // This class implements iSCSI CRC-32 check outlined in IETF RFC 3720. // it's marked internal so that DataModel CIT can access it internal static class CRCHashCode { // Reflected value for iSCSI CRC-32 polynomial 0x1edc6f41 const UInt32 polynomial = 0x82f63b78; [Fx.Tag.SecurityNote(Critical = "Critical because it is marked unsafe.", Safe = "Safe because we aren't leaking anything. We are just using pointers to get into the string.")] [SecuritySafeCritical] public unsafe static UInt32 Calculate(string s) { UInt32 result = 0xffffffff; int byteLength = s.Length * sizeof(char); fixed (char* pString = s) { byte* pbString = (byte*)pString; for (int i = 0; i < byteLength; i++) { result ^= pbString[i]; result = ((result & 1) * polynomial) ^ (result >> 1); result = ((result & 1) * polynomial) ^ (result >> 1); result = ((result & 1) * polynomial) ^ (result >> 1); result = ((result & 1) * polynomial) ^ (result >> 1); result = ((result & 1) * polynomial) ^ (result >> 1); result = ((result & 1) * polynomial) ^ (result >> 1); result = ((result & 1) * polynomial) ^ (result >> 1); result = ((result & 1) * polynomial) ^ (result >> 1); } } return ~result; } } class InternalEvaluationOrderComparer : IComparer<RuntimeArgument> { public int Compare(RuntimeArgument x, RuntimeArgument y) { if (!x.IsEvaluationOrderSpecified) { if (y.IsEvaluationOrderSpecified) { return -1; } else { return CompareNameHashes(x, y); } } else { if (y.IsEvaluationOrderSpecified) { return x.BoundArgument.EvaluationOrder.CompareTo(y.BoundArgument.EvaluationOrder); } else { return 1; } } } int CompareNameHashes(RuntimeArgument x, RuntimeArgument y) { x.EnsureHash(); y.EnsureHash(); if (x.nameHash != y.nameHash) { return x.nameHash.CompareTo(y.nameHash); } else { return string.Compare(x.Name, y.Name, StringComparison.CurrentCulture); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { public partial struct ImmutableArray<T> { /// <summary> /// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/> /// instance without allocating memory. /// </summary> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))] public sealed class Builder : IList<T>, IReadOnlyList<T> { /// <summary> /// The backing array for the builder. /// </summary> private T[] _elements; /// <summary> /// The number of initialized elements in the array. /// </summary> private int _count; /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> /// <param name="capacity">The initial capacity of the internal array.</param> internal Builder(int capacity) { Requires.Range(capacity >= 0, nameof(capacity)); _elements = new T[capacity]; _count = 0; } /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> internal Builder() : this(8) { } /// <summary> /// Get and sets the length of the internal array. When set the internal array is /// reallocated to the given capacity if it is not already the specified length. /// </summary> public int Capacity { get { return _elements.Length; } set { if (value < _count) { throw new ArgumentException(SR.CapacityMustBeGreaterThanOrEqualToCount, paramName: nameof(value)); } if (value != _elements.Length) { if (value > 0) { var temp = new T[value]; if (_count > 0) { Array.Copy(_elements, 0, temp, 0, _count); } _elements = temp; } else { _elements = ImmutableArray<T>.Empty.array; } } } } /// <summary> /// Gets or sets the length of the builder. /// </summary> /// <remarks> /// If the value is decreased, the array contents are truncated. /// If the value is increased, the added elements are initialized to the default value of type <typeparamref name="T"/>. /// </remarks> public int Count { get { return _count; } set { Requires.Range(value >= 0, nameof(value)); if (value < _count) { // truncation mode // Clear the elements of the elements that are effectively removed. // PERF: Array.Clear works well for big arrays, // but may have too much overhead with small ones (which is the common case here) if (_count - value > 64) { Array.Clear(_elements, value, _count - value); } else { for (int i = value; i < this.Count; i++) { _elements[i] = default(T); } } } else if (value > _count) { // expansion this.EnsureCapacity(value); } _count = value; } } /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> /// <exception cref="IndexOutOfRangeException"> /// </exception> public T this[int index] { get { if (index >= this.Count) { throw new IndexOutOfRangeException(); } return _elements[index]; } set { if (index >= this.Count) { throw new IndexOutOfRangeException(); } _elements[index] = value; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool ICollection<T>.IsReadOnly { get { return false; } } /// <summary> /// Returns an immutable copy of the current contents of this collection. /// </summary> /// <returns>An immutable array.</returns> public ImmutableArray<T> ToImmutable() { if (Count == 0) { return Empty; } return new ImmutableArray<T>(this.ToArray()); } /// <summary> /// Extracts the internal array as an <see cref="ImmutableArray{T}"/> and replaces it /// with a zero length array. /// </summary> /// <exception cref="InvalidOperationException">When <see cref="ImmutableArray{T}.Builder.Count"/> doesn't /// equal <see cref="ImmutableArray{T}.Builder.Capacity"/>.</exception> public ImmutableArray<T> MoveToImmutable() { if (Capacity != Count) { throw new InvalidOperationException(SR.CapacityMustEqualCountOnMove); } T[] temp = _elements; _elements = ImmutableArray<T>.Empty.array; _count = 0; return new ImmutableArray<T>(temp); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> public void Clear() { this.Count = 0; } /// <summary> /// Inserts an item to the <see cref="IList{T}"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="IList{T}"/>.</param> public void Insert(int index, T item) { Requires.Range(index >= 0 && index <= this.Count, nameof(index)); this.EnsureCapacity(this.Count + 1); if (index < this.Count) { Array.Copy(_elements, index, _elements, index + 1, this.Count - index); } _count++; _elements[index] = item; } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> public void Add(T item) { this.EnsureCapacity(this.Count + 1); _elements[_count++] = item; } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(IEnumerable<T> items) { Requires.NotNull(items, nameof(items)); int count; if (items.TryGetCount(out count)) { this.EnsureCapacity(this.Count + count); } foreach (var item in items) { this.Add(item); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(params T[] items) { Requires.NotNull(items, nameof(items)); var offset = this.Count; this.Count += items.Length; Array.Copy(items, 0, _elements, offset, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(TDerived[] items) where TDerived : T { Requires.NotNull(items, nameof(items)); var offset = this.Count; this.Count += items.Length; Array.Copy(items, 0, _elements, offset, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> /// <param name="length">The number of elements from the source array to add.</param> public void AddRange(T[] items, int length) { Requires.NotNull(items, nameof(items)); Requires.Range(length >= 0 && length <= items.Length, nameof(length)); var offset = this.Count; this.Count += length; Array.Copy(items, 0, _elements, offset, length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(ImmutableArray<T> items) { this.AddRange(items, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> /// <param name="length">The number of elements from the source array to add.</param> public void AddRange(ImmutableArray<T> items, int length) { Requires.Range(length >= 0, nameof(length)); if (items.array != null) { this.AddRange(items.array, length); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T { if (items.array != null) { this.AddRange(items.array); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(Builder items) { Requires.NotNull(items, nameof(items)); this.AddRange(items._elements, items.Count); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T { Requires.NotNull(items, nameof(items)); this.AddRange(items._elements, items.Count); } /// <summary> /// Removes the specified element. /// </summary> /// <param name="element">The element.</param> /// <returns>A value indicating whether the specified element was found and removed from the collection.</returns> public bool Remove(T element) { int index = this.IndexOf(element); if (index >= 0) { this.RemoveAt(index); return true; } return false; } /// <summary> /// Removes the <see cref="IList{T}"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> public void RemoveAt(int index) { Requires.Range(index >= 0 && index < this.Count, nameof(index)); if (index < this.Count - 1) { Array.Copy(_elements, index + 1, _elements, index, this.Count - index - 1); } this.Count--; } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> public bool Contains(T item) { return this.IndexOf(item) >= 0; } /// <summary> /// Creates a new array with the current contents of this Builder. /// </summary> public T[] ToArray() { T[] result = new T[this.Count]; Array.Copy(_elements, 0, result, 0, this.Count); return result; } /// <summary> /// Copies the current contents to the specified array. /// </summary> /// <param name="array">The array to copy to.</param> /// <param name="index">The starting index of the target array.</param> public void CopyTo(T[] array, int index) { Requires.NotNull(array, nameof(array)); Requires.Range(index >= 0 && index + this.Count <= array.Length, nameof(index)); Array.Copy(_elements, 0, array, index, this.Count); } /// <summary> /// Resizes the array to accommodate the specified capacity requirement. /// </summary> /// <param name="capacity">The required capacity.</param> private void EnsureCapacity(int capacity) { if (_elements.Length < capacity) { int newCapacity = Math.Max(_elements.Length * 2, capacity); Array.Resize(ref _elements, newCapacity); } } /// <summary> /// Determines the index of a specific item in the <see cref="IList{T}"/>. /// </summary> /// <param name="item">The object to locate in the <see cref="IList{T}"/>.</param> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> [Pure] public int IndexOf(T item) { return this.IndexOf(item, 0, _count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex) { return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex, int count) { return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer) { if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex)); Requires.Range(count >= 0 && startIndex + count <= this.Count, nameof(count)); equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(_elements, item, startIndex, count); } else { for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(_elements[i], item)) { return i; } } return -1; } } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item) { if (this.Count == 0) { return -1; } return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex) { if (this.Count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex)); return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex, int count) { return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer) { if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex)); Requires.Range(count >= 0 && startIndex - count + 1 >= 0, nameof(count)); equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; if (equalityComparer == EqualityComparer<T>.Default) { return Array.LastIndexOf(_elements, item, startIndex, count); } else { for (int i = startIndex; i >= startIndex - count + 1; i--) { if (equalityComparer.Equals(item, _elements[i])) { return i; } } return -1; } } /// <summary> /// Reverses the order of elements in the collection. /// </summary> public void Reverse() { // The non-generic Array.Reverse is not used because it does not perform // well for non-primitive value types. // If/when a generic Array.Reverse<T> becomes available, the below code // can be deleted and replaced with a call to Array.Reverse<T>. int i = 0; int j = _count - 1; T[] array = _elements; while (i < j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } } /// <summary> /// Sorts the array. /// </summary> public void Sort() { if (Count > 1) { Array.Sort(_elements, 0, this.Count, Comparer<T>.Default); } } /// <summary> /// Sorts the elements in the entire array using /// the specified <see cref="Comparison{T}"/>. /// </summary> /// <param name="comparison"> /// The <see cref="Comparison{T}"/> to use when comparing elements. /// </param> /// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception> [Pure] public void Sort(Comparison<T> comparison) { Requires.NotNull(comparison, nameof(comparison)); if (Count > 1) { Array.Sort(_elements, comparison); } } /// <summary> /// Sorts the array. /// </summary> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public void Sort(IComparer<T> comparer) { if (Count > 1) { Array.Sort(_elements, 0, _count, comparer); } } /// <summary> /// Sorts the array. /// </summary> /// <param name="index">The index of the first element to consider in the sort.</param> /// <param name="count">The number of elements to include in the sort.</param> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public void Sort(int index, int count, IComparer<T> comparer) { // Don't rely on Array.Sort's argument validation since our internal array may exceed // the bounds of the publicly addressable region. Requires.Range(index >= 0, nameof(index)); Requires.Range(count >= 0 && index + count <= this.Count, nameof(count)); if (count > 1) { Array.Sort(_elements, index, count, comparer); } } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> public IEnumerator<T> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return this[i]; } } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Adds items to this collection. /// </summary> /// <typeparam name="TDerived">The type of source elements.</typeparam> /// <param name="items">The source array.</param> /// <param name="length">The number of elements to add to this array.</param> private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T { this.EnsureCapacity(this.Count + length); var offset = this.Count; this.Count += length; var nodes = _elements; for (int i = 0; i < length; i++) { nodes[offset + i] = items[i]; } } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal sealed class ImmutableArrayBuilderDebuggerProxy<T> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableArray<T>.Builder _builder; /// <summary> /// Initializes a new instance of the <see cref="ImmutableArrayBuilderDebuggerProxy{T}"/> class. /// </summary> /// <param name="builder">The collection to display in the debugger</param> public ImmutableArrayBuilderDebuggerProxy(ImmutableArray<T>.Builder builder) { _builder = builder; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] A { get { return _builder.ToArray(); } } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Collections; using System.Collections.Generic; using System.Text; using System.Net.NetworkInformation; namespace LumiSoft.Net.Dns.Client { /// <summary> /// Dns client. /// </summary> /// <example> /// <code> /// // Set dns servers /// Dns_Client.DnsServers = new string[]{"194.126.115.18"}; /// /// Dns_Client dns = Dns_Client(); /// /// // Get MX records. /// DnsServerResponse resp = dns.Query("lumisoft.ee",QTYPE.MX); /// if(resp.ConnectionOk &amp;&amp; resp.ResponseCode == RCODE.NO_ERROR){ /// MX_Record[] mxRecords = resp.GetMXRecords(); /// /// // Do your stuff /// } /// else{ /// // Handle error there, for more exact error info see RCODE /// } /// /// </code> /// </example> public class Dns_Client { private static IPAddress[] m_DnsServers = null; private static bool m_UseDnsCache = true; private static int m_ID = 100; /// <summary> /// Static constructor. /// </summary> static Dns_Client() { // Try to get system dns servers try{ List<IPAddress> dnsServers = new List<IPAddress>(); foreach(NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()){ if(nic.OperationalStatus == OperationalStatus.Up){ foreach(IPAddress ip in nic.GetIPProperties().DnsAddresses){ if(ip.AddressFamily == AddressFamily.InterNetwork){ if(!dnsServers.Contains(ip)){ dnsServers.Add(ip); } } } } } m_DnsServers = dnsServers.ToArray(); } catch{ } } /// <summary> /// Default constructor. /// </summary> public Dns_Client() { } #region method Query /// <summary> /// Queries server with specified query. /// </summary> /// <param name="queryText">Query text. It depends on queryType.</param> /// <param name="queryType">Query type.</param> /// <returns></returns> public DnsServerResponse Query(string queryText,QTYPE queryType) { if(queryType == QTYPE.PTR){ string ip = queryText; // See if IP is ok. IPAddress ipA = IPAddress.Parse(ip); queryText = ""; // IPv6 if(ipA.AddressFamily == AddressFamily.InterNetworkV6){ // 4321:0:1:2:3:4:567:89ab // would be // b.a.9.8.7.6.5.0.4.0.0.0.3.0.0.0.2.0.0.0.1.0.0.0.0.0.0.0.1.2.3.4.IP6.ARPA char[] ipChars = ip.Replace(":","").ToCharArray(); for(int i=ipChars.Length - 1;i>-1;i--){ queryText += ipChars[i] + "."; } queryText += "IP6.ARPA"; } // IPv4 else{ // 213.35.221.186 // would be // 186.221.35.213.in-addr.arpa string[] ipParts = ip.Split('.'); //--- Reverse IP ---------- for(int i=3;i>-1;i--){ queryText += ipParts[i] + "."; } queryText += "in-addr.arpa"; } } return QueryServer(2000,queryText,queryType,1); } #endregion #region method GetHostAddresses /// <summary> /// Gets specified host IP addresses(A and AAAA). /// </summary> /// <param name="host">Host name.</param> /// <returns>Returns specified host IP addresses.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>host</b> is null reference.</exception> public IPAddress[] GetHostAddresses(string host) { if(host == null){ throw new ArgumentNullException("host"); } List<IPAddress> retVal = new List<IPAddress>(); // This is probably NetBios name if(host.IndexOf(".") == -1){ return System.Net.Dns.GetHostEntry(host).AddressList; } else{ DnsServerResponse response = Query(host,QTYPE.A); if(response.ResponseCode != RCODE.NO_ERROR){ throw new DNS_ClientException(response.ResponseCode); } foreach(DNS_rr_A record in response.GetARecords()){ retVal.Add(record.IP); } response = Query(host,QTYPE.AAAA); if(response.ResponseCode != RCODE.NO_ERROR){ throw new DNS_ClientException(response.ResponseCode); } foreach(DNS_rr_A record in response.GetARecords()){ retVal.Add(record.IP); } } return retVal.ToArray(); } #endregion #region static method Resolve /// <summary> /// Resolves host names to IP addresses. /// </summary> /// <param name="hosts">Host names to resolve.</param> /// <returns>Returns specified hosts IP addresses.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>hosts</b> is null.</exception> public static IPAddress[] Resolve(string[] hosts) { if(hosts == null){ throw new ArgumentNullException("hosts"); } List<IPAddress> retVal = new List<IPAddress>(); foreach(string host in hosts){ IPAddress[] addresses = Resolve(host); foreach(IPAddress ip in addresses){ if(!retVal.Contains(ip)){ retVal.Add(ip); } } } return retVal.ToArray(); } /// <summary> /// Resolves host name to IP addresses. /// </summary> /// <param name="host">Host name or IP address.</param> /// <returns>Return specified host IP addresses.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>host</b> is null.</exception> public static IPAddress[] Resolve(string host) { if(host == null){ throw new ArgumentNullException("host"); } // If hostName_IP is IP try{ return new IPAddress[]{IPAddress.Parse(host)}; } catch{ } // This is probably NetBios name if(host.IndexOf(".") == -1){ return System.Net.Dns.GetHostEntry(host).AddressList; } else{ // hostName_IP must be host name, try to resolve it's IP Dns_Client dns = new Dns_Client(); DnsServerResponse resp = dns.Query(host,QTYPE.A); if(resp.ResponseCode == RCODE.NO_ERROR){ DNS_rr_A[] records = resp.GetARecords(); IPAddress[] retVal = new IPAddress[records.Length]; for(int i=0;i<records.Length;i++){ retVal[i] = records[i].IP; } return retVal; } else{ throw new Exception(resp.ResponseCode.ToString()); } } } #endregion #region method QueryServer /// <summary> /// Sends query to server. /// </summary> /// <param name="timeout">Query timeout in milli seconds.</param> /// <param name="qname">Query text.</param> /// <param name="qtype">Query type.</param> /// <param name="qclass">Query class.</param> /// <returns></returns> private DnsServerResponse QueryServer(int timeout,string qname,QTYPE qtype,int qclass) { if(m_DnsServers == null || m_DnsServers.Length == 0){ throw new Exception("Dns server isn't specified !"); } // See if query is in cache if(m_UseDnsCache){ DnsServerResponse resopnse = DnsCache.GetFromCache(qname,(int)qtype); if(resopnse != null){ return resopnse; } } int queryID = Dns_Client.ID; byte[] query = CreateQuery(queryID,qname,qtype,qclass); // Create sending UDP socket. Socket udpClient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); udpClient.SendTimeout = 500; // Send parallel query to all dns servers and get first answer. DateTime startTime = DateTime.Now; while(startTime.AddMilliseconds(timeout) > DateTime.Now){ foreach(IPAddress dnsServer in m_DnsServers){ try{ udpClient.SendTo(query,new IPEndPoint(dnsServer,53)); } catch{ } } // Wait 10 ms response to arrive, if no response, retransmit query. if(udpClient.Poll(10,SelectMode.SelectRead)){ try{ byte[] retVal = new byte[1024]; int countRecieved = udpClient.Receive(retVal); // If reply is ok, return it DnsServerResponse serverResponse = ParseQuery(retVal,queryID); // Cache query if(m_UseDnsCache && serverResponse.ResponseCode == RCODE.NO_ERROR){ DnsCache.AddToCache(qname,(int)qtype,serverResponse); } return serverResponse; } catch{ } } } udpClient.Close(); // If we reach so far, we probably won't get connection to dsn server return new DnsServerResponse(false,RCODE.SERVER_FAILURE,new List<DNS_rr_base>(),new List<DNS_rr_base>(),new List<DNS_rr_base>()); } #endregion #region method CreateQuery /// <summary> /// Creates new query. /// </summary> /// <param name="ID">Query ID.</param> /// <param name="qname">Query text.</param> /// <param name="qtype">Query type.</param> /// <param name="qclass">Query class.</param> /// <returns></returns> private byte[] CreateQuery(int ID,string qname,QTYPE qtype,int qclass) { byte[] query = new byte[512]; //---- Create header --------------------------------------------// // Header is first 12 bytes of query /* 4.1.1. Header section format 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ QR A one bit field that specifies whether this message is a query (0), or a response (1). OPCODE A four bit field that specifies kind of query in this message. This value is set by the originator of a query and copied into the response. The values are: 0 a standard query (QUERY) 1 an inverse query (IQUERY) 2 a server status request (STATUS) */ //--------- Header part -----------------------------------// query[0] = (byte) (ID >> 8); query[1] = (byte) (ID & 0xFF); query[2] = (byte) 1; query[3] = (byte) 0; query[4] = (byte) 0; query[5] = (byte) 1; query[6] = (byte) 0; query[7] = (byte) 0; query[8] = (byte) 0; query[9] = (byte) 0; query[10] = (byte) 0; query[11] = (byte) 0; //---------------------------------------------------------// //---- End of header --------------------------------------------// //----Create query ------------------------------------// /* Rfc 1035 4.1.2. Question section format 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | | / QNAME / / / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QTYPE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QCLASS | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ QNAME a domain name represented as a sequence of labels, where each label consists of a length octet followed by that number of octets. The domain name terminates with the zero length octet for the null label of the root. Note that this field may be an odd number of octets; no padding is used. */ string[] labels = qname.Split(new char[] {'.'}); int position = 12; // Copy all domain parts(labels) to query // eg. lumisoft.ee = 2 labels, lumisoft and ee. // format = label.length + label(bytes) foreach(string label in labels){ // add label lenght to query query[position++] = (byte)(label.Length); // convert label string to byte array byte[] b = Encoding.ASCII.GetBytes(label); b.CopyTo(query,position); // Move position by label length position += b.Length; } // Terminate domain (see note above) query[position++] = (byte) 0; // Set QTYPE query[position++] = (byte) 0; query[position++] = (byte)qtype; // Set QCLASS query[position++] = (byte) 0; query[position++] = (byte)qclass; //-------------------------------------------------------// return query; } #endregion #region method GetQName internal static bool GetQName(byte[] reply,ref int offset,ref string name) { try{ // Do while not terminator while(reply[offset] != 0){ // Check if it's pointer(In pointer first two bits always 1) bool isPointer = ((reply[offset] & 0xC0) == 0xC0); // If pointer if(isPointer){ // Pointer location number is 2 bytes long // 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 # byte 2 # 0 | 1 | 2 | | 3 | 4 | 5 | 6 | 7 // empty | < ---- pointer location number ---------------------------------> int pStart = ((reply[offset] & 0x3F) << 8) | (reply[++offset]); offset++; return GetQName(reply,ref pStart,ref name); } else{ // label length (length = 8Bit and first 2 bits always 0) // 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 // empty | lablel length in bytes int labelLength = (reply[offset] & 0x3F); offset++; // Copy label into name name += Encoding.ASCII.GetString(reply,offset,labelLength); offset += labelLength; } // If the next char isn't terminator, // label continues - add dot between two labels if (reply[offset] != 0){ name += "."; } } // Move offset by terminator length offset++; return true; } catch{ return false; } } #endregion #region method ParseQuery /// <summary> /// Parses query. /// </summary> /// <param name="reply">Dns server reply.</param> /// <param name="queryID">Query id of sent query.</param> /// <returns></returns> private DnsServerResponse ParseQuery(byte[] reply,int queryID) { //--- Parse headers ------------------------------------// /* RFC 1035 4.1.1. Header section format 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ QDCOUNT an unsigned 16 bit integer specifying the number of entries in the question section. ANCOUNT an unsigned 16 bit integer specifying the number of resource records in the answer section. NSCOUNT an unsigned 16 bit integer specifying the number of name server resource records in the authority records section. ARCOUNT an unsigned 16 bit integer specifying the number of resource records in the additional records section. */ // Get reply code int id = (reply[0] << 8 | reply[1]); OPCODE opcode = (OPCODE)((reply[2] >> 3) & 15); RCODE replyCode = (RCODE)(reply[3] & 15); int queryCount = (reply[4] << 8 | reply[5]); int answerCount = (reply[6] << 8 | reply[7]); int authoritiveAnswerCount = (reply[8] << 8 | reply[9]); int additionalAnswerCount = (reply[10] << 8 | reply[11]); //---- End of headers ---------------------------------// // Check that it's query what we want if(queryID != id){ throw new Exception("This isn't query with ID what we expected"); } int pos = 12; //----- Parse question part ------------// for(int q=0;q<queryCount;q++){ string dummy = ""; GetQName(reply,ref pos,ref dummy); //qtype + qclass pos += 4; } //--------------------------------------// // 1) parse answers // 2) parse authoritive answers // 3) parse additional answers List<DNS_rr_base> answers = ParseAnswers(reply,answerCount,ref pos); List<DNS_rr_base> authoritiveAnswers = ParseAnswers(reply,authoritiveAnswerCount,ref pos); List<DNS_rr_base> additionalAnswers = ParseAnswers(reply,additionalAnswerCount,ref pos); return new DnsServerResponse(true,replyCode,answers,authoritiveAnswers,additionalAnswers); } #endregion #region method ParseAnswers /// <summary> /// Parses specified count of answers from query. /// </summary> /// <param name="reply">Server returned query.</param> /// <param name="answerCount">Number of answers to parse.</param> /// <param name="offset">Position from where to start parsing answers.</param> /// <returns></returns> private List<DNS_rr_base> ParseAnswers(byte[] reply,int answerCount,ref int offset) { /* RFC 1035 4.1.3. Resource record format 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | | / / / NAME / | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | TYPE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | CLASS | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | TTL | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | RDLENGTH | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--| / RDATA / / / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ List<DNS_rr_base> answers = new List<DNS_rr_base>(); //---- Start parsing answers ------------------------------------------------------------------// for(int i=0;i<answerCount;i++){ string name = ""; if(!GetQName(reply,ref offset,ref name)){ throw new Exception("Error parsing anser"); } int type = reply[offset++] << 8 | reply[offset++]; int rdClass = reply[offset++] << 8 | reply[offset++]; int ttl = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++]; int rdLength = reply[offset++] << 8 | reply[offset++]; if((QTYPE)type == QTYPE.A){ answers.Add(DNS_rr_A.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.NS){ answers.Add(DNS_rr_NS.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.CNAME){ answers.Add(DNS_rr_CNAME.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.SOA){ answers.Add(DNS_rr_SOA.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.PTR){ answers.Add(DNS_rr_PTR.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.HINFO){ answers.Add(DNS_rr_HINFO.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.MX){ answers.Add(DNS_rr_MX.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.TXT){ answers.Add(DNS_rr_TXT.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.AAAA){ answers.Add(DNS_rr_AAAA.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.SRV){ answers.Add(DNS_rr_SRV.Parse(reply,ref offset,rdLength,ttl)); } else if((QTYPE)type == QTYPE.NAPTR){ answers.Add(DNS_rr_NAPTR.Parse(reply,ref offset,rdLength,ttl)); } else{ // Unknown record, skip it. offset += rdLength; } } return answers; } #endregion #region method ReadCharacterString /// <summary> /// Reads character-string from spefcified data and offset. /// </summary> /// <param name="data">Data from where to read.</param> /// <param name="offset">Offset from where to start reading.</param> /// <returns>Returns readed string.</returns> internal static string ReadCharacterString(byte[] data,ref int offset) { /* RFC 1035 3.3. <character-string> is a single length octet followed by that number of characters. <character-string> is treated as binary information, and can be up to 256 characters in length (including the length octet). */ int dataLength = (int)data[offset++]; string retVal = Encoding.Default.GetString(data,offset,dataLength); offset += dataLength; return retVal; } #endregion #region Properties Implementation /// <summary> /// Gets or sets dns servers. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public static string[] DnsServers { get{ string[] retVal = new string[m_DnsServers.Length]; for(int i=0;i<m_DnsServers.Length;i++){ retVal[i] = m_DnsServers[i].ToString(); } return retVal; } set{ if(value == null){ throw new ArgumentNullException(); } IPAddress[] retVal = new IPAddress[value.Length]; for(int i=0;i<value.Length;i++){ retVal[i] = IPAddress.Parse(value[i]); } m_DnsServers = retVal; } } /// <summary> /// Gets or sets if to use dns caching. /// </summary> public static bool UseDnsCache { get{ return m_UseDnsCache; } set{ m_UseDnsCache = value; } } /// <summary> /// Get next query ID. /// </summary> internal static int ID { get{ if(m_ID >= 65535){ m_ID = 100; } return m_ID++; } } #endregion } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Branding.DeployCustomThemeWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Purchasing.Core.Domain; using Purchasing.Tests.Core; using UCDArch.Core.PersistanceSupport; using UCDArch.Data.NHibernate; using UCDArch.Testing; namespace Purchasing.Tests.RepositoryTests { /// <summary> /// Entity Name: Account /// LookupFieldName: Name /// </summary> [TestClass] public class AccountRepositoryTests : AbstractRepositoryTests<Account, string, AccountMap> { /// <summary> /// Gets or sets the Account repository. /// </summary> /// <value>The Account repository.</value> public IRepository<Account> AccountRepository { get; set; } public IRepositoryWithTypedId<Organization, string> OrganizationRepository { get; set; } #region Init and Overrides /// <summary> /// Initializes a new instance of the <see cref="AccountRepositoryTests"/> class. /// </summary> public AccountRepositoryTests() { AccountRepository = new Repository<Account>(); OrganizationRepository = new RepositoryWithTypedId<Organization, string>(); } /// <summary> /// Gets the valid entity of type T /// </summary> /// <param name="counter">The counter.</param> /// <returns>A valid entity of type T</returns> protected override Account GetValid(int? counter) { return CreateValidEntities.Account(counter); } /// <summary> /// A Query which will return a single record /// </summary> /// <param name="numberAtEnd"></param> /// <returns></returns> protected override IQueryable<Account> GetQuery(int numberAtEnd) { return AccountRepository.Queryable.Where(a => a.Name.EndsWith(numberAtEnd.ToString(System.Globalization.CultureInfo.InvariantCulture))); } /// <summary> /// A way to compare the entities that were read. /// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment); /// </summary> /// <param name="entity"></param> /// <param name="counter"></param> protected override void FoundEntityComparison(Account entity, int counter) { Assert.AreEqual("Name" + counter, entity.Name); } /// <summary> /// Updates , compares, restores. /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> protected override void UpdateUtility(Account entity, ARTAction action) { const string updateValue = "Updated"; switch (action) { case ARTAction.Compare: Assert.AreEqual(updateValue, entity.Name); break; case ARTAction.Restore: entity.Name = RestoreValue; break; case ARTAction.Update: RestoreValue = entity.Name; entity.Name = updateValue; break; } } /// <summary> /// Loads the data. /// </summary> protected override void LoadData() { AccountRepository.DbContext.BeginTransaction(); LoadRecords(5); AccountRepository.DbContext.CommitTransaction(); } [TestMethod] public override void CanUpdateEntity() { CanUpdateEntity(false); } #endregion Init and Overrides #region Name Tests #region Valid Tests /// <summary> /// Tests the Name with null value saves. /// </summary> [TestMethod] public void TestNameWithNullValueSaves() { #region Arrange var account = GetValid(9); account.Name = null; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the Name with empty string saves. /// </summary> [TestMethod] public void TestNameWithEmptyStringSaves() { #region Arrange var account = GetValid(9); account.Name = string.Empty; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the Name with one space saves. /// </summary> [TestMethod] public void TestNameWithOneSpaceSaves() { #region Arrange var account = GetValid(9); account.Name = " "; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the Name with one character saves. /// </summary> [TestMethod] public void TestNameWithOneCharacterSaves() { #region Arrange var account = GetValid(9); account.Name = "x"; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the Name with long value saves. /// </summary> [TestMethod] public void TestNameWithLongValueSaves() { #region Arrange var account = GetValid(9); account.Name = "x".RepeatTimes(999); #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(999, account.Name.Length); Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } #endregion Valid Tests #endregion Name Tests #region AccountManager Tests #region Valid Tests /// <summary> /// Tests the AccountManager with null value saves. /// </summary> [TestMethod] public void TestAccountManagerWithNullValueSaves() { #region Arrange var account = GetValid(9); account.AccountManager = null; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the AccountManager with empty string saves. /// </summary> [TestMethod] public void TestAccountManagerWithEmptyStringSaves() { #region Arrange var account = GetValid(9); account.AccountManager = string.Empty; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the AccountManager with one space saves. /// </summary> [TestMethod] public void TestAccountManagerWithOneSpaceSaves() { #region Arrange var account = GetValid(9); account.AccountManager = " "; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the AccountManager with one character saves. /// </summary> [TestMethod] public void TestAccountManagerWithOneCharacterSaves() { #region Arrange var account = GetValid(9); account.AccountManager = "x"; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the AccountManager with long value saves. /// </summary> [TestMethod] public void TestAccountManagerWithLongValueSaves() { #region Arrange var account = GetValid(9); account.AccountManager = "x".RepeatTimes(999); #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(999, account.AccountManager.Length); Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } #endregion Valid Tests #endregion AccountManager Tests #region AccountManagerId Tests #region Valid Tests /// <summary> /// Tests the AccountManagerId with null value saves. /// </summary> [TestMethod] public void TestAccountManagerIdWithNullValueSaves() { #region Arrange var account = GetValid(9); account.AccountManagerId = null; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the AccountManagerId with empty string saves. /// </summary> [TestMethod] public void TestAccountManagerIdWithEmptyStringSaves() { #region Arrange var account = GetValid(9); account.AccountManagerId = string.Empty; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the AccountManagerId with one space saves. /// </summary> [TestMethod] public void TestAccountManagerIdWithOneSpaceSaves() { #region Arrange var account = GetValid(9); account.AccountManagerId = " "; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the AccountManagerId with one character saves. /// </summary> [TestMethod] public void TestAccountManagerIdWithOneCharacterSaves() { #region Arrange var account = GetValid(9); account.AccountManagerId = "x"; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the AccountManagerId with long value saves. /// </summary> [TestMethod] public void TestAccountManagerIdWithLongValueSaves() { #region Arrange var account = GetValid(9); account.AccountManagerId = "x".RepeatTimes(999); #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(999, account.AccountManagerId.Length); Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } #endregion Valid Tests #endregion AccountManagerId Tests #region PrincipalInvestigator Tests #region Valid Tests /// <summary> /// Tests the PrincipalInvestigator with null value saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorWithNullValueSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigator = null; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the PrincipalInvestigator with empty string saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorWithEmptyStringSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigator = string.Empty; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the PrincipalInvestigator with one space saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorWithOneSpaceSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigator = " "; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the PrincipalInvestigator with one character saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorWithOneCharacterSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigator = "x"; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the PrincipalInvestigator with long value saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorWithLongValueSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigator = "x".RepeatTimes(999); #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(999, account.PrincipalInvestigator.Length); Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } #endregion Valid Tests #endregion PrincipalInvestigator Tests #region PrincipalInvestigatorId Tests #region Valid Tests /// <summary> /// Tests the PrincipalInvestigatorId with null value saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorIdWithNullValueSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigatorId = null; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the PrincipalInvestigatorId with empty string saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorIdWithEmptyStringSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigatorId = string.Empty; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the PrincipalInvestigatorId with one space saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorIdWithOneSpaceSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigatorId = " "; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the PrincipalInvestigatorId with one character saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorIdWithOneCharacterSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigatorId = "x"; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the PrincipalInvestigatorId with long value saves. /// </summary> [TestMethod] public void TestPrincipalInvestigatorIdWithLongValueSaves() { #region Arrange var account = GetValid(9); account.PrincipalInvestigatorId = "x".RepeatTimes(999); #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(999, account.PrincipalInvestigatorId.Length); Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } #endregion Valid Tests #endregion PrincipalInvestigatorId Tests #region IsActive Tests /// <summary> /// Tests the IsActive is false saves. /// </summary> [TestMethod] public void TestIsActiveIsFalseSaves() { #region Arrange Account account = GetValid(9); account.IsActive = false; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsActive); Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the IsActive is true saves. /// </summary> [TestMethod] public void TestIsActiveIsTrueSaves() { #region Arrange var account = GetValid(9); account.IsActive = true; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsTrue(account.IsActive); Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } #endregion IsActive Tests #region NameAndId Tests [TestMethod] public void TestNameAndIdReturnsExpectedString() { #region Arrange var record = CreateValidEntities.Account(4); record.SetIdTo("IdTest"); #endregion Arrange #region Act var result = record.NameAndId; #endregion Act #region Assert Assert.AreEqual("Name4 (IdTest)", result); #endregion Assert } #endregion NameAndId Tests #region SubAccounts Tests #region Invalid Tests [TestMethod] [ExpectedException(typeof(NHibernate.StaleStateException))] public void TestSubAccountsWithANewValueDoesNotSave() { Account record = null; try { #region Arrange record = GetValid(9); record.SubAccounts.Add(CreateValidEntities.SubAccount(1)); #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(record); AccountRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception ex) { Assert.IsNotNull(record); Assert.IsNotNull(ex); Assert.AreEqual("Unexpected row count: 0; expected: 1", ex.Message); throw; } } #endregion Invalid Tests #region Valid Tests [TestMethod] public void TestSubAccountsWithEmptyListWillSave() { #region Arrange Account record = GetValid(9); #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(record); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsNotNull(record.SubAccounts); Assert.AreEqual(0, record.SubAccounts.Count); Assert.IsFalse(record.IsTransient()); Assert.IsTrue(record.IsValid()); #endregion Assert } #endregion Valid Tests #endregion SubAccounts Tests #region OrganizationId Tests #region Valid Tests /// <summary> /// Tests the OrganizationId with null value saves. /// </summary> [TestMethod] public void TestOrganizationIdWithNullValueSaves() { #region Arrange var account = GetValid(9); account.OrganizationId = null; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } ///// <summary> ///// Tests the OrganizationId with empty string saves. ///// </summary> //[TestMethod, Ignore] //public void TestOrganizationIdWithEmptyStringSaves() //{ // #region Arrange // var account = GetValid(9); // account.OrganizationId = string.Empty; // #endregion Arrange // #region Act // AccountRepository.DbContext.BeginTransaction(); // AccountRepository.EnsurePersistent(account); // AccountRepository.DbContext.CommitTransaction(); // #endregion Act // #region Assert // Assert.IsFalse(account.IsTransient()); // Assert.IsTrue(account.IsValid()); // #endregion Assert //} /// <summary> /// Tests the OrganizationId with one space saves. /// </summary> [TestMethod] public void TestOrganizationIdWithOneSpaceSaves() { #region Arrange OrganizationRepository.DbContext.BeginTransaction(); var organization = CreateValidEntities.Organization(1); organization.SetIdTo(" "); OrganizationRepository.EnsurePersistent(organization); OrganizationRepository.DbContext.CommitTransaction(); var account = GetValid(9); account.OrganizationId = " "; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the OrganizationId with one character saves. /// Must match foreign key value /// </summary> [TestMethod] public void TestOrganizationIdWithOneCharacterSaves() { #region Arrange OrganizationRepository.DbContext.BeginTransaction(); LoadOrganizations(3); OrganizationRepository.DbContext.CommitTransaction(); var account = GetValid(9); account.OrganizationId = "2"; #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } /// <summary> /// Tests the OrganizationId with long value saves. /// </summary> [TestMethod] public void TestOrganizationIdWithLongValueSaves() { #region Arrange OrganizationRepository.DbContext.BeginTransaction(); var organization = CreateValidEntities.Organization(1); organization.SetIdTo("x".RepeatTimes(999)); OrganizationRepository.EnsurePersistent(organization); OrganizationRepository.DbContext.CommitTransaction(); var account = GetValid(9); account.OrganizationId = "x".RepeatTimes(999); #endregion Arrange #region Act AccountRepository.DbContext.BeginTransaction(); AccountRepository.EnsurePersistent(account); AccountRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(999, account.OrganizationId.Length); Assert.IsFalse(account.IsTransient()); Assert.IsTrue(account.IsValid()); #endregion Assert } #endregion Valid Tests #endregion OrganizationId Tests #region Reflection of Database. /// <summary> /// Tests all fields in the database have been tested. /// If this fails and no other tests, it means that a field has been added which has not been tested above. /// </summary> [TestMethod] public void TestAllFieldsInTheDatabaseHaveBeenTested() { #region Arrange var expectedFields = new List<NameAndType>(); expectedFields.Add(new NameAndType("AccountManager", "System.String", new List<string>())); expectedFields.Add(new NameAndType("AccountManagerId", "System.String", new List<string>())); expectedFields.Add(new NameAndType("Id", "System.String", new List<string> { "[Newtonsoft.Json.JsonPropertyAttribute()]", "[System.Xml.Serialization.XmlIgnoreAttribute()]" })); expectedFields.Add(new NameAndType("IsActive", "System.Boolean", new List<string>())); expectedFields.Add(new NameAndType("Name", "System.String", new List<string>())); expectedFields.Add(new NameAndType("NameAndId", "System.String", new List<string>())); expectedFields.Add(new NameAndType("OrganizationId", "System.String", new List<string>())); expectedFields.Add(new NameAndType("PrincipalInvestigator", "System.String", new List<string>())); expectedFields.Add(new NameAndType("PrincipalInvestigatorId", "System.String", new List<string>())); expectedFields.Add(new NameAndType("SubAccounts", "System.Collections.Generic.IList`1[Purchasing.Core.Domain.SubAccount]", new List<string>())); #endregion Arrange AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(Account)); } #endregion Reflection of Database. } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Payment Method ///<para>SObject Name: PaymentMethod</para> ///<para>Custom Object: False</para> ///</summary> public class SfPaymentMethod : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "PaymentMethod"; } } ///<summary> /// Payment Method ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Implementor Type /// <para>Name: ImplementorType</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "implementorType")] [Updateable(false), Createable(false)] public string ImplementorType { get; set; } ///<summary> /// Account ID /// <para>Name: AccountId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "accountId")] [Updateable(false), Createable(false)] public string AccountId { get; set; } ///<summary> /// ReferenceTo: Account /// <para>RelationshipName: Account</para> ///</summary> [JsonProperty(PropertyName = "account")] [Updateable(false), Createable(false)] public SfAccount Account { get; set; } ///<summary> /// Nickname /// <para>Name: NickName</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "nickName")] [Updateable(false), Createable(false)] public string NickName { get; set; } ///<summary> /// Company Name /// <para>Name: CompanyName</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "companyName")] [Updateable(false), Createable(false)] public string CompanyName { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "status")] [Updateable(false), Createable(false)] public string Status { get; set; } ///<summary> /// Comments /// <para>Name: Comments</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "comments")] [Updateable(false), Createable(false)] public string Comments { get; set; } ///<summary> /// Street /// <para>Name: PaymentMethodStreet</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodStreet")] [Updateable(false), Createable(false)] public string PaymentMethodStreet { get; set; } ///<summary> /// City /// <para>Name: PaymentMethodCity</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodCity")] [Updateable(false), Createable(false)] public string PaymentMethodCity { get; set; } ///<summary> /// State /// <para>Name: PaymentMethodState</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodState")] [Updateable(false), Createable(false)] public string PaymentMethodState { get; set; } ///<summary> /// Postal Code /// <para>Name: PaymentMethodPostalCode</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodPostalCode")] [Updateable(false), Createable(false)] public string PaymentMethodPostalCode { get; set; } ///<summary> /// Country /// <para>Name: PaymentMethodCountry</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodCountry")] [Updateable(false), Createable(false)] public string PaymentMethodCountry { get; set; } ///<summary> /// Latitude /// <para>Name: PaymentMethodLatitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodLatitude")] [Updateable(false), Createable(false)] public double? PaymentMethodLatitude { get; set; } ///<summary> /// Longitude /// <para>Name: PaymentMethodLongitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodLongitude")] [Updateable(false), Createable(false)] public double? PaymentMethodLongitude { get; set; } ///<summary> /// GeoCode Accuracy /// <para>Name: PaymentMethodGeocodeAccuracy</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodGeocodeAccuracy")] [Updateable(false), Createable(false)] public string PaymentMethodGeocodeAccuracy { get; set; } ///<summary> /// Payment Method Address /// <para>Name: PaymentMethodAddress</para> /// <para>SF Type: address</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodAddress")] [Updateable(false), Createable(false)] public Address PaymentMethodAddress { get; set; } ///<summary> /// User ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// User ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Name /// <para>Name: Name</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "name")] [Updateable(false), Createable(false)] public string Name { get; set; } } }
// 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.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Scripting.CSharp { /// <summary> /// A factory for creating and running C# scripts. /// </summary> public static class CSharpScript { /// <summary> /// Create a new C# script. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="options">The script options.</param> /// <typeparam name="T">The return type of the script</typeparam> public static Script<T> Create<T>(string code, ScriptOptions options) { return new CSharpScript<T>(code, null, options, null, null, null); } /// <summary> /// Create a new C# script. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="options">The script options.</param> public static Script<object> Create(string code, ScriptOptions options) { return Create<object>(code, options); } /// <summary> /// Create a new C# script. /// </summary> /// <param name="code">The source code of the script.</param> public static Script<object> Create(string code) { return Create<object>(code, null); } /// <summary> /// Run a C# script. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="options">The script options.</param> /// <param name="globals">An object instance whose members can be accessed by the script as global variables, /// or a <see cref="ScriptState"/> instance that was the output from a previously run script.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <typeparam name="T">The return type of the submission</typeparam> public static ScriptState<T> RunAsync<T>(string code, ScriptOptions options, object globals, CancellationToken cancellationToken = default(CancellationToken)) { return Create<T>(code, options).RunAsync(globals, cancellationToken); } /// <summary> /// Run a C# script. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="options">The script options.</param> /// <param name="globals">An object instance whose members can be accessed by the script as global variables, /// or a <see cref="ScriptState"/> instance that was the output from a previously run script.</param> /// <param name="cancellationToken">Cancellation token.</param> public static ScriptState<object> RunAsync(string code, ScriptOptions options, object globals, CancellationToken cancellationToken = default(CancellationToken)) { return RunAsync<object>(code, options, globals, cancellationToken); } /// <summary> /// Run a C# script. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="options">The script options.</param> /// <param name="cancellationToken">Cancellation token.</param> public static ScriptState<object> RunAsync(string code, ScriptOptions options, CancellationToken cancellationToken = default(CancellationToken)) { return RunAsync<object>(code, options, null, cancellationToken); } /// <summary> /// Run a C# script. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="globals">An object instance whose members can be accessed by the script as global variables, /// or a <see cref="ScriptState"/> instance that was the output from a previously run script.</param> /// <param name="cancellationToken">Cancellation token.</param> public static ScriptState<object> RunAsync(string code, object globals, CancellationToken cancellationToken = default(CancellationToken)) { return RunAsync<object>(code, null, globals, cancellationToken); } /// <summary> /// Run a C# script. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="cancellationToken">Cancellation token.</param> public static ScriptState<object> RunAsync(string code, CancellationToken cancellationToken = default(CancellationToken)) { return RunAsync<object>(code, null, null, cancellationToken); } /// <summary> /// Run a C# script and return its resulting value. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="options">The script options.</param> /// <param name="globals">An object instance whose members can be accessed by the script as global variables, /// or a <see cref="ScriptState"/> instance that was the output from a previously run script.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <typeparam name="T">The return type of the submission</typeparam> /// <return>Returns the value returned by running the script.</return> public static Task<T> EvaluateAsync<T>(string code, ScriptOptions options, object globals, CancellationToken cancellationToken = default(CancellationToken)) { return RunAsync<T>(code, options, globals, cancellationToken).ReturnValue; } /// <summary> /// Run a C# script and return its resulting value. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="options">The script options.</param> /// <param name="globals">An object instance whose members can be accessed by the script as global variables, /// or a <see cref="ScriptState"/> instance that was the output from a previously run script.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <return>Returns the value returned by running the script.</return> public static Task<object> EvaluateAsync(string code, ScriptOptions options, object globals, CancellationToken cancellationToken = default(CancellationToken)) { return EvaluateAsync<object>(code, options, globals, cancellationToken); } /// <summary> /// Run a C# script and return its resulting value. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="options">The script options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <return>Returns the value returned by running the script.</return> public static Task<object> EvaluateAsync(string code, ScriptOptions options, CancellationToken cancellationToken = default(CancellationToken)) { return EvaluateAsync<object>(code, options, null, cancellationToken); } /// <summary> /// Run a C# script and return its resulting value. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="globals">An object instance whose members can be accessed by the script as global variables, /// or a <see cref="ScriptState"/> instance that was the output from a previously run script.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <return>Returns the value returned by running the script.</return> public static Task<object> EvaluateAsync(string code, object globals, CancellationToken cancellationToken = default(CancellationToken)) { return EvaluateAsync<object>(code, null, globals, cancellationToken); } /// <summary> /// Run a C# script and return its resulting value. /// </summary> /// <param name="code">The source code of the script.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <return>Returns the value returned by running the script.</return> public static Task<object> EvaluateAsync(string code, CancellationToken cancellationToken = default(CancellationToken)) { return EvaluateAsync<object>(code, null, null, cancellationToken); } } internal sealed class CSharpScript<T> : Script<T> { internal CSharpScript(string code, string path, ScriptOptions options, Type globalsType, ScriptBuilder builder, Script previous) : base(code, path, options, globalsType, builder, previous) { } internal override Script<T> Make(string code, string path, ScriptOptions options, Type globalsType, ScriptBuilder builder, Script previous) { return new CSharpScript<T>(code, path, options, globalsType, builder, previous); } #region Compilation private static readonly CSharpParseOptions s_defaultInteractive = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6, kind: SourceCodeKind.Interactive); private static readonly CSharpParseOptions s_defaultScript = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6, kind: SourceCodeKind.Script); protected override Compilation CreateCompilation() { Compilation previousSubmission = null; if (this.Previous != null) { previousSubmission = this.Previous.GetCompilation(); } var references = this.GetReferencesForCompilation(); var parseOptions = this.Options.IsInteractive ? s_defaultInteractive : s_defaultScript; var tree = SyntaxFactory.ParseSyntaxTree(this.Code, parseOptions, path: this.Path); string assemblyName, submissionTypeName; this.Builder.GenerateSubmissionId(out assemblyName, out submissionTypeName); var compilation = CSharpCompilation.CreateSubmission( assemblyName, tree, references, new CSharpCompilationOptions( outputKind: OutputKind.DynamicallyLinkedLibrary, mainTypeName: null, scriptClassName: submissionTypeName, usings: this.Options.Namespaces, optimizationLevel: OptimizationLevel.Debug, // TODO checkOverflow: false, // TODO allowUnsafe: true, // TODO platform: Platform.AnyCpu, warningLevel: 4, xmlReferenceResolver: null, // don't support XML file references in interactive (permissions & doc comment includes) sourceReferenceResolver: SourceFileResolver.Default, // TODO metadataReferenceResolver: this.Options.ReferenceResolver, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default ), previousSubmission, this.ReturnType, this.GlobalsType ); return compilation; } protected override string FormatDiagnostic(Diagnostic diagnostic, CultureInfo culture) { return CSharpDiagnosticFormatter.Instance.Format(diagnostic, culture); } #endregion } }
using Orleans.Runtime; using System; using System.Runtime.Serialization; namespace Orleans.Transactions { /// <summary> /// Base class for all transaction exceptions /// </summary> [Serializable] public class OrleansTransactionException : OrleansException { public OrleansTransactionException() : base("Orleans transaction error.") { } public OrleansTransactionException(string message) : base(message) { } public OrleansTransactionException(string message, Exception innerException) : base(message, innerException) { } protected OrleansTransactionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Orleans transactions are disabled. /// </summary> [Serializable] public class OrleansTransactionsDisabledException : OrleansTransactionException { public OrleansTransactionsDisabledException() : base("Orleans transactions have not been enabled. Transactions are disabled by default and must be configured to be used.") { } public OrleansTransactionsDisabledException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the runtime was unable to start a transaction. /// </summary> [Serializable] public class OrleansStartTransactionFailedException : OrleansTransactionException { public OrleansStartTransactionFailedException(Exception innerException) : base("Failed to start transaction. Check InnerException for details", innerException) { } public OrleansStartTransactionFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that transaction runtime is overloaded /// </summary> [Serializable] public class OrleansTransactionOverloadException : OrleansTransactionException { public OrleansTransactionOverloadException() : base("Transaction is overloaded on current silo, please try again later.") { } } /// <summary> /// Signifies that the runtime is unable to determine whether a transaction /// has committed. /// </summary> [Serializable] public class OrleansTransactionInDoubtException : OrleansTransactionException { public string TransactionId { get; private set; } public OrleansTransactionInDoubtException(string transactionId) : base(string.Format("Transaction {0} is InDoubt", transactionId)) { this.TransactionId = transactionId; } public OrleansTransactionInDoubtException(string transactionId, Exception exc) : base(string.Format("Transaction {0} is InDoubt", transactionId), exc) { this.TransactionId = transactionId; } public OrleansTransactionInDoubtException(string transactionId, string msg) : base(string.Format("Transaction {0} is InDoubt: {1}", transactionId, msg)) { this.TransactionId = transactionId; } public OrleansTransactionInDoubtException(SerializationInfo info, StreamingContext context) : base(info, context) { this.TransactionId = info.GetString(nameof(this.TransactionId)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(this.TransactionId), this.TransactionId); } } /// <summary> /// Signifies that the executing transaction has aborted. /// </summary> [Serializable] public class OrleansTransactionAbortedException : OrleansTransactionException { /// <summary> /// The unique identifier of the aborted transaction. /// </summary> public string TransactionId { get; private set; } public OrleansTransactionAbortedException(string transactionId, string msg) : base(msg) { this.TransactionId = transactionId; } public OrleansTransactionAbortedException(string transactionId, Exception innerException) : base($"Transaction {transactionId} Aborted because of an unhandled exception in a grain method call. See InnerException for details.", innerException) { TransactionId = transactionId; } public OrleansTransactionAbortedException(SerializationInfo info, StreamingContext context) : base(info, context) { this.TransactionId = info.GetString(nameof(this.TransactionId)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(this.TransactionId), this.TransactionId); } } /// <summary> /// Signifies that the executing transaction has aborted because a dependent transaction aborted. /// </summary> [Serializable] public class OrleansCascadingAbortException : OrleansTransactionTransientFailureException { public string DependentTransactionId { get; private set; } public OrleansCascadingAbortException(string transactionId, string dependentId) : base(transactionId, string.Format("Transaction {0} aborted because its dependent transaction {1} aborted", transactionId, dependentId)) { this.DependentTransactionId = dependentId; } public OrleansCascadingAbortException(string transactionId) : base(transactionId, string.Format("Transaction {0} aborted because a dependent transaction aborted", transactionId)) { } public OrleansCascadingAbortException(SerializationInfo info, StreamingContext context) : base(info, context) { this.DependentTransactionId = info.GetString(nameof(this.DependentTransactionId)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(this.DependentTransactionId), this.DependentTransactionId); } } /// <summary> /// Signifies that the executing transaction has aborted because a method did not await all its pending calls. /// </summary> [Serializable] public class OrleansOrphanCallException : OrleansTransactionAbortedException { public OrleansOrphanCallException(string transactionId, int pendingCalls) : base( transactionId, $"Transaction {transactionId} aborted because method did not await all its outstanding calls ({pendingCalls})") { } public OrleansOrphanCallException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing read-only transaction has aborted because it attempted to write to a grain. /// </summary> [Serializable] public class OrleansReadOnlyViolatedException : OrleansTransactionAbortedException { public OrleansReadOnlyViolatedException(string transactionId) : base(transactionId, string.Format("Transaction {0} aborted because it attempted to write a grain", transactionId)) { } public OrleansReadOnlyViolatedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class OrleansTransactionServiceNotAvailableException : OrleansTransactionException { public OrleansTransactionServiceNotAvailableException() : base("Transaction service not available") { } public OrleansTransactionServiceNotAvailableException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing transaction has aborted because its execution lock was broken /// </summary> [Serializable] public class OrleansBrokenTransactionLockException : OrleansTransactionTransientFailureException { public OrleansBrokenTransactionLockException(string transactionId, string situation) : base(transactionId, $"Transaction {transactionId} aborted because a broken lock was detected, {situation}") { } public OrleansBrokenTransactionLockException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing transaction has aborted because it could not upgrade some lock /// </summary> [Serializable] public class OrleansTransactionLockUpgradeException : OrleansTransactionTransientFailureException { public OrleansTransactionLockUpgradeException(string transactionId) : base(transactionId, $"Transaction {transactionId} Aborted because it could not upgrade a lock, because of a higher-priority conflicting transaction") { } public OrleansTransactionLockUpgradeException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing transaction has aborted because the TM did not receive all prepared messages in time /// </summary> [Serializable] public class OrleansTransactionPrepareTimeoutException : OrleansTransactionTransientFailureException { public OrleansTransactionPrepareTimeoutException(string transactionId) : base(transactionId, $"Transaction {transactionId} Aborted because the prepare phase did not complete within the timeout limit") { } public OrleansTransactionPrepareTimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing transaction has aborted because some possibly transient problem, such as internal /// timeouts for locks or protocol responses, or speculation failures. /// </summary> [Serializable] public class OrleansTransactionTransientFailureException : OrleansTransactionAbortedException { public OrleansTransactionTransientFailureException(string transactionId, string msg) : base(transactionId, msg) { } public OrleansTransactionTransientFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
//#define debug using System; using System.Collections.Generic; using System.Text; namespace ICSimulator { /** * @brief This is an implementation of buffered ring network interface proposed in * Ravindran et al. "A Performance Comparison of Hierarchical Ring- and Mesh-Connected Multiprocessor Networks", * HPCA 1997. * * << NIC >> * Although it's supposed to be using a wormhole flow control, it's actually more like a cut-through * flow control since its ring buffer size is exactly 1 packet in the paper. * * Injection policy: * 1. if the ring buffer is empty and no packet is being transmitted, injection of a new packet can * bypass the ring buffer to the next node. Priority is given over to response packets over * request packets. * 2. Ring buffer is not empty, injection is not allowed. One exception is that once the header flit * of the inject packet is started. Priority is given over to injection until it's done. * * Ring buffer: * Header flit allocated it and a tail flit deallocates it. * * Arbitration: * As mentioned above, arbitration to the next node is always given to in-flight flit (ones in the buffer), * except for the case that a local injection has already started for a packet. * Arbitration always need to check the downstream buffer and see if it's available. * * Caveat: No bypassing. * * TODO: prioritization at the injection queue pool * **/ public class WormholeBuffer { Queue<Flit> buf; // Due to pipelining, we need to increment the buffer count ahead of // time. Sort of like credit. int bufSize, lookAheadSize; bool bWorm; public WormholeBuffer(int size) { bufSize = size; lookAheadSize = 0; if (size < 1) throw new Exception("The buffer size must be at least 1-flit big."); buf = new Queue<Flit>(); bWorm = false; } public void enqueue(Flit f) { if (buf.Count == bufSize) throw new Exception("Cannot enqueue into the ring buffer due to size limit."); buf.Enqueue(f); Simulator.stats.totalBufferEnqCount.Add(); } public Flit dequeue() { Flit f = buf.Dequeue(); lookAheadSize--; // Take care of the cases when queue becomes empty while there is // still more body flits coming in. This is needed because the // arbitration simply looks at the queue and see if it's empty. It // assumes the worm is gone if queue is empty. TODO: this doesn't // fix the deadlock case when buffer size is less than 2. if (f.isHeadFlit && f.packet.nrOfFlits != 1) bWorm = true; if (f.isTailFlit && f.packet.nrOfFlits != 1) bWorm = false; return f; } public bool IsWorm {get { return bWorm;} } public Flit peek() { Flit f = null; if (buf.Count > 0) f = buf.Peek(); return f; } public bool canEnqNewFlit(Flit f) { #if debug Console.WriteLine("cyc {0} flit asking for enq pkt ID {1} flitNr {2}", Simulator.CurrentRound, f.packet.ID, f.flitNr); #endif if (lookAheadSize < bufSize) { lookAheadSize++; return true; } return false; } } public class Router_Node_Buffer : Router { Flit m_injectSlot_CW; Flit m_injectSlot_CCW; RC_Coord rc_coord; Queue<Flit>[] ejectBuffer; WormholeBuffer[] m_ringBuf; int starveCounter; int Local = 0;// defined in router_bridge public Router_Node_Buffer(Coord myCoord) : base(myCoord) { // the node Router is just a Ring node. A Flit gets ejected or moves straight forward linkOut = new Link[2]; linkIn = new Link[2]; m_injectSlot_CW = null; m_injectSlot_CCW = null; throttle[ID] = false; starved[ID] = false; starveCounter = 0; m_ringBuf = new WormholeBuffer[2]; for (int i = 0; i < 2; i++) m_ringBuf[i] = new WormholeBuffer(Config.ringBufferSize); } public Router_Node_Buffer(RC_Coord RC_c, Coord c) : base(c) { linkOut = new Link[2]; linkIn = new Link[2]; m_injectSlot_CW = null; m_injectSlot_CCW = null; rc_coord = RC_c; ejectBuffer = new Queue<Flit> [2]; for (int i = 0; i < 2; i++) ejectBuffer[i] = new Queue<Flit>(); throttle[ID] = false; starved[ID] = false; starveCounter = 0; m_ringBuf = new WormholeBuffer[2]; for (int i = 0; i < 2; i++) m_ringBuf[i] = new WormholeBuffer(Config.ringBufferSize); } // TODO: later on need to check ejection fifo public override bool creditAvailable(Flit f) { return m_ringBuf[f.packet.pktParity].canEnqNewFlit(f); } protected void acceptFlit(Flit f) { statsEjectFlit(f); if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits) statsEjectPacket(f.packet); m_n.receiveFlit(f); } Flit ejectLocal() { // eject locally-destined flit (highest-ranked, if multiple) Flit ret = null; int flitsTryToEject = 0; int bestDir = -1; // Check both directions for (int dir = 0; dir < 2; dir++) { if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.state != Flit.State.Placeholder && linkIn[dir].Out.dest.ID == ID) { ret = linkIn[dir].Out; bestDir = dir; flitsTryToEject ++; } } if (bestDir != -1) linkIn[bestDir].Out = null; Simulator.stats.flitsTryToEject[flitsTryToEject].Add(); #if debug if (ret != null) Console.WriteLine("ejecting flit {0} flitnr {1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, coord, Simulator.CurrentRound); #endif return ret; } // TODO: Caveat: THIS MIGHT NOT BE NECESSARY. Can put this in // do step. Imagine injeciton slow as part of fifo. // Injection into the ring: // TODO: need to check downstream buffer occupancy: // 1) If eject next node check next node's ejeciton buffer // 2) If some other nodes, check next node's ring buffer // TODO: How do I take care of the case that the next cycle the ring buffer becomes occupied and it also wants // to eject at the same node? // Ans: Since I already send the head, I have to continue sending. // public override bool canInjectFlit(Flit f) { if (throttle[ID]) return false; bool can; // Body flits and tail flits have to follow the head flit // direction since we are using wormhole flow control if (!f.isHeadFlit) { f.parity = f.packet.pktParity; } if (f.parity == 0) { if (m_injectSlot_CW != null) f.timeWaitToInject ++; can = m_injectSlot_CW == null; } else if (f.parity == 1) { if (m_injectSlot_CCW != null) f.timeWaitToInject ++; can = m_injectSlot_CCW == null; } else if (f.parity == -1) { if (m_injectSlot_CW != null && m_injectSlot_CCW != null) f.timeWaitToInject ++; can = (m_injectSlot_CW == null || m_injectSlot_CCW == null); } else throw new Exception("Unkown parity value!"); // Being blocked in the injection queue // TODO: this starvation count seems incorrect here! Because there // is no guarantee on injection of m_injectSlot_CW and // m_injectSlow_CCW since these can just be imagined as a 1-flit // buffer. if (!can) { starveCounter ++; Simulator.stats.injStarvation.Add(); } // TODO: this is for guaranteeing delievery? if (starveCounter == Config.starveThreshold) starved[ID] = true; return can; } public override void InjectFlit(Flit f) { //if (Config.topology != Topology.Mesh && Config.topology != Topology.MeshOfRings && f.parity != -1) // throw new Exception("In Ring based topologies, the parity must be -1"); starveCounter = 0; starved[ID] = false; if (f.parity == 0) { if (m_injectSlot_CW == null) m_injectSlot_CW = f; else throw new Exception("InjectFlit fault: The slot is empty!"); } else if (f.parity == 1) { if (m_injectSlot_CCW == null) m_injectSlot_CCW = f; else throw new Exception("InjectFlit fault: The slot is empty!"); } else { // Preference on which ring to route to. As long as there is // one ring open for injection, there's no correctness issue. int preference = -1; int dest = f.packet.dest.ID; int src = f.packet.src.ID; if (Config.topology == Topology.SingleRing) { if ((dest - src + Config.N) % Config.N < Config.N / 2) preference = 0; else preference = 1; } else if (dest / 4 == src / 4) { if ((dest - src + 4) % 4 < 2) preference = 0; else if ((dest - src + 4) % 4 > 2) preference = 1; } else if (Config.topology == Topology.HR_4drop) { if (ID == 1 || ID == 2 || ID == 5 || ID == 6 || ID == 8 || ID == 11 || ID == 12 || ID == 15 ) preference = 0; else preference = 1; } else if (Config.topology == Topology.HR_8drop || Config.topology == Topology.HR_8_8drop) { if (ID % 2 == 0) preference = 0; else preference = 1; } else if (Config.topology == Topology.HR_8_16drop) { if (dest / 8 == src / 8) { if ((dest - src + 8) % 8 < 4) preference = 0; else preference = 1; } else { if (ID % 2 == 0) preference = 1; else preference = 0; } } if (Config.NoPreference) preference = -1; if (preference == -1) preference = Simulator.rand.Next(2); if (preference == 0) { if (m_injectSlot_CW == null) m_injectSlot_CW = f; else if (m_injectSlot_CCW == null) m_injectSlot_CCW = f; } else if (preference == 1) { if (m_injectSlot_CCW == null) m_injectSlot_CCW = f; else if (m_injectSlot_CW == null) m_injectSlot_CW = f; } else throw new Exception("Unknown preference!"); // Set the direction for the entire packet since we are doing // wormhole flow control in buffered ring if (f.isHeadFlit) { if (m_injectSlot_CW == f) f.packet.pktParity = 0; else if (m_injectSlot_CCW == f) f.packet.pktParity = 1; } } #if debug if (f != null) { if (m_injectSlot_CW == f) Console.WriteLine("Router Inject flit cyc {0} node coord {3} id {4} -> flit id {5} flitNr {1} :: CW pktParity {2}", Simulator.CurrentRound, f.flitNr, f.packet.pktParity, coord, ID, f.packet.ID); else if (m_injectSlot_CCW == f) Console.WriteLine("Router Inject flit cyc {0} node coord {3} id {4} -> flit id {5} flitNr {1} :: CCW pktParity {2}", Simulator.CurrentRound, f.flitNr, f.packet.pktParity, coord, ID, f.packet.ID); } #endif } protected override void _doStep() { // Record timing for (int i = 0; i < 2; i++) { if (linkIn[i].Out != null && Config.N == 16) { Flit f = linkIn[i].Out; if (f.packet.src.ID / 4 == ID / 4) f.timeInTheSourceRing+=1; else if (f.packet.dest.ID / 4 == ID / 4) f.timeInTheDestRing +=1; else f.timeInTheTransitionRing += 1; } } // Ejection to the local node Flit f1 = null, f2 = null; // This is using two ejection buffers, BUT there's only ejection // port to the local PE. if (Config.EjectBufferSize != -1 && Config.RingEjectTrial == -1) { for (int dir =0; dir < 2; dir ++) { if (linkIn[dir].Out != null && linkIn[dir].Out.packet.dest.ID == ID && ejectBuffer[dir].Count < Config.EjectBufferSize) { ejectBuffer[dir].Enqueue(linkIn[dir].Out); linkIn[dir].Out = null; } } int bestdir = -1; for (int dir = 0; dir < 2; dir ++) { // if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Peek().injectionTime < ejectBuffer[bestdir].Peek().injectionTime)) if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Count > ejectBuffer[bestdir].Count)) // if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || Simulator.rand.Next(2) == 1)) bestdir = dir; } if (bestdir != -1) acceptFlit(ejectBuffer[bestdir].Dequeue()); } else { for (int i = 0; i < Config.RingEjectTrial; i++) { Flit eject = ejectLocal(); if (i == 0) f1 = eject; else if (i == 1) f2 = eject; if (eject != null) acceptFlit(eject); } if (f1 != null && f2 != null && f1.packet == f2.packet) Simulator.stats.ejectsFromSamePacket.Add(1); else if (f1 != null && f2 != null) Simulator.stats.ejectsFromSamePacket.Add(0); } // Arbitration and flow control for (int dir = 0; dir < 2; dir++) { // Enqueue into the buffer if (linkIn[dir].Out != null) { #if debug Console.WriteLine("cyc {0} dir {2} node {4} id {5}:: enq {1} flitNr {3}", Simulator.CurrentRound, linkIn[dir].Out.packet.ID, dir, linkIn[dir].Out.flitNr, coord, ID); #endif m_ringBuf[dir].enqueue(linkIn[dir].Out); linkIn[dir].Out = null; Simulator.stats.flitsPassBy.Add(1); } // Arbitrate betwen local flit and buffered flit Flit winner = null; Flit _injSlot = (dir == 0) ? m_injectSlot_CW : m_injectSlot_CCW; Flit _bufHead = m_ringBuf[dir].peek(); #if debug Console.WriteLine("cyc {0} arb: buf_null {1} injslot_null {2}", Simulator.CurrentRound, _bufHead == null, _injSlot == null); #endif if (_injSlot != null && _bufHead == null && m_ringBuf[dir].IsWorm == false) winner = _injSlot; else if (_injSlot == null && _bufHead != null) winner = _bufHead; else if (_injSlot != null && _bufHead != null) { // Priority is always given to flit in the ring buffer, // execpt if the header flit of the local injection // buffer has already been sent downstream. This is to // ensure wormhole flow control if (_injSlot.isHeadFlit && _bufHead.isHeadFlit) winner = _bufHead; else if (_injSlot.isHeadFlit && !_bufHead.isHeadFlit) winner = _bufHead; else if (!_injSlot.isHeadFlit && _bufHead.isHeadFlit) winner = _injSlot; else throw new Exception("Impossible for both flits in ring buffer and injection slot in active state."); } // Check downstream credit, if ring/ejection buffer is available then send it. if (winner != null) { #if debug Console.Write("cyc {0} :: dir {2} node_ID {4} arb winner {1} ishead {3} dest {5}-> ", Simulator.CurrentRound, winner.packet.ID, dir, winner.isHeadFlit, ID, winner.dest.ID); if (winner == m_ringBuf[dir].peek()) Console.WriteLine("winner In ring buffer"); else if (winner == m_injectSlot_CW) Console.WriteLine("winner In inj cw"); else if (winner == m_injectSlot_CCW) Console.WriteLine("winner In inj ccw"); #endif // TODO: not sure why we need to check whether linkOut.in // is empty or not. Double check on this. // Need to check downstream buffer occupancy: // 1) If eject next node check next node's ejeciton buffer // 2) If some other nodes, check next node's ring buffer if (checkDownStreamCredit(winner) && linkOut[dir].In == null) { if (winner == m_ringBuf[dir].peek()) m_ringBuf[dir].dequeue(); else if (winner == m_injectSlot_CW) m_injectSlot_CW = null; else if (winner == m_injectSlot_CCW) m_injectSlot_CCW = null; linkOut[dir].In = winner; Console.WriteLine("inject"); statsInjectFlit(winner); } else { // Being blocked } } } } /* * In order to check downstream ID, we need to know the topology and * whether we should check local ring's or global ring's buffer and * ejection buffer. * * TODO: currently we do not check ejection fifos since we do not have * them. * */ bool checkDownStreamCredit(Flit f) { if (f == null) throw new Exception("Null flit checking credit."); if (Config.topology == Topology.SingleRing) { int _nextNodeID; if (f.packet.pktParity == 0) _nextNodeID = (ID + 1) % Config.N; else _nextNodeID = (ID == 0) ? Config.N-1 : (ID - 1) % Config.N; #if debug Console.WriteLine("cyc {0} flit asking for credit ID {1} flitNr {2} dir {3} nextNodeID {4}", Simulator.CurrentRound, f.packet.ID, f.flitNr, f.packet.pktParity, _nextNodeID); #endif // TODO: assume always successful ejection if (f.dest.ID == _nextNodeID) return true; return Simulator.network.nodeRouters[_nextNodeID].creditAvailable(f); } else if (Config.topology == Topology.HR_4drop) { int subNodeID = ID % 4; int localRingID = ID / 4; int _nextNodeID, _nextBridgeID; // Determining if there's a bridge router between current // node and the next node if (f.packet.pktParity == 0) { _nextNodeID = (subNodeID + 1) % 4 + localRingID * 4; _nextBridgeID = Array.IndexOf(Simulator.network.GetCWnext, _nextNodeID); #if debug2 Console.WriteLine("Bridge search cyc {0} CW : bridge index {1}", Simulator.CurrentRound, _nextBridgeID); #endif } else { _nextNodeID = (subNodeID == 0) ? 3 : subNodeID - 1; _nextNodeID += localRingID * 4; _nextBridgeID = Array.IndexOf(Simulator.network.GetCCWnext, _nextNodeID); #if debug2 Console.WriteLine("Bridge search cyc {0} CW : bridge index {1}", Simulator.CurrentRound, _nextBridgeID); #endif } #if debug Console.WriteLine("cyc {0} flit asking for credit ID {1} flitNr {2} dir {3} nextNodeID {4} nextBridge {5}", Simulator.CurrentRound, f.packet.ID, f.flitNr, f.packet.pktParity, _nextNodeID, _nextBridgeID); #endif // If bridge is there, check if we are ejecting to bridge if (_nextBridgeID != -1) { if (Simulator.network.bridgeRouters[_nextBridgeID].productive(f, Local) == true) { return Simulator.network.bridgeRouters[_nextBridgeID].creditAvailable(f); } } if (f.dest.ID == _nextNodeID) return true; return Simulator.network.nodeRouters[_nextNodeID].creditAvailable(f); } else throw new Exception("Not Supported"); return false; } } public class Router_Switch_Buffer : Router { int bufferDepth = 1; public static int[,] bufferCurD = new int[Config.N,4]; Flit[,] buffers;// = new Flit[4,32]; public Router_Switch_Buffer(int ID) : base() { coord.ID = ID; enable = true; m_n = null; buffers = new Flit[4,32]; // actual buffer depth is decided by bufferDepth for (int i = 0; i < 4; i++) for (int n = 0; n < bufferDepth; n++) buffers[i, n] = null; } int Local_CW = 0; int Local_CCW = 1; int GL_CW = 2; int GL_CCW = 3; // different routing algorithms can be implemented by changing this function private bool productiveRouter(Flit f, int port) { // Console.WriteLine("Net/RouterRing.cs"); int RingID = ID / 4; if (Config.HR_NoBias) { if ((port == Local_CW || port == Local_CCW) && RingID == f.packet.dest.ID / 4) return false; else if ((port == Local_CW || port == Local_CCW) && RingID != f.packet.dest.ID / 4) return true; else if ((port == GL_CW || port == GL_CCW) && RingID == f.packet.dest.ID / 4) return true; else if ((port == GL_CW || port == GL_CCW) && RingID != f.packet.dest.ID / 4) return false; else throw new Exception("Unknown port of switchRouter"); } else if (Config.HR_SimpleBias) { if ((port == Local_CW || port == Local_CCW) && RingID == f.packet.dest.ID / 4) return false; else if ((port == Local_CW || port == Local_CCW) && RingID != f.packet.dest.ID / 4) // if (RingID + f.packet.dest.ID / 4 == 3) //diagonal. can always inject return true; /* else if (RingID == 0 && destID == 1) return ID == 2 || ID == 1; else if (RingID == 0 && destID == 2) return ID == 3 || ID == 0; else if (RingID == 1 && destID == 0) return ID == 4 || ID == 5; else if (RingID == 1 && destID == 3) return ID == 6 || ID == 7; else if (RingID == 2 && destID == 0) return ID == 8 || ID == 9; else if (RingID == 2 && destID == 3) return ID == 10 || ID == 11; else if (RingID == 3 && destID == 1) return ID == 13 || ID == 14; else if (RingID == 3 && destID == 2) return ID == 12 || ID == 15; else throw new Exception("Unknown src and dest in Hierarchical Ring");*/ else if ((port == GL_CW || port == GL_CCW) && RingID == f.packet.dest.ID / 4) return true; else if ((port == GL_CW || port == GL_CCW) && RingID != f.packet.dest.ID / 4) return false; else throw new Exception("Unknown port of switchRouter"); } else throw new Exception("Unknow Routing Algorithm for Hierarchical Ring"); } protected override void _doStep() { switchRouterStats(); // consider 4 input ports seperately. If not productive, keep circling if (!enable) return; /* if (ID == 3) { if (linkIn[0].Out != null && linkIn[0].Out.packet.dest.ID == 11) Console.WriteLine("parity : {0}, src:{1}", linkIn[0].Out.parity, linkIn[0].Out.packet.src.ID); }*/ for (int dir = 0; dir < 4; dir ++) { int i; for (i = 0; i < bufferDepth; i++) if (buffers[dir, i] == null) break; //Console.WriteLine("linkIn[dir] == null:{0},ID:{1}, dir:{2}", linkIn[dir] == null, ID, dir); bool productive = (linkIn[dir].Out != null)? productiveRouter(linkIn[dir].Out, dir) : false; //Console.WriteLine("productive: {0}", productive); if (linkIn[dir].Out != null && (!productive || i == bufferDepth)) // nonproductive or the buffer is full : bypass the router { linkOut[dir].In = linkIn[dir].Out; Console.WriteLine("transit"); linkIn[dir].Out = null; } else if (linkIn[dir].Out != null) //productive direction and the buffer has empty space, add into buffer { int k; for (k = 0; k < bufferDepth; k++) { if (buffers[dir, k] == null) { buffers[dir, k] = linkIn[dir].Out; linkIn[dir].Out = null; break; } //Console.WriteLine("{0}", k); } if (k == bufferDepth) throw new Exception("The buffer is full!!"); } } // if there're extra slots in the same direction network, inject from the buffer for (int dir = 0; dir < 4; dir ++) { if (linkOut[dir].In == null) // extra slot available { int posdir = (dir+2) % 4; if (buffers[posdir, 0] != null) { linkOut[dir].In = buffers[posdir, 0]; buffers[posdir, 0] = null; } } } // if the productive direction with the same parity is not available. The direction with the other parity is also fine for (int dir = 0; dir < 4; dir ++) { int crossdir = 3 - dir; if (linkOut[dir].In == null) // extra slot available { if (buffers[crossdir, 0] != null) { // for HR_SimpleBias is the dir is not a local ring, can't change rotating direction if (Config.HR_SimpleBias && (dir == GL_CW || dir == GL_CCW)) continue; linkOut[dir].In = buffers[crossdir, 0]; Console.WriteLine("transit"); buffers[crossdir, 0] = null; } } } if (Config.HR_NoBuffer) { for (int dir = 0; dir < 4; dir ++) { if (buffers[dir, 0] != null) { if (linkOut[dir].In != null) throw new Exception("The outlet of the buffer is blocked"); linkOut[dir].In = buffers[dir, 0]; buffers[dir, 0] = null; } } } // move all the flits in the buffer if the head flit is null for (int dir = 0; dir < 4; dir ++) { if (buffers[dir, 0] == null) { for (int i = 0; i < bufferDepth - 1; i++) buffers[dir, i] = buffers[dir, i + 1]; buffers[dir, bufferDepth-1] = null; } } for (int dir = 0; dir < 4; dir ++) { int i; for (i = 0; i < bufferDepth; i++) if (buffers[dir, i] == null) break; bufferCurD[ID,dir] = i; } } void switchRouterStats() { for (int dir = 0; dir < 4; dir ++) { Flit f = linkIn[dir].Out; if (f != null && (dir == Local_CW || dir == Local_CCW)) { if (f.packet.src.ID / 4 == ID / 4) f.timeInTheSourceRing ++; else if (f.packet.dest.ID / 4 == ID / 4) f.timeInTheDestRing ++; } else if (f != null && (dir == GL_CW || dir == GL_CCW)) f.timeInGR += 2; } return; } public override bool canInjectFlit(Flit f) { return false; } public override void InjectFlit(Flit f) { return; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Restful.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using SaNi.Mono.Math; using System; using System.Runtime.CompilerServices; namespace SaNi.Mono.Graphics.Renderables { public sealed class Circle : IRenderable { #region Constants public const uint SmoothCircle = 36; public const uint RoughCircle = 9; #endregion #region Fields private Transform transform; private Rectf localBounds; private Rectf globalbounds; private Rectf textureSource; private Color borderfill; private Color fill; private Texture2D texture; private readonly int id; private readonly uint ptr; private uint layer; private bool destroyed; #endregion #region Properties public Transform Transform { get { GetTransform(ref transform); return transform; } set { SetTransform(value); } } public Rectf LocalBounds { get { GetLocalBounds(ref localBounds); return localBounds; } set { SetLocalBounds(value); } } public Rectf GlobalBounds { get { GetGlobalBounds(ref globalbounds); return globalbounds; } } public Rectf TextureSource { get { GetTextureSource(ref textureSource); return textureSource; } set { SetTextureSource(value); } } public Texture2D Texture { get { GetTexture(ref texture); return texture; } set { SetTexture(value); } } public int ID { get { return id; } } public bool Visible { get { var value = false; GetVisible(ref value); return value; } set { SetVisible(value); } } public float Radius { get { var value = 0.0f; GetRadius(ref value); return value; } set { SetRadius(value); } } public float BorderThickness { get { var value = 0.0f; GetBorderThickness(ref value); return value; } set { SetBorderThickness(value); } } public Color BorderFill { get { GetBorderFill(ref borderfill); return borderfill; } set { SetBorderFill(value); } } public Color Fill { get { GetFill(ref fill); return fill; } set { SetFill(value); } } #endregion public Circle(float x, float y, float radius, uint vertices = SmoothCircle) { transform = Transform.Empty(); localBounds = Rectf.Empty(); globalbounds = Rectf.Empty(); borderfill = new Color(); fill = new Color(); Instantiate(x, y, radius, vertices, ref id, ref ptr); } public Circle(Vector2 position, float radius, uint vertices = SmoothCircle) : this(position.x, position.y, radius, vertices) { } public Circle(Vector3 xyr, uint vertices = SmoothCircle) : this(xyr.x, xyr.y, xyr.z, vertices) { } [MethodImpl(MethodImplOptions.InternalCall)] private extern void Instantiate(float x, float y, float radius, uint vertices, ref int id, ref uint ptr); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Release(); #region Internal get/set methods [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetTransform(ref Transform value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetTransform(Transform value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetLocalBounds(ref Rectf value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetLocalBounds(Rectf value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetGlobalBounds(ref Rectf value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetTextureSource(ref Rectf value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetTextureSource(Rectf value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetTexture(ref Texture2D value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetTexture(Texture2D value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetVisible(ref bool value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetVisible(bool value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetRadius(ref float value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetRadius(float value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetBorderThickness(ref float value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetBorderThickness(float value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetBorderFill(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetBorderFill(Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetFill(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetFill(Color value); #endregion public void Destroy() { if (destroyed) return; Release(); GC.SuppressFinalize(this); destroyed = true; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Management.Automation.Language; using System.Net.NetworkInformation; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Xml; namespace System.Management.Automation { /// <summary> /// Defines generic utilities and helper methods for PowerShell. /// </summary> internal static class PsUtils { // Cache of the current process' parentId private static int? s_currentParentProcessId; private static readonly int s_currentProcessId = Environment.ProcessId; /// <summary> /// Retrieve the parent process of a process. /// /// Previously this code used WMI, but WMI is causing a CPU spike whenever the query gets called as it results in /// tzres.dll and tzres.mui.dll being loaded into every process to convert the time information to local format. /// For perf reasons, we resort to P/Invoke. /// </summary> /// <param name="current">The process we want to find the /// parent of</param> internal static Process GetParentProcess(Process current) { var processId = current.Id; // This is a common query (parent id for the current process) // Use cached value if available var parentProcessId = processId == s_currentProcessId && s_currentParentProcessId.HasValue ? s_currentParentProcessId.Value : Microsoft.PowerShell.ProcessCodeMethods.GetParentPid(current); // cache the current process parent pid if it hasn't been done yet if (processId == s_currentProcessId && !s_currentParentProcessId.HasValue) { s_currentParentProcessId = parentProcessId; } if (parentProcessId == 0) return null; try { Process returnProcess = Process.GetProcessById(parentProcessId); // Ensure the process started before the current // process, as it could have gone away and had the // PID recycled. if (returnProcess.StartTime <= current.StartTime) return returnProcess; else return null; } catch (ArgumentException) { // GetProcessById throws an ArgumentException when // you reach the top of the chain -- Explorer.exe // has a parent process, but you cannot retrieve it. return null; } } /// <summary> /// Return true/false to indicate whether the processor architecture is ARM. /// </summary> /// <returns></returns> internal static bool IsRunningOnProcessorArchitectureARM() { Architecture arch = RuntimeInformation.OSArchitecture; return arch == Architecture.Arm || arch == Architecture.Arm64; } /// <summary> /// Get a temporary directory to use, needs to be unique to avoid collision. /// </summary> internal static string GetTemporaryDirectory() { string tempDir = string.Empty; string tempPath = Path.GetTempPath(); do { tempDir = Path.Combine(tempPath, System.Guid.NewGuid().ToString()); } while (Directory.Exists(tempDir)); try { Directory.CreateDirectory(tempDir); } catch (UnauthorizedAccessException) { tempDir = string.Empty; // will become current working directory } return tempDir; } internal static string GetHostName() { IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties(); string hostname = ipProperties.HostName; string domainName = ipProperties.DomainName; // CoreFX on Unix calls GLibc getdomainname() // which returns "(none)" if a domain name is not set by setdomainname() if (!string.IsNullOrEmpty(domainName) && !domainName.Equals("(none)", StringComparison.Ordinal)) { hostname = hostname + "." + domainName; } return hostname; } internal static uint GetNativeThreadId() { #if UNIX return Platform.NonWindowsGetThreadId(); #else return NativeMethods.GetCurrentThreadId(); #endif } private static class NativeMethods { [DllImport(PinvokeDllNames.GetCurrentThreadIdDllName)] internal static extern uint GetCurrentThreadId(); } #region ASTUtils /// <summary> /// This method is to get the unique key for a UsingExpressionAst. The key is a base64 /// encoded string based on the text of the UsingExpressionAst. /// /// This method is used when handling a script block that contains $using for Invoke-Command. /// /// When run Invoke-Command targeting a machine that runs PSv3 or above, we pass a dictionary /// to the remote end that contains the key of each UsingExpressionAst and its value. This method /// is used to generate the key. /// </summary> /// <param name="usingAst">A using expression.</param> /// <returns>Base64 encoded string as the key of the UsingExpressionAst.</returns> internal static string GetUsingExpressionKey(Language.UsingExpressionAst usingAst) { Diagnostics.Assert(usingAst != null, "Caller makes sure the parameter is not null"); // We cannot call ToLowerInvariant unconditionally, because usingAst might // contain IndexExpressionAst in its SubExpression, such as // $using:bar["AAAA"] // and the index "AAAA" might not get us the same value as "aaaa". // // But we do want a unique key to represent the same UsingExpressionAst's as much // as possible, so as to avoid sending redundant key-value's to remote machine. // As a workaround, we call ToLowerInvariant when the SubExpression of usingAst // is a VariableExpressionAst, because: // (1) Variable name is case insensitive; // (2) People use $using to refer to a variable most of the time. string usingAstText = usingAst.ToString(); if (usingAst.SubExpression is Language.VariableExpressionAst) { usingAstText = usingAstText.ToLowerInvariant(); } return StringToBase64Converter.StringToBase64String(usingAstText); } #endregion ASTUtils #region EvaluatePowerShellDataFile /// <summary> /// Evaluate a powershell data file as if it's a module manifest. /// </summary> /// <param name="parameterName"></param> /// <param name="psDataFilePath"></param> /// <param name="context"></param> /// <param name="skipPathValidation"></param> /// <returns></returns> internal static Hashtable EvaluatePowerShellDataFileAsModuleManifest( string parameterName, string psDataFilePath, ExecutionContext context, bool skipPathValidation) { // Use the same capabilities as the module manifest // e.g. allow 'PSScriptRoot' variable return EvaluatePowerShellDataFile( parameterName, psDataFilePath, context, Microsoft.PowerShell.Commands.ModuleCmdletBase.PermittedCmdlets, new[] { "PSScriptRoot" }, allowEnvironmentVariables: true, skipPathValidation: skipPathValidation); } /// <summary> /// Get a Hashtable object out of a PowerShell data file (.psd1) /// </summary> /// <param name="parameterName"> /// Name of the parameter that takes the specified .psd1 file as a value /// </param> /// <param name="psDataFilePath"> /// Path to the powershell data file /// </param> /// <param name="context"> /// ExecutionContext to use /// </param> /// <param name="allowedCommands"> /// Set of command names that are allowed to use in the .psd1 file /// </param> /// <param name="allowedVariables"> /// Set of variable names that are allowed to use in the .psd1 file /// </param> /// <param name="allowEnvironmentVariables"> /// If true, allow to use environment variables in the .psd1 file /// </param> /// <param name="skipPathValidation"> /// If true, caller guarantees the path is valid /// </param> /// <returns></returns> internal static Hashtable EvaluatePowerShellDataFile( string parameterName, string psDataFilePath, ExecutionContext context, IEnumerable<string> allowedCommands, IEnumerable<string> allowedVariables, bool allowEnvironmentVariables, bool skipPathValidation) { if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); } if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException(nameof(psDataFilePath)); } if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } string resolvedPath; if (skipPathValidation) { resolvedPath = psDataFilePath; } else { #region "ValidatePowerShellDataFilePath" bool isPathValid = true; // File extension needs to be .psd1 string pathExt = Path.GetExtension(psDataFilePath); if (string.IsNullOrEmpty(pathExt) || !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } ProviderInfo provider; var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider); // ConfigPath should be resolved as FileSystem provider if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } // ConfigPath should be resolved to a single path if (resolvedPaths.Count != 1) { isPathValid = false; } if (!isPathValid) { throw PSTraceSource.NewArgumentException( parameterName, ParserStrings.CannotResolvePowerShellDataFilePath, psDataFilePath); } resolvedPath = resolvedPaths[0]; #endregion "ValidatePowerShellDataFilePath" } #region "LoadAndEvaluatePowerShellDataFile" object evaluationResult; try { // Create the scriptInfo for the .psd1 file string dataFileName = Path.GetFileName(resolvedPath); var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context); ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock; // Validate the scriptblock scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables); // Evaluate the scriptblock object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); try { // Set the $PSScriptRoot before the evaluation context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath)); evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs()); } finally { context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot); } } catch (RuntimeException ex) { throw PSTraceSource.NewInvalidOperationException( ex, ParserStrings.CannotLoadPowerShellDataFile, psDataFilePath, ex.Message); } if (!(evaluationResult is Hashtable retResult)) { throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, psDataFilePath); } #endregion "LoadAndEvaluatePowerShellDataFile" return retResult; } #endregion EvaluatePowerShellDataFile internal static readonly string[] ManifestModuleVersionPropertyName = new[] { "ModuleVersion" }; internal static readonly string[] ManifestGuidPropertyName = new[] { "GUID" }; internal static readonly string[] ManifestPrivateDataPropertyName = new[] { "PrivateData" }; internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] { "AliasesToExport", "CmdletsToExport", "CompatiblePSEditions", "FunctionsToExport", "NestedModules", "RootModule", "ModuleToProcess", "ModuleVersion" }; internal static Hashtable GetModuleManifestProperties(string psDataFilePath, string[] keys) { string dataFileContents = ScriptAnalysis.ReadScript(psDataFilePath); ParseError[] parseErrors; var ast = (new Parser()).Parse(psDataFilePath, dataFileContents, null, out parseErrors, ParseMode.ModuleAnalysis); if (parseErrors.Length > 0) { var pe = new ParseException(parseErrors); throw PSTraceSource.NewInvalidOperationException( pe, ParserStrings.CannotLoadPowerShellDataFile, psDataFilePath, pe.Message); } string unused1; string unused2; var pipeline = ast.GetSimplePipeline(false, out unused1, out unused2); if (pipeline != null) { var hashtableAst = pipeline.GetPureExpression() as HashtableAst; if (hashtableAst != null) { var result = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (var pair in hashtableAst.KeyValuePairs) { var key = pair.Item1 as StringConstantExpressionAst; if (key != null && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase)) { try { var val = pair.Item2.SafeGetValue(); result[key.Value] = val; } catch { throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, psDataFilePath); } } } return result; } } throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, psDataFilePath); } } /// <summary> /// This class provides helper methods for converting to/fro from /// string to base64string. /// </summary> internal static class StringToBase64Converter { /// <summary> /// Converts string to base64 encoded string. /// </summary> /// <param name="input">String to encode.</param> /// <returns>Base64 encoded string.</returns> internal static string StringToBase64String(string input) { // NTRAID#Windows Out Of Band Releases-926471-2005/12/27-JonN // shell crashes if you pass an empty script block to a native command if (input == null) { throw PSTraceSource.NewArgumentNullException(nameof(input)); } string base64 = Convert.ToBase64String ( Encoding.Unicode.GetBytes(input.ToCharArray()) ); return base64; } /// <summary> /// Decodes base64 encoded string. /// </summary> /// <param name="base64">Base64 string to decode.</param> /// <returns>Decoded string.</returns> internal static string Base64ToString(string base64) { if (string.IsNullOrEmpty(base64)) { throw PSTraceSource.NewArgumentNullException(nameof(base64)); } string output = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64))); return output; } /// <summary> /// Decodes base64 encoded string in to args array. /// </summary> /// <param name="base64"></param> /// <returns></returns> internal static object[] Base64ToArgsConverter(string base64) { if (string.IsNullOrEmpty(base64)) { throw PSTraceSource.NewArgumentNullException(nameof(base64)); } string decoded = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64))); // Deserialize string XmlReader reader = XmlReader.Create(new StringReader(decoded), InternalDeserializer.XmlReaderSettingsForCliXml); object dso; Deserializer deserializer = new Deserializer(reader); dso = deserializer.Deserialize(); if (!deserializer.Done()) { // This helper function should move to host and it should provide appropriate // error message there. throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter); } if (!(dso is PSObject mo)) { // This helper function should move the host. Provide appropriate error message. // Format of args parameter is not correct. throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter); } if (!(mo.BaseObject is ArrayList argsList)) { // This helper function should move the host. Provide appropriate error message. // Format of args parameter is not correct. throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter); } return argsList.ToArray(); } } /// <summary> /// A simple implementation of CRC32. /// See "CRC-32 algorithm" in https://en.wikipedia.org/wiki/Cyclic_redundancy_check. /// </summary> internal static class CRC32Hash { // CRC-32C polynomial representations private const uint polynomial = 0x1EDC6F41; private static readonly uint[] table; static CRC32Hash() { uint temp = 0; table = new uint[256]; for (int i = 0; i < table.Length; i++) { temp = (uint)i; for (int j = 0; j < 8; j++) { if ((temp & 1) == 1) { temp = (temp >> 1) ^ polynomial; } else { temp >>= 1; } } table[i] = temp; } } private static uint Compute(byte[] buffer) { uint crc = 0xFFFFFFFF; for (int i = 0; i < buffer.Length; ++i) { var index = (byte)(crc ^ buffer[i] & 0xff); crc = (crc >> 8) ^ table[index]; } return ~crc; } internal static byte[] ComputeHash(byte[] buffer) { uint crcResult = Compute(buffer); return BitConverter.GetBytes(crcResult); } internal static string ComputeHash(string input) { byte[] hashBytes = ComputeHash(Encoding.UTF8.GetBytes(input)); return BitConverter.ToString(hashBytes).Replace("-", string.Empty); } } #region ReferenceEqualityComparer /// <summary> /// Equality comparer based on Object Identity. /// </summary> internal class ReferenceEqualityComparer : IEqualityComparer { bool IEqualityComparer.Equals(object x, object y) { return Object.ReferenceEquals(x, y); } int IEqualityComparer.GetHashCode(object obj) { // The Object.GetHashCode and RuntimeHelpers.GetHashCode methods are used in the following scenarios: // // Object.GetHashCode is useful in scenarios where you care about object value. Two strings with identical // contents will return the same value for Object.GetHashCode. // // RuntimeHelpers.GetHashCode is useful in scenarios where you care about object identity. Two strings with // identical contents will return different values for RuntimeHelpers.GetHashCode, because they are different // string objects, although their contents are the same. return RuntimeHelpers.GetHashCode(obj); } } #endregion }
/// Copyright (C) 2012-2014 Soomla 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; using System.Collections; using System.Collections.Generic; namespace Soomla.Levelup { /// <summary> /// A representation of one or more <c>Gate</c>s which together define a /// composite criteria for progressing between the game's <c>World</c>s /// or <code>Level</code>s. /// </summary> public abstract class GatesList : Gate { /// <summary> /// The list of <c>Gate</c>s. /// </summary> protected List<Gate> Gates = new List<Gate>(); /// <summary> /// Constructor. /// </summary> /// <param name="id">GatesList ID.</param> public GatesList(string id) : base(id) { } /// <summary> /// Constructor for GatesList with one gate. /// </summary> /// <param name="id">ID.</param> /// <param name="singleGate">Single gate in this gateslist.</param> public GatesList(string id, Gate singleGate) : base(id) { Add(singleGate); } /// <summary> /// Constructor. /// </summary> /// <param name="id">ID.</param> /// <param name="gates">List of gates.</param> public GatesList(string id, List<Gate> gates) : base(id) { // Iterate over gates in given list and add them to Gates making a // copy and attaching listeners foreach (Gate gate in gates) { Add(gate); } } /// <summary> /// Constructor. /// </summary> /// <param name="jsonGate">JSON gate.</param> public GatesList(JSONObject jsonGate) : base(jsonGate) { List<JSONObject> gatesJSON = jsonGate[LUJSONConsts.LU_GATES].list; // Iterate over all gates in the JSON array and for each one create // an instance according to the gate type foreach (JSONObject gateJSON in gatesJSON) { Gate gate = Gate.fromJSONObject(gateJSON); if (gate != null) { Add(gate); } } } /// <summary> /// Converts this gateslist into a JSONObject. /// </summary> /// <returns>The JSON object.</returns> public override JSONObject toJSONObject() { JSONObject obj = base.toJSONObject(); JSONObject gatesJSON = new JSONObject(JSONObject.Type.ARRAY); foreach(Gate gate in Gates) { gatesJSON.Add(gate.toJSONObject()); } obj.AddField(LUJSONConsts.LU_GATES, gatesJSON); return obj; } /// <summary> /// Converts the given JSONObject into a gateslist. /// </summary> /// <returns>GatesList.</returns> /// <param name="gateObj">The JSON object to convert.</param> public new static GatesList fromJSONObject(JSONObject gateObj) { string className = gateObj[JSONConsts.SOOM_CLASSNAME].str; GatesList gatesList = (GatesList) Activator.CreateInstance(Type.GetType("Soomla.Levelup." + className), new object[] { gateObj }); return gatesList; } /// <summary> /// Counts the number of gates in this gateslist. /// </summary> /// <value>The number of gates.</value> public int Count { get { return Gates.Count; } } /// <summary> /// Adds the given gate to this gateslist. /// </summary> /// <param name="gate">Gate to add.</param> public void Add(Gate gate) { gate.OnAttached(); Gates.Add(gate); } /// <summary> /// Removes the given gate from this gateslist. /// </summary> /// <param name="gate">Gate to remove.</param> public void Remove(Gate gate) { Gates.Remove(gate); gate.OnDetached(); } /// <summary> /// Retrieves from this gateslist the gate with the given ID. /// </summary> /// <param name="id">ID of gate to be retrieved.</param> public Gate this[string id] { get { foreach(Gate g in Gates) { if (g.ID == id) { return g; } } return null; } } /// <summary> /// get: Retrieves from this gateslist the gate at the given index. /// set: Sets this gateslist at the given index to be `value`. /// </summary> /// <param name="idx">Index.</param> public Gate this[int idx] { get { return Gates[idx]; } set { Gate indexGate = Gates[idx]; if (indexGate != value) { if (indexGate != null) { indexGate.OnDetached(); } Gates[idx] = value; if (value != null) { value.OnAttached(); } } } } /// <summary> /// Registers relevant events: gate-opened event. /// </summary> protected override void registerEvents() { if (!IsOpen ()) { LevelUpEvents.OnGateOpened += onGateOpened; } } /// <summary> /// Unregisters relevant events: gate-opened event. /// </summary> protected override void unregisterEvents() { LevelUpEvents.OnGateOpened -= onGateOpened; } /// <summary> /// Opens this gateslist if it can be opened (its criteria has been met). /// </summary> /// <returns>If the gate has been opened returns <c>true</c>; otherwise /// <c>false</c>.</returns> protected override bool openInner() { if (CanOpen()) { // There's nothing to do here... If CanOpen returns true it means that the // gates list meets the condition for being opened. ForceOpen(true); return true; } return false; } /// <summary> /// Opens this gateslist if the gate-opened event causes the GatesList composite criteria to be met. /// </summary> /// <param name="gate">Gate that was opened.</param> private void onGateOpened(Gate gate) { if(Gates.Contains(gate)) { if (CanOpen()) { ForceOpen(true); } } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using TestCases.SS.UserModel; using System; using NUnit.Framework; using NPOI.SS.UserModel; using NPOI.OpenXml4Net.OPC; namespace NPOI.XSSF.UserModel { [TestFixture] public class TestXSSFHyperlink : BaseTestHyperlink { public TestXSSFHyperlink() : base(XSSFITestDataProvider.instance) { } [SetUp] public void SetUp() { // Use system out logger Environment.SetEnvironmentVariable( "NPOI.util.POILogger", "NPOI.util.SystemOutLogger" ); } [Test] public void TestLoadExisting() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("WithMoreVariousData.xlsx"); Assert.AreEqual(3, workbook.NumberOfSheets); XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0); // Check the hyperlinks Assert.AreEqual(4, sheet.NumHyperlinks); doTestHyperlinkContents(sheet); } [Test] public void TestCreate() { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.CreateSheet() as XSSFSheet; XSSFRow row = sheet.CreateRow(0) as XSSFRow; XSSFCreationHelper CreateHelper = workbook.GetCreationHelper() as XSSFCreationHelper; String[] urls = { "http://apache.org/", "www.apache.org", "/temp", "file:///c:/temp", "http://apache.org/default.php?s=isTramsformed&submit=Search&la=*&li=*"}; for (int i = 0; i < urls.Length; i++) { String s = urls[i]; XSSFHyperlink link = CreateHelper.CreateHyperlink(HyperlinkType.Url) as XSSFHyperlink; link.Address=(s); XSSFCell cell = row.CreateCell(i) as XSSFCell; cell.Hyperlink=(link); } workbook = XSSFTestDataSamples.WriteOutAndReadBack(workbook) as XSSFWorkbook; sheet = workbook.GetSheetAt(0) as XSSFSheet; PackageRelationshipCollection rels = sheet.GetPackagePart().Relationships; Assert.AreEqual(urls.Length, rels.Size); for (int i = 0; i < rels.Size; i++) { PackageRelationship rel = rels.GetRelationship(i); if (rel.TargetUri.IsAbsoluteUri&&rel.TargetUri.IsFile) Assert.AreEqual(urls[i].Replace("file:///","").Replace("/","\\"),rel.TargetUri.LocalPath); else // there should be a relationship for each URL Assert.AreEqual(urls[i], rel.TargetUri.ToString()); } // Bugzilla 53041: Hyperlink relations are duplicated when saving XSSF file workbook = XSSFTestDataSamples.WriteOutAndReadBack(workbook) as XSSFWorkbook; sheet = workbook.GetSheetAt(0) as XSSFSheet; rels = sheet.GetPackagePart().Relationships; Assert.AreEqual(urls.Length, rels.Size); for (int i = 0; i < rels.Size; i++) { PackageRelationship rel = rels.GetRelationship(i); if (rel.TargetUri.IsAbsoluteUri && rel.TargetUri.IsFile) Assert.AreEqual(urls[i].Replace("file:///", "").Replace("/", "\\"), rel.TargetUri.LocalPath); else // there should be a relationship for each URL Assert.AreEqual(urls[i], rel.TargetUri.ToString()); } } [Test] public void TestInvalidURLs() { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFCreationHelper CreateHelper = workbook.GetCreationHelper() as XSSFCreationHelper; String[] invalidURLs = { "http:\\apache.org", "www.apache .org", "c:\\temp", "\\poi"}; foreach (String s in invalidURLs) { try { CreateHelper.CreateHyperlink(HyperlinkType.Url).Address = (s); Assert.Fail("expected ArgumentException: " + s); } catch (ArgumentException) { } } } [Test] public void TestLoadSave() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("WithMoreVariousData.xlsx"); ICreationHelper CreateHelper = workbook.GetCreationHelper(); Assert.AreEqual(3, workbook.NumberOfSheets); XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0); // Check hyperlinks Assert.AreEqual(4, sheet.NumHyperlinks); doTestHyperlinkContents(sheet); // Write out, and check // Load up again, check all links still there XSSFWorkbook wb2 = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook); Assert.AreEqual(3, wb2.NumberOfSheets); Assert.IsNotNull(wb2.GetSheetAt(0)); Assert.IsNotNull(wb2.GetSheetAt(1)); Assert.IsNotNull(wb2.GetSheetAt(2)); sheet = (XSSFSheet)wb2.GetSheetAt(0); // Check hyperlinks again Assert.AreEqual(4, sheet.NumHyperlinks); doTestHyperlinkContents(sheet); // Add one more, and re-check IRow r17 = sheet.CreateRow(17); ICell r17c = r17.CreateCell(2); IHyperlink hyperlink = CreateHelper.CreateHyperlink(HyperlinkType.Url); hyperlink.Address = ("http://poi.apache.org/spreadsheet/"); hyperlink.Label = "POI SS Link"; r17c.Hyperlink=(hyperlink); Assert.AreEqual(5, sheet.NumHyperlinks); doTestHyperlinkContents(sheet); Assert.AreEqual(HyperlinkType.Url, sheet.GetRow(17).GetCell(2).Hyperlink.Type); Assert.AreEqual("POI SS Link", sheet.GetRow(17).GetCell(2).Hyperlink.Label); Assert.AreEqual("http://poi.apache.org/spreadsheet/", sheet.GetRow(17).GetCell(2).Hyperlink.Address); // Save and re-load once more XSSFWorkbook wb3 = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb2); Assert.AreEqual(3, wb3.NumberOfSheets); Assert.IsNotNull(wb3.GetSheetAt(0)); Assert.IsNotNull(wb3.GetSheetAt(1)); Assert.IsNotNull(wb3.GetSheetAt(2)); sheet = (XSSFSheet)wb3.GetSheetAt(0); Assert.AreEqual(5, sheet.NumHyperlinks); doTestHyperlinkContents(sheet); Assert.AreEqual(HyperlinkType.Url, sheet.GetRow(17).GetCell(2).Hyperlink.Type); Assert.AreEqual("POI SS Link", sheet.GetRow(17).GetCell(2).Hyperlink.Label); Assert.AreEqual("http://poi.apache.org/spreadsheet/", sheet.GetRow(17).GetCell(2).Hyperlink.Address); } /** * Only for WithMoreVariousData.xlsx ! */ private static void doTestHyperlinkContents(XSSFSheet sheet) { Assert.IsNotNull(sheet.GetRow(3).GetCell(2).Hyperlink); Assert.IsNotNull(sheet.GetRow(14).GetCell(2).Hyperlink); Assert.IsNotNull(sheet.GetRow(15).GetCell(2).Hyperlink); Assert.IsNotNull(sheet.GetRow(16).GetCell(2).Hyperlink); // First is a link to poi Assert.AreEqual(HyperlinkType.Url, sheet.GetRow(3).GetCell(2).Hyperlink.Type); Assert.AreEqual(null, sheet.GetRow(3).GetCell(2).Hyperlink.Label); Assert.AreEqual("http://poi.apache.org/", sheet.GetRow(3).GetCell(2).Hyperlink.Address); // Next is an internal doc link Assert.AreEqual(HyperlinkType.Document, sheet.GetRow(14).GetCell(2).Hyperlink.Type); Assert.AreEqual("Internal hyperlink to A2", sheet.GetRow(14).GetCell(2).Hyperlink.Label); Assert.AreEqual("Sheet1!A2", sheet.GetRow(14).GetCell(2).Hyperlink.Address); // Next is a file Assert.AreEqual(HyperlinkType.File, sheet.GetRow(15).GetCell(2).Hyperlink.Type); Assert.AreEqual(null, sheet.GetRow(15).GetCell(2).Hyperlink.Label); Assert.AreEqual("WithVariousData.xlsx", sheet.GetRow(15).GetCell(2).Hyperlink.Address); // Last is a mailto Assert.AreEqual(HyperlinkType.Email, sheet.GetRow(16).GetCell(2).Hyperlink.Type); Assert.AreEqual(null, sheet.GetRow(16).GetCell(2).Hyperlink.Label); Assert.AreEqual("mailto:dev@poi.apache.org?subject=XSSF Hyperlinks", sheet.GetRow(16).GetCell(2).Hyperlink.Address); } [Test] public void Test52716() { XSSFWorkbook wb1 = XSSFTestDataSamples.OpenSampleWorkbook("52716.xlsx"); XSSFSheet sh1 = wb1.GetSheetAt(0) as XSSFSheet; XSSFWorkbook wb2 = XSSFTestDataSamples.WriteOutAndReadBack(wb1) as XSSFWorkbook; XSSFSheet sh2 = wb2.GetSheetAt(0) as XSSFSheet; Assert.AreEqual(sh1.NumberOfComments, sh2.NumberOfComments); XSSFHyperlink l1 = sh1.GetHyperlink(0, 1); Assert.AreEqual(HyperlinkType.Document, l1.Type); Assert.AreEqual("B1", l1.GetCellRef()); Assert.AreEqual("Sort on Titel", l1.Tooltip); XSSFHyperlink l2 = sh2.GetHyperlink(0, 1); Assert.AreEqual(l1.Tooltip, l2.Tooltip); Assert.AreEqual(HyperlinkType.Document, l2.Type); Assert.AreEqual("B1", l2.GetCellRef()); } [Test] public void Test53734() { XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("53734.xlsx"); XSSFHyperlink link = wb.GetSheetAt(0).GetRow(0).GetCell(0).Hyperlink as XSSFHyperlink; Assert.AreEqual("javascript:///", link.Address); wb = XSSFTestDataSamples.WriteOutAndReadBack(wb) as XSSFWorkbook; link = wb.GetSheetAt(0).GetRow(0).GetCell(0).Hyperlink as XSSFHyperlink; Assert.AreEqual("javascript:///", link.Address); } [Test] [Ignore] public void Test53282() { //since limitation in .NET Uri class, it's impossible to accept uri like mailto:nobody@nowhere.uk%C2%A0 XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("53282.xlsx"); XSSFHyperlink link = wb.GetSheetAt(0).GetRow(0).GetCell(14).Hyperlink as XSSFHyperlink; Assert.AreEqual("mailto:nobody@nowhere.uk%C2%A0", link.Address); wb = XSSFTestDataSamples.WriteOutAndReadBack(wb) as XSSFWorkbook; link = wb.GetSheetAt(0).GetRow(0).GetCell(14).Hyperlink as XSSFHyperlink; Assert.AreEqual("mailto:nobody@nowhere.uk%C2%A0", link.Address); } } }
// // SignatureWriter.cs // // Author: // Jb Evain (jbevain@gmail.com) // // (C) 2005 - 2007 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. // namespace Mono.Cecil.Signatures { using System; using System.Text; using Mono.Cecil; using Mono.Cecil.Binary; using Mono.Cecil.Metadata; internal sealed class SignatureWriter : BaseSignatureVisitor { MetadataWriter m_mdWriter; MemoryBinaryWriter m_sigWriter; public SignatureWriter (MetadataWriter mdWriter) { m_mdWriter = mdWriter; m_sigWriter = new MemoryBinaryWriter (); } uint GetPointer () { return m_mdWriter.AddBlob (m_sigWriter.ToArray ()); } public uint AddMethodDefSig (MethodDefSig methSig) { return AddSignature (methSig); } public uint AddMethodRefSig (MethodRefSig methSig) { return AddSignature (methSig); } public uint AddPropertySig (PropertySig ps) { return AddSignature (ps); } public uint AddFieldSig (FieldSig fSig) { return AddSignature (fSig); } public uint AddLocalVarSig (LocalVarSig lvs) { return AddSignature (lvs); } uint AddSignature (Signature s) { m_sigWriter.Empty (); s.Accept (this); return GetPointer (); } public uint AddTypeSpec (TypeSpec ts) { m_sigWriter.Empty (); Write (ts); return GetPointer (); } public uint AddMethodSpec (MethodSpec ms) { m_sigWriter.Empty (); Write (ms); return GetPointer (); } public uint AddMarshalSig (MarshalSig ms) { m_sigWriter.Empty (); Write (ms); return GetPointer (); } public uint AddCustomAttribute (CustomAttrib ca, MethodReference ctor) { CompressCustomAttribute (ca, ctor, m_sigWriter); return GetPointer (); } public byte [] CompressCustomAttribute (CustomAttrib ca, MethodReference ctor) { MemoryBinaryWriter writer = new MemoryBinaryWriter (); CompressCustomAttribute (ca, ctor, writer); return writer.ToArray (); } public byte [] CompressFieldSig (FieldSig field) { m_sigWriter.Empty (); VisitFieldSig (field); return m_sigWriter.ToArray (); } public byte [] CompressLocalVar (LocalVarSig.LocalVariable var) { m_sigWriter.Empty (); Write (var); return m_sigWriter.ToArray (); } void CompressCustomAttribute (CustomAttrib ca, MethodReference ctor, MemoryBinaryWriter writer) { m_sigWriter.Empty (); Write (ca, ctor, writer); } public override void VisitMethodDefSig (MethodDefSig methodDef) { m_sigWriter.Write (methodDef.CallingConvention); if (methodDef.GenericParameterCount > 0) Write (methodDef.GenericParameterCount); Write (methodDef.ParamCount); Write (methodDef.RetType); Write (methodDef.Parameters, methodDef.Sentinel); } public override void VisitMethodRefSig (MethodRefSig methodRef) { m_sigWriter.Write (methodRef.CallingConvention); Write (methodRef.ParamCount); Write (methodRef.RetType); Write (methodRef.Parameters, methodRef.Sentinel); } public override void VisitFieldSig (FieldSig field) { m_sigWriter.Write (field.CallingConvention); Write (field.CustomMods); Write (field.Type); } public override void VisitPropertySig (PropertySig property) { m_sigWriter.Write (property.CallingConvention); Write (property.ParamCount); Write (property.CustomMods); Write (property.Type); Write (property.Parameters); } public override void VisitLocalVarSig (LocalVarSig localvar) { m_sigWriter.Write (localvar.CallingConvention); Write (localvar.Count); Write (localvar.LocalVariables); } void Write (LocalVarSig.LocalVariable [] vars) { foreach (LocalVarSig.LocalVariable var in vars) Write (var); } void Write (LocalVarSig.LocalVariable var) { Write (var.CustomMods); if ((var.Constraint & Constraint.Pinned) != 0) Write (ElementType.Pinned); if (var.ByRef) Write (ElementType.ByRef); Write (var.Type); } void Write (RetType retType) { Write (retType.CustomMods); if (retType.Void) Write (ElementType.Void); else if (retType.TypedByRef) Write (ElementType.TypedByRef); else if (retType.ByRef) { Write (ElementType.ByRef); Write (retType.Type); } else Write (retType.Type); } void Write (Param [] parameters, int sentinel) { for (int i = 0; i < parameters.Length; i++) { if (i == sentinel) Write (ElementType.Sentinel); Write (parameters [i]); } } void Write (Param [] parameters) { foreach (Param p in parameters) Write (p); } void Write (ElementType et) { Write ((int) et); } void Write (SigType t) { Write ((int) t.ElementType); switch (t.ElementType) { case ElementType.ValueType : Write ((int) Utilities.CompressMetadataToken ( CodedIndex.TypeDefOrRef, ((VALUETYPE) t).Type)); break; case ElementType.Class : Write ((int) Utilities.CompressMetadataToken ( CodedIndex.TypeDefOrRef, ((CLASS) t).Type)); break; case ElementType.Ptr : PTR p = (PTR) t; if (p.Void) Write (ElementType.Void); else { Write (p.CustomMods); Write (p.PtrType); } break; case ElementType.FnPtr : FNPTR fp = (FNPTR) t; if (fp.Method is MethodRefSig) (fp.Method as MethodRefSig).Accept (this); else (fp.Method as MethodDefSig).Accept (this); break; case ElementType.Array : ARRAY ary = (ARRAY) t; Write (ary.CustomMods); ArrayShape shape = ary.Shape; Write (ary.Type); Write (shape.Rank); Write (shape.NumSizes); foreach (int size in shape.Sizes) Write (size); Write (shape.NumLoBounds); foreach (int loBound in shape.LoBounds) Write (loBound); break; case ElementType.SzArray : SZARRAY sa = (SZARRAY) t; Write (sa.CustomMods); Write (sa.Type); break; case ElementType.Var : Write (((VAR) t).Index); break; case ElementType.MVar : Write (((MVAR) t).Index); break; case ElementType.GenericInst : GENERICINST gi = t as GENERICINST; Write (gi.ValueType ? ElementType.ValueType : ElementType.Class); Write ((int) Utilities.CompressMetadataToken ( CodedIndex.TypeDefOrRef, gi.Type)); Write (gi.Signature); break; } } void Write (TypeSpec ts) { Write (ts.CustomMods); Write (ts.Type); } void Write (MethodSpec ms) { Write (0x0a); Write (ms.Signature); } void Write (GenericInstSignature gis) { Write (gis.Arity); for (int i = 0; i < gis.Arity; i++) Write (gis.Types [i]); } void Write (GenericArg arg) { Write (arg.CustomMods); Write (arg.Type); } void Write (Param p) { Write (p.CustomMods); if (p.TypedByRef) Write (ElementType.TypedByRef); else if (p.ByRef) { Write (ElementType.ByRef); Write (p.Type); } else Write (p.Type); } void Write (CustomMod [] customMods) { foreach (CustomMod cm in customMods) Write (cm); } void Write (CustomMod cm) { switch (cm.CMOD) { case CustomMod.CMODType.OPT : Write (ElementType.CModOpt); break; case CustomMod.CMODType.REQD : Write (ElementType.CModReqD); break; } Write ((int) Utilities.CompressMetadataToken ( CodedIndex.TypeDefOrRef, cm.TypeDefOrRef)); } void Write (MarshalSig ms) { Write ((int) ms.NativeInstrinsic); switch (ms.NativeInstrinsic) { case NativeType.ARRAY : MarshalSig.Array ar = (MarshalSig.Array) ms.Spec; Write ((int) ar.ArrayElemType); if (ar.ParamNum != -1) Write (ar.ParamNum); if (ar.NumElem != -1) Write (ar.NumElem); if (ar.ElemMult != -1) Write (ar.ElemMult); break; case NativeType.CUSTOMMARSHALER : MarshalSig.CustomMarshaler cm = (MarshalSig.CustomMarshaler) ms.Spec; Write (cm.Guid); Write (cm.UnmanagedType); Write (cm.ManagedType); Write (cm.Cookie); break; case NativeType.FIXEDARRAY : MarshalSig.FixedArray fa = (MarshalSig.FixedArray) ms.Spec; Write (fa.NumElem); if (fa.ArrayElemType != NativeType.NONE) Write ((int) fa.ArrayElemType); break; case NativeType.SAFEARRAY : Write ((int) ((MarshalSig.SafeArray) ms.Spec).ArrayElemType); break; case NativeType.FIXEDSYSSTRING : Write (((MarshalSig.FixedSysString) ms.Spec).Size); break; } } void Write (CustomAttrib ca, MethodReference ctor, MemoryBinaryWriter writer) { if (ca == null) return; if (ca.Prolog != CustomAttrib.StdProlog) return; writer.Write (ca.Prolog); for (int i = 0; i < ctor.Parameters.Count; i++) Write (ca.FixedArgs [i], writer); writer.Write (ca.NumNamed); for (int i = 0; i < ca.NumNamed; i++) Write (ca.NamedArgs [i], writer); } void Write (CustomAttrib.FixedArg fa, MemoryBinaryWriter writer) { if (fa.SzArray) writer.Write (fa.NumElem); foreach (CustomAttrib.Elem elem in fa.Elems) Write (elem, writer); } void Write (CustomAttrib.NamedArg na, MemoryBinaryWriter writer) { if (na.Field) writer.Write ((byte) 0x53); else if (na.Property) writer.Write ((byte) 0x54); else throw new MetadataFormatException ("Unknown kind of namedarg"); if (na.FixedArg.SzArray) writer.Write ((byte) ElementType.SzArray); if (na.FieldOrPropType == ElementType.Object) writer.Write ((byte) ElementType.Boxed); else writer.Write ((byte) na.FieldOrPropType); if (na.FieldOrPropType == ElementType.Enum) Write (na.FixedArg.Elems [0].ElemType.FullName); Write (na.FieldOrPropName); Write (na.FixedArg, writer); } void Write (CustomAttrib.Elem elem, MemoryBinaryWriter writer) // TODO { if (elem.String) elem.FieldOrPropType = ElementType.String; else if (elem.Type) elem.FieldOrPropType = ElementType.Type; else if (elem.BoxedValueType) Write (elem.FieldOrPropType); switch (elem.FieldOrPropType) { case ElementType.Boolean : writer.Write ((byte) ((bool) elem.Value ? 1 : 0)); break; case ElementType.Char : writer.Write ((ushort) (char) elem.Value); break; case ElementType.R4 : writer.Write ((float) elem.Value); break; case ElementType.R8 : writer.Write ((double) elem.Value); break; case ElementType.I1 : writer.Write ((sbyte) elem.Value); break; case ElementType.I2 : writer.Write ((short) elem.Value); break; case ElementType.I4 : writer.Write ((int) elem.Value); break; case ElementType.I8 : writer.Write ((long) elem.Value); break; case ElementType.U1 : writer.Write ((byte) elem.Value); break; case ElementType.U2 : writer.Write ((ushort) elem.Value); break; case ElementType.U4 : writer.Write ((uint) elem.Value); break; case ElementType.U8 : writer.Write ((long) elem.Value); break; case ElementType.String : case ElementType.Type : string s = elem.Value as string; if (s == null) writer.Write ((byte) 0xff); else if (s.Length == 0) writer.Write ((byte) 0x00); else Write (s); break; case ElementType.Object : if (elem.Value != null) throw new NotSupportedException ("Unknown state"); writer.Write ((byte) 0xff); break; default : throw new NotImplementedException ("WriteElem " + elem.FieldOrPropType.ToString ()); } } void Write (string s) { byte [] str = Encoding.UTF8.GetBytes (s); Write (str.Length); m_sigWriter.Write (str); } void Write (int i) { Utilities.WriteCompressedInteger (m_sigWriter, i); } } }
#region Using directives using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Collections.Specialized; #endregion namespace System.Windows.Forms { // this renderer supports high contrast for ToolStripProfessional and ToolStripSystemRenderer. internal class ToolStripHighContrastRenderer : ToolStripSystemRenderer { private const int GRIP_PADDING = 4; BitVector32 options = new BitVector32(); private static readonly int optionsDottedBorder = BitVector32.CreateMask(); private static readonly int optionsDottedGrip = BitVector32.CreateMask(optionsDottedBorder); private static readonly int optionsFillWhenSelected = BitVector32.CreateMask(optionsDottedGrip); public ToolStripHighContrastRenderer(bool systemRenderMode) { options[optionsDottedBorder | optionsDottedGrip | optionsFillWhenSelected] = !systemRenderMode; } public bool DottedBorder { get { return options[optionsDottedBorder]; } } public bool DottedGrip { get { return options[optionsDottedGrip]; } } public bool FillWhenSelected{ get { return options[optionsFillWhenSelected]; } } // this is a renderer override, so return null so we dont get into an infinite loop. internal override ToolStripRenderer RendererOverride { get { return null; } } protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) { base.OnRenderArrow(e); } protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) { if (DottedGrip) { Graphics g = e.Graphics; Rectangle bounds = e.GripBounds; ToolStrip toolStrip = e.ToolStrip; int height = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Height : bounds.Width; int width = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Width : bounds.Height; int numRectangles = (height - (GRIP_PADDING * 2)) / 4; if (numRectangles > 0) { Rectangle[] shadowRects = new Rectangle[numRectangles]; int startY = GRIP_PADDING; int startX = (width / 2); for (int i = 0; i < numRectangles; i++) { shadowRects[i] = (toolStrip.Orientation == Orientation.Horizontal) ? new Rectangle(startX, startY, 2, 2) : new Rectangle(startY, startX, 2, 2); startY += 4; } g.FillRectangles(SystemBrushes.ControlLight, shadowRects); } } else { base.OnRenderGrip(e); } } protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) { if (FillWhenSelected) { RenderItemInternalFilled(e, false); } else { base.OnRenderDropDownButtonBackground(e); if (e.Item.Pressed) { e.Graphics.DrawRectangle(SystemPens.ButtonHighlight, new Rectangle(0, 0, e.Item.Width - 1, e.Item.Height - 1)); } } } protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { base.OnRenderItemCheck(e); } protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) { // do nothing } protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e) { base.OnRenderItemBackground(e); } protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) { ToolStripSplitButton item = e.Item as ToolStripSplitButton; Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); Graphics g = e.Graphics; if (item != null) { Rectangle dropDownRect = item.DropDownButtonBounds; if (item.Pressed) { g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } else if (item.Selected) { g.FillRectangle(SystemBrushes.Highlight, bounds); g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width-1, bounds.Height -1); g.DrawRectangle(SystemPens.ButtonHighlight, dropDownRect); } DrawArrow(new ToolStripArrowRenderEventArgs(g, item, dropDownRect, SystemColors.ControlText, ArrowDirection.Down)); } } protected override void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e) { base.OnRenderStatusStripSizingGrip(e); } protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) { if (FillWhenSelected) { RenderItemInternalFilled(e); } else { base.OnRenderLabelBackground(e); } } protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) { base.OnRenderMenuItemBackground(e); if (!e.Item.IsOnDropDown && e.Item.Pressed) { e.Graphics.DrawRectangle(SystemPens.ButtonHighlight, 0, 0, e.Item.Width - 1, e.Item.Height - 1); } } protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) { if (FillWhenSelected) { RenderItemInternalFilled(e, /*pressFill = */false); ToolStripItem item = e.Item; Graphics g = e.Graphics; Color arrowColor = item.Enabled ? SystemColors.ControlText : SystemColors.ControlDark; DrawArrow(new ToolStripArrowRenderEventArgs(g, item, new Rectangle(Point.Empty, item.Size), arrowColor, ArrowDirection.Down)); } else { base.OnRenderOverflowButtonBackground(e); } } protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { if (e.TextColor != SystemColors.HighlightText && e.TextColor != SystemColors.ControlText) { // we'll change the DefaultTextColor, if someone wants to change this,manually set the TextColor property. if (e.Item.Selected || e.Item.Pressed) { e.DefaultTextColor = SystemColors.HighlightText; } else { e.DefaultTextColor = SystemColors.ControlText; } } base.OnRenderItemText(e); } protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) { // do nothing. LOGO requirements ask us not to paint background effects behind } protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); Graphics g = e.Graphics; if (e.ToolStrip is ToolStripDropDown) { g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); if (!(e.ToolStrip is ToolStripOverflow)) { // make the neck connected. g.FillRectangle(SystemBrushes.Control, e.ConnectedArea); } } else if (e.ToolStrip is MenuStrip) { // do nothing } else if (e.ToolStrip is StatusStrip) { g.DrawRectangle(SystemPens.ButtonShadow, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } else { RenderToolStripBackgroundInternal(e); } } private void RenderToolStripBackgroundInternal(ToolStripRenderEventArgs e) { Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); Graphics g = e.Graphics; if (DottedBorder) { using (Pen p = new Pen(SystemColors.ButtonShadow)) { p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; bool oddWidth = ((bounds.Width & 0x1) == 0x1); bool oddHeight = ((bounds.Height & 0x1) == 0x1); int indent = 2; // top g.DrawLine(p, bounds.X + indent, bounds.Y, bounds.Width - 1, bounds.Y); // bottom g.DrawLine(p, bounds.X + indent, bounds.Height - 1, bounds.Width - 1, bounds.Height - 1); // left g.DrawLine(p, bounds.X, bounds.Y + indent, bounds.X, bounds.Height - 1); // right g.DrawLine(p, bounds.Width - 1, bounds.Y + indent, bounds.Width - 1, bounds.Height - 1); // connecting pixels // top left conntecting pixel - always drawn g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, 1, 1, 1)); if (oddWidth) { // top right pixel g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, 1, 1, 1)); } // bottom conntecting pixels - drawn only if height is odd if (oddHeight) { // bottom left g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, bounds.Height - 2, 1, 1)); } // top and bottom right conntecting pixel - drawn only if height and width are odd if (oddHeight && oddWidth) { // bottom right g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, bounds.Height - 2, 1, 1)); } } } else { // draw solid border bounds.Width -= 1; bounds.Height -= 1; g.DrawRectangle(SystemPens.ButtonShadow, bounds); } } protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) { Pen foreColorPen = SystemPens.ButtonShadow; Graphics g = e.Graphics; Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); if (e.Vertical) { if (bounds.Height >= 8) { bounds.Inflate(0, -4); // scoot down 4PX and start drawing } // Draw dark line int startX = bounds.Width / 2; g.DrawLine(foreColorPen, startX, bounds.Top, startX, bounds.Bottom - 1); } else { // // horizontal separator if (bounds.Width >= 4) { bounds.Inflate(-2, 0); // scoot over 2PX and start drawing } // Draw dark line int startY = bounds.Height / 2; g.DrawLine(foreColorPen, bounds.Left, startY, bounds.Right - 1, startY); } } // Indicates whether system is currently set to high contrast 'white on black' mode internal static bool IsHighContrastWhiteOnBlack() { return SystemColors.Control.ToArgb() == Color.Black.ToArgb(); } protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) { Image image = e.Image; if (image != null) { if (Image.GetPixelFormatSize(image.PixelFormat) > 16) { // for 24, 32 bit images, just paint normally - mapping the color table is not // going to work when you can have full color. base.OnRenderItemImage(e); return; } Graphics g = e.Graphics; ToolStripItem item = e.Item; Rectangle imageRect = e.ImageRectangle; using (ImageAttributes attrs = new ImageAttributes()) { if (IsHighContrastWhiteOnBlack() && !(FillWhenSelected && (e.Item.Pressed || e.Item.Selected))) { // translate white, black and blue to colors visible in high contrast mode. ColorMap cm1 = new ColorMap(); ColorMap cm2 = new ColorMap(); ColorMap cm3 = new ColorMap(); cm1.OldColor = Color.Black; cm1.NewColor = Color.White; cm2.OldColor = Color.White; cm2.NewColor = Color.Black; cm3.OldColor = Color.FromArgb(0, 0, 128); cm3.NewColor = Color.White; attrs.SetRemapTable(new ColorMap[] { cm1, cm2, cm3 }, ColorAdjustType.Bitmap); } if (item.ImageScaling == ToolStripItemImageScaling.None) { g.DrawImage(image, imageRect, 0, 0, imageRect.Width, imageRect.Height, GraphicsUnit.Pixel, attrs); } else { g.DrawImage(image, imageRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attrs); } } } } protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) { if (FillWhenSelected) { ToolStripButton button = e.Item as ToolStripButton; if (button != null && button.Checked) { Graphics g = e.Graphics; Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); if (button.CheckState == CheckState.Checked) { g.FillRectangle(SystemBrushes.Highlight, bounds); } g.DrawRectangle(SystemPens.ControlLight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } else { RenderItemInternalFilled(e); } } else { base.OnRenderButtonBackground(e); } } private void RenderItemInternalFilled(ToolStripItemRenderEventArgs e) { RenderItemInternalFilled(e, /*pressFill=*/true); } private void RenderItemInternalFilled(ToolStripItemRenderEventArgs e, bool pressFill) { Graphics g = e.Graphics; Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); if (e.Item.Pressed) { if (pressFill) { g.FillRectangle(SystemBrushes.Highlight, bounds); } else { g.DrawRectangle(SystemPens.ControlLight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } else if (e.Item.Selected) { g.FillRectangle(SystemBrushes.Highlight, bounds); g.DrawRectangle(SystemPens.ControlLight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Binary; using Apache.Ignite.Platform.Model; /// <summary> /// Java service proxy interface. /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] public interface IJavaService { /** */ bool isCancelled(); /** */ bool isInitialized(); /** */ bool isExecuted(); /** */ byte test(byte x); /** */ short test(short x); /** */ int test(int x); /** */ long test(long x); /** */ float test(float x); /** */ double test(double x); /** */ char test(char x); /** */ string test(string x); /** */ bool test(bool x); /** */ DateTime test(DateTime x); /** */ Guid test(Guid x); /** */ byte? testWrapper(byte? x); /** */ short? testWrapper(short? x); /** */ int? testWrapper(int? x); /** */ long? testWrapper(long? x); /** */ float? testWrapper(float? x); /** */ double? testWrapper(double? x); /** */ char? testWrapper(char? x); /** */ bool? testWrapper(bool? x); /** */ byte[] testArray(byte[] x); /** */ short[] testArray(short[] x); /** */ int[] testArray(int[] x); /** */ long[] testArray(long[] x); /** */ float[] testArray(float[] x); /** */ double[] testArray(double[] x); /** */ char[] testArray(char[] x); /** */ string[] testArray(string[] x); /** */ bool[] testArray(bool[] x); /** */ DateTime?[] testArray(DateTime?[] x); /** */ Guid?[] testArray(Guid?[] x); /** */ int test(int x, string y); /** */ int test(string x, int y); /** */ int? testNull(int? x); /** */ DateTime? testNullTimestamp(DateTime? x); /** */ Guid? testNullUUID(Guid? x); /** */ int testParams(params object[] args); /** */ ServicesTest.PlatformComputeBinarizable testBinarizable(ServicesTest.PlatformComputeBinarizable x); /** */ object[] testBinarizableArrayOfObjects(object[] x); /** */ IBinaryObject[] testBinaryObjectArray(IBinaryObject[] x); /** */ ServicesTest.PlatformComputeBinarizable[] testBinarizableArray(ServicesTest.PlatformComputeBinarizable[] x); /** */ ICollection testBinarizableCollection(ICollection x); /** */ IBinaryObject testBinaryObject(IBinaryObject x); /** */ Address testAddress(Address addr); /** */ int testOverload(int count, Employee[] emps); /** */ int testOverload(int first, int second); /** */ int testOverload(int count, Parameter[] param); /** */ Employee[] testEmployees(Employee[] emps); /** */ Account[] testAccounts(); /** */ User[] testUsers(); /** */ ICollection testDepartments(ICollection deps); /** */ IDictionary testMap(IDictionary<Key, Value> dict); /** */ void testDateArray(DateTime?[] dates); /** */ DateTime testDate(DateTime date); /** */ void testUTCDateFromCache(); /** */ void testLocalDateFromCache(); /** */ void testException(string exceptionClass); /** */ void sleep(long delayMs); } }
// StreamManipulator.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace GitHub.ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// This class allows us to retrieve a specified number of bits from /// the input buffer, as well as copy big byte blocks. /// /// It uses an int buffer to store up to 31 bits for direct /// manipulation. This guarantees that we can get at least 16 bits, /// but we only need at most 15, so this is all safe. /// /// There are some optimizations in this class, for example, you must /// never peek more than 8 bits more than needed, and you must first /// peek bits before you may drop them. This is not a general purpose /// class but optimized for the behaviour of the Inflater. /// /// authors of the original java version : John Leuner, Jochen Hoenicke /// </summary> public class StreamManipulator { #region Constructors /// <summary> /// Constructs a default StreamManipulator with all buffers empty /// </summary> public StreamManipulator() { } #endregion /// <summary> /// Get the next sequence of bits but don't increase input pointer. bitCount must be /// less or equal 16 and if this call succeeds, you must drop /// at least n - 8 bits in the next call. /// </summary> /// <param name="bitCount">The number of bits to peek.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. */ /// </returns> public int PeekBits(int bitCount) { if (bitsInBuffer_ < bitCount) { if (windowStart_ == windowEnd_) { return -1; // ok } buffer_ |= (uint)((window_[windowStart_++] & 0xff | (window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_); bitsInBuffer_ += 16; } return (int)(buffer_ & ((1 << bitCount) - 1)); } /// <summary> /// Drops the next n bits from the input. You should have called PeekBits /// with a bigger or equal n before, to make sure that enough bits are in /// the bit buffer. /// </summary> /// <param name="bitCount">The number of bits to drop.</param> public void DropBits(int bitCount) { buffer_ >>= bitCount; bitsInBuffer_ -= bitCount; } /// <summary> /// Gets the next n bits and increases input pointer. This is equivalent /// to <see cref="PeekBits"/> followed by <see cref="DropBits"/>, except for correct error handling. /// </summary> /// <param name="bitCount">The number of bits to retrieve.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. /// </returns> public int GetBits(int bitCount) { int bits = PeekBits(bitCount); if (bits >= 0) { DropBits(bitCount); } return bits; } /// <summary> /// Gets the number of bits available in the bit buffer. This must be /// only called when a previous PeekBits() returned -1. /// </summary> /// <returns> /// the number of bits available. /// </returns> public int AvailableBits { get { return bitsInBuffer_; } } /// <summary> /// Gets the number of bytes available. /// </summary> /// <returns> /// The number of bytes available. /// </returns> public int AvailableBytes { get { return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3); } } /// <summary> /// Skips to the next byte boundary. /// </summary> public void SkipToByteBoundary() { buffer_ >>= (bitsInBuffer_ & 7); bitsInBuffer_ &= ~7; } /// <summary> /// Returns true when SetInput can be called /// </summary> public bool IsNeedingInput { get { return windowStart_ == windowEnd_; } } /// <summary> /// Copies bytes from input buffer to output buffer starting /// at output[offset]. You have to make sure, that the buffer is /// byte aligned. If not enough bytes are available, copies fewer /// bytes. /// </summary> /// <param name="output"> /// The buffer to copy bytes to. /// </param> /// <param name="offset"> /// The offset in the buffer at which copying starts /// </param> /// <param name="length"> /// The length to copy, 0 is allowed. /// </param> /// <returns> /// The number of bytes copied, 0 if no bytes were available. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Length is less than zero /// </exception> /// <exception cref="InvalidOperationException"> /// Bit buffer isnt byte aligned /// </exception> public int CopyBytes(byte[] output, int offset, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } if ((bitsInBuffer_ & 7) != 0) { // bits_in_buffer may only be 0 or a multiple of 8 throw new InvalidOperationException("Bit buffer is not byte aligned!"); } int count = 0; while ((bitsInBuffer_ > 0) && (length > 0)) { output[offset++] = (byte) buffer_; buffer_ >>= 8; bitsInBuffer_ -= 8; length--; count++; } if (length == 0) { return count; } int avail = windowEnd_ - windowStart_; if (length > avail) { length = avail; } System.Array.Copy(window_, windowStart_, output, offset, length); windowStart_ += length; if (((windowStart_ - windowEnd_) & 1) != 0) { // We always want an even number of bytes in input, see peekBits buffer_ = (uint)(window_[windowStart_++] & 0xff); bitsInBuffer_ = 8; } return count + length; } /// <summary> /// Resets state and empties internal buffers /// </summary> public void Reset() { buffer_ = 0; windowStart_ = windowEnd_ = bitsInBuffer_ = 0; } /// <summary> /// Add more input for consumption. /// Only call when IsNeedingInput returns true /// </summary> /// <param name="buffer">data to be input</param> /// <param name="offset">offset of first byte of input</param> /// <param name="count">number of bytes of input to add.</param> public void SetInput(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if (windowStart_ < windowEnd_) { throw new InvalidOperationException("Old input was not completely processed"); } int end = offset + count; // We want to throw an ArrayIndexOutOfBoundsException early. // Note the check also handles integer wrap around. if ((offset > end) || (end > buffer.Length) ) { throw new ArgumentOutOfRangeException("count"); } if ((count & 1) != 0) { // We always want an even number of bytes in input, see PeekBits buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_); bitsInBuffer_ += 8; } window_ = buffer; windowStart_ = offset; windowEnd_ = end; } #region Instance Fields private byte[] window_; private int windowStart_; private int windowEnd_; private uint buffer_; private int bitsInBuffer_; #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.IO; using System.Xml; using System.Xml.Serialization; namespace Zelous { public partial class MainForm : Form, ISerializationClient { public static MainForm Instance = null; // Provides global access to the main form private WorldMap mWorldMap; // The map data (the "model" on which the mWorldMapView "views") private TileMapView mWorldMapView; // The main TileMapView for the world map (top panel) private TileMapView[] mTileSetViews; // Array of TileMapViews used for tile sets (bottom panel) private string mCurrMapFile = ""; private TileMapView.Brush mActiveBrush; private readonly CommandManager mCommandManager = new CommandManager(); private readonly GameEventFactory mGameEventFactory = new GameEventFactory(); private readonly GameTileSetGroupMgr mGameTileSetGroupMgr = new GameTileSetGroupMgr(); public struct ShellCommandArgs { public ShellCommandArgs(string cmd, string args) { mCmd = cmd; mArgs = args; } public string mCmd; public string mArgs; } // This build script will rebuild the NDS file with the updates files in nitrofiles directory (which includes the map files, for example) private ShellCommandArgs mBuildGameShellCommandArgs = new ShellCommandArgs(@"%NDSGAMEROOT%\Game\ZeldaDS\build.bat", @"build DEBUG"); // This commmand runs the emulator with the game private ShellCommandArgs mRunGameShellCommandArgs = new ShellCommandArgs(@"%NDSGAMEROOT%\Tools\desmume\desmume_dev.exe", @"%NDSGAMEROOT%\Game\ZeldaDS\ZeldaDS_d.nds"); private string mAppSettingsFilePath = Directory.GetCurrentDirectory() + @"\ZelousSettings.xml"; private SerializationMgr mAppSettingsMgr = new SerializationMgr(); // Properties public CommandManager CommandManager { get { return mCommandManager; } } public GameEventFactory GameEventFactory { get { return mGameEventFactory; } } public GameTileSetGroupMgr GameTileSetGroupMgr { get { return mGameTileSetGroupMgr; } } /////////////////////////////////////////////////////////////////////// // Settings /////////////////////////////////////////////////////////////////////// //@TODO: Move to MainForm.Settings.cs (along with ISerializationClient) public SerializationMgr AppSettingsMgr { get { return mAppSettingsMgr; } } [XmlRootAttribute(Namespace = "MainFormSettings")] public class Settings { public string mMapFile = ""; public ShellCommandArgs mBuildGameShellCommandArgs; public ShellCommandArgs mRunGameShellCommandArgs; public FormWindowState mWindowState; public Point mLocation; public Size mSize; public int mSplitterDistance; public int[] mTabPageIconIndices; } void ISerializationClient.OnSerialize(Serializer serializer, ref object saveData) { Settings settings = (Settings)saveData; serializer.Assign(ref settings.mMapFile, ref mCurrMapFile); serializer.Assign(ref settings.mBuildGameShellCommandArgs, ref mBuildGameShellCommandArgs); serializer.Assign(ref settings.mRunGameShellCommandArgs, ref mRunGameShellCommandArgs); serializer.AssignProperty(ref settings.mWindowState, "WindowState", this); // Don't allow minimized if (WindowState == FormWindowState.Minimized) { WindowState = FormWindowState.Normal; } // Saving or loading, we only care about location + size if we're normal if (WindowState == FormWindowState.Normal) { serializer.AssignProperty(ref settings.mLocation, "Location", this); serializer.AssignProperty(ref settings.mSize, "Size", this); } serializer.AssignProperty(ref settings.mSplitterDistance, "SplitterDistance", mSplitContainer); // Serialize the visibility icon on the tab controls. This is a bit more complicated // because the tab control doesn't natively support sending out a "image index changed" // event. if (serializer.IsSaving) { int[] iconIndices = mTabControl.GetTabPageIconIndices(); serializer.Assign(ref settings.mTabPageIconIndices, ref iconIndices); } else { int[] iconIndices = null; serializer.Assign(ref settings.mTabPageIconIndices, ref iconIndices); mTabControl.SetTabPageIconIndices(iconIndices); } if (serializer.IsLoading) { if (settings.mMapFile.Length > 0) { LoadMap(settings.mMapFile); } } } /////////////////////////////////////////////////////////////////////// // Implementation /////////////////////////////////////////////////////////////////////// public MainForm() { Instance = this; AppSettingsMgr.RegisterSerializable(this, typeof(Settings)); InitializeComponent(); // Initialize designer-controlled (static) components InitializeDynamicComponents(); // Initialize dynamically allocated components // Set KeyPreview to true to allow the form to process the key before the control with focus processes it (MainForm_KeyDown) this.KeyPreview = true; // Use to hook into windows messages the application level before they are processed //Application.AddMessageFilter(new AppMessageFilter()); mCommandManager.OnCommand += new CommandManager.CommandEventHandler(OnCommandManagerCommand); mTabControl.OnIconToggled += new IconToggleTabControl.IconToggledEventHandler(mTabControl_OnIconToggled); // Load game-specific data GameEventHelpers.LoadGameEventFactoryFromXml("GameEvents.xml", mGameEventFactory); mGameTileSetGroupMgr.LoadGameTileSetsFromXml("GameTileSetGroups.xml"); // Always start with a "new map", which initializes all controls NewMap(false); } public void InitializeDynamicComponents() { this.SuspendLayout(); mTabControl.SuspendLayout(); // Create world map view (top panel) mWorldMapView = CreateTileMapViewControl("mWorldMapView"); mWorldMapView.Init("World Map", WorldMap.NumLayers); mWorldMapView.OnBrushCreated += new TileMapView.BrushCreatedEventHandler(this.OnBrushCreated); mWorldMapView.OnBrushPasteRequested += new TileMapView.BrushPasteRequestedEventHandler(this.OnBrushPasteRequested); mSplitContainer.Panel1.Controls.Add(this.mWorldMapView); // Create and initialize the tile set views (bottom panel of tab pages) mTileSetViews = new TileMapView[WorldMap.NumLayers]; string[] tileSetViewTitles = new string[] { "Background", "Foreground", "Collision", "Characters", "Events" }; for (int i = 0; i < mTileSetViews.Length; ++i) { TileMapView tileMapView = null; TabPage tabPage = null; CreateTileSetView(i, out tileMapView, out tabPage); tileMapView.Init("", 1); // These contain exactly 1 layer tileMapView.ShowScreenGridOption = false; tileMapView.OnBrushCreated += new TileMapView.BrushCreatedEventHandler(this.OnBrushCreated); tabPage.Text = tileSetViewTitles[i]; // Set title on parent tab page (not on TileMapView) mTabControl.Controls.Add(tabPage); mTileSetViews[i] = tileMapView; } // Initialize the visibility icon on the tab pages from the world map view { bool[] renderableLayers = mWorldMapView.RenderableLayers; int[] iconIndices = new int[renderableLayers.Length]; for (int i = 0; i < renderableLayers.Length; ++i) { iconIndices[i] = renderableLayers[i] ? 1 : 0; } mTabControl.SetTabPageIconIndices(iconIndices); } mTabControl.ResumeLayout(); this.ResumeLayout(); } private static TileMapView CreateTileMapViewControl(string controlName) { TileMapView tileMapView = new TileMapView(); tileMapView.SuspendLayout(); tileMapView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; tileMapView.Dock = System.Windows.Forms.DockStyle.Fill; tileMapView.Name = controlName; tileMapView.TabIndex = 0; //tileMapView.Location = new System.Drawing.Point(3, 3); //tileMapView.Size = new System.Drawing.Size(667, 167); // Does this even matter? //tileMapView.Title = "TileMapView Title"; tileMapView.ResumeLayout(); return tileMapView; } private static TabPage CreateTabPageControl(string controlName) { TabPage tabPage = new TabPage(); tabPage.SuspendLayout(); tabPage.Name = controlName; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.TabIndex = 0; //@TODO: Can we set these when the rest are hard-coded via the designer? tabPage.UseVisualStyleBackColor = true; //tabPage.Location = new System.Drawing.Point(4, 23); //tabPage.Size = new System.Drawing.Size(673, 173); tabPage.ResumeLayout(); return tabPage; } // Creates a TileMapView for tile sets, and a parent TabPage private static void CreateTileSetView(int index, out TileMapView tileMapView, out TabPage tabPage) { tileMapView = CreateTileMapViewControl("mTileSetView" + index); tabPage = CreateTabPageControl("tabPage" + index); tabPage.Controls.Add(tileMapView); } // Used to reset a TileMapView used for viewing/selecting from a TileSet private static void ResetTileSetView(TileMapView tileMapView, TileSet tileSet) { // Reset tile set view - we create a layer that simply displays all the tiles // in the tile set (same dimensions) TileLayer tileSetLayer = new TileLayer(); tileSetLayer.Init(tileSet.NumTiles.X, tileSet.NumTiles.Y, tileSet); int value = 0; for (int y = 0; y < tileSetLayer.TileMap.GetLength(1); ++y) { for (int x = 0; x < tileSetLayer.TileMap.GetLength(0); ++x) { tileSetLayer.TileMap[x, y].Index = value++; } } tileMapView.Reset(new TileLayer[] { tileSetLayer }); } // Used to reset all the TileMapViews (for the main map view and the tile sets). // Eventually this function will take args telling it what tile sets we need to load (overworld, underworld, etc.) private void ResetTileMapViews() { for (int i = 0; i < mTileSetViews.Length; ++i) foreach (TileMapView view in mTileSetViews) { // Bind view to the tileset it represents ResetTileSetView(mTileSetViews[i], mWorldMap.TileLayers[i].TileSet); } mWorldMapView.Reset(mWorldMap.TileLayers); // Bind mWorldMapView to the data (layers) in mWorldMap } private void OnCommandManagerCommand(CommandManager sender, CommandAction action, Command command) { OnModifiedStateChanged(mCommandManager.IsModified()); } private void OnBrushCreated(TileMapView sender, TileMapView.BrushCreatedEventArgs e) { if (sender != mWorldMapView) { // Remap the brush's single layer to the layer it represents on the world map view Debug.Assert(e.Brush.Layers.Length == 1); e.Brush.Layers[0].LayerIndex = mTabControl.TabPages.IndexOf((TabPage)sender.Parent); } mActiveBrush = e.Brush; } private void OnBrushPasteRequested(TileMapView sender, TileMapView.BrushPasteRequestedEventArgs e) { Debug.Assert(sender == mWorldMapView); // Pasting only allowed on the world map view if (mActiveBrush == null) // No active brush selected, bail return; mCommandManager.DoCommand(new PasteBrushCommand(sender, e.TargetTilePos, mActiveBrush)); UpdateUndoRedoToolStripItems(); } private void OnModifiedStateChanged(bool isModified) { UpdateTitle(); // Update title to show asterisk if modified } private void UpdateTitle() { string title = Application.ProductName + " (v" + Application.ProductVersion + ")"; title += " - " + (mCurrMapFile.Length > 0? mCurrMapFile : "Untitled"); if (mCommandManager.IsModified()) { title += "*"; } this.Text = title; } private void SetCurrMap(string file) { mCurrMapFile = file; } // If the map needs saving, queries the user about it. Returns whether it's okay to continue (user saved, or map // was already saved). public bool QueryUserIfCurrentMapNeedsSaving(string action) { if (mCommandManager.IsModified()) { DialogResult result = MessageBox.Show(this, "The current map is not saved, are you sure you want to " + action + " without saving?", "Create New Map", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (result == DialogResult.No) { return false; } } return true; } public void NewMap(bool interactive) { int numScreensX = 20; int numScreensY = 10; int tileSetGroupIndex = 0; if (interactive) { NewMapDlg newMapDlg = new NewMapDlg(); DialogResult result = newMapDlg.ShowDialog(this); if (result == DialogResult.Cancel) { return; } numScreensX = newMapDlg.NumScreensX; numScreensY = newMapDlg.NumScreensY; tileSetGroupIndex = newMapDlg.TileSetGroupIndex; } mWorldMap = new WorldMap(); mWorldMap.NewMap(numScreensX, numScreensY, tileSetGroupIndex); ResetTileMapViews(); mWorldMapView.RedrawTileMap(); SetCurrMap(""); mCommandManager.OnNewMap(); UpdateUndoRedoToolStripItems(); GC.Collect(); // Good time to clean up any references left behind } private void LoadMap(string fileName) { //@TODO: Check if file exists, if it doesn't we should return false. Calling code should handle this. mWorldMap = new WorldMap(); mWorldMap.LoadMap(fileName); ResetTileMapViews(); mWorldMapView.RedrawTileMap(); SetCurrMap(fileName); mCommandManager.OnLoadMap(); UpdateUndoRedoToolStripItems(); GC.Collect(); // Good time to clean up any references left behind } private void SaveCurrMap(bool forceSave) { Debug.Assert(mCurrMapFile.Length > 0); // No need to save unless we're modified if (forceSave || mCommandManager.IsModified()) { mWorldMap.SaveMap(mCurrMapFile); mCommandManager.OnSaveMap(); } else { //@TODO: DEBUG ONLY, save the map to a temporary file, and compare it to the actual file, // making sure they are exactly the same. If they are not, there's something wrong with // how we track the modified state of a file. } } bool AttemptSaveCurrMap(bool forceSaveAs) { if (!forceSaveAs && mCurrMapFile.Length > 0) { SaveCurrMap(false); return true; } else { using (SaveFileDialog fileDlg = new SaveFileDialog()) { fileDlg.Filter = "map files (*.map)|*.map"; fileDlg.FileName = mCurrMapFile; //fileDlg.InitialDirectory = Environment.CurrentDirectory; DialogResult dlgRes = fileDlg.ShowDialog(this); if (dlgRes == DialogResult.OK) { SetCurrMap(fileDlg.FileName); SaveCurrMap(true); // Force save, even if file is not modified return true; } } } return false; } //@TODO: make this private again! public void UpdateUndoRedoToolStripItems() { undoToolStripMenuItem.Enabled = mCommandManager.NumUndoCommands > 0; redoToolStripMenuItem.Enabled = mCommandManager.NumRedoCommands > 0; undoToolStripMenuItem.Text = undoToolStripMenuItem.Enabled? "&Undo " + mCommandManager.GetLastUndoCommand().GetDescription() : "&Undo"; redoToolStripMenuItem.Text = redoToolStripMenuItem.Enabled? "&Redo " + mCommandManager.GetLastRedoCommand().GetDescription() : "&Redo"; } /////////////////////////////////////////////////////////////////////// // Control Events /////////////////////////////////////////////////////////////////////// private void MainForm_Load(object sender, EventArgs e) { // We load our settings here, right before the MainForm is displayed, so that // all controls are created and positioned, and can have their values modified. AppSettingsMgr.Load(mAppSettingsFilePath); } private void MainForm_KeyDown(object sender, KeyEventArgs e) { // Control + [Shift + ] Tab switches tile set tab if (e.Control && e.KeyCode == Keys.Tab) { ControlHelpers.TabControl_SelectAdjacentTab(mTabControl, !e.Shift); e.SuppressKeyPress = true; } // <Number> selects a tab, Alt + <Number> toggles visibility on that tab if (Char.IsNumber((char)e.KeyValue) && !(e.Control || e.Shift)) { int numberPressed = e.KeyValue - (int)Keys.D0; // For the user, the layer number is 1-based if (numberPressed >= 1 && numberPressed <= mTileSetViews.Length) { int layer = numberPressed - 1; // For the user, the layer number is 1-based if (layer < mTileSetViews.Length) { if (e.Alt) { mTabControl.ToggleTabPageIconIndex(layer); } else { mTabControl.SelectedIndex = layer; } e.SuppressKeyPress = true; } } } // V toggles visibiliy of current tab if (e.KeyCode == Keys.V) { mTabControl.ToggleTabPageIconIndex(mTabControl.SelectedIndex); e.SuppressKeyPress = true; } // Give TileMapViews a chance to handle global key presses without requiring focus //@TODO: Iterate all TileMapViews here, and if e.Handled is true after call, break the loop mWorldMapView.OnGlobalKeyDown(e); } private void MainForm_KeyUp(object sender, KeyEventArgs e) { //@TODO: Iterate all TileMapViews here, and if e.Handled is true after call, break the loop mWorldMapView.OnGlobalKeyUp(e); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (!QueryUserIfCurrentMapNeedsSaving("exit " + Application.ProductName)) { e.Cancel = true; return; } AppSettingsMgr.Save(mAppSettingsFilePath); } private void mTabControl_OnIconToggled(IconToggleTabControl sender, IconToggleTabControl.IconToggledEventArgs e) { bool layerVisible = e.IconIndex != 0; mWorldMapView.RenderableLayers[e.TabPageIndex] = layerVisible; // What you see is what you select mWorldMapView.SelectableLayers[e.TabPageIndex] = layerVisible; mWorldMapView.RedrawTileMap(); } /////////////////////////////////////////////////////////////////////// // Menu Events /////////////////////////////////////////////////////////////////////// // New private void newToolStripMenuItem_Click(object sender, EventArgs e) { if (!QueryUserIfCurrentMapNeedsSaving("create a new map")) { return; } NewMap(true); } // Save private void saveMapToolStripMenuItem_Click(object sender, EventArgs e) { AttemptSaveCurrMap(false); } // Save As private void saveMapAsToolStripMenuItem_Click(object sender, EventArgs e) { AttemptSaveCurrMap(true); } // Open private void openMapToolStripMenuItem_Click(object sender, EventArgs e) { if (!QueryUserIfCurrentMapNeedsSaving("open another map")) { return; } using (OpenFileDialog fileDlg = new OpenFileDialog()) { fileDlg.Filter = "map files (*.map)|*.map"; //fileDlg.InitialDirectory = Environment.CurrentDirectory; DialogResult dlgRes = fileDlg.ShowDialog(this); if (dlgRes == DialogResult.OK) { LoadMap(fileDlg.FileName); } } } // Save, Build & Run Map private void buildAndTestMapToolStripMenuItem_Click(object sender, EventArgs e) { if (!AttemptSaveCurrMap(false)) { return; } ProcessHelpers.RunCommand(mBuildGameShellCommandArgs.mCmd, mBuildGameShellCommandArgs.mArgs); ProcessHelpers.RunCommand(mRunGameShellCommandArgs.mCmd, mRunGameShellCommandArgs.mArgs); } // Exit private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); // Eventually calls MainForm_FormClosing() } // Undo private void undoToolStripMenuItem_Click(object sender, EventArgs e) { mCommandManager.UndoCommand(); UpdateUndoRedoToolStripItems(); mWorldMapView.Refresh(); } // Redo private void redoToolStripMenuItem_Click(object sender, EventArgs e) { mCommandManager.RedoCommand(); UpdateUndoRedoToolStripItems(); mWorldMapView.Refresh(); } // About private void aboutZelousToolStripMenuItem_Click(object sender, EventArgs e) { using (AboutBox aboutBox = new AboutBox()) { aboutBox.ShowDialog(this); } } } public class AppMessageFilter : IMessageFilter { public bool PreFilterMessage(ref Message m) { bool blockMessage = false; return blockMessage; } } //@TODO: Move into own file public class ControlHelpers { public static void TabControl_SelectAdjacentTab(TabControl tabControl, bool nextTab) { int tabCount = tabControl.TabCount; if (tabCount <= 1) { return; } if (nextTab) { tabControl.SelectedIndex = ++tabControl.SelectedIndex % tabCount; } else // Previous tab { int tabIndex = --tabControl.SelectedIndex; tabControl.SelectedIndex = tabIndex >= 0? tabIndex : tabCount - 1; } } } //@TODO: Move into own file public class GraphicsHelpers { public static void PrepareGraphics(Graphics gfx) { gfx.InterpolationMode = InterpolationMode.NearestNeighbor; gfx.SmoothingMode = SmoothingMode.None; gfx.PixelOffsetMode = PixelOffsetMode.Half; // Required for scaling to work gfx.PageUnit = GraphicsUnit.Pixel; } } //@TODO: Move into own file public class ProcessHelpers { public static void RunCommand(string cmd, string args) { cmd = Environment.ExpandEnvironmentVariables(cmd); cmd = Path.GetFullPath(cmd); args = Environment.ExpandEnvironmentVariables(args); string path = System.IO.Path.GetDirectoryName(cmd); ProcessStartInfo psi = new ProcessStartInfo(cmd); psi.Arguments = args; psi.WindowStyle = ProcessWindowStyle.Hidden; psi.UseShellExecute = false; psi.WorkingDirectory = path; Process proc = Process.Start(psi); // While waiting for the process to exit, show the wait cursor MainForm.Instance.UseWaitCursor = true; while (!proc.WaitForExit(10)) { Application.DoEvents(); // Required for the wait cursor to actually display and animate } MainForm.Instance.UseWaitCursor = false; //@TODO: When user exits process, the cursor will remain in waiting state until // it's moved, for some reason. Investigate this. } } //@TODO: Move into own file public class ArrayHelpers { public static void CopyArray2d<T>(T[,] srcTileMap, Rectangle srcRect, ref T[,] dstTileMap, Point dstPos) { for (int x = 0; x < srcRect.Width; ++x) { for (int y = 0; y < srcRect.Height; ++y) { dstTileMap[dstPos.X + x, dstPos.Y + y] = srcTileMap[srcRect.X + x, srcRect.Y + y]; } } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Reflection; using System.Resources; using System.Threading; using System.Windows.Forms; using Alchemi.Core; using Alchemi.Core.Owner; using log4net; using log4net.Config; using AlchemiRenderer; // Configure log4net using the .config file [assembly: XmlConfigurator(Watch=true)] namespace Alchemi.Examples.Renderer { /// <summary> /// Summary description for RendererForm. /// </summary> public class RendererForm : Form { private Button render; private Label label1; private Label label2; private Label label3; private Label label4; private int imageWidth = 0; private int imageHeight = 0; private int columns = 0; private int rows = 0; private int segmentWidth = 0; private int segmentHeight = 0; private GApplication ga = null; private bool initted = false; private Bitmap composite = null; private String modelPath = ""; private String[] paths = null; private bool drawnFirstSegment = false; private ComboBox widthCombo; private ComboBox heightCombo; private NumericUpDown columnsUpDown; private NumericUpDown rowsUpDown; private Label label5; private ComboBox modelCombo; private Button stop; // Create a logger for use in this class private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ProgressBar pbar; private Label lbProgress; private string basepath = "%POVRAY_HOME%"; private MenuStrip menuStrip1; private ToolStripMenuItem toolStripMenuItem1; private ToolStripMenuItem optionsToolStripMenuItem; private ToolStripMenuItem exitToolStripMenuItem; private object threadCompleteLock = new object(); private CheckBox stretchCheckBox; private Image busyGif; private EventHandler busyHandler; private Panel panel1; private PictureBox pictureBox1; /// <summary> /// Required designer variable. /// </summary> private Container components = null; public RendererForm() { // // Required for Windows Form Designer support // InitializeComponent(); Logger.LogHandler += new LogEventHandler(LogHandler); } private void LogHandler(object sender, LogEventArgs e) { switch (e.Level) { case LogLevel.Debug: string message = e.Source + ":" + e.Member + " - " + e.Message; logger.Debug(message,e.Exception); break; case LogLevel.Info: logger.Info(e.Message); break; case LogLevel.Error: logger.Error(e.Message,e.Exception); break; case LogLevel.Warn: logger.Warn(e.Message, e.Exception); break; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RendererForm)); this.render = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.widthCombo = new System.Windows.Forms.ComboBox(); this.heightCombo = new System.Windows.Forms.ComboBox(); this.columnsUpDown = new System.Windows.Forms.NumericUpDown(); this.rowsUpDown = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.modelCombo = new System.Windows.Forms.ComboBox(); this.stop = new System.Windows.Forms.Button(); this.pbar = new System.Windows.Forms.ProgressBar(); this.lbProgress = new System.Windows.Forms.Label(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.stretchCheckBox = new System.Windows.Forms.CheckBox(); this.panel1 = new System.Windows.Forms.Panel(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.columnsUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.rowsUpDown)).BeginInit(); this.menuStrip1.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // render // this.render.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.render.Location = new System.Drawing.Point(513, 560); this.render.Name = "render"; this.render.Size = new System.Drawing.Size(100, 30); this.render.TabIndex = 5; this.render.Text = "render"; this.render.Click += new System.EventHandler(this.render_Click); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(8, 569); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(32, 13); this.label1.TabIndex = 6; this.label1.Text = "width"; this.label1.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(8, 599); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(36, 13); this.label2.TabIndex = 7; this.label2.Text = "height"; this.label2.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label3 // this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(143, 569); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(46, 13); this.label3.TabIndex = 8; this.label3.Text = "columns"; this.label3.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label4 // this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(160, 599); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(29, 13); this.label4.TabIndex = 9; this.label4.Text = "rows"; this.label4.TextAlign = System.Drawing.ContentAlignment.TopRight; // // widthCombo // this.widthCombo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.widthCombo.Location = new System.Drawing.Point(57, 566); this.widthCombo.Name = "widthCombo"; this.widthCombo.Size = new System.Drawing.Size(80, 21); this.widthCombo.TabIndex = 10; this.widthCombo.Text = "width"; // // heightCombo // this.heightCombo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.heightCombo.Location = new System.Drawing.Point(57, 596); this.heightCombo.Name = "heightCombo"; this.heightCombo.Size = new System.Drawing.Size(80, 21); this.heightCombo.TabIndex = 11; this.heightCombo.Text = "height"; // // columnsUpDown // this.columnsUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.columnsUpDown.Location = new System.Drawing.Point(195, 567); this.columnsUpDown.Name = "columnsUpDown"; this.columnsUpDown.Size = new System.Drawing.Size(56, 20); this.columnsUpDown.TabIndex = 12; // // rowsUpDown // this.rowsUpDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.rowsUpDown.Location = new System.Drawing.Point(195, 597); this.rowsUpDown.Name = "rowsUpDown"; this.rowsUpDown.Size = new System.Drawing.Size(56, 20); this.rowsUpDown.TabIndex = 13; // // label5 // this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(279, 569); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(35, 13); this.label5.TabIndex = 14; this.label5.Text = "model"; // // modelCombo // this.modelCombo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.modelCombo.Location = new System.Drawing.Point(320, 566); this.modelCombo.Name = "modelCombo"; this.modelCombo.Size = new System.Drawing.Size(177, 21); this.modelCombo.TabIndex = 15; // // stop // this.stop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.stop.Enabled = false; this.stop.Location = new System.Drawing.Point(513, 598); this.stop.Name = "stop"; this.stop.Size = new System.Drawing.Size(100, 30); this.stop.TabIndex = 16; this.stop.Text = "stop"; this.stop.Click += new System.EventHandler(this.stop_Click); // // pbar // this.pbar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pbar.Location = new System.Drawing.Point(4, 537); this.pbar.Name = "pbar"; this.pbar.Size = new System.Drawing.Size(614, 12); this.pbar.Style = System.Windows.Forms.ProgressBarStyle.Continuous; this.pbar.TabIndex = 19; // // lbProgress // this.lbProgress.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.lbProgress.AutoSize = true; this.lbProgress.Location = new System.Drawing.Point(6, 519); this.lbProgress.Name = "lbProgress"; this.lbProgress.Size = new System.Drawing.Size(79, 13); this.lbProgress.TabIndex = 20; this.lbProgress.Text = "Not Rendering."; this.lbProgress.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem1}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(624, 24); this.menuStrip1.TabIndex = 21; this.menuStrip1.Text = "menuStrip1"; // // toolStripMenuItem1 // this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.optionsToolStripMenuItem, this.exitToolStripMenuItem}); this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(35, 20); this.toolStripMenuItem1.Text = "&File"; // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(123, 22); this.optionsToolStripMenuItem.Text = "&Options..."; this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(123, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // stretchCheckBox // this.stretchCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.stretchCheckBox.AutoSize = true; this.stretchCheckBox.Location = new System.Drawing.Point(282, 596); this.stretchCheckBox.Name = "stretchCheckBox"; this.stretchCheckBox.Size = new System.Drawing.Size(89, 17); this.stretchCheckBox.TabIndex = 18; this.stretchCheckBox.Text = "stretch image"; this.stretchCheckBox.Visible = false; this.stretchCheckBox.CheckedChanged += new System.EventHandler(this.stretchCheckBox_CheckedChanged); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.AutoScroll = true; this.panel1.AutoScrollMargin = new System.Drawing.Size(2, 2); this.panel1.AutoScrollMinSize = new System.Drawing.Size(512, 480); this.panel1.BackColor = System.Drawing.Color.Black; this.panel1.Controls.Add(this.pictureBox1); this.panel1.Location = new System.Drawing.Point(4, 27); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(616, 488); this.panel1.TabIndex = 22; this.panel1.Resize += new System.EventHandler(this.panel1_Resize); // // pictureBox1 // this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pictureBox1.BackColor = System.Drawing.Color.Black; this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(127, 69); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(382, 289); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.pictureBox1.TabIndex = 2; this.pictureBox1.TabStop = false; // // RendererForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.AutoScrollMargin = new System.Drawing.Size(4, 4); this.ClientSize = new System.Drawing.Size(624, 635); this.Controls.Add(this.panel1); this.Controls.Add(this.lbProgress); this.Controls.Add(this.pbar); this.Controls.Add(this.stretchCheckBox); this.Controls.Add(this.stop); this.Controls.Add(this.modelCombo); this.Controls.Add(this.label5); this.Controls.Add(this.rowsUpDown); this.Controls.Add(this.columnsUpDown); this.Controls.Add(this.heightCombo); this.Controls.Add(this.widthCombo); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.render); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.MinimumSize = new System.Drawing.Size(632, 662); this.Name = "RendererForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Alchemi Renderer"; this.Closing += new System.ComponentModel.CancelEventHandler(this.RendererForm_Closing); this.Load += new System.EventHandler(this.RenderForm_Load); ((System.ComponentModel.ISupportInitialize)(this.columnsUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.rowsUpDown)).EndInit(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void RenderForm_Load(object sender, EventArgs e) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(DefaultErrorHandler); //for windows forms apps unhandled exceptions on the main thread Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); widthCombo.Items.AddRange(new object[] {"100", "160", "200", "240", "320", "480", "512", "600", "640", "800", "1024", "1280"}); heightCombo.Items.AddRange(new object[] {"100", "120", "200", "240", "320", "384", "480", "600", "640", "768", "800", "1024"}); widthCombo.SelectedIndex = 9; heightCombo.SelectedIndex = 8; columnsUpDown.Value = 6; columnsUpDown.Maximum = 100; columnsUpDown.Minimum = 1; rowsUpDown.Value = 5; rowsUpDown.Maximum = 100; rowsUpDown.Minimum = 1; busyGif = Image.FromFile("status_anim.gif"); busyHandler = new EventHandler(this.OnFrameChanged); paths = new String[] {basepath+"/scenes/advanced/chess2.pov +L"+basepath+"/include", basepath+"/scenes/advanced/isocacti.pov +L"+basepath+"/include", basepath+"/scenes/advanced/glasschess/glasschess.pov +L"+basepath+"/scenes/advanced/glasschess/", basepath+"/scenes/advanced/biscuit.pov +L"+basepath+"/include", basepath+"/scenes/advanced/landscape.pov +L"+basepath+"/include", basepath+"/scenes/advanced/mediasky.pov +L"+basepath+"/include", basepath+"/scenes/advanced/abyss.pov +L"+basepath+"/include", basepath+"/scenes/advanced/wineglass.pov +L"+basepath+"/include", basepath+"/scenes/advanced/skyvase.pov +L"+basepath+"/include", basepath+"/scenes/advanced/newdiffract.pov +L"+basepath+"/include", basepath+"/scenes/advanced/quilt1.pov +L"+basepath+"/include"//, //basepath+"/scenes/advanced/fish13/fish13.pov +L"+basepath+"scenes/advanced/fish13/" }; modelCombo.Items.AddRange(new object[] {"chess", "cacti", "glass chess", "biscuits", "landscape", "mediasky", "abyss", "wineglass", "skyvase", "diffract", "ball"//, //"fish" } ); modelCombo.SelectedIndex = 5; } private void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { HandleAllUnknownErrors(sender.ToString(),e.Exception); } private void DefaultErrorHandler(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception) args.ExceptionObject; HandleAllUnknownErrors(sender.ToString(),e); } private void HandleAllUnknownErrors(string sender, Exception e) { logger.Error("Unknown Error from: " + sender,e); MessageBox.Show(e.ToString(), "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void showSplash() { ResourceManager resources = new ResourceManager(typeof(RendererForm)); pictureBox1.Image = (Image)(resources.GetObject("pictureBox1.Image")); } private void clearImage() { if (imageWidth > 0 && imageHeight > 0) { composite = new Bitmap(imageWidth,imageHeight); pictureBox1.Image = composite; } } private void displayImage(Bitmap segment, int col, int row) { if (!drawnFirstSegment) { clearImage(); drawnFirstSegment = true; //auto-size picture box to image size. //if it is bigger pictureBox1.Size = new Size(imageWidth, imageHeight); panel1.AutoScrollMinSize = new Size(imageWidth, imageHeight); } Graphics g = Graphics.FromImage(composite); Rectangle sourceRectangle; Rectangle destRectangle; int x = 0; int y = 0; x = (col-1)*segmentWidth; y = (row-1)*segmentHeight; logger.Debug("Displaying segment c, r: "+col+", "+row); try { sourceRectangle = new Rectangle(0, 0, segment.Width, segment.Height); destRectangle = new Rectangle(x, y, segment.Width, segment.Height); g.DrawImage(segment, destRectangle, sourceRectangle, GraphicsUnit.Pixel); } catch (Exception e) { logger.Debug("!!!ERROR:\n"+e.StackTrace); } pictureBox1.Image = composite; } private void printStdFiles(RenderThread thread) { try { logger.Info("Output : " + thread.Stdout); logger.Info("Error : " + thread.Stderr); } catch (Exception ex) { logger.Error("Error getting stdfiles from thread", ex); } } private void unpackThread(GThread thread) { RenderThread rth = (RenderThread)thread; if (rth!=null) { Bitmap bit = rth.RenderedImageSegment; if (bit!=null) { logger.Debug("Loading from bitmap"); displayImage(bit, rth.Col, rth.Row); } else { logger.Debug ("bit is null! " + thread.Id ); } } } private void UpdateStatus() { if (pbar.Value==pbar.Maximum) { lbProgress.Text = string.Format("All {0} threads completed.",pbar.Maximum); } else if (pbar.Value < pbar.Maximum) { pbar.Increment(1); lbProgress.Text = string.Format("Thread {0} of {1} completed.",pbar.Value, pbar.Maximum); } } private void StopApp() { try { if (ga != null && ga.Running) { ga.Stop(); logger.Debug("Application stopped."); } else { if (ga == null) { logger.Debug("ga is null"); } else { logger.Debug("ga running returned false..."); } } stop.Enabled = false; render.Enabled = !stop.Enabled; } catch (Exception ex) { MessageBox.Show("Error stopping application: "+ex.Message); } } #region BusyGIFAnimation private void ShowBusyGif() { pictureBox1.Image = busyGif; ImageAnimator.Animate(busyGif, busyHandler); } //private void StopBusyGif() //{ // ImageAnimator.StopAnimate(busyGif, busyHandler); //} private void OnFrameChanged(object sender, EventArgs e) { pictureBox1.Invalidate(); } protected override void OnPaint(PaintEventArgs e) { if (!drawnFirstSegment) { //Get the next frame ready for rendering. ImageAnimator.UpdateFrames(); //Draw the next frame in the animation. //pictureBox1.Image = busyGif; //Graphics g = pictureBox1.CreateGraphics(); //g.DrawImage(busyGif, ); } } #endregion #region Alchemi Grid Events private void ga_ThreadFinish(GThread thread) { //to prevent multiple events from over-writing each other lock (threadCompleteLock) { logger.Debug("Thread finished: " + thread.Id); UpdateStatus(); unpackThread(thread); printStdFiles(thread as RenderThread); } } private void ga_ThreadFailed(GThread thread, Exception e) { //to prevent multiple events from over-writing each other lock (threadCompleteLock) { logger.Debug("Thread failed: " + thread.Id + "\n" + e.ToString()); UpdateStatus(); printStdFiles(thread as RenderThread); } } private void ga_ApplicationFinish() { //initted = false; UpdateStatus(); logger.Debug("Application Finished"); //displayImages(); MessageBox.Show("Rendering Finished"); //displayImages(); stop.Enabled = false; render.Enabled = !stop.Enabled; } #endregion #region Form Events private void render_Click(object sender, EventArgs e) { stop.Enabled = true; render.Enabled = !stop.Enabled; drawnFirstSegment = false; showSplash(); // model path modelPath = paths[modelCombo.SelectedIndex]; // get width and height from combo box imageWidth = Int32.Parse(widthCombo.SelectedItem.ToString()); imageHeight = Int32.Parse(heightCombo.SelectedItem.ToString()); // get cols and rows from up downs columns = Decimal.ToInt32(columnsUpDown.Value); rows = Decimal.ToInt32(rowsUpDown.Value); segmentWidth = imageWidth/columns; segmentHeight = imageHeight/rows; int x = 0; int y = 0; logger.Debug("WIDTH:"+imageWidth); logger.Debug("HEIGHT:"+imageHeight); logger.Debug("COLUMNS:"+columns); logger.Debug("ROWS:"+rows); logger.Debug(""+modelPath); // reset the display clearImage(); if (!initted) { GConnectionDialog gcd = new GConnectionDialog(); gcd.ShowDialog(); ga = new GApplication(true); ga.ApplicationName = "Alchemi POV-Ray Renderer - Alchemi sample"; ga.Connection = gcd.Connection; ga.ThreadFinish += new GThreadFinish(ga_ThreadFinish); ga.ThreadFailed += new GThreadFailed(ga_ThreadFailed); ga.ApplicationFinish += new GApplicationFinish(ga_ApplicationFinish); ga.Manifest.Add(new ModuleDependency(typeof(RenderThread).Module)); initted = true; } if (ga!=null && ga.Running) { ga.Stop(); } pbar.Maximum = columns*rows; pbar.Minimum = 0; pbar.Value = 0; lbProgress.Text = "Starting to render image ... "; for (int col=0; col<columns; col++) { for (int row=0; row<rows; row++) { x = col*segmentWidth; y = row*segmentHeight; int startRowPixel = y + 1; int endRowPixel = y + segmentHeight; int startColPixel = x + 1; int endColPixel = x + segmentWidth; RenderThread rth = new RenderThread(modelPath, imageWidth, imageHeight, segmentWidth, segmentHeight, startRowPixel, endRowPixel, startColPixel, endColPixel, ""); rth.BasePath = this.basepath; rth.Col = col+1; rth.Row = row+1; ga.Threads.Add(rth); } } try { ga.Start(); } catch (Exception ex) { Console.WriteLine(""+ex.StackTrace); MessageBox.Show("Alchemi Rendering Failed!"+ex.ToString()); } lbProgress.Text = "Rendering image ... "; ShowBusyGif(); } private void stop_Click(object sender, EventArgs e) { StopApp(); } private void stretchCheckBox_CheckedChanged(object sender, EventArgs e) { if (stretchCheckBox.Checked) { pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; } else { pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage; } } private void RendererForm_Closing(object sender, CancelEventArgs e) { StopApp(); } private void optionsToolStripMenuItem_Click(object sender, EventArgs e) { Options opt = new Options(); opt.txPath.Text = basepath; opt.ShowDialog(this); basepath = opt.txPath.Text; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { StopApp(); this.Close(); } private void panel1_Resize(object sender, EventArgs e) { //set the pic box to the middle of the panel. int x = (panel1.Width - pictureBox1.Width) / 2; int y = (panel1.Height - pictureBox1.Height) / 2; pictureBox1.Location = new Point(x, y); } #endregion } }
// // ImportManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using Mono.Unix; using Hyena; using Hyena.Jobs; using Hyena.Collections; using Banshee.IO; using Banshee.Base; using Banshee.ServiceStack; namespace Banshee.Collection { public class ImportManager : QueuePipeline<string> { #region Importing Pipeline Element private class ImportElement : QueuePipelineElement<string> { private ImportManager manager; public ImportElement (ImportManager manager) { this.manager = manager; } public override void Enqueue (string item) { base.Enqueue (item); manager.UpdateScannerProgress (); } protected override string ProcessItem (string item) { try { manager.OnImportRequested (item); } catch (Exception e) { Hyena.Log.Exception (e); } return null; } } #endregion private static NumberFormatInfo number_format = new NumberFormatInfo (); private DirectoryScannerPipelineElement scanner_element; private ImportElement import_element; private readonly object user_job_mutex = new object (); private UserJob user_job; private uint timer_id; public event ImportEventHandler ImportRequested; public ImportManager () { AddElement (scanner_element = new DirectoryScannerPipelineElement ()); AddElement (import_element = new ImportElement (this)); } #region Public API public virtual void Enqueue (UriList uris) { CreateUserJob (); foreach (string path in uris.LocalPaths) { base.Enqueue (path); } } public override void Enqueue (string source) { Enqueue (new UriList (source)); } public void Enqueue (string [] paths) { Enqueue (new UriList (paths)); } public bool IsImportInProgress { get { return import_element.Processing; } } private bool keep_user_job_hidden = false; public bool KeepUserJobHidden { get { return keep_user_job_hidden; } set { keep_user_job_hidden = value; } } #endregion #region User Job / Interaction private void CreateUserJob () { lock (user_job_mutex) { if (user_job != null || KeepUserJobHidden) { return; } timer_id = Log.DebugTimerStart (); user_job = new UserJob (Title, Catalog.GetString ("Scanning for media")); user_job.SetResources (Resource.Cpu, Resource.Disk, Resource.Database); user_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped; user_job.IconNames = new string [] { "system-search", "gtk-find" }; user_job.CancelMessage = CancelMessage; user_job.CanCancel = true; user_job.CancelRequested += OnCancelRequested; if (!KeepUserJobHidden) { user_job.Register (); } } } private void DestroyUserJob () { lock (user_job_mutex) { if (user_job == null) { return; } if (!KeepUserJobHidden) { Log.DebugTimerPrint (timer_id, Title + " duration: {0}"); } user_job.CancelRequested -= OnCancelRequested; user_job.Finish (); user_job = null; } } private void OnCancelRequested (object o, EventArgs args) { scanner_element.Cancel (); } protected void UpdateProgress (string message) { CreateUserJob (); if (user_job != null) { double new_progress = (double)import_element.ProcessedCount / (double)import_element.TotalCount; double old_progress = user_job.Progress; if (new_progress >= 0.0 && new_progress <= 1.0 && Math.Abs (new_progress - old_progress) > 0.001) { lock (number_format) { string disp_progress = String.Format (ProgressMessage, import_element.ProcessedCount, import_element.TotalCount); user_job.Title = disp_progress; user_job.Status = String.IsNullOrEmpty (message) ? Catalog.GetString ("Scanning...") : message; user_job.Progress = new_progress; } } } } private DateTime last_enqueue_display = DateTime.Now; private void UpdateScannerProgress () { CreateUserJob (); if (user_job != null) { if (DateTime.Now - last_enqueue_display > TimeSpan.FromMilliseconds (400)) { lock (number_format) { number_format.NumberDecimalDigits = 0; user_job.Status = String.Format (Catalog.GetString ("Scanning ({0} files)..."), import_element.TotalCount.ToString ("N", number_format)); last_enqueue_display = DateTime.Now; } } } } #endregion #region Protected Import Hooks protected virtual void OnImportRequested (string path) { ImportEventHandler handler = ImportRequested; if (handler != null && path != null) { ImportEventArgs args = new ImportEventArgs (path); handler (this, args); UpdateProgress (args.ReturnMessage); } else { UpdateProgress (null); } } protected override void OnFinished () { DestroyUserJob (); base.OnFinished (); } #endregion #region Properties private string title = Catalog.GetString ("Importing Media"); public string Title { get { return title; } set { title = value; } } private string cancel_message = Catalog.GetString ( "The import process is currently running. Would you like to stop it?"); public string CancelMessage { get { return cancel_message; } set { cancel_message = value; } } private string progress_message = Catalog.GetString ("Importing {0} of {1}"); public string ProgressMessage { get { return progress_message; } set { progress_message = value; } } public bool Threaded { set { import_element.Threaded = scanner_element.Threaded = value; } } protected int TotalCount { get { return import_element == null ? 0 : import_element.TotalCount; } } #endregion } }
/// <license> /// This is a port of the SciMark2a Java Benchmark to C# by /// Chris Re (cmr28@cornell.edu) and Werner Vogels (vogels@cs.cornell.edu) /// /// For details on the original authors see http://math.nist.gov/scimark2 /// /// This software is likely to burn your processor, bitflip your memory chips /// anihilate your screen and corrupt all your disks, so you it at your /// own risk. /// </license> using System; namespace SciMark2 { /// <summary>Computes FFT's of complex, double precision data where n is an integer power of 2. /// This appears to be slower than the Radix2 method, /// but the code is smaller and simpler, and it requires no extra storage. /// </P> /// </summary> /// /// <author> /// Bruce R. Miller bruce.miller@nist.gov, /// Derived from GSL (Gnu Scientific Library), /// GSL's FFT Code by Brian Gough bjg@vvv.lanl.gov /// </author> public class FFT { public static double num_flops(int N) { double Nd = (double)N; double logN = (double)log2(N); return (5.0 * Nd - 2) * logN + 2 * (Nd + 1); } /// <summary> /// Compute Fast Fourier Transform of (complex) data, in place. /// </summary> public static void transform(double[] data) { transform_internal(data, -1); } /// <summary> /// Compute Inverse Fast Fourier Transform of (complex) data, in place. /// </summary> public static void inverse(double[] data) { transform_internal(data, +1); // Normalize int nd = data.Length; int n = nd / 2; double norm = 1 / ((double)n); for (int i = 0; i < nd; i++) data[i] *= norm; } /// <summary> /// Accuracy check on FFT of data. Make a copy of data, Compute the FFT, then /// the inverse and compare to the original. Returns the rms difference. /// </summary> public static double test(double[] data) { int nd = data.Length; // Make duplicate for comparison double[] copy = new double[nd]; Array.Copy(data, 0, copy, 0, nd); // Transform & invert transform(data); inverse(data); // Compute RMS difference. double diff = 0.0; for (int i = 0; i < nd; i++) { double d = data[i] - copy[i]; diff += d * d; } return Math.Sqrt(diff / nd); } /// <summary> /// Make a random array of n (complex) elements. /// </summary> public static double[] makeRandom(int n) { int nd = 2 * n; double[] data = new double[nd]; System.Random r = new System.Random(); for (int i = 0; i < nd; i++) data[i] = r.NextDouble(); return data; } protected internal static int log2(int n) { int log = 0; for (int k = 1; k < n; k *= 2, log++) ; if (n != (1 << log)) throw new Exception("FFT: Data length is not a power of 2!: " + n); return log; } protected internal static void transform_internal(double[] data, int direction) { if (data.Length == 0) return; int n = data.Length / 2; if (n == 1) return; // Identity operation! int logn = log2(n); /* bit reverse the input data for decimation in time algorithm */ bitreverse(data); /* apply fft recursion */ /* this loop executed log2(N) times */ for (int bit = 0, dual = 1; bit < logn; bit++, dual *= 2) { double w_real = 1.0; double w_imag = 0.0; double theta = 2.0 * direction * Math.PI / (2.0 * (double)dual); double s = Math.Sin(theta); double t = Math.Sin(theta / 2.0); double s2 = 2.0 * t * t; /* a = 0 */ for (int b = 0; b < n; b += 2 * dual) { int i = 2 * b; int j = 2 * (b + dual); double wd_real = data[j]; double wd_imag = data[j + 1]; data[j] = data[i] - wd_real; data[j + 1] = data[i + 1] - wd_imag; data[i] += wd_real; data[i + 1] += wd_imag; } /* a = 1 .. (dual-1) */ for (int a = 1; a < dual; a++) { /* trignometric recurrence for w-> exp(i theta) w */ { double tmp_real = w_real - s * w_imag - s2 * w_real; double tmp_imag = w_imag + s * w_real - s2 * w_imag; w_real = tmp_real; w_imag = tmp_imag; } for (int b = 0; b < n; b += 2 * dual) { int i = 2 * (b + a); int j = 2 * (b + a + dual); double z1_real = data[j]; double z1_imag = data[j + 1]; double wd_real = w_real * z1_real - w_imag * z1_imag; double wd_imag = w_real * z1_imag + w_imag * z1_real; data[j] = data[i] - wd_real; data[j + 1] = data[i + 1] - wd_imag; data[i] += wd_real; data[i + 1] += wd_imag; } } } } protected internal static void bitreverse(double[] data) { /* This is the Goldrader bit-reversal algorithm */ int n = data.Length / 2; int nm1 = n - 1; int i = 0; int j = 0; for (; i < nm1; i++) { //int ii = 2*i; int ii = i << 1; //int jj = 2*j; int jj = j << 1; //int k = n / 2 ; int k = n >> 1; if (i < j) { double tmp_real = data[ii]; double tmp_imag = data[ii + 1]; data[ii] = data[jj]; data[ii + 1] = data[jj + 1]; data[jj] = tmp_real; data[jj + 1] = tmp_imag; } while (k <= j) { //j = j - k ; j -= k; //k = k / 2 ; k >>= 1; } j += k; } } } }
#region Using directives using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Collections; using EnvDTE; using EnvDTE80; using System.IO; using Knowledge.Editor.AddIn; using System.Runtime.InteropServices; using System.Diagnostics; using System.Threading; using System.Reflection; #endregion namespace Knowledge.Editor.View { partial class AddPropertyForm : Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AddPropertyForm)); this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this.listBox1 = new System.Windows.Forms.ListBox(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripContainer2 = new System.Windows.Forms.ToolStripContainer(); this.listBox2 = new System.Windows.Forms.ListBox(); this.toolStrip2 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.toolStripButton3 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton4 = new System.Windows.Forms.ToolStripButton(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.toolStripContainer2.ContentPanel.SuspendLayout(); this.toolStripContainer2.TopToolStripPanel.SuspendLayout(); this.toolStripContainer2.SuspendLayout(); this.toolStrip2.SuspendLayout(); this.imageList_AspectIcons = new System.Windows.Forms.ImageList(this.components); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(14, 14); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(34, 13); this.label1.TabIndex = 0; this.label1.Text = "Name:"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(14, 30); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(207, 20); this.textBox1.TabIndex = 1; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(15, 58); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(56, 13); this.label2.TabIndex = 2; this.label2.Text = "Value type:"; // // toolStripContainer1 // this.toolStripContainer1.BottomToolStripPanelVisible = false; // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.Controls.Add(this.listBox1); this.toolStripContainer1.LeftToolStripPanelVisible = false; this.toolStripContainer1.Location = new System.Drawing.Point(16, 112); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.RightToolStripPanelVisible = false; this.toolStripContainer1.Size = new System.Drawing.Size(205, 97); this.toolStripContainer1.TabIndex = 4; this.toolStripContainer1.Text = "toolStripContainer1"; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip1); // // listBox1 // this.listBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.listBox1.FormattingEnabled = true; this.listBox1.Location = new System.Drawing.Point(0, 0); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(205, 69); this.listBox1.TabIndex = 0; // // toolStrip1 // this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel1, this.toolStripButton1, this.toolStripButton2}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(128, 25); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Text = "Domain:"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Text = "Add"; // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image"))); this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Text = "Delete"; // // toolStripContainer2 // this.toolStripContainer2.BottomToolStripPanelVisible = false; // // toolStripContainer2.ContentPanel // this.toolStripContainer2.ContentPanel.Controls.Add(this.listBox2); this.toolStripContainer2.LeftToolStripPanelVisible = false; this.toolStripContainer2.Location = new System.Drawing.Point(16, 230); this.toolStripContainer2.Name = "toolStripContainer2"; this.toolStripContainer2.RightToolStripPanelVisible = false; this.toolStripContainer2.Size = new System.Drawing.Size(205, 82); this.toolStripContainer2.TabIndex = 5; this.toolStripContainer2.Text = "toolStripContainer2"; // // toolStripContainer2.TopToolStripPanel // this.toolStripContainer2.TopToolStripPanel.Controls.Add(this.toolStrip2); // // listBox2 // this.listBox2.Dock = System.Windows.Forms.DockStyle.Fill; this.listBox2.FormattingEnabled = true; this.listBox2.Location = new System.Drawing.Point(0, 0); this.listBox2.Name = "listBox2"; this.listBox2.Size = new System.Drawing.Size(205, 56); this.listBox2.TabIndex = 0; // // toolStrip2 // this.toolStrip2.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel2, this.toolStripButton3, this.toolStripButton4}); this.toolStrip2.Location = new System.Drawing.Point(0, 0); this.toolStrip2.Name = "toolStrip2"; this.toolStrip2.Size = new System.Drawing.Size(124, 25); this.toolStrip2.TabIndex = 0; this.toolStrip2.Text = "toolStrip2"; // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Text = "Range:"; // // toolStripButton3 // this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image"))); this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton3.Name = "toolStripButton3"; this.toolStripButton3.Text = "Add"; // // toolStripButton4 // this.toolStripButton4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton4.Image"))); this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton4.Name = "toolStripButton4"; this.toolStripButton4.Text = "Delete"; // // button1 // this.button1.Location = new System.Drawing.Point(15, 330); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 6; this.button1.Text = "OK"; // // button2 // this.button2.Location = new System.Drawing.Point(146, 330); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 7; this.button2.Text = "Cancel"; // // comboBox1 // this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(15, 74); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(206, 21); this.comboBox1.TabIndex = 8; // // imageList_AspectIcons // this.imageList_AspectIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList_AspectIcons.ImageStream"))); this.imageList_AspectIcons.Images.SetKeyName(0, "kn_file.bmp"); this.imageList_AspectIcons.Images.SetKeyName(1, "kn_folder.bmp"); this.imageList_AspectIcons.Images.SetKeyName(2, "kn_frame.bmp"); this.imageList_AspectIcons.Images.SetKeyName(3, "kn_slot.bmp"); this.imageList_AspectIcons.Images.SetKeyName(4, "kn_concept.bmp"); this.imageList_AspectIcons.Images.SetKeyName(5, "kn_prop.bmp"); this.imageList_AspectIcons.Images.SetKeyName(6, "kn_inst.bmp"); // // AddPropertyForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(237, 366); /* this.Controls.Add(this.comboBox1); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.toolStripContainer2); this.Controls.Add(this.toolStripContainer1); this.Controls.Add(this.label2); this.Controls.Add(this.textBox1); */ this.Controls.Add(this.label1); this.Name = "AddPropertyForm"; this.Text = "AddPropertyForm"; this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStripContainer2.ContentPanel.ResumeLayout(false); this.toolStripContainer2.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer2.TopToolStripPanel.PerformLayout(); this.toolStripContainer2.ResumeLayout(false); this.toolStripContainer2.PerformLayout(); this.toolStrip2.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ImageList imageList_AspectIcons; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ToolStripContainer toolStripContainer1; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripContainer toolStripContainer2; private System.Windows.Forms.ListBox listBox2; private System.Windows.Forms.ToolStrip toolStrip2; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripButton toolStripButton3; private System.Windows.Forms.ToolStripButton toolStripButton4; } }
//--------------------------------------------------------------------------- // // File: HtmlLexicalAnalyzer.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Lexical analyzer for Html-to-Xaml converter // //--------------------------------------------------------------------------- using System; using System.IO; using System.Diagnostics; using System.Collections; using System.Text; namespace HtmlToXamlConversion { /// <summary> /// lexical analyzer class /// recognizes tokens as groups of characters separated by arbitrary amounts of whitespace /// also classifies tokens according to type /// </summary> internal class HtmlLexicalAnalyzer { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// initializes the _inputStringReader member with the string to be read /// also sets initial values for _nextCharacterCode and _nextTokenType /// </summary> /// <param name="inputTextString"> /// text string to be parsed for xml content /// </param> internal HtmlLexicalAnalyzer(string inputTextString) { _inputStringReader = new StringReader(inputTextString); _nextCharacterCode = 0; _nextCharacter = ' '; _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; _previousCharacter = ' '; _ignoreNextWhitespace = true; _nextToken = new StringBuilder(100); _nextTokenType = HtmlTokenType.Text; // read the first character so we have some value for the NextCharacter property this.GetNextCharacter(); } #endregion Constructors // --------------------------------------------------------------------- // // Internal methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// retrieves next recognizable token from input string /// and identifies its type /// if no valid token is found, the output parameters are set to null /// if end of stream is reached without matching any token, token type /// paramter is set to EOF /// </summary> internal void GetNextContentToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } if (this.IsAtTagStart) { this.GetNextCharacter(); if (this.NextCharacter == '/') { _nextToken.Append("</"); _nextTokenType = HtmlTokenType.ClosingTagStart; // advance this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespaces after closing tags are significant } else { _nextTokenType = HtmlTokenType.OpeningTagStart; _nextToken.Append("<"); _ignoreNextWhitespace = true; // Whitespaces after opening tags are insignificant } } else if (this.IsAtDirectiveStart) { // either a comment or CDATA this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // cdata this.ReadDynamicContent(); } else if (_lookAheadCharacter == '-') { this.ReadComment(); } else { // neither a comment nor cdata, should be something like DOCTYPE // skip till the next tag ender this.ReadUnknownDirective(); } } else { // read text content, unless you encounter a tag _nextTokenType = HtmlTokenType.Text; while (!this.IsAtTagStart && !this.IsAtEndOfStream && !this.IsAtDirectiveStart) { if (this.NextCharacter == '<' && !this.IsNextCharacterEntity && _lookAheadCharacter == '?') { // ignore processing directive this.SkipProcessingDirective(); } else { if (this.NextCharacter <= ' ') { // Respect xml:preserve or its equivalents for whitespace processing if (_ignoreNextWhitespace) { // Ignore repeated whitespaces } else { // Treat any control character sequence as one whitespace _nextToken.Append(' '); } _ignoreNextWhitespace = true; // and keep ignoring the following whitespaces } else { _nextToken.Append(this.NextCharacter); _ignoreNextWhitespace = false; } this.GetNextCharacter(); } } } } /// <summary> /// Unconditionally returns a token which is one of: TagEnd, EmptyTagEnd, Name, Atom or EndOfStream /// Does not guarantee token reader advancing. /// </summary> internal void GetNextTagToken() { _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } this.SkipWhiteSpace(); if (this.NextCharacter == '>' && !this.IsNextCharacterEntity) { // &gt; should not end a tag, so make sure it's not an entity _nextTokenType = HtmlTokenType.TagEnd; _nextToken.Append('>'); this.GetNextCharacter(); // Note: _ignoreNextWhitespace must be set appropriately on tag start processing } else if (this.NextCharacter == '/' && _lookAheadCharacter == '>') { // could be start of closing of empty tag _nextTokenType = HtmlTokenType.EmptyTagEnd; _nextToken.Append("/>"); this.GetNextCharacter(); this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespace after no-scope tags are sifnificant } else if (IsGoodForNameStart(this.NextCharacter)) { _nextTokenType = HtmlTokenType.Name; // starts a name // we allow character entities here // we do not throw exceptions here if end of stream is encountered // just stop and return whatever is in the token // if the parser is not expecting end of file after this it will call // the get next token function and throw an exception while (IsGoodForName(this.NextCharacter) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } else { // Unexpected type of token for a tag. Reprot one character as Atom, expecting that HtmlParser will ignore it. _nextTokenType = HtmlTokenType.Atom; _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns equal sign token. Even if there is no /// real equal sign in the stream, it behaves as if it were there. /// Does not guarantee token reader advancing. /// </summary> internal void GetNextEqualSignToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; _nextToken.Append('='); _nextTokenType = HtmlTokenType.EqualSign; this.SkipWhiteSpace(); if (this.NextCharacter == '=') { // '=' is not in the list of entities, so no need to check for entities here this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns an atomic value for an attribute /// Even if there is no appropriate token it returns Atom value /// Does not guarantee token reader advancing. /// </summary> internal void GetNextAtomToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; this.SkipWhiteSpace(); _nextTokenType = HtmlTokenType.Atom; if ((this.NextCharacter == '\'' || this.NextCharacter == '"') && !this.IsNextCharacterEntity) { char startingQuote = this.NextCharacter; this.GetNextCharacter(); // Consume all characters between quotes while (!(this.NextCharacter == startingQuote && !this.IsNextCharacterEntity) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } if (this.NextCharacter == startingQuote) { this.GetNextCharacter(); } // complete the quoted value // NOTE: our recovery here is different from IE's // IE keeps reading until it finds a closing quote or end of file // if end of file, it treats current value as text // if it finds a closing quote at any point within the text, it eats everything between the quotes // TODO: Suggestion: // however, we could stop when we encounter end of file or an angle bracket of any kind // and assume there was a quote there // so the attribute value may be meaningless but it is never treated as text } else { while (!this.IsAtEndOfStream && !Char.IsWhiteSpace(this.NextCharacter) && this.NextCharacter != '>') { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties internal HtmlTokenType NextTokenType { get { return _nextTokenType; } } internal string NextToken { get { return _nextToken.ToString(); } } #endregion Internal Properties // --------------------------------------------------------------------- // // Private methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Advances a reading position by one character code /// and reads the next availbale character from a stream. /// This character becomes available as NextCharacter property. /// </summary> /// <remarks> /// Throws InvalidOperationException if attempted to be called on EndOfStream /// condition. /// </remarks> private void GetNextCharacter() { if (_nextCharacterCode == -1) { throw new InvalidOperationException("GetNextCharacter method called at the end of a stream"); } _previousCharacter = _nextCharacter; _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; // next character not an entity as of now _isNextCharacterEntity = false; this.ReadLookAheadCharacter(); if (_nextCharacter == '&') { if (_lookAheadCharacter == '#') { // numeric entity - parse digits - &#DDDDD; int entityCode; entityCode = 0; this.ReadLookAheadCharacter(); // largest numeric entity is 7 characters for (int i = 0; i < 7 && Char.IsDigit(_lookAheadCharacter); i++) { entityCode = 10 * entityCode + (_lookAheadCharacterCode - (int)'0'); this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // correct format - advance this.ReadLookAheadCharacter(); _nextCharacterCode = entityCode; // if this is out of range it will set the character to '?' _nextCharacter = (char)_nextCharacterCode; // as far as we are concerned, this is an entity _isNextCharacterEntity = true; } else { // not an entity, set next character to the current lookahread character // we would have eaten up some digits _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } else if (Char.IsLetter(_lookAheadCharacter)) { // entity is written as a string string entity = ""; // maximum length of string entities is 10 characters for (int i = 0; i < 10 && (Char.IsLetter(_lookAheadCharacter) || Char.IsDigit(_lookAheadCharacter)); i++) { entity += _lookAheadCharacter; this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // advance this.ReadLookAheadCharacter(); if (HtmlSchema.IsEntity(entity)) { _nextCharacter = HtmlSchema.EntityCharacterValue(entity); _nextCharacterCode = (int)_nextCharacter; _isNextCharacterEntity = true; } else { // just skip the whole thing - invalid entity // move on to the next character _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); // not an entity _isNextCharacterEntity = false; } } else { // skip whatever we read after the ampersand // set next character and move on _nextCharacter = _lookAheadCharacter; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } } } private void ReadLookAheadCharacter() { if (_lookAheadCharacterCode != -1) { _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; } } /// <summary> /// skips whitespace in the input string /// leaves the first non-whitespace character available in the NextCharacter property /// this may be the end-of-file character, it performs no checking /// </summary> private void SkipWhiteSpace() { // TODO: handle character entities while processing comments, cdata, and directives // TODO: SUGGESTION: we could check if lookahead and previous characters are entities also while (true) { if (_nextCharacter == '<' && (_lookAheadCharacter == '?' || _lookAheadCharacter == '!')) { this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // Skip CDATA block and DTDs(?) while (!this.IsAtEndOfStream && !(_previousCharacter == ']' && _nextCharacter == ']' && _lookAheadCharacter == '>')) { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } else { // Skip processing instruction, comments while (!this.IsAtEndOfStream && _nextCharacter != '>') { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } } if (!Char.IsWhiteSpace(this.NextCharacter)) { break; } this.GetNextCharacter(); } } /// <summary> /// checks if a character can be used to start a name /// if this check is true then the rest of the name can be read /// </summary> /// <param name="character"> /// character value to be checked /// </param> /// <returns> /// true if the character can be the first character in a name /// false otherwise /// </returns> private bool IsGoodForNameStart(char character) { return character == '_' || Char.IsLetter(character); } /// <summary> /// checks if a character can be used as a non-starting character in a name /// uses the IsExtender and IsCombiningCharacter predicates to see /// if a character is an extender or a combining character /// </summary> /// <param name="character"> /// character to be checked for validity in a name /// </param> /// <returns> /// true if the character can be a valid part of a name /// </returns> private bool IsGoodForName(char character) { // we are not concerned with escaped characters in names // we assume that character entities are allowed as part of a name return this.IsGoodForNameStart(character) || character == '.' || character == '-' || character == ':' || Char.IsDigit(character) || IsCombiningCharacter(character) || IsExtender(character); } /// <summary> /// identifies a character as being a combining character, permitted in a name /// TODO: only a placeholder for now but later to be replaced with comparisons against /// the list of combining characters in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is a combining character, false otherwise /// </returns> private bool IsCombiningCharacter(char character) { // TODO: put actual code with checks against all combining characters here return false; } /// <summary> /// identifies a character as being an extender, permitted in a name /// TODO: only a placeholder for now but later to be replaced with comparisons against /// the list of extenders in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is an extender, false otherwise /// </returns> private bool IsExtender(char character) { // TODO: put actual code with checks against all extenders here return false; } /// <summary> /// skips dynamic content starting with '<![' and ending with ']>' /// </summary> private void ReadDynamicContent() { // verify that we are at dynamic content, which may include CDATA Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '['); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance twice, once to get the lookahead character and then to reach the start of the cdata this.GetNextCharacter(); this.GetNextCharacter(); // NOTE: 10/12/2004: modified this function to check when called if's reading CDATA or something else // some directives may start with a <![ and then have some data and they will just end with a ]> // this function is modified to stop at the sequence ]> and not ]]> // this means that CDATA and anything else expressed in their own set of [] within the <! [...]> // directive cannot contain a ]> sequence. However it is doubtful that cdata could contain such // sequence anyway, it probably stops at the first ] while (!(_nextCharacter == ']' && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } /// <summary> /// skips comments starting with '<!-' and ending with '-->' /// NOTE: 10/06/2004: processing changed, will now skip anything starting with /// the "<!-" sequence and ending in "!>" or "->", because in practice many html pages do not /// use the full comment specifying conventions /// </summary> private void ReadComment() { // verify that we are at a comment Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '-'); // Initialize a token _nextTokenType = HtmlTokenType.Comment; _nextToken.Length = 0; // advance to the next character, so that to be at the start of comment value this.GetNextCharacter(); // get first '-' this.GetNextCharacter(); // get second '-' this.GetNextCharacter(); // get first character of comment content while (true) { // Read text until end of comment // Note that in many actual html pages comments end with "!>" (while xml standard is "-->") while (!this.IsAtEndOfStream && !(_nextCharacter == '-' && _lookAheadCharacter == '-' || _nextCharacter == '!' && _lookAheadCharacter == '>')) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } // Finish comment reading this.GetNextCharacter(); if (_previousCharacter == '-' && _nextCharacter == '-' && _lookAheadCharacter == '>') { // Standard comment end. Eat it and exit the loop this.GetNextCharacter(); // get '>' break; } else if (_previousCharacter == '!' && _nextCharacter == '>') { // Nonstandard but possible comment end - '!>'. Exit the loop break; } else { // Not an end. Save character and continue continue reading _nextToken.Append(_previousCharacter); continue; } } // Read end of comment combination if (_nextCharacter == '>') { this.GetNextCharacter(); } } /// <summary> /// skips past unknown directives that start with "<!" but are not comments or Cdata /// ignores content of such directives until the next ">" character /// applies to directives such as DOCTYPE, etc that we do not presently support /// </summary> private void ReadUnknownDirective() { // verify that we are at an unknown directive Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && !(_lookAheadCharacter == '-' || _lookAheadCharacter == '[')); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance to the next character this.GetNextCharacter(); // skip to the first tag end we find while (!(_nextCharacter == '>' && !IsNextCharacterEntity) && !this.IsAtEndOfStream) { this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance past the tag end this.GetNextCharacter(); } } /// <summary> /// skips processing directives starting with the characters '<?' and ending with '?>' /// NOTE: 10/14/2004: IE also ends processing directives with a />, so this function is /// being modified to recognize that condition as well /// </summary> private void SkipProcessingDirective() { // verify that we are at a processing directive Debug.Assert(_nextCharacter == '<' && _lookAheadCharacter == '?'); // advance twice, once to get the lookahead character and then to reach the start of the drective this.GetNextCharacter(); this.GetNextCharacter(); while (!((_nextCharacter == '?' || _nextCharacter == '/') && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance // we don't need to check for entities here because '?' is not an entity // and even though > is an entity there is no entity processing when reading lookahead character this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } #endregion Private Methods // --------------------------------------------------------------------- // // Private Properties // // --------------------------------------------------------------------- #region Private Properties private char NextCharacter { get { return _nextCharacter; } } private bool IsAtEndOfStream { get { return _nextCharacterCode == -1; } } private bool IsAtTagStart { get { return _nextCharacter == '<' && (_lookAheadCharacter == '/' || IsGoodForNameStart(_lookAheadCharacter)) && !_isNextCharacterEntity; } } private bool IsAtTagEnd { // check if at end of empty tag or regular tag get { return (_nextCharacter == '>' || (_nextCharacter == '/' && _lookAheadCharacter == '>')) && !_isNextCharacterEntity; } } private bool IsAtDirectiveStart { get { return (_nextCharacter == '<' && _lookAheadCharacter == '!' && !this.IsNextCharacterEntity); } } private bool IsNextCharacterEntity { // check if next character is an entity get { return _isNextCharacterEntity; } } #endregion Private Properties // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // string reader which will move over input text private StringReader _inputStringReader; // next character code read from input that is not yet part of any token // and the character it represents private int _nextCharacterCode; private char _nextCharacter; private int _lookAheadCharacterCode; private char _lookAheadCharacter; private char _previousCharacter; private bool _ignoreNextWhitespace; private bool _isNextCharacterEntity; // store token and type in local variables before copying them to output parameters StringBuilder _nextToken; HtmlTokenType _nextTokenType; #endregion Private Fields } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DriveItemChildrenCollectionRequest. /// </summary> public partial class DriveItemChildrenCollectionRequest : BaseRequest, IDriveItemChildrenCollectionRequest { /// <summary> /// Constructs a new DriveItemChildrenCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DriveItemChildrenCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified DriveItem to the collection via POST. /// </summary> /// <param name="driveItem">The DriveItem to add.</param> /// <returns>The created DriveItem.</returns> public System.Threading.Tasks.Task<DriveItem> AddAsync(DriveItem driveItem) { return this.AddAsync(driveItem, CancellationToken.None); } /// <summary> /// Adds the specified DriveItem to the collection via POST. /// </summary> /// <param name="driveItem">The DriveItem to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DriveItem.</returns> public System.Threading.Tasks.Task<DriveItem> AddAsync(DriveItem driveItem, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<DriveItem>(driveItem, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IDriveItemChildrenCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IDriveItemChildrenCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<DriveItemChildrenCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Expand(Expression<Func<DriveItem, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Select(Expression<Func<DriveItem, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
/* **************************************************************************** * * 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 * ironpy@microsoft.com. 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.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.Project { #region structures [StructLayoutAttribute(LayoutKind.Sequential)] internal struct _DROPFILES { public Int32 pFiles; public Int32 X; public Int32 Y; public Int32 fNC; public Int32 fWide; } #endregion #region enums /// <summary> /// The type of build performed. /// </summary> public enum BuildKind { Sync, Async } /// <summary> /// Defines possible types of output that can produced by a language project /// </summary> [PropertyPageTypeConverterAttribute(typeof(OutputTypeConverter))] public enum OutputType { /// <summary> /// The output type is a class library. /// </summary> Library, /// <summary> /// The output type is a windows executable. /// </summary> WinExe, /// <summary> /// The output type is an executable. /// </summary> Exe } /// <summary> /// Debug values used by DebugModeConverter. /// </summary> [PropertyPageTypeConverterAttribute(typeof(DebugModeConverter))] public enum DebugMode { Project, Program, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URL")] URL } /// <summary> /// An enumeration that describes the type of action to be taken by the build. /// </summary> [PropertyPageTypeConverterAttribute(typeof(BuildActionConverter))] public enum BuildAction { None, Compile, Content, EmbeddedResource } /// <summary> /// Defines the version of the CLR that is appropriate to the project. /// </summary> [PropertyPageTypeConverterAttribute(typeof(PlatformTypeConverter))] public enum PlatformType { [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "not")] notSpecified, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v1, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v11, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v2, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v3, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v35, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v4, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "cli")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "cli")] cli1 } /// <summary> /// Defines the currect state of a property page. /// </summary> [Flags] public enum PropPageStatus { Dirty = 0x1, Validate = 0x2, Clean = 0x4 } [Flags] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum ModuleKindFlags { ConsoleApplication, WindowsApplication, DynamicallyLinkedLibrary, ManifestResourceFile, UnmanagedDynamicallyLinkedLibrary } /// <summary> /// Defines the status of the command being queried /// </summary> [Flags] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum QueryStatusResult { /// <summary> /// The command is not supported. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NOTSUPPORTED")] NOTSUPPORTED = 0, /// <summary> /// The command is supported /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SUPPORTED")] SUPPORTED = 1, /// <summary> /// The command is enabled /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ENABLED")] ENABLED = 2, /// <summary> /// The command is toggled on /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "LATCHED")] LATCHED = 4, /// <summary> /// The command is toggled off (the opposite of LATCHED). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NINCHED")] NINCHED = 8, /// <summary> /// The command is invisible. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "INVISIBLE")] INVISIBLE = 16 } /// <summary> /// Defines the type of item to be added to the hierarchy. /// </summary> public enum HierarchyAddType { AddNewItem, AddExistingItem } /// <summary> /// Defines the component from which a command was issued. /// </summary> public enum CommandOrigin { [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ui")] UiHierarchy, OleCommandTarget } /// <summary> /// Defines the current status of the build process. /// </summary> public enum MSBuildResult { /// <summary> /// The build is currently suspended. /// </summary> Suspended, /// <summary> /// The build has been restarted. /// </summary> Resumed, /// <summary> /// The build failed. /// </summary> Failed, /// <summary> /// The build was successful. /// </summary> Successful, } /// <summary> /// Defines the type of action to be taken in showing the window frame. /// </summary> public enum WindowFrameShowAction { DoNotShow, Show, ShowNoActivate, Hide, } /// <summary> /// Defines drop types /// </summary> internal enum DropDataType { None, Shell, VsStg, VsRef } /// <summary> /// Used by the hierarchy node to decide which element to redraw. /// </summary> [Flags] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] public enum UIHierarchyElement { None = 0, /// <summary> /// This will be translated to VSHPROPID_IconIndex /// </summary> Icon = 1, /// <summary> /// This will be translated to VSHPROPID_StateIconIndex /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] SccState = 2, /// <summary> /// This will be translated to VSHPROPID_Caption /// </summary> Caption = 4 } /// <summary> /// Defines the global propeties used by the msbuild project. /// </summary> public enum GlobalProperty { /// <summary> /// Property specifying that we are building inside VS. /// </summary> BuildingInsideVisualStudio, /// <summary> /// The VS installation directory. This is the same as the $(DevEnvDir) macro. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Env")] DevEnvDir, /// <summary> /// The name of the solution the project is created. This is the same as the $(SolutionName) macro. /// </summary> SolutionName, /// <summary> /// The file name of the solution. This is the same as $(SolutionFileName) macro. /// </summary> SolutionFileName, /// <summary> /// The full path of the solution. This is the same as the $(SolutionPath) macro. /// </summary> SolutionPath, /// <summary> /// The directory of the solution. This is the same as the $(SolutionDir) macro. /// </summary> SolutionDir, /// <summary> /// The extension of teh directory. This is the same as the $(SolutionExt) macro. /// </summary> SolutionExt, /// <summary> /// The fxcop installation directory. /// </summary> FxCopDir, /// <summary> /// The ResolvedNonMSBuildProjectOutputs msbuild property /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "VSIDE")] VSIDEResolvedNonMSBuildProjectOutputs, /// <summary> /// The Configuartion property. /// </summary> Configuration, /// <summary> /// The platform property. /// </summary> Platform, /// <summary> /// The RunCodeAnalysisOnce property /// </summary> RunCodeAnalysisOnce, /// <summary> /// The VisualStudioStyleErrors property /// </summary> VisualStudioStyleErrors, } #endregion public class AfterProjectFileOpenedEventArgs : EventArgs { #region fields private bool added; #endregion #region properties /// <summary> /// True if the project is added to the solution after the solution is opened. false if the project is added to the solution while the solution is being opened. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal bool Added { get { return this.added; } } #endregion #region ctor internal AfterProjectFileOpenedEventArgs(bool added) { this.added = added; } #endregion } public class BeforeProjectFileClosedEventArgs : EventArgs { #region fields private bool removed; #endregion #region properties /// <summary> /// true if the project was removed from the solution before the solution was closed. false if the project was removed from the solution while the solution was being closed. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal bool Removed { get { return this.removed; } } #endregion #region ctor internal BeforeProjectFileClosedEventArgs(bool removed) { this.removed = removed; } #endregion } /// <summary> /// This class is used for the events raised by a HierarchyNode object. /// </summary> internal class HierarchyNodeEventArgs : EventArgs { private HierarchyNode child; internal HierarchyNodeEventArgs(HierarchyNode child) { this.child = child; } public HierarchyNode Child { get { return this.child; } } } /// <summary> /// Event args class for triggering file change event arguments. /// </summary> internal class FileChangedOnDiskEventArgs : EventArgs { #region Private fields /// <summary> /// File name that was changed on disk. /// </summary> private string fileName; /// <summary> /// The item ide of the file that has changed. /// </summary> private uint itemID; /// <summary> /// The reason the file has changed on disk. /// </summary> private _VSFILECHANGEFLAGS fileChangeFlag; #endregion /// <summary> /// Constructs a new event args. /// </summary> /// <param name="fileName">File name that was changed on disk.</param> /// <param name="id">The item id of the file that was changed on disk.</param> internal FileChangedOnDiskEventArgs(string fileName, uint id, _VSFILECHANGEFLAGS flag) { this.fileName = fileName; this.itemID = id; this.fileChangeFlag = flag; } /// <summary> /// Gets the file name that was changed on disk. /// </summary> /// <value>The file that was changed on disk.</value> internal string FileName { get { return this.fileName; } } /// <summary> /// Gets item id of the file that has changed /// </summary> /// <value>The file that was changed on disk.</value> internal uint ItemID { get { return this.itemID; } } /// <summary> /// The reason while the file has chnaged on disk. /// </summary> /// <value>The reason while the file has chnaged on disk.</value> internal _VSFILECHANGEFLAGS FileChangeFlag { get { return this.fileChangeFlag; } } } /// <summary> /// Defines the event args for the active configuration chnage event. /// </summary> public class ActiveConfigurationChangedEventArgs : EventArgs { #region Private fields /// <summary> /// The hierarchy whose configuration has changed /// </summary> private IVsHierarchy hierarchy; #endregion /// <summary> /// Constructs a new event args. /// </summary> /// <param name="fileName">The hierarchy that has changed its configuration.</param> internal ActiveConfigurationChangedEventArgs(IVsHierarchy hierarchy) { this.hierarchy = hierarchy; } /// <summary> /// The hierarchy whose configuration has changed /// </summary> internal IVsHierarchy Hierarchy { get { return this.hierarchy; } } } /// <summary> /// Argument of the event raised when a project property is changed. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class ProjectPropertyChangedArgs : EventArgs { private string propertyName; private string oldValue; private string newValue; internal ProjectPropertyChangedArgs(string propertyName, string oldValue, string newValue) { this.propertyName = propertyName; this.oldValue = oldValue; this.newValue = newValue; } public string NewValue { get { return newValue; } } public string OldValue { get { return oldValue; } } public string PropertyName { get { return propertyName; } } } }
/* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * 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 holder is ArangoDB GmbH, Cologne, Germany */ namespace ArangoDB.Velocypack { using System.Collections.Generic; using global::ArangoDB.Velocypack.Exceptions; using global::ArangoDB.Velocypack.Internal; using global::ArangoDB.Velocypack.Internal.Util; /// <author>Mark - mark at arangodb.com</author> public class VPackSlice { private const long serialVersionUID = -3452953589283603980L; public static readonly VPackAttributeTranslator attributeTranslator = new VPackAttributeTranslatorImpl(); private readonly byte[] vpack; private readonly int start; protected internal VPackSlice() : this(new byte[] { unchecked((int)0x00) }, 0) { } public VPackSlice(byte[] vpack) : this(vpack, 0) { } public VPackSlice(byte[] vpack, int start) : base() { this.vpack = vpack; this.start = start; } public virtual byte head() { return this.vpack[this.start]; } public virtual byte[] getBuffer() { return this.vpack; } public virtual int getStart() { return this.start; } protected internal virtual ValueType type() { return ValueTypeUtil.get(this.head()); } private int length() { return ValueLengthUtil.get(this.head()) - 1; } private bool isType(ValueType type) { return type() == type; } public virtual bool isNone() { return this.isType(ValueType.NONE); } public virtual bool isNull() { return this.isType(ValueType.NULL); } public virtual bool isIllegal() { return this.isType(ValueType.ILLEGAL); } public virtual bool isBoolean() { return this.isType(ValueType.BOOL); } public virtual bool isTrue() { return this.head() == unchecked((int)0x1a); } public virtual bool isFalse() { return this.head() == unchecked((int)0x19); } public virtual bool isArray() { return this.isType(ValueType.ARRAY); } public virtual bool isObject() { return this.isType(ValueType.OBJECT); } public virtual bool isDouble() { return this.isType(ValueType.DOUBLE); } public virtual bool isDate() { return this.isType(ValueType.UTC_DATE); } public virtual bool isExternal() { return this.isType(ValueType.EXTERNAL); } public virtual bool isMinKey() { return this.isType(ValueType.MIN_KEY); } public virtual bool isMaxKey() { return this.isType(ValueType.MAX_KEY); } public virtual bool isInt() { return this.isType(ValueType.INT); } public virtual bool isUInt() { return this.isType(ValueType.UINT); } public virtual bool isSmallInt() { return this.isType(ValueType.SMALLINT); } public virtual bool isInteger() { return this.isInt() || this.isUInt() || this.isSmallInt(); } public virtual bool isNumber() { return this.isInteger() || this.isDouble(); } public virtual bool isString() { return this.isType(ValueType.STRING); } public virtual bool isBinary() { return this.isType(ValueType.BINARY); } public virtual bool isBCD() { return this.isType(ValueType.BCD); } public virtual bool isCustom() { return this.isType(ValueType.CUSTOM); } public virtual bool getAsBoolean() { if (!this.isBoolean()) { throw new VPackValueTypeException(ValueType .BOOL); } return this.isTrue(); } public virtual double getAsDouble() { if (!this.isDouble()) { throw new VPackValueTypeException(ValueType .DOUBLE); } return this.getAsDoubleUnchecked(); } private double getAsDoubleUnchecked() { return NumberUtil.toDouble(this.vpack, this.start + 1, this.length()); } public virtual java.math.BigDecimal getAsBigDecimal() { return new java.math.BigDecimal(this.getAsDouble()); } private long getSmallInt() { byte head = head(); long smallInt; if (head >= unchecked((int)0x30) && (sbyte)head <= unchecked((int)0x39)) { smallInt = head - unchecked((int)0x30); } else { /* if (head >= 0x3a && head <= 0x3f) */ smallInt = head - unchecked((int)0x3a) - 6; } return smallInt; } private long getInt() { return NumberUtil.toLong(this.vpack, this.start + 1, this.length()); } private long getUInt() { return NumberUtil.toLong(this.vpack, this.start + 1, this.length()); } public virtual java.lang.Number getAsNumber() { java.lang.Number result; if (this.isSmallInt()) { result = this.getSmallInt(); } else { if (this.isInt()) { result = this.getInt(); } else { if (this.isUInt()) { result = this.getUInt(); } else { if (this.isDouble()) { result = this.getAsDouble(); } else { throw new VPackValueTypeException(ValueType .INT, ValueType.UINT, ValueType. SMALLINT); } } } } return result; } public virtual long getAsLong() { return this.getAsNumber(); } public virtual int getAsInt() { return this.getAsNumber(); } public virtual float getAsFloat() { return (float)this.getAsDoubleUnchecked(); } public virtual short getAsShort() { return this.getAsNumber(); } public virtual java.math.BigInteger getAsBigInteger() { if (this.isSmallInt() || this.isInt()) { return java.math.BigInteger.valueOf(this.getAsLong()); } else { if (this.isUInt()) { return NumberUtil.toBigInteger(this.vpack, this.start + 1, this.length()); } else { throw new VPackValueTypeException(ValueType .INT, ValueType.UINT, ValueType. SMALLINT); } } } public virtual System.DateTime getAsDate() { if (!this.isDate()) { throw new VPackValueTypeException(ValueType .UTC_DATE); } return DateUtil.toDate(this.vpack, this.start + 1, this.length ()); } public virtual java.sql.Date getAsSQLDate() { if (!this.isDate()) { throw new VPackValueTypeException(ValueType .UTC_DATE); } return DateUtil.toSQLDate(this.vpack, this.start + 1 , this.length()); } public virtual java.sql.Timestamp getAsSQLTimestamp() { if (!this.isDate()) { throw new VPackValueTypeException(ValueType .UTC_DATE); } return DateUtil.toSQLTimestamp(this.vpack, this.start + 1, this.length()); } public virtual string getAsString() { if (!this.isString()) { throw new VPackValueTypeException(ValueType .STRING); } return this.isLongString() ? this.getLongString() : this.getShortString(); } public virtual char getAsChar() { return this.getAsString()[0]; } private bool isLongString() { return this.head() == unchecked((byte)unchecked((int)0xbf)); } private string getShortString() { return StringUtil.toString(this.vpack, this.start + 1, this.length()); } private string getLongString() { return StringUtil.toString(this.vpack, this.start + 9, this.getLongStringLength()); } private int getLongStringLength() { return (int)NumberUtil.toLong(this.vpack, this.start + 1, 8); } private int getStringLength() { return this.isLongString() ? this.getLongStringLength() : this.head() - unchecked((int)0x40); } public virtual byte[] getAsBinary() { if (!this.isBinary()) { throw new VPackValueTypeException(ValueType .BINARY); } byte[] binary = BinaryUtil.toBinary(this.vpack, this.start + 1 + this.head() - unchecked((byte)unchecked((int)0xbf)), this.getBinaryLength( )); return binary; } public virtual int getBinaryLength() { if (!this.isBinary()) { throw new VPackValueTypeException(ValueType .BINARY); } return this.getBinaryLengthUnchecked(); } private int getBinaryLengthUnchecked() { return (int)NumberUtil.toLong(this.vpack, this.start + 1, this.head() - unchecked((byte)unchecked((int)0xbf))); } /// <returns>the number of members for an Array, Object or String</returns> public virtual int getLength() { long length; if (this.isString()) { length = this.getStringLength(); } else { if (!this.isArray() && !this.isObject()) { throw new VPackValueTypeException(ValueType .ARRAY, ValueType.OBJECT, ValueType .STRING); } else { byte head = head(); if (head == unchecked((int)0x01) || head == unchecked((int)0x0a)) { // empty length = 0; } else { if (head == unchecked((int)0x13) || head == unchecked((int)0x14)) { // compact array or object long end = NumberUtil.readVariableValueLength (this.vpack, this.start + 1, false); length = NumberUtil.readVariableValueLength (this.vpack, (int)(this.start + end - 1), true); } else { int offsetsize = ObjectArrayUtil.getOffsetSize (head); long end = NumberUtil.toLong(this.vpack, this.start + 1, offsetsize); if ((sbyte)head <= unchecked((int)0x05)) { // array with no offset table or length int dataOffset = this.findDataOffset(); VPackSlice first = new VPackSlice (this.vpack, this.start + dataOffset); length = (end - dataOffset) / first.getByteSize(); } else { if (offsetsize < 8) { length = NumberUtil.toLong(this.vpack, this.start + 1 + offsetsize, offsetsize); } else { length = NumberUtil.toLong(this.vpack, (int)(this.start + end - offsetsize), offsetsize); } } } } } } return (int)length; } public virtual int size() { return this.getLength(); } /// <summary>Must be called for a nonempty array or object at start():</summary> protected internal virtual int findDataOffset() { int fsm = ObjectArrayUtil.getFirstSubMap(this.head ()); int offset; if (fsm <= 2 && this.vpack[this.start + 2] != 0) { offset = 2; } else { if (fsm <= 3 && this.vpack[this.start + 3] != 0) { offset = 3; } else { if (fsm <= 5 && this.vpack[this.start + 6] != 0) { offset = 5; } else { offset = 9; } } } return offset; } public virtual int getByteSize() { long size; byte head = head(); int valueLength = ValueLengthUtil.get(head ); if (valueLength != 0) { size = valueLength; } else { switch (this.type()) { case ValueType.ARRAY: case ValueType.OBJECT: { if (head == unchecked((int)0x13) || head == unchecked((int)0x14)) { // compact Array or Object size = NumberUtil.readVariableValueLength( this.vpack, this.start + 1, false); } else { /* if (head <= 0x14) */ size = NumberUtil.toLong(this.vpack, this.start + 1, ObjectArrayUtil.getOffsetSize(head)); } break; } case ValueType.STRING: { // long UTF-8 String size = this.getLongStringLength() + 1 + 8; break; } case ValueType.BINARY: { size = 1 + head - unchecked((byte)unchecked((int)0xbf)) + this.getBinaryLengthUnchecked (); break; } case ValueType.BCD: { if ((sbyte)head <= unchecked((int)0xcf)) { size = 1 + head + unchecked((byte)unchecked((int)0xc7)) + NumberUtil .toLong(this.vpack, this.start + 1, head - unchecked((byte)unchecked((int)0xc7))); } else { size = 1 + head - unchecked((byte)unchecked((int)0xcf)) + NumberUtil .toLong(this.vpack, this.start + 1, head - unchecked((byte)unchecked((int)0xcf))); } break; } case ValueType.CUSTOM: { if (head == unchecked((int)0xf4) || head == unchecked((int)0xf5) || head == unchecked( (int)0xf6)) { size = 2 + NumberUtil.toLong(this.vpack, this.start + 1, 1); } else { if (head == unchecked((int)0xf7) || head == unchecked((int)0xf8) || head == unchecked( (int)0xf9)) { size = 3 + NumberUtil.toLong(this.vpack, this.start + 1, 2); } else { if (head == unchecked((int)0xfa) || head == unchecked((int)0xfb) || head == unchecked( (int)0xfc)) { size = 5 + NumberUtil.toLong(this.vpack, this.start + 1, 4); } else { /* if (head == 0xfd || head == 0xfe || head == 0xff) */ size = 9 + NumberUtil.toLong(this.vpack, this.start + 1, 8); } } } break; } default: { // TODO throw new java.lang.InternalError(); } } } return (int)size; } /// <returns>array value at the specified index</returns> /// <exception cref="VPackValueTypeException"/> public virtual VPackSlice get(int index) { if (!this.isArray()) { throw new VPackValueTypeException(ValueType .ARRAY); } return this.getNth(index); } /// <exception cref="VPackException"/> public virtual VPackSlice get(string attribute) { if (!this.isObject()) { throw new VPackValueTypeException(ValueType .OBJECT); } byte head = head(); VPackSlice result = new VPackSlice (); if (head == unchecked((int)0x0a)) { // special case, empty object result = new VPackSlice(); } else { if (head == unchecked((int)0x14)) { // compact Object result = this.getFromCompactObject(attribute); } else { int offsetsize = ObjectArrayUtil.getOffsetSize (head); long end = NumberUtil.toLong(this.vpack, this.start + 1, offsetsize); long n; if (offsetsize < 8) { n = NumberUtil.toLong(this.vpack, this.start + 1 + offsetsize , offsetsize); } else { n = NumberUtil.toLong(this.vpack, (int)(this.start + end - offsetsize), offsetsize); } if (n == 1) { // Just one attribute, there is no index table! VPackSlice key = new VPackSlice(this.vpack , this.start + this.findDataOffset()); if (key.isString()) { if (key.isEqualString(attribute)) { result = new VPackSlice(this.vpack, key.start + key.getByteSize ()); } else { // no match result = new VPackSlice(); } } else { if (key.isInteger()) { // translate key if (VPackSlice.attributeTranslator == null) { throw new VPackNeedAttributeTranslatorException (); } if (key.translateUnchecked().isEqualString(attribute)) { result = new VPackSlice(this.vpack, key.start + key.getByteSize ()); } else { // no match result = new VPackSlice(); } } else { // no match result = new VPackSlice(); } } } else { long ieBase = end - n * offsetsize - (offsetsize == 8 ? 8 : 0); // only use binary search for attributes if we have at least // this many entries // otherwise we'll always use the linear search long sortedSearchEntriesThreshold = 4; bool sorted = head >= unchecked((int)0x0b) && (sbyte)head <= unchecked((int)0x0e); if (sorted && n >= sortedSearchEntriesThreshold) { // This means, we have to handle the special case n == 1 // only in the linear search! result = this.searchObjectKeyBinary(attribute, ieBase, offsetsize, n); } else { result = this.searchObjectKeyLinear(attribute, ieBase, offsetsize, n); } } } } return result; } /// <summary>translates an integer key into a string, without checks</summary> protected internal virtual VPackSlice translateUnchecked( ) { VPackSlice result = attributeTranslator.translate(this.getAsInt ()); return result != null ? result : new VPackSlice(); } /// <exception cref="com.arangodb.velocypack.exception.VPackKeyTypeException"/> /// <exception cref="com.arangodb.velocypack.exception.VPackNeedAttributeTranslatorException /// "/> protected internal virtual VPackSlice makeKey() { if (this.isString()) { return this; } if (this.isInteger()) { if (VPackSlice.attributeTranslator == null) { throw new VPackNeedAttributeTranslatorException (); } return this.translateUnchecked(); } throw new VPackKeyTypeException("Cannot translate key of this type" ); } /// <exception cref="com.arangodb.velocypack.exception.VPackKeyTypeException"/> /// <exception cref="com.arangodb.velocypack.exception.VPackNeedAttributeTranslatorException /// "/> private VPackSlice getFromCompactObject(string attribute) { for (System.Collections.Generic.IEnumerator<KeyValuePair<string, VPackSlice>> iterator = this.objectIterator(); iterator .MoveNext();) { System.Collections.Generic.KeyValuePair<string, VPackSlice > next = iterator.Current; if (next.Key.Equals(attribute)) { return next.Value; } } // not found return new VPackSlice(); } /// <exception cref="com.arangodb.velocypack.exception.VPackValueTypeException"/> /// <exception cref="com.arangodb.velocypack.exception.VPackNeedAttributeTranslatorException /// "/> private VPackSlice searchObjectKeyBinary(string attribute , long ieBase, int offsetsize, long n) { bool useTranslator = VPackSlice.attributeTranslator != null; VPackSlice result; long l = 0; long r = n - 1; for (;;) { // midpoint long index = l + (r - l) / 2; long offset = ieBase + index * offsetsize; long keyIndex = NumberUtil.toLong(this.vpack, ( int)(this.start + offset), offsetsize); VPackSlice key = new VPackSlice(this.vpack , (int)(this.start + keyIndex)); int res = 0; if (key.isString()) { res = key.compareString(attribute); } else { if (key.isInteger()) { // translate key if (!useTranslator) { // no attribute translator throw new VPackNeedAttributeTranslatorException (); } res = key.translateUnchecked().compareString(attribute); } else { // invalid key result = new VPackSlice(); break; } } if (res == 0) { // found result = new VPackSlice(this.vpack, key.start + key.getByteSize ()); break; } if (res > 0) { if (index == 0) { result = new VPackSlice(); break; } r = index - 1; } else { l = index + 1; } if (r < l) { result = new VPackSlice(); break; } } return result; } /// <exception cref="com.arangodb.velocypack.exception.VPackValueTypeException"/> /// <exception cref="com.arangodb.velocypack.exception.VPackNeedAttributeTranslatorException /// "/> private VPackSlice searchObjectKeyLinear(string attribute , long ieBase, int offsetsize, long n) { bool useTranslator = VPackSlice.attributeTranslator != null; VPackSlice result = new VPackSlice (); for (long index = 0; index < n; index++) { long offset = ieBase + index * offsetsize; long keyIndex = NumberUtil.toLong(this.vpack, ( int)(this.start + offset), offsetsize); VPackSlice key = new VPackSlice(this.vpack , (int)(this.start + keyIndex)); if (key.isString()) { if (!key.isEqualString(attribute)) { continue; } } else { if (key.isInteger()) { // translate key if (!useTranslator) { // no attribute translator throw new VPackNeedAttributeTranslatorException (); } if (!key.translateUnchecked().isEqualString(attribute)) { continue; } } else { // invalid key type result = new VPackSlice(); break; } } // key is identical. now return value result = new VPackSlice(this.vpack, key.start + key.getByteSize ()); break; } return result; } public virtual VPackSlice keyAt(int index) { if (!this.isObject()) { throw new VPackValueTypeException(ValueType .OBJECT); } return this.getNthKey(index); } public virtual VPackSlice valueAt(int index) { if (!this.isObject()) { throw new VPackValueTypeException(ValueType .OBJECT); } VPackSlice key = this.getNthKey(index); return new VPackSlice(this.vpack, key.start + key.getByteSize( )); } private VPackSlice getNthKey(int index) { return new VPackSlice(this.vpack, this.start + this.getNthOffset(index)); } private VPackSlice getNth(int index) { return new VPackSlice(this.vpack, this.start + this.getNthOffset(index)); } /// <returns>the offset for the nth member from an Array or Object type</returns> private int getNthOffset(int index) { int offset; byte head = head(); if (head == unchecked((int)0x13) || head == unchecked((int)0x14)) { // compact Array or Object offset = this.getNthOffsetFromCompact(index); } else { if (head == unchecked((int)0x01) || head == unchecked((int)0x0a)) { // special case: empty Array or empty Object throw new System.IndexOutOfRangeException(); } else { long n; int offsetsize = ObjectArrayUtil.getOffsetSize (head); long end = NumberUtil.toLong(this.vpack, this.start + 1, offsetsize); int dataOffset = this.findDataOffset(); if ((sbyte)head <= unchecked((int)0x05)) { // array with no offset table or length VPackSlice first = new VPackSlice (this.vpack, this.start + dataOffset); n = (end - dataOffset) / first.getByteSize(); } else { if (offsetsize < 8) { n = NumberUtil.toLong(this.vpack, this.start + 1 + offsetsize , offsetsize); } else { n = NumberUtil.toLong(this.vpack, (int)(this.start + end - offsetsize), offsetsize); } } if (index >= n) { throw new System.IndexOutOfRangeException(); } if ((sbyte)head <= unchecked((int)0x05) || n == 1) { // no index table, but all array items have the same length // or only one item is in the array // now fetch first item and determine its length if (dataOffset == 0) { dataOffset = this.findDataOffset(); } offset = dataOffset + index * new VPackSlice(this.vpack, this.start + dataOffset).getByteSize(); } else { long ieBase = end - n * offsetsize + index * offsetsize - (offsetsize == 8 ? 8 : 0); offset = (int)NumberUtil.toLong(this.vpack, (int )(this.start + ieBase), offsetsize); } } } return offset; } /// <returns>the offset for the nth member from a compact Array or Object type</returns> private int getNthOffsetFromCompact(int index) { long end = NumberUtil.readVariableValueLength (this.vpack, this.start + 1, false); long n = NumberUtil.readVariableValueLength (this.vpack, (int)(this.start + end - 1), true); if (index >= n) { throw new System.IndexOutOfRangeException(); } byte head = head(); long offset = 1 + NumberUtil.getVariableValueLength (end); long current = 0; while (current != index) { long byteSize = new VPackSlice(this.vpack, (int)(this.start + offset )).getByteSize(); offset += byteSize; if (head == unchecked((int)0x14)) { offset += byteSize; } ++current; } return (int)offset; } private bool isEqualString(string s) { string @string = this.getAsString(); return @string.Equals(s); } private int compareString(string s) { string @string = this.getAsString(); return string.CompareOrdinal(@string, s); } public virtual System.Collections.Generic.IEnumerator<VPackSlice > arrayIterator() { if (this.isArray()) { return new ArrayIterator(this); } else { throw new VPackValueTypeException(ValueType .ARRAY); } } public virtual System.Collections.Generic.IEnumerator<KeyValuePair<string, VPackSlice>> objectIterator() { if (this.isObject()) { return new ObjectIterator(this); } else { throw new VPackValueTypeException(ValueType .OBJECT); } } protected internal virtual byte[] getRawVPack() { return java.util.Arrays.copyOfRange(this.vpack, this.start, this.start + this.getByteSize()); } public override string ToString() { try { return new VPackParser().toJson(this, true); } catch (VPackException) { return base.ToString(); } } public override int GetHashCode() { int prime = 31; int result = 1; result = prime * result + this.start; result = prime * result + java.util.Arrays.hashCode(this.getRawVPack()); return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (Sharpen.Runtime.getClassForObject(this) != Sharpen.Runtime.getClassForObject( obj)) { return false; } VPackSlice other = (VPackSlice)obj; if (this.start != other.start) { return false; } if (!java.util.Arrays.equals(this.getRawVPack(), other.getRawVPack())) { return false; } return true; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.IO; using System.Linq; using Gallio.Common.Collections; using Gallio.Runner.Reports; using Gallio.Runner.Reports.Schema; using Gallio.Runtime.Logging; using Gallio.Runtime.ProgressMonitoring; using Gallio.Model; using Gallio.Model.Filters; using Gallio.Common.Reflection; using Gallio.Runner; using MbUnit.Framework; using Gallio.NAntTasks; using NAnt.Core; using NAnt.Core.Types; namespace Gallio.NAntTasks.Tests { /// <summary> /// A set of unit tests for the <see cref="GallioTask" /> class (a custom Gallio task for NAnt). /// </summary> /// <remarks> /// <para> /// If you modify these tests please make sure to review the corresponding /// tests for the Gallio MSBuild task, since the both the tasks for NAnt and MSBuild /// should exhibit a similar behavior and features set. /// </para> /// </remarks> [TestFixture] [TestsOn(typeof(GallioTask))] [Category("UnitTests")] public class GallioTaskUnitTest { [Test] public void TaskPassesDefaultArgumentsToLauncher() { var task = new StubbedGallioTask(); task.SetRunLauncherAction(launcher => { Assert.IsFalse(launcher.DoNotRun); Assert.IsTrue(launcher.EchoResults); Assert.IsTrue(launcher.TestExecutionOptions.FilterSet.IsEmpty); Assert.AreEqual(LogSeverity.Important, ((FilteredLogger)launcher.Logger).MinSeverity); Assert.IsInstanceOfType(typeof(LogProgressMonitorProvider), launcher.ProgressMonitorProvider); Assert.AreEqual("Reports", launcher.TestProject.ReportDirectory); Assert.IsFalse(launcher.TestProject.IsReportDirectorySpecified); Assert.AreElementsEqual(new string[] { }, launcher.ReportFormats); Assert.AreEqual("test-report-{0}-{1}", launcher.TestProject.ReportNameFormat); Assert.IsFalse(launcher.TestProject.IsReportNameFormatSpecified); Assert.IsFalse(launcher.ShowReports); Assert.IsNull(launcher.RunTimeLimit); Assert.AreEqual(ReportArchive.Normal, launcher.TestProject.ReportArchive); Assert.AreEqual(StandardTestRunnerFactoryNames.IsolatedProcess, launcher.TestProject.TestRunnerFactoryName); Assert.IsFalse(launcher.TestProject.IsTestRunnerFactoryNameSpecified); Assert.Count(0, launcher.TestProject.TestRunnerExtensions); Assert.AreElementsEqual(new string[] { }, launcher.TestProject.TestRunnerExtensionSpecifications); Assert.IsNull(launcher.RuntimeSetup.ConfigurationFilePath); Assert.AreEqual(Path.GetDirectoryName(AssemblyUtils.GetAssemblyLocalPath(typeof(GallioTask).Assembly)), launcher.RuntimeSetup.RuntimePath); Assert.AreElementsEqual(new string[] { }, launcher.RuntimeSetup.PluginDirectories); Assert.AreElementsEqual(new string[] { }, from x in launcher.FilePatterns select x.ToString()); Assert.AreElementsEqual(new string[] { }, from x in launcher.TestProject.TestPackage.HintDirectories select x.ToString()); Assert.IsNull(launcher.TestProject.TestPackage.ApplicationBaseDirectory); Assert.IsFalse(launcher.TestProject.TestPackage.IsApplicationBaseDirectorySpecified); Assert.IsNull(launcher.TestProject.TestPackage.WorkingDirectory); Assert.IsFalse(launcher.TestProject.TestPackage.IsWorkingDirectorySpecified); Assert.IsFalse(launcher.TestProject.TestPackage.ShadowCopy); Assert.IsFalse(launcher.TestProject.TestPackage.IsShadowCopySpecified); Assert.IsNull(launcher.TestProject.TestPackage.DebuggerSetup); Assert.IsFalse(launcher.TestProject.TestPackage.IsDebuggerSetupSpecified); Assert.IsNull(launcher.TestProject.TestPackage.RuntimeVersion); Assert.IsFalse(launcher.TestProject.TestPackage.IsRuntimeVersionSpecified); Assert.AreEqual(new PropertySet(), launcher.TestRunnerOptions.Properties); Assert.AreEqual(new PropertySet(), launcher.ReportFormatterOptions.Properties); var result = new TestLauncherResult(new Report()); result.SetResultCode(ResultCode.Success); return result; }); Assert.DoesNotThrow(() => task.InternalExecute()); } [Test] public void TaskPassesSpecifiedArgumentsToLauncher() { var task = new StubbedGallioTask(); task.DoNotRun = true; task.EchoResults = false; task.Filter = "Type: SimpleTest"; task.ReportDirectory = "dir"; task.ReportTypes = "XML;Html"; task.ReportNameFormat = "report"; task.ShowReports = true; task.ReportArchive = "zip"; task.RunTimeLimit = 7200; // seconds task.Verbosity = Verbosity.Debug; task.RunnerType = StandardTestRunnerFactoryNames.Local; task.RunnerExtensions.Add(new Argument("DebugExtension,Gallio")); task.PluginDirectories = new DirSet[] { CreateDirSet("plugin") }; task.Files = new FileSet[] { CreateFileSet("assembly1"), CreateFileSet("assembly2") }; task.HintDirectories = new DirSet[] { CreateDirSet("hint1"), CreateDirSet("hint2") }; task.ApplicationBaseDirectory = "baseDir"; task.ShadowCopy = true; task.Debug = true; task.WorkingDirectory = "workingDir"; task.RuntimeVersion = "v4.0.30319"; task.RunnerProperties.AddRange(new[] { new Argument("RunnerOption1=RunnerValue1"), new Argument(" RunnerOption2 "), new Argument("RunnerOption3 = 'RunnerValue3'"), new Argument("RunnerOption4=\"'RunnerValue4'\"") }); task.ReportFormatterProperties.AddRange(new[] { new Argument("FormatterOption1=FormatterValue1"), new Argument(" FormatterOption2 "), new Argument("FormatterOption3 = 'FormatterValue3'"), new Argument("FormatterOption4=\"'FormatterValue4'\"") }); task.SetRunLauncherAction(launcher => { Assert.IsTrue(launcher.DoNotRun); Assert.IsFalse(launcher.EchoResults); Assert.AreEqual("Type: SimpleTest", launcher.TestExecutionOptions.FilterSet.ToFilterSetExpr()); Assert.AreEqual(LogSeverity.Debug, ((FilteredLogger)launcher.Logger).MinSeverity); Assert.IsInstanceOfType(typeof(LogProgressMonitorProvider), launcher.ProgressMonitorProvider); Assert.AreEqual("dir", launcher.TestProject.ReportDirectory); Assert.IsTrue(launcher.TestProject.IsReportDirectorySpecified); Assert.AreElementsEqual(new string[] { "XML", "Html" }, launcher.ReportFormats); Assert.AreEqual("report", launcher.TestProject.ReportNameFormat); Assert.IsTrue(launcher.TestProject.IsReportNameFormatSpecified); Assert.IsTrue(launcher.ShowReports); Assert.AreEqual(TimeSpan.FromMinutes(120), launcher.RunTimeLimit); Assert.AreEqual(ReportArchive.Zip, launcher.TestProject.ReportArchive); Assert.AreEqual(StandardTestRunnerFactoryNames.Local, launcher.TestProject.TestRunnerFactoryName); Assert.IsTrue(launcher.TestProject.IsTestRunnerFactoryNameSpecified); Assert.AreEqual(0, launcher.TestProject.TestRunnerExtensions.Count); Assert.AreElementsEqual(new[] { "DebugExtension,Gallio" }, launcher.TestProject.TestRunnerExtensionSpecifications); Assert.IsNull(launcher.RuntimeSetup.ConfigurationFilePath); Assert.AreEqual(Path.GetDirectoryName(AssemblyUtils.GetAssemblyLocalPath(typeof(GallioTask).Assembly)), launcher.RuntimeSetup.RuntimePath); Assert.AreElementsEqual(new[] { "plugin" }, launcher.RuntimeSetup.PluginDirectories); Assert.AreElementsEqual(new[] { "assembly1", "assembly2" }, from x in launcher.FilePatterns select x.ToString()); Assert.AreElementsEqual(new[] { "hint1", "hint2" }, from x in launcher.TestProject.TestPackage.HintDirectories select x.ToString()); Assert.AreEqual("baseDir", launcher.TestProject.TestPackage.ApplicationBaseDirectory.ToString()); Assert.IsTrue(launcher.TestProject.TestPackage.IsApplicationBaseDirectorySpecified); Assert.AreEqual("workingDir", launcher.TestProject.TestPackage.WorkingDirectory.ToString()); Assert.IsTrue(launcher.TestProject.TestPackage.IsWorkingDirectorySpecified); Assert.IsTrue(launcher.TestProject.TestPackage.ShadowCopy); Assert.IsTrue(launcher.TestProject.TestPackage.IsShadowCopySpecified); Assert.IsNotNull(launcher.TestProject.TestPackage.DebuggerSetup); Assert.IsTrue(launcher.TestProject.TestPackage.IsDebuggerSetupSpecified); Assert.AreEqual("v4.0.30319", launcher.TestProject.TestPackage.RuntimeVersion); Assert.IsTrue(launcher.TestProject.TestPackage.IsRuntimeVersionSpecified); Assert.AreEqual(new PropertySet() { { "RunnerOption1", "RunnerValue1" }, { "RunnerOption2", "" }, { "RunnerOption3", "RunnerValue3" }, { "RunnerOption4", "'RunnerValue4'" } }, launcher.TestRunnerOptions.Properties); Assert.AreEqual(new PropertySet() { { "FormatterOption1", "FormatterValue1" }, { "FormatterOption2", "" }, { "FormatterOption3", "FormatterValue3" }, { "FormatterOption4", "'FormatterValue4'" } }, launcher.ReportFormatterOptions.Properties); var result = new TestLauncherResult(new Report()); result.SetResultCode(ResultCode.NoTests); return result; }); Assert.DoesNotThrow(task.InternalExecute); } [Test] public void TaskExposesResultsReturnedByLauncher() { var task = new StubbedGallioTask(); task.ResultProperty = "ExitCode"; task.StatisticsPropertiesPrefix = "Stats."; task.SetRunLauncherAction(launcher => { var report = new Report(); report.TestPackageRun = new TestPackageRun(); report.TestPackageRun.Statistics.AssertCount = 42; report.TestPackageRun.Statistics.Duration = 1.5; report.TestPackageRun.Statistics.FailedCount = 5; report.TestPackageRun.Statistics.InconclusiveCount = 11; report.TestPackageRun.Statistics.PassedCount = 21; report.TestPackageRun.Statistics.SkippedCount = 1; report.TestPackageRun.Statistics.StepCount = 30; report.TestPackageRun.Statistics.TestCount = 28; var result = new TestLauncherResult(report); result.SetResultCode(ResultCode.Failure); return result; }); Assert.Throws<BuildException>(task.InternalExecute); Assert.AreEqual(ResultCode.Failure.ToString(), task.Properties["ExitCode"]); Assert.AreEqual("42", task.Properties["Stats.AssertCount"]); Assert.AreEqual("1.5", task.Properties["Stats.Duration"]); Assert.AreEqual("5", task.Properties["Stats.FailedCount"]); Assert.AreEqual("11", task.Properties["Stats.InconclusiveCount"]); Assert.AreEqual("21", task.Properties["Stats.PassedCount"]); Assert.AreEqual("1", task.Properties["Stats.SkippedCount"]); Assert.AreEqual("30", task.Properties["Stats.StepCount"]); Assert.AreEqual("28", task.Properties["Stats.TestCount"]); } [Test] public void FailOnErrorWhenSetToFalseCausesABuildExceptionToNotBeThrownOnFailures() { var task = new StubbedGallioTask(); task.FailOnError = false; task.SetRunLauncherAction(delegate { var result = new TestLauncherResult(new Report()); result.SetResultCode(ResultCode.Failure); return result; }); Assert.DoesNotThrow(task.InternalExecute); } [Test] public void ExceptionsCauseTheTaskToFailRegardlessOfFailOnError() { var task = new StubbedGallioTask(); task.FailOnError = false; task.SetRunLauncherAction(delegate { throw new Exception("Simulated error."); }); Assert.Throws<Exception>(task.InternalExecute); } private static DirSet CreateDirSet(string dirName) { var dirSet = new DirSet(); dirSet.DirectoryNames.Add(dirName); return dirSet; } private static FileSet CreateFileSet(string fileName) { var fileSet = new FileSet(); fileSet.FileNames.Add(fileName); return fileSet; } } }
// Copyright (c) .NET Foundation. 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.Buffers; using System.IO.Pipelines; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace HtcSharp.HttpModule.Core.Internal.Infrastructure.PipeWriterHelpers { // SourceTools-Start // Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Internal\Infrastructure\PipeWriterHelpers\ConcurrentPipeWriter.cs // Start-At-Remote-Line 12 // SourceTools-End /// <summary> /// Wraps a PipeWriter so you can start appending more data to the pipe prior to the previous flush completing. /// </summary> internal sealed class ConcurrentPipeWriter : PipeWriter { // The following constants were copied from https://github.com/dotnet/corefx/blob/de3902bb56f1254ec1af4bf7d092fc2c048734cc/src/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs // and the associated StreamPipeWriterOptions defaults. private const int InitialSegmentPoolSize = 4; // 16K private const int MaxSegmentPoolSize = 256; // 1MB private const int MinimumBufferSize = 4096; // 4K private static readonly Exception _successfullyCompletedSentinel = new Exception(); private readonly object _sync; private readonly PipeWriter _innerPipeWriter; private readonly MemoryPool<byte> _pool; private readonly BufferSegmentStack _bufferSegmentPool = new BufferSegmentStack(InitialSegmentPoolSize); private BufferSegment _head; private BufferSegment _tail; private Memory<byte> _tailMemory; private int _tailBytesBuffered; private long _bytesBuffered; // When _currentFlushTcs is null and _head/_tail is also null, the ConcurrentPipeWriter is in passthrough mode. // When the ConcurrentPipeWriter is not in passthrough mode, that could be for one of two reasons: // // 1. A flush of the _innerPipeWriter is in progress. // 2. Or the last flush of the _innerPipeWriter completed between external calls to GetMemory/Span() and Advance(). // // In either case, we need to manually append buffer segments until the loop in the current or next call to FlushAsync() // flushes all the buffers putting the ConcurrentPipeWriter back into passthrough mode. // The manual buffer appending logic is borrowed from corefx's StreamPipeWriter. private TaskCompletionSource<FlushResult> _currentFlushTcs; private bool _bufferedWritePending; // We're trusting the Http2FrameWriter and Http1OutputProducer to not call into the PipeWriter after calling Abort() or Complete(). // If an Abort() is called while a flush is in progress, we clean up after the next flush completes, and don't flush again. private bool _aborted; // If an Complete() is called while a flush is in progress, we clean up after the flush loop completes, and call Complete() on the inner PipeWriter. private Exception _completeException; public ConcurrentPipeWriter(PipeWriter innerPipeWriter, MemoryPool<byte> pool, object sync) { _innerPipeWriter = innerPipeWriter; _pool = pool; _sync = sync; } public override Memory<byte> GetMemory(int sizeHint = 0) { if (_currentFlushTcs == null && _head == null) { return _innerPipeWriter.GetMemory(sizeHint); } AllocateMemoryUnsynchronized(sizeHint); return _tailMemory; } public override Span<byte> GetSpan(int sizeHint = 0) { if (_currentFlushTcs == null && _head == null) { return _innerPipeWriter.GetSpan(sizeHint); } AllocateMemoryUnsynchronized(sizeHint); return _tailMemory.Span; } public override void Advance(int bytes) { if (_currentFlushTcs == null && _head == null) { _innerPipeWriter.Advance(bytes); return; } if ((uint) bytes > (uint) _tailMemory.Length) { ThrowArgumentOutOfRangeException(nameof(bytes)); } _tailBytesBuffered += bytes; _bytesBuffered += bytes; _tailMemory = _tailMemory.Slice(bytes); _bufferedWritePending = false; } public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default) { if (_currentFlushTcs != null) { return new ValueTask<FlushResult>(_currentFlushTcs.Task); } if (_bytesBuffered > 0) { CopyAndReturnSegmentsUnsynchronized(); } var flushTask = _innerPipeWriter.FlushAsync(cancellationToken); if (flushTask.IsCompletedSuccessfully) { if (_currentFlushTcs != null) { CompleteFlushUnsynchronized(flushTask.GetAwaiter().GetResult(), null); } return flushTask; } // Use a TCS instead of something custom so it can be awaited by multiple awaiters. _currentFlushTcs = new TaskCompletionSource<FlushResult>(TaskCreationOptions.RunContinuationsAsynchronously); var result = new ValueTask<FlushResult>(_currentFlushTcs.Task); // FlushAsyncAwaited clears the TCS prior to completing. Make sure to construct the ValueTask // from the TCS before calling FlushAsyncAwaited in case FlushAsyncAwaited completes inline. _ = FlushAsyncAwaited(flushTask, cancellationToken); return result; } private async Task FlushAsyncAwaited(ValueTask<FlushResult> flushTask, CancellationToken cancellationToken) { try { // This while (true) does look scary, but the real continuation condition is at the start of the loop // after the await, so the _sync lock can be acquired. while (true) { var flushResult = await flushTask; lock (_sync) { if (_bytesBuffered == 0 || _aborted) { CompleteFlushUnsynchronized(flushResult, null); return; } if (flushResult.IsCanceled) { // Complete anyone currently awaiting a flush with the canceled FlushResult since CancelPendingFlush() was called. _currentFlushTcs.SetResult(flushResult); // Reset _currentFlushTcs, so we don't enter passthrough mode while we're still flushing. _currentFlushTcs = new TaskCompletionSource<FlushResult>(TaskCreationOptions.RunContinuationsAsynchronously); } CopyAndReturnSegmentsUnsynchronized(); flushTask = _innerPipeWriter.FlushAsync(cancellationToken); } } } catch (Exception ex) { lock (_sync) { CompleteFlushUnsynchronized(default, ex); } } } public override void CancelPendingFlush() { // FlushAsyncAwaited never ignores a canceled FlushResult. _innerPipeWriter.CancelPendingFlush(); } // To return all the segments without completing the inner pipe, call Abort(). public override void Complete(Exception exception = null) { // Store the exception or sentinel in a field so that if a flush is ongoing, we call the // inner Complete() method with the correct exception or lack thereof once the flush loop ends. _completeException = exception ?? _successfullyCompletedSentinel; if (_currentFlushTcs == null) { if (_bytesBuffered > 0) { CopyAndReturnSegmentsUnsynchronized(); } CleanupSegmentsUnsynchronized(); _innerPipeWriter.Complete(exception); } } public void Abort() { _aborted = true; // If we're flushing, the cleanup will happen after the flush. if (_currentFlushTcs == null) { CleanupSegmentsUnsynchronized(); } } private void CleanupSegmentsUnsynchronized() { BufferSegment segment = _head; while (segment != null) { BufferSegment returnSegment = segment; segment = segment.NextSegment; returnSegment.ResetMemory(); } _head = null; _tail = null; _tailMemory = null; } private void CopyAndReturnSegmentsUnsynchronized() { // Update any buffered data _tail.End += _tailBytesBuffered; _tailBytesBuffered = 0; var segment = _head; while (segment != null) { _innerPipeWriter.Write(segment.Memory.Span); var returnSegment = segment; segment = segment.NextSegment; // We haven't reached the tail of the linked list yet, so we can always return the returnSegment. if (segment != null) { returnSegment.ResetMemory(); ReturnSegmentUnsynchronized(returnSegment); } } if (_bufferedWritePending) { // If an advance is pending, so is a flush, so the _tail segment should still get returned eventually. _head = _tail; } else { _tail.ResetMemory(); ReturnSegmentUnsynchronized(_tail); _head = _tail = null; } // Even if a non-passthrough call to Advance is pending, there a 0 bytes currently buffered. _bytesBuffered = 0; } private void CompleteFlushUnsynchronized(FlushResult flushResult, Exception flushEx) { // Ensure all blocks are returned prior to the last call to FlushAsync() completing. if (_completeException != null || _aborted) { CleanupSegmentsUnsynchronized(); } if (ReferenceEquals(_completeException, _successfullyCompletedSentinel)) { _innerPipeWriter.Complete(); } else if (_completeException != null) { _innerPipeWriter.Complete(_completeException); } if (flushEx != null) { _currentFlushTcs.SetException(flushEx); } else { _currentFlushTcs.SetResult(flushResult); } _currentFlushTcs = null; } // The methods below were copied from https://github.com/dotnet/corefx/blob/de3902bb56f1254ec1af4bf7d092fc2c048734cc/src/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs private void AllocateMemoryUnsynchronized(int sizeHint) { _bufferedWritePending = true; if (_head == null) { // We need to allocate memory to write since nobody has written before BufferSegment newSegment = AllocateSegmentUnsynchronized(sizeHint); // Set all the pointers _head = _tail = newSegment; _tailBytesBuffered = 0; } else { int bytesLeftInBuffer = _tailMemory.Length; if (bytesLeftInBuffer == 0 || bytesLeftInBuffer < sizeHint) { if (_tailBytesBuffered > 0) { // Flush buffered data to the segment _tail.End += _tailBytesBuffered; _tailBytesBuffered = 0; } BufferSegment newSegment = AllocateSegmentUnsynchronized(sizeHint); _tail.SetNext(newSegment); _tail = newSegment; } } } private BufferSegment AllocateSegmentUnsynchronized(int sizeHint) { BufferSegment newSegment = CreateSegmentUnsynchronized(); if (sizeHint <= _pool.MaxBufferSize) { // Use the specified pool if it fits newSegment.SetOwnedMemory(_pool.Rent(GetSegmentSize(sizeHint, _pool.MaxBufferSize))); } else { // We can't use the pool so allocate an array newSegment.SetUnownedMemory(new byte[sizeHint]); } _tailMemory = newSegment.AvailableMemory; return newSegment; } private BufferSegment CreateSegmentUnsynchronized() { if (_bufferSegmentPool.TryPop(out BufferSegment segment)) { return segment; } return new BufferSegment(); } private void ReturnSegmentUnsynchronized(BufferSegment segment) { if (_bufferSegmentPool.Count < MaxSegmentPoolSize) { _bufferSegmentPool.Push(segment); } } private static int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue) { // First we need to handle case where hint is smaller than minimum segment size sizeHint = Math.Max(MinimumBufferSize, sizeHint); // After that adjust it to fit into pools max buffer size var adjustedToMaximumSize = Math.Min(maxBufferSize, sizeHint); return adjustedToMaximumSize; } // Copied from https://github.com/dotnet/corefx/blob/de3902bb56f1254ec1af4bf7d092fc2c048734cc/src/System.Memory/src/System/ThrowHelper.cs private static void ThrowArgumentOutOfRangeException(string argumentName) { throw CreateArgumentOutOfRangeException(argumentName); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException(string argumentName) { return new ArgumentOutOfRangeException(argumentName); } } }
using System; using UnityEngine; using Random = UnityEngine.Random; namespace UnityStandardAssets.Vehicles.Car { [RequireComponent(typeof (CarController))] public class CarAIControl : MonoBehaviour { public enum BrakeCondition { NeverBrake, // the car simply accelerates at full throttle all the time. TargetDirectionDifference, // the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners. TargetDistance, // the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to // head for a stationary target and come to rest when it arrives there. } // This script provides input to the car controller in the same way that the user control script does. // As such, it is really 'driving' the car, with no special physics or animation tricks to make the car behave properly. // "wandering" is used to give the cars a more human, less robotic feel. They can waver slightly // in speed and direction while driving towards their target. [SerializeField] [Range(0, 1)] private float m_CautiousSpeedFactor = 0.05f; // percentage of max speed to use when being maximally cautious [SerializeField] [Range(0, 180)] private float m_CautiousMaxAngle = 50f; // angle of approaching corner to treat as warranting maximum caution [SerializeField] private float m_CautiousMaxDistance = 100f; // distance at which distance-based cautiousness begins [SerializeField] private float m_CautiousAngularVelocityFactor = 30f; // how cautious the AI should be when considering its own current angular velocity (i.e. easing off acceleration if spinning!) [SerializeField] private float m_SteerSensitivity = 0.05f; // how sensitively the AI uses steering input to turn to the desired direction [SerializeField] private float m_AccelSensitivity = 0.04f; // How sensitively the AI uses the accelerator to reach the current desired speed [SerializeField] private float m_BrakeSensitivity = 1f; // How sensitively the AI uses the brake to reach the current desired speed [SerializeField] private float m_LateralWanderDistance = 0f; // how far the car will wander laterally towards its target [SerializeField] private float m_LateralWanderSpeed = 0.1f; // how fast the lateral wandering will fluctuate [SerializeField] [Range(0, 1)] private float m_AccelWanderAmount = 0.1f; // how much the cars acceleration will wander [SerializeField] private float m_AccelWanderSpeed = 0.1f; // how fast the cars acceleration wandering will fluctuate [SerializeField] private BrakeCondition m_BrakeCondition = BrakeCondition.TargetDistance; // what should the AI consider when accelerating/braking? [SerializeField] private bool m_Driving; // whether the AI is currently actively driving or stopped. public Transform m_Target; // 'target' the target object to aim for. [SerializeField] private bool m_StopWhenTargetReached; // should we stop driving when we reach the target? [SerializeField] private float m_ReachTargetThreshold = 2; // proximity to target to consider we 'reached' it, and stop driving. private float m_RandomPerlin; // A random value for the car to base its wander on (so that AI cars don't all wander in the same pattern) private CarController m_CarController; // Reference to actual car controller we are controlling private float m_AvoidOtherCarTime; // time until which to avoid the car we recently collided with private float m_AvoidOtherCarSlowdown; // how much to slow down due to colliding with another car, whilst avoiding private float m_AvoidPathOffset; // direction (-1 or 1) in which to offset path to avoid other car, whilst avoiding private Rigidbody m_Rigidbody; private CarMainController main; private void Awake() { // get the car controller reference m_CarController = GetComponent<CarController>(); // give the random perlin a random value m_RandomPerlin = Random.value*100; m_Rigidbody = GetComponent<Rigidbody>(); main = GetComponent<CarMainController>(); } private float Bezier(float distance) { float t = 1 - (distance - 10) / 50; t = Mathf.Min(1, t); t = Mathf.Max(0, t); float D = 1; float A = 0.01f; float B = 0.7f; float C = 0.3f; return Mathf.Pow(1 - t, 3) * A + 3 * Mathf.Pow(1 - t, 2) * t * B + 3 * (1 - t) * Mathf.Pow(t, 2) * C + Mathf.Pow(t, 3) * D; } private float AdjustSpeedToFrontCar(float desiredSpeed) { Vector3 position; RaycastHit hit; int layerMask = 1 << 8; position = transform.position; position += transform.forward * 3; position += transform.up; if (Physics.Raycast(position, transform.forward, out hit, 60, layerMask)) { var mySpeed = m_CarController.CurrentSpeed; var frontCarSpeed = hit.rigidbody.GetComponent<CarController>().CurrentSpeed; var frontCarSpeedDiff = mySpeed - frontCarSpeed; if (hit.distance < 10) { desiredSpeed = 0; } else { desiredSpeed = Mathf.Min(desiredSpeed, m_CarController.MaxSpeed - frontCarSpeedDiff * Bezier(hit.distance)); } } return desiredSpeed; } private float AdjustSpeedToIntersection(float desiredSpeed) { Vertex vertex = main.GetPosition(); Vector3 position = vertex.transform.position; float distance = Vector3.Distance(transform.position, position); bool veryClose = distance < 10; if (!vertex.CanGo(transform.position, veryClose && m_CarController.CurrentSpeed > 10)) { if (veryClose) { desiredSpeed = 0; } else if (distance < 60) { desiredSpeed = Math.Min(desiredSpeed, m_CarController.MaxSpeed * (1.0f - Bezier(distance))); } } return desiredSpeed; } private void FixedUpdate() { if (m_Target == null || !m_Driving) { // Car should not be moving, // use handbrake to stop m_CarController.Move(0, 0, -1f, 1f); } else { Vector3 fwd = transform.forward; if (m_Rigidbody.velocity.magnitude > m_CarController.MaxSpeed*0.1f) { fwd = m_Rigidbody.velocity; } float desiredSpeed = m_CarController.MaxSpeed; // now it's time to decide if we should be slowing down... switch (m_BrakeCondition) { case BrakeCondition.TargetDirectionDifference: { // the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners. // check out the angle of our target compared to the current direction of the car float approachingCornerAngle = Vector3.Angle(m_Target.forward, fwd); // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle float spinningAngle = m_Rigidbody.angularVelocity.magnitude*m_CautiousAngularVelocityFactor; // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount float cautiousnessRequired = Mathf.InverseLerp(0, m_CautiousMaxAngle, Mathf.Max(spinningAngle, approachingCornerAngle)); desiredSpeed = Mathf.Lerp(m_CarController.MaxSpeed, m_CarController.MaxSpeed*m_CautiousSpeedFactor, cautiousnessRequired); break; } case BrakeCondition.TargetDistance: { // the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to // head for a stationary target and come to rest when it arrives there. // check out the distance to target Vector3 delta = m_Target.position - transform.position; float distanceCautiousFactor = Mathf.InverseLerp(m_CautiousMaxDistance, 0, delta.magnitude); // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle float spinningAngle = m_Rigidbody.angularVelocity.magnitude*m_CautiousAngularVelocityFactor; // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount float cautiousnessRequired = Mathf.Max( Mathf.InverseLerp(0, m_CautiousMaxAngle, spinningAngle), distanceCautiousFactor); desiredSpeed = Mathf.Lerp(m_CarController.MaxSpeed, m_CarController.MaxSpeed*m_CautiousSpeedFactor, cautiousnessRequired); break; } case BrakeCondition.NeverBrake: break; } // Evasive action due to collision with other cars: // our target position starts off as the 'real' target position Vector3 offsetTargetPos = m_Target.position; // if are we currently taking evasive action to prevent being stuck against another car: if (Time.time < m_AvoidOtherCarTime) { // slow down if necessary (if we were behind the other car when collision occured) desiredSpeed *= m_AvoidOtherCarSlowdown; // and veer towards the side of our path-to-target that is away from the other car offsetTargetPos += m_Target.right*m_AvoidPathOffset; } else { // no need for evasive action, we can just wander across the path-to-target in a random way, // which can help prevent AI from seeming too uniform and robotic in their driving offsetTargetPos += m_Target.right* (Mathf.PerlinNoise(Time.time*m_LateralWanderSpeed, m_RandomPerlin)*2 - 1)* m_LateralWanderDistance; } desiredSpeed = AdjustSpeedToFrontCar(desiredSpeed); desiredSpeed = AdjustSpeedToIntersection(desiredSpeed); //Debug.Log(desiredSpeed); if (desiredSpeed == 0) { m_CarController.Move(0, 0, -1f, 1f); return; } // use different sensitivity depending on whether accelerating or braking: float accelBrakeSensitivity = (desiredSpeed < m_CarController.CurrentSpeed) ? m_BrakeSensitivity : m_AccelSensitivity; // decide the actual amount of accel/brake input to achieve desired speed. float accel = Mathf.Clamp((desiredSpeed - m_CarController.CurrentSpeed)*accelBrakeSensitivity, -1, 1); // add acceleration 'wander', which also prevents AI from seeming too uniform and robotic in their driving // i.e. increasing the accel wander amount can introduce jostling and bumps between AI cars in a race accel *= (1 - m_AccelWanderAmount) + (Mathf.PerlinNoise(Time.time*m_AccelWanderSpeed, m_RandomPerlin)*m_AccelWanderAmount); // calculate the local-relative position of the target, to steer towards Vector3 localTarget = transform.InverseTransformPoint(offsetTargetPos); // work out the local angle towards the target float targetAngle = Mathf.Atan2(localTarget.x, localTarget.z)*Mathf.Rad2Deg; // get the amount of steering needed to aim the car towards the target float steer = Mathf.Clamp(targetAngle*m_SteerSensitivity, -1, 1)*Mathf.Sign(m_CarController.CurrentSpeed); // feed input to the car controller. m_CarController.Move(steer, accel, accel, 0f); // if appropriate, stop driving when we're close enough to the target. if (m_StopWhenTargetReached && localTarget.magnitude < m_ReachTargetThreshold) { m_Driving = false; } } } private void OnCollisionStay(Collision col) { // detect collision against other cars, so that we can take evasive action if (col.rigidbody != null) { var otherAI = col.rigidbody.GetComponent<CarAIControl>(); if (otherAI != null) { // we'll take evasive action for 1 second m_AvoidOtherCarTime = Time.time + 1; // but who's in front?... if (Vector3.Angle(transform.forward, otherAI.transform.position - transform.position) < 90) { // the other ai is in front, so it is only good manners that we ought to brake... m_AvoidOtherCarSlowdown = 0.5f; } else { // we're in front! ain't slowing down for anybody... m_AvoidOtherCarSlowdown = 1; } // both cars should take evasive action by driving along an offset from the path centre, // away from the other car var otherCarLocalDelta = transform.InverseTransformPoint(otherAI.transform.position); float otherCarAngle = Mathf.Atan2(otherCarLocalDelta.x, otherCarLocalDelta.z); m_AvoidPathOffset = m_LateralWanderDistance*-Mathf.Sign(otherCarAngle); } } } public void SetTarget(Transform target) { m_Target = target; m_Driving = true; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcsv = Google.Cloud.SecurityCenter.V1P1Beta1; using sys = System; namespace Google.Cloud.SecurityCenter.V1P1Beta1 { /// <summary>Resource name for the <c>OrganizationSettings</c> resource.</summary> public sealed partial class OrganizationSettingsName : gax::IResourceName, sys::IEquatable<OrganizationSettingsName> { /// <summary>The possible contents of <see cref="OrganizationSettingsName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>organizations/{organization}/organizationSettings</c>. /// </summary> Organization = 1, } private static gax::PathTemplate s_organization = new gax::PathTemplate("organizations/{organization}/organizationSettings"); /// <summary>Creates a <see cref="OrganizationSettingsName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="OrganizationSettingsName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static OrganizationSettingsName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new OrganizationSettingsName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="OrganizationSettingsName"/> with the pattern /// <c>organizations/{organization}/organizationSettings</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="OrganizationSettingsName"/> constructed from the provided ids. /// </returns> public static OrganizationSettingsName FromOrganization(string organizationId) => new OrganizationSettingsName(ResourceNameType.Organization, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="OrganizationSettingsName"/> with pattern /// <c>organizations/{organization}/organizationSettings</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="OrganizationSettingsName"/> with pattern /// <c>organizations/{organization}/organizationSettings</c>. /// </returns> public static string Format(string organizationId) => FormatOrganization(organizationId); /// <summary> /// Formats the IDs into the string representation of this <see cref="OrganizationSettingsName"/> with pattern /// <c>organizations/{organization}/organizationSettings</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="OrganizationSettingsName"/> with pattern /// <c>organizations/{organization}/organizationSettings</c>. /// </returns> public static string FormatOrganization(string organizationId) => s_organization.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId))); /// <summary> /// Parses the given resource name string into a new <see cref="OrganizationSettingsName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/organizationSettings</c></description></item> /// </list> /// </remarks> /// <param name="organizationSettingsName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="OrganizationSettingsName"/> if successful.</returns> public static OrganizationSettingsName Parse(string organizationSettingsName) => Parse(organizationSettingsName, false); /// <summary> /// Parses the given resource name string into a new <see cref="OrganizationSettingsName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/organizationSettings</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="organizationSettingsName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="OrganizationSettingsName"/> if successful.</returns> public static OrganizationSettingsName Parse(string organizationSettingsName, bool allowUnparsed) => TryParse(organizationSettingsName, allowUnparsed, out OrganizationSettingsName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="OrganizationSettingsName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/organizationSettings</c></description></item> /// </list> /// </remarks> /// <param name="organizationSettingsName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="OrganizationSettingsName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string organizationSettingsName, out OrganizationSettingsName result) => TryParse(organizationSettingsName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="OrganizationSettingsName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/organizationSettings</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="organizationSettingsName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="OrganizationSettingsName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string organizationSettingsName, bool allowUnparsed, out OrganizationSettingsName result) { gax::GaxPreconditions.CheckNotNull(organizationSettingsName, nameof(organizationSettingsName)); gax::TemplatedResourceName resourceName; if (s_organization.TryParseName(organizationSettingsName, out resourceName)) { result = FromOrganization(resourceName[0]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(organizationSettingsName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private OrganizationSettingsName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string organizationId = null) { Type = type; UnparsedResource = unparsedResourceName; OrganizationId = organizationId; } /// <summary> /// Constructs a new instance of a <see cref="OrganizationSettingsName"/> class from the component parts of /// pattern <c>organizations/{organization}/organizationSettings</c> /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> public OrganizationSettingsName(string organizationId) : this(ResourceNameType.Organization, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Organization</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string OrganizationId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.Organization: return s_organization.Expand(OrganizationId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as OrganizationSettingsName); /// <inheritdoc/> public bool Equals(OrganizationSettingsName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(OrganizationSettingsName a, OrganizationSettingsName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(OrganizationSettingsName a, OrganizationSettingsName b) => !(a == b); } public partial class OrganizationSettings { /// <summary> /// <see cref="gcsv::OrganizationSettingsName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::OrganizationSettingsName OrganizationSettingsName { get => string.IsNullOrEmpty(Name) ? null : gcsv::OrganizationSettingsName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AngularJS.App.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; using System.Text; using System.Threading.Tasks; using System.Threading; using VCM.Common.Log; using DAL; using System.Data; /// <summary> /// Summary description for MarketDataHub /// </summary> public class MarketDataHub : Hub { Service ws = new Service(); public void Send(string name, string message, string GUID, string ClientType) { string ConnectionIDSignalR = "0"; string ConnectionID = "0"; string UserID = "0"; string CustomerID = "0"; string UserMode = "0"; string SpecialImageID = "0"; string InstanceID = ""; string ProductID = "0"; string GroupName = ""; string actualUserID = "0"; string actualCustID = "0"; string username = ""; /*TruMID*/ string SwarmID = ""; try { ConnectionIDSignalR = Context.ConnectionId; string[] userInfoAry = message.Split('#'); if (userInfoAry.Length > 0) { actualUserID = userInfoAry[0]; actualCustID = userInfoAry[1]; if (userInfoAry.Length == 4) { SwarmID = userInfoAry[3]; } if (userInfoAry[2].Split('~').Length > 1) { UserMode = userInfoAry[2].Split('~')[0]; InstanceID = userInfoAry[2].Split('~')[1]; } else { UserMode = userInfoAry[2]; } } if (UserMode.Trim().ToLower() == "spe") { SpecialImageID = "sp1"; } else if (UserMode.Trim().ToLower() == "user") { UserID = userInfoAry[0]; } else if (UserMode.Trim().ToLower() == "cust") { CustomerID = userInfoAry[1]; } else if (UserMode.Trim().ToLower() == "conn") { ConnectionID = Context.ConnectionId; } if (AppsInfo.Instance._dirImgSID == null || AppsInfo.Instance._dirImgSID.Count == 0) { BeastImageSID(); } string eProductName = name; ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID[eProductName]); string[] ValidToken = null; if (InstanceID == "") { ValidToken = VCMComet.Instance.ValidateAuthToken(actualUserID, ClientType, GUID); if (ValidToken[0] == "False") { string eleID = "Send()^ConnectionID:" + ConnectionID + "^UserID:" + UserID + "^CustomerID:" + CustomerID + "^ConnectionIDSignalR:" + ConnectionIDSignalR + "^ClientType:" + ClientType + "^UserMode:" + UserMode + "^CalcName:" + eProductName; VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "alrt", "m", eleID, ValidToken[1], "AuthInvalid"); return; } username = ""; if (SwarmID != "") { username += "#" + SwarmID; } if (name == "vcm_calc_cmefuture") { if (SpecialImageID != "0") { //Thread.Sleep(2000); ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_cmefuture"]); SpecialImageID = "BI_CMEFuture1"; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); JoinGroup(GroupName); VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR, eProductName.ToString(), UserMode, username); //Thread.Sleep(2000); SpecialImageID = "BI_CMEFuture2"; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); JoinGroup(GroupName); VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR, eProductName.ToString(), UserMode, username); //Thread.Sleep(3000); SpecialImageID = "BI_CMEFuture3"; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); JoinGroup(GroupName); VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR, eProductName.ToString(), UserMode, username); //Thread.Sleep(4000); SpecialImageID = "BI_CMEFuture4"; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); JoinGroup(GroupName); VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR, eProductName.ToString(), UserMode, username); } else { ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_cmefuture"]); GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); JoinGroup(GroupName); VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR, eProductName.ToString(), UserMode, username); } } else { GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); JoinGroup(GroupName); VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR, eProductName.ToString(), UserMode, username); } //if (name == "vcm_calc_bond_depth_grid_excel" || name == "vcm_calc_bond_grid_Excel" || name == "vcm_calc_kcg_bonds_submit_order_excel" || name == "vcm_calc_excelshare")) if (AppsInfo.Instance.GetPropertyInfo(AppsInfo.Properties.IsGridImage, AppsInfo.Properties.SIF_Id, ProductID) == "1") { // this if condition is added because of we need to block submit last calc entry in database of these 3 calc // these calc is available in excel but not in web so. } else { ws.SubmitLastOpenCalc(Convert.ToInt64(actualUserID.Trim()), name, message); // Last Calc } // VCMComet.Instance.AddConnectionToDir(actualUserID, GUID, ConnectionIDSignalR, eProductName, ProductID); LogUtility.Info("MarketDataHub.cs", "Send()", "$$UserID:" + actualUserID + ":" + (int)OpenBeast.Utilities.SysLogEnum.CREATECALCULATOR + " $$Token:" + GUID + "$$ClientType:" + ClientType + "$$ConnectionID:" + ConnectionIDSignalR + "$$ImageName:" + eProductName + "$$ImageSIFID:" + ProductID + "$$ImageCreationTime:" + System.DateTime.Now); } else { ValidToken = VCMComet.Instance.ValidateAuthToken(userInfoAry[2].Split('~')[3], ClientType, GUID); if (ValidToken[0] == "False") { string eleID = "Send()^ConnectionID:" + ConnectionID + "^UserID:" + UserID + "^CustomerID:" + CustomerID + "^ConnectionIDSignalR:" + ConnectionIDSignalR + "^ClientType:" + ClientType + "^UserMode:" + UserMode + "^CalcName:" + eProductName; VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "alrt", "m", eleID, ValidToken[1], "AuthInvalid"); return; } if (userInfoAry[2].Split('~').Length >= 4) { username = userInfoAry[2].Split('~')[4]; } ConnectionID = userInfoAry[2].Split('~')[2]; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); JoinGroup(GroupName); VCMComet.Instance.connectToSharedBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR, eProductName.ToString(), InstanceID, username); //VCMComet.Instance.AddConnectionToDir(userInfoAry[2].Split('~')[3], GUID, ConnectionIDSignalR, eProductName, ProductID); LogUtility.Info("MarketDataHub.cs", "Send()", "$$UserID:" + "0" + ":" + (int)OpenBeast.Utilities.SysLogEnum.OPENSHAREDCALCULATOR + " $$Token:" + GUID + "$$ClientType:" + ClientType + "$$ConnectionID:" + ConnectionIDSignalR + "$$ImageName:" + eProductName + "$$ImageSIFID:" + ProductID + "$$ImageCreationTime:" + System.DateTime.Now); } //LogUtility.Info("MarketDataHub.cs", "Send()", "$$UserID:" + actualUserID + ":" + (int)OpenBeast.Utilities.SysLogEnum.CREATECALCULATOR + " $$Token:" + GUID + "$$ClientType:" + ClientType + "$$ConnectionID:" + ConnectionIDSignalR + "$$ImageName:" + eProductName + "$$ImageSIFID:" + ProductID + "$$ImageCreationTime:" + System.DateTime.Now); VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "", "m", "", ConnectionIDSignalR, "ConnectionIDSignalR"); string strlogDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID " + SpecialImageID + "; ConnectionIDSignalR :" + ConnectionIDSignalR + "; send "; LogUtility.Debug("MarketDataHub.cs", "Send()", strlogDesc); } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("MarketDataHub.cs:: Send :: " + errorMessage.ToString()); string strErrorDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID " + SpecialImageID + "; ConnectionIDSignalR :" + ConnectionIDSignalR + "; " + ex.Message; LogUtility.Error("MarketDataHub.cs", "Send()", strErrorDesc, ex); } } public void BeastImageSID() { try { AppsInfo.Instance._dirImgSID = new Dictionary<string, int>(); clsDAL objclsDAL = new clsDAL(false); DataSet dsImgSID = new DataSet(); dsImgSID = objclsDAL.GetBeastImageSID(); DataRow _dr; for (int index = 0; index < dsImgSID.Tables[0].Rows.Count; index++) { AppsInfo.Instance._dirImgSID.Add(Convert.ToString(dsImgSID.Tables[0].Rows[index]["AppName"]), Convert.ToInt32(dsImgSID.Tables[0].Rows[index]["BeastImageSID"])); _dr = AppsInfo.Instance._dtAppsInfo.NewRow(); _dr["App_Id"] = Convert.ToInt32(dsImgSID.Tables[0].Rows[index]["AppId"]); _dr["Reg_Id"] = Convert.ToInt32(dsImgSID.Tables[0].Rows[index]["RegId"]); _dr["SIF_Id"] = Convert.ToInt32(dsImgSID.Tables[0].Rows[index]["BeastImageSID"]); _dr["Name"] = Convert.ToString(dsImgSID.Tables[0].Rows[index]["AppName"]).Trim(); _dr["IsGridImage"] = Convert.ToInt32(dsImgSID.Tables[0].Rows[index]["IsGridImage"]); _dr["IsSharable"] = Convert.ToInt32(dsImgSID.Tables[0].Rows[index]["ISshareable"]); _dr["ShareExpirationTime"] = Convert.ToInt32(dsImgSID.Tables[0].Rows[index]["shareminitues"]); AppsInfo.Instance._dtAppsInfo.Rows.Add(_dr); //_dirImgExpirationTime } } catch (Exception ex) { LogUtility.Error("MarketDataHub.cs", "BeastImageSID()", "", ex); } } public void sharerequest(string name, string message, string userToShare, string senderEmail, string GUID, string ClientType) { string senderMessage = ""; string ConnectionIDSignalR = "0"; string ConnectionID = "0"; string UserID = "0"; string CustomerID = "0"; string UserMode = "0"; string SpecialImageID = "0"; string InstanceID = ""; long SenderID = 0; string ProductID = "0"; string GroupName = ""; // string AuthToken = ""; try { // AuthToken = ws.getAuthToken(userToShare, ClientType); ConnectionIDSignalR = Context.ConnectionId; string[] userInfoAry = message.Split('#'); if (userInfoAry.Length > 0) { UserMode = userInfoAry[2].Split('~')[0]; } if (UserMode.Trim().ToLower() == "spe") { SpecialImageID = "sp1"; } else if (UserMode.Trim().ToLower() == "user") { UserID = userInfoAry[0]; } else if (UserMode.Trim().ToLower() == "cust") { CustomerID = userInfoAry[1]; } else if (UserMode.Trim().ToLower() == "conn") { ConnectionID = Context.ConnectionId; } SenderID = Convert.ToInt64(userInfoAry[0]); // Definations.BeastImageAppID eProductName = (Definations.BeastImageAppID)Enum.Parse(typeof(Definations.BeastImageAppID), name); string eProductName = name; ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID[eProductName]); //int isAppSharable = Convert.ToInt32(AppsInfo.Instance.GetPropertyInfo(AppsInfo.Properties.IsSharable, AppsInfo.Properties.SIF_Id, ProductID)); //if (isAppSharable == 1) //{ int iExpirationTime = 0; iExpirationTime = Convert.ToInt32(AppsInfo.Instance.GetPropertyInfo(AppsInfo.Properties.ShareExpirationTime, AppsInfo.Properties.SIF_Id, ProductID)); GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); InstanceID = VCMComet.Instance.getImageInstanceID(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR, eProductName.ToString()); string shareStatusMsg = ""; if (userToShare.Trim().ToLower() == "bulkshare@thebeastapps.com#") { shareStatusMsg = ws.SubmitBeastCalcAutoUrlShare(SenderID, InstanceID, message + "~" + name + "~" + ConnectionID, "", userToShare, senderEmail, senderMessage, ClientType, GUID, iExpirationTime, true); } else { shareStatusMsg = ws.SubmitBeastCalcAutoUrlShare(SenderID, InstanceID, message + "~" + name + "~" + ConnectionID, "", userToShare, senderEmail, senderMessage, ClientType, GUID, iExpirationTime, false); } if (shareStatusMsg.Contains("#")) { if (shareStatusMsg.Split('#')[0] == "AuthInvalid") { string invalidmessage = "Session expired"; if (shareStatusMsg.Split('#')[1] == "Your session has expired. Please relogin") { invalidmessage = "Your session has expired"; } else if (shareStatusMsg.Split('#')[1] == "Authentication list is empty") { invalidmessage = "Token list is empty"; } string eleID = "sharerequest()^ConnectionID:" + ConnectionID + "^UserID:" + UserID + "^CustomerID:" + CustomerID + "^ConnectionIDSignalR:" + ConnectionIDSignalR + "^ClientType:" + ClientType + "^UserMode:" + UserMode + "^CalcName:" + eProductName + "^userToShare: " + userToShare + "^senderEmail:" + senderEmail + "^senderMessage:" + senderMessage; VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "alrt", "m", eleID, invalidmessage, "AuthInvalid"); } else if (shareStatusMsg.Split('#')[0] == "-1") { //No emails to share string invalidmessage = shareStatusMsg.Split('#')[1]; VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "alrt", "m", "", invalidmessage, ""); } } else { VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "alrt", "m", "", shareStatusMsg, ""); string strlogDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID :" + SpecialImageID + "; userToShare : " + userToShare + "; senderEmail :" + senderEmail + "; senderMessage :" + senderMessage + "; sharerequest "; LogUtility.Debug("MarketDataHub.cs", "sharerequest()", strlogDesc); if (!userToShare.Contains('#')) { userToShare = userToShare + "#"; } LogUtility.Info("MarketDataHub.cs", "sharerequest()", "$$UserID:" + SenderID + ":" + (int)OpenBeast.Utilities.SysLogEnum.SHARECALCULATOR + " $$Token:" + GUID + "$$ClientType:" + ClientType + "$$ConnectionID:" + ConnectionIDSignalR + "$$ImageName:" + eProductName + "$$ImageSIFID:" + ProductID + "$$SharedUser:" + userToShare + "$$SharedCalcTime:" + System.DateTime.Now); } //} //else //{ // string invalidmessage = "This App is not sharable !"; // VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "alrt", "m", "", invalidmessage, ""); // string strlogDesc = "Share request rejected from server. " + "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID :" + SpecialImageID + "; userToShare : " + userToShare + "; senderEmail :" + senderEmail + "; senderMessage :" + senderMessage + "; sharerequest "; // LogUtility.Info("MarketDataHub.cs", "sharerequest()", strlogDesc); //} } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("MarketDataHub.cs:: sharerequest :: " + errorMessage.ToString()); string strErrorDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID :" + SpecialImageID + "; userToShare : " + userToShare + "; senderEmail :" + senderEmail + "; " + ex.Message; LogUtility.Error("MarketDataHub.cs", "sharerequest()", strErrorDesc, ex); } } public void closeimage(string ImageName, string ConnectionID, string UserID, string CustomerID, string SpecialImageID) { try { string ProductID = "0"; if (ImageName.Contains(',')) { string[] ArrImagename = ImageName.Split(','); foreach (var item in ArrImagename) { if (AppsInfo.Instance._dirImgSID.ContainsKey(item)) { ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID[item]); BeastConn.Instance.CloseImageBeastConn(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID); } } } else { if (AppsInfo.Instance._dirImgSID.ContainsKey(ImageName)) { ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID[ImageName]); BeastConn.Instance.CloseImageBeastConn(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID); } } } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; //UtilityHandler.SendEmailForError("MarketDataHub.cs:: CloseImage :: " + errorMessage.ToString()); LogUtility.Error("MarketDataHub.cs", "CloseImage()", "", ex); } } public void closeimageForExcel(string ConnectionID, string UserID) { try { BeastConn.Instance.CloseInitiatorImageForExcel(ConnectionID, UserID); } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("MarketDataHub.cs:: closeimageForExcel :: " + errorMessage.ToString()); LogUtility.Error("MarketDataHub.cs", "closeimageForExcel()", "", ex); } } //public void joinGroupExplicit(string name, string message) //{ // try // { // string ConnectionIDSignalR = "0"; // string ConnectionID = "0"; // string UserID = "0"; // string CustomerID = "0"; // string UserMode = "0"; // string SpecialImageID = "0"; // string ProductID = "0"; // string GroupName = ""; // ConnectionIDSignalR = Context.ConnectionId; // string[] userInfoAry = message.Split('#'); // if (userInfoAry.Length > 0) // { // UserMode = userInfoAry[2]; // } // if (UserMode.Trim().ToLower() == "spe") // { // SpecialImageID = "sp1"; // } // else if (UserMode.Trim().ToLower() == "user") // { // UserID = userInfoAry[0]; // } // else if (UserMode.Trim().ToLower() == "cust") // { // CustomerID = userInfoAry[1]; // } // else if (UserMode.Trim().ToLower() == "conn") // { // ConnectionID = Context.ConnectionId; // } // Definations.BeastImageAppID eProductName = (Definations.BeastImageAppID)Enum.Parse(typeof(Definations.BeastImageAppID), name); // ProductID = Convert.ToString((int)eProductName); // if (name == Definations.BeastImageAppID.vcm_calc_cmefuture.ToString()) // { // if (SpecialImageID != "0") // { // ProductID = Convert.ToString((int)Definations.BeastImageAppID.vcm_calc_cmefuture); // SpecialImageID = "BI_CMEFuture1"; // GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); // JoinGroup(GroupName); // VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR); // SpecialImageID = "BI_CMEFuture2"; // GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); // JoinGroup(GroupName); // VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR); // SpecialImageID = "BI_CMEFuture3"; // GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); // JoinGroup(GroupName); // VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR); // SpecialImageID = "BI_CMEFuture4"; // GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); // JoinGroup(GroupName); // VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR); // } // else // { // ProductID = Convert.ToString((int)Definations.BeastImageAppID.vcm_calc_cmefuture); // GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); // JoinGroup(GroupName); // VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR); // } // } // else // { // GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); // JoinGroup(GroupName); // VCMComet.Instance.connectToBeastImage(GroupName, ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, ConnectionIDSignalR); // } // } // catch (Exception ex) // { // string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; // UtilityHandler.SendEmailForError("MarketDataHub.cs:: Send :: " + errorMessage.ToString()); // } //} public void unJoinGroupExplicit(string name, string message, string GUID, string ClientType) { string ConnectionIDSignalR = "0"; string ConnectionID = "0"; string UserID = "0"; string CustomerID = "0"; string UserMode = "0"; string SpecialImageID = "0"; string ProductID = "0"; string GroupName = ""; string[] ValidToken = null; try { ConnectionIDSignalR = Context.ConnectionId; string[] userInfoAry = message.Split('#'); if (userInfoAry.Length > 0) { UserMode = userInfoAry[2]; } if (UserMode.Trim().ToLower() == "spe") { SpecialImageID = "sp1"; } else if (UserMode.Trim().ToLower() == "user") { UserID = userInfoAry[0]; } else if (UserMode.Trim().ToLower() == "cust") { CustomerID = userInfoAry[1]; } else if (UserMode.Trim().ToLower() == "conn") { ConnectionID = ConnectionIDSignalR; } ValidToken = VCMComet.Instance.ValidateAuthToken(userInfoAry[0], ClientType, GUID); if (ValidToken[0] == "False") { string eleID = "unJoinGroupExplicit()^ConnectionID:" + ConnectionID + "^UserID:" + UserID + "^CustomerID:" + CustomerID + "^ConnectionIDSignalR:" + ConnectionIDSignalR + "^ClientType:" + ClientType + "^UserMode:" + UserMode + "^CalcName:" + name; VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "alrt", "m", eleID, ValidToken[1], "AuthInvalid"); return; } //Definations.BeastImageAppID eProductName = (Definations.BeastImageAppID)Enum.Parse(typeof(Definations.BeastImageAppID), name); string eProductName = name; ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID[eProductName]); if (name == "vcm_calc_cmefuture") { if (SpecialImageID != "0") { ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_cmefuture"]); SpecialImageID = "BI_CMEFuture1"; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); UnJoinGroup(GroupName, ConnectionIDSignalR); SpecialImageID = "BI_CMEFuture2"; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); UnJoinGroup(GroupName, ConnectionIDSignalR); SpecialImageID = "BI_CMEFuture3"; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); UnJoinGroup(GroupName, ConnectionIDSignalR); SpecialImageID = "BI_CMEFuture4"; GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); UnJoinGroup(GroupName, ConnectionIDSignalR); } else { ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID["vcm_calc_cmefuture"]); GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); UnJoinGroup(GroupName, ConnectionIDSignalR); } } else { GroupName = createGroupName(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, UserMode); UnJoinGroup(GroupName, ConnectionIDSignalR); } // VCMComet.Instance.SetImageClosingTime(userInfoAry[0], GUID, ConnectionIDSignalR, ProductID); string strlogDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; ConnectionIDSignalR :" + ConnectionIDSignalR + "; SpecialImageID :" + SpecialImageID + "; unJoinGroupExplicit "; LogUtility.Debug("MarketDataHub.cs", "unJoinGroupExplicit()", strlogDesc); LogUtility.Info("MarketDataHub.cs", "unJoinGroupExplicit()", "$$UserID:" + userInfoAry[0] + "$$Token:" + GUID + "$$ClientType:" + ClientType + "$$ConnectionID:" + ConnectionIDSignalR + "$$ImageName:" + eProductName + "$$ImageSIFID:" + ProductID + "$$ImageCloseTime:" + System.DateTime.Now); closeimage(eProductName, ConnectionID, UserID, CustomerID, SpecialImageID); } catch (Exception ex) { string errorMessage = ex.Message + "</br>" + ex.Source + "</br>" + ex.Source; UtilityHandler.SendEmailForError("MarketDataHub.cs:: unJoinGroupExplicit :: " + errorMessage.ToString()); string strErrorDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; ConnectionIDSignalR :" + ConnectionIDSignalR + "; SpecialImageID :" + SpecialImageID + "; " + ex.Message; LogUtility.Error("MarketDataHub.cs", "unJoinGroupExplicit()", strErrorDesc, ex); } } public void sendbeast(string name, string message, string GUID, string ClientType) { string ConnectionID = "0"; string UserID = "0"; string CustomerID = "0"; string UserMode = "0"; string SpecialImageID = "0"; string ProductID = "0"; string paraValues = name.Split('#')[1]; string paraName = name.Split('#')[0]; string InstanceID = ""; string connectionIDFromShareReq = ""; string ConnectionIDSignalR = "0"; string actualCustID = "0"; string eProductName = ""; string username = ""; try { ConnectionIDSignalR = Context.ConnectionId; string[] userInfoAry = paraValues.Split('^'); if (userInfoAry.Length > 0) { actualCustID = userInfoAry[0]; if (userInfoAry[2].Split('~').Length > 1) { UserMode = userInfoAry[2].Split('~')[0]; InstanceID = userInfoAry[2].Split('~')[1]; connectionIDFromShareReq = userInfoAry[2].Split('~')[2]; } else { UserMode = userInfoAry[2]; } } if (UserMode.Trim().ToLower() == "spe") { SpecialImageID = "sp1"; } else if (UserMode.Trim().ToLower() == "user") { UserID = userInfoAry[0]; } else if (UserMode.Trim().ToLower() == "cust") { CustomerID = userInfoAry[1]; } else if (UserMode.Trim().ToLower() == "conn") { if (connectionIDFromShareReq == "") ConnectionID = Context.ConnectionId; else ConnectionID = connectionIDFromShareReq; } string[] ValidToken = null; string SenderUserID = ""; if (userInfoAry[2].Split('~').Length > 3) { SenderUserID = userInfoAry[2].Split('~')[3]; } else { SenderUserID = actualCustID; } if (ClientType.Contains("!")) { username = ClientType.Split('!')[1]; ClientType = ClientType.Split('!')[0]; } if (userInfoAry[2].Split('~').Length >= 4) { username = userInfoAry[2].Split('~')[4]; } ValidToken = VCMComet.Instance.ValidateAuthToken(SenderUserID, ClientType, GUID); eProductName = paraName; ProductID = Convert.ToString(AppsInfo.Instance._dirImgSID[eProductName]); if (ValidToken[0] == "False") { string eleID = "sendbeast()^ConnectionID:" + ConnectionID + "^UserID:" + UserID + "^CustomerID:" + CustomerID + "^ConnectionIDSignalR:" + ConnectionIDSignalR + "^ClientType:" + ClientType + "^UserMode:" + UserMode + "^CalcName:" + paraName + "^$ImageName:" + eProductName + "^ImageSIFID:" + ProductID + "^senderDet:" + message.Split('#')[0] + "^parentId:" + message.Split('#')[1] + "^Value:" + message.Split('#')[2]; VCMComet.Instance.Send_Message_To_Client_Connection_Generic(ConnectionIDSignalR, "alrt", "m", eleID, ValidToken[1], "AuthInvalid"); return; } LogUtility.Info("MarketDataHub.cs", "sendbeast()", "$$UserID:" + SenderUserID + ":" + (int)OpenBeast.Utilities.SysLogEnum.CHANGECALCVALUE + " $$Token:" + GUID + "$$ClientType:" + ClientType + "$$ConnectionID:" + ConnectionIDSignalR + "$$ImageName:" + eProductName + "$$ImageSIFID:" + ProductID + "$$senderDet:" + message.Split('#')[0] + "$$parentId:" + message.Split('#')[1] + "$$Value:" + message.Split('#')[2] + "$$SendValueTime:" + System.DateTime.Now); //Definations.BeastImageAppID eProductName = (Definations.BeastImageAppID)Enum.Parse(typeof(Definations.BeastImageAppID), paraName); if (eProductName == "vcm_calc_ChatApp") { message = message + "|" + "(" + String.Format("{0:00}", System.DateTime.UtcNow.Hour) + ":" + String.Format("{0:00}", System.DateTime.UtcNow.Minute) + ")"; } VCMComet.Instance.setValueInBeastImage(ProductID, ConnectionID, UserID, CustomerID, SpecialImageID, paraName, message, eProductName.ToString(), username); // VCMComet.Instance.SetImageLastActivityTime(SenderUserID, GUID, ConnectionIDSignalR, ProductID); string strlogDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID :" + SpecialImageID + "; paraName" + paraName + "; sendbeast "; LogUtility.Debug("MarketDataHub.cs", "sendbeast()", strlogDesc); } catch (Exception ex) { string errorMessage = Convert.ToString(ex.Message) + "</br>" + ex.Source; UtilityHandler.SendEmailForError("MarketDataHub.cs:: sendbeast :: App=" + eProductName + " Error=" + errorMessage); string strErrorDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID :" + SpecialImageID + "; paraName" + paraName + "; " + ex.Message; LogUtility.Error("MarketDataHub.cs", "sendbeast()", strErrorDesc, ex); } } private string createGroupName(string ProductID, string ConnectionID, string UserID, string CustomerID, string SpecialImageID, string UserMode) { string grpName = ""; try { grpName = ProductID + "_" + ConnectionID + "_" + UserID + "_" + CustomerID + "_" + SpecialImageID; string strlogDesc = "ProductId: " + ProductID + "; UserId: " + UserID + "; CustomerId: " + CustomerID + "; ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID :" + SpecialImageID + "; createGroupName "; LogUtility.Info("MarketDataHub.cs", "createGroupName()", strlogDesc); } catch (Exception ex) { string strErrorDesc = "ProductId: " + ProductID + "; " + "UserId: " + UserID + "; " + "CustomerId: " + CustomerID + "; " + "ConnectionId: " + ConnectionID + "; UserMod : " + UserMode + "; SpecialImageID :" + SpecialImageID + "; " + ex.Message; LogUtility.Error("MarketDataHub.cs", "createGroupName()", strErrorDesc, ex); } return grpName; } //private void JoinGroup(string groupName) //{ // Groups.Add(Context.ConnectionId, groupName); //} public void JoinGroup(string groupName) { try { Groups.Add(Context.ConnectionId, groupName); string strlogDesc = "GroupName: " + groupName + "; ConnectionId: " + Context.ConnectionId + "; JoinGroup "; LogUtility.Info("MarketDataHub.cs", "JoinGroup()", strlogDesc); } catch (Exception ex) { string strErrorDesc = "GroupName: " + groupName + "; " + "ConnectionId: " + Context.ConnectionId + "; " + ex.Message; LogUtility.Error("MarketDataHub.cs", "JoinGroup()", strErrorDesc, ex); } } public void UnJoinGroup(string groupName, string ConnectionID) { try { Groups.Remove(ConnectionID, groupName); string strlogDesc = "GroupName: " + groupName + "; ConnectionId: " + ConnectionID + "; UnJoinGroup "; LogUtility.Info("MarketDataHub.cs", "UnJoinGroup()", strlogDesc); } catch (Exception ex) { string strErrorDesc = "GroupName: " + groupName + "; " + "ConnectionId: " + ConnectionID + "; " + ex.Message; LogUtility.Error("MarketDataHub.cs", "UnJoinGroup()", strErrorDesc, ex); } } public void Receive(string name, string message) { try { // Call the broadcastMessage method to update clients. Clients.All.handleIncomingMessageFromBeastSignalR("premdata", message); string strlogDesc = "name: " + name + "; message: " + message + "; Receive "; LogUtility.Info("MarketDataHub.cs", "Receive()", strlogDesc); } catch (Exception ex) { LogUtility.Error("MarketDataHub.cs", "Receive()", "Name: " + name + "; " + "Message: " + message + "; " + ex.Message, ex); } } public override Task OnConnected() { string ConnectionID = Context.ConnectionId; return null; } public override Task OnDisconnected(bool bDisconnectType) { //bDisconnectType = True : indicates whether it was due to a timeout. //bDisconnectType = False : indicates whether it was NOT due to a timeout. try { TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs excArgs) => { excArgs.SetObserved(); }; string ConnectionID = Context.ConnectionId; // VCMComet.Instance.deleteBeastImagesForConnectionID(ConnectionID); } catch (Exception ex) { LogUtility.Error("MarketDataHub.cs", "OnDisconnected()", "ConnectionId: " + Context.ConnectionId + "; " + ex.Message, ex); } return null; } #region LoadTest public void loadtesthub(string name, string message) { try { if (name == "joinloadtest") { Clients.Group("loadtestadmin").LoadTestAdmin(name, message); } else if (name == "loadtestadmin") { JoinGroup(name); } else { Clients.Group("loadtestadmin").LoadTestAdmin(name, message); } string strlogDesc = "name: " + name + "; message: " + message + "; loadtesthub "; LogUtility.Info("MarketDataHub.cs", "loadtesthub()", strlogDesc); } catch (Exception ex) { LogUtility.Error("MarketDataHub.cs", "loadtesthub()", "Name: " + name + "; " + "Message: " + message + "; " + ex.Message, ex); } } #endregion //public override Task OnReconnected() //{ // string ConnectionID = Context.ConnectionId; // return Clients.All.rejoined(Context.ConnectionId, DateTime.Now.ToString()); //} #region FullUpdate public void getfullupdate(string pAppName, string pConnectionId, string pUserId, string pCustomerId, string pSpecialImageId) { string pProductId = Convert.ToString(AppsInfo.Instance._dirImgSID[pAppName]); BeastConn.Instance.GetFullUpdate(pProductId, pConnectionId, pUserId, pCustomerId, pSpecialImageId); } #endregion }
// Copyright (C) 2014 dot42 // // Original filename: Junit.Framework.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Junit.Framework { /// <summary> /// <para>Thrown when an assert equals for Strings failed.</para><para>Inspired by a patch from Alex Chaffee </para> /// </summary> /// <java-name> /// junit/framework/ComparisonFailure /// </java-name> [Dot42.DexImport("junit/framework/ComparisonFailure", AccessFlags = 33)] public partial class ComparisonFailure : global::Junit.Framework.AssertionFailedError /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a comparison failure. </para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public ComparisonFailure(string message, string expected, string actual) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns "..." in place of common prefix and "..." in place of common suffix between expected and actual.</para><para><para>Throwable::getMessage() </para></para> /// </summary> /// <java-name> /// getMessage /// </java-name> [Dot42.DexImport("getMessage", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMessage() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Gets the actual string value </para> /// </summary> /// <returns> /// <para>the actual string value </para> /// </returns> /// <java-name> /// getActual /// </java-name> [Dot42.DexImport("getActual", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetActual() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Gets the expected string value </para> /// </summary> /// <returns> /// <para>the expected string value </para> /// </returns> /// <java-name> /// getExpected /// </java-name> [Dot42.DexImport("getExpected", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetExpected() /* MethodBuilder.Create */ { return default(string); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ComparisonFailure() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Gets the actual string value </para> /// </summary> /// <returns> /// <para>the actual string value </para> /// </returns> /// <java-name> /// getActual /// </java-name> public string Actual { [Dot42.DexImport("getActual", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetActual(); } } /// <summary> /// <para>Gets the expected string value </para> /// </summary> /// <returns> /// <para>the expected string value </para> /// </returns> /// <java-name> /// getExpected /// </java-name> public string Expected { [Dot42.DexImport("getExpected", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetExpected(); } } } /// <summary> /// <para>A <code>TestSuite</code> is a <code>Composite</code> of Tests. It runs a collection of test cases. Here is an example using the dynamic test definition. <pre> /// TestSuite suite= new TestSuite(); /// suite.addTest(new MathTest("testAdd")); /// suite.addTest(new MathTest("testDivideByZero")); /// </pre> </para><para>Alternatively, a TestSuite can extract the tests to be run automatically. To do so you pass the class of your TestCase class to the TestSuite constructor. <pre> /// TestSuite suite= new TestSuite(MathTest.class); /// </pre> </para><para>This constructor creates a suite with all the methods starting with "test" that take no arguments.</para><para>A final option is to do the same for a large array of test classes. <pre> /// Class[] testClasses = { MathTest.class, AnotherTest.class } /// TestSuite suite= new TestSuite(testClasses); /// </pre> </para><para><para>Test </para></para> /// </summary> /// <java-name> /// junit/framework/TestSuite /// </java-name> [Dot42.DexImport("junit/framework/TestSuite", AccessFlags = 33)] public partial class TestSuite : global::Junit.Framework.ITest /* scope: __dot42__ */ { /// <summary> /// <para>Constructs an empty TestSuite. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public TestSuite() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<*>;)V")] public TestSuite(global::System.Type type) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/Class;Ljava/lang/String;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<+Ljunit/framework/TestCase;>;Ljava/lang/String;)V")] public TestSuite(global::System.Type type, string @string) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public TestSuite(string @string) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "([Ljava/lang/Class;)V", AccessFlags = 129, Signature = "([Ljava/lang/Class<*>;)V")] public TestSuite(params global::System.Type[] type) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "([Ljava/lang/Class;Ljava/lang/String;)V", AccessFlags = 1, Signature = "([Ljava/lang/Class<+Ljunit/framework/TestCase;>;Ljava/lang/String;)V")] public TestSuite(global::System.Type[] type, string @string) /* MethodBuilder.Create */ { } /// <summary> /// <para>...as the moon sets over the early morning Merlin, Oregon mountains, our intrepid adventurers type... </para> /// </summary> /// <java-name> /// createTest /// </java-name> [Dot42.DexImport("createTest", "(Ljava/lang/Class;Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 9, Signature = "(Ljava/lang/Class<*>;Ljava/lang/String;)Ljunit/framework/Test;")] public static global::Junit.Framework.ITest CreateTest(global::System.Type theClass, string name) /* MethodBuilder.Create */ { return default(global::Junit.Framework.ITest); } /// <summary> /// <para>Gets a constructor which takes a single String as its argument or a no arg constructor. </para> /// </summary> /// <java-name> /// getTestConstructor /// </java-name> [Dot42.DexImport("getTestConstructor", "(Ljava/lang/Class;)Ljava/lang/reflect/Constructor;", AccessFlags = 9, Signature = "(Ljava/lang/Class<*>;)Ljava/lang/reflect/Constructor<*>;")] public static global::System.Reflection.ConstructorInfo GetTestConstructor(global::System.Type theClass) /* MethodBuilder.Create */ { return default(global::System.Reflection.ConstructorInfo); } /// <summary> /// <para>Returns a test which will fail and log a warning message. </para> /// </summary> /// <java-name> /// warning /// </java-name> [Dot42.DexImport("warning", "(Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 9)] public static global::Junit.Framework.ITest Warning(string message) /* MethodBuilder.Create */ { return default(global::Junit.Framework.ITest); } /// <summary> /// <para>Adds a test to the suite. </para> /// </summary> /// <java-name> /// addTest /// </java-name> [Dot42.DexImport("addTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)] public virtual void AddTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <summary> /// <para>Adds the tests from the given class to the suite </para> /// </summary> /// <java-name> /// addTestSuite /// </java-name> [Dot42.DexImport("addTestSuite", "(Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<+Ljunit/framework/TestCase;>;)V")] public virtual void AddTestSuite(global::System.Type testClass) /* MethodBuilder.Create */ { } /// <summary> /// <para>Counts the number of test cases that will be run by this test. </para> /// </summary> /// <java-name> /// countTestCases /// </java-name> [Dot42.DexImport("countTestCases", "()I", AccessFlags = 1)] public virtual int CountTestCases() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns the name of the suite. Not all test suites have a name and this method can return null. </para> /// </summary> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Runs the tests and collects their result in a TestResult. </para> /// </summary> /// <java-name> /// run /// </java-name> [Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)] public virtual void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */ { } /// <java-name> /// runTest /// </java-name> [Dot42.DexImport("runTest", "(Ljunit/framework/Test;Ljunit/framework/TestResult;)V", AccessFlags = 1)] public virtual void RunTest(global::Junit.Framework.ITest test, global::Junit.Framework.TestResult result) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets the name of the suite. </para> /// </summary> /// <java-name> /// setName /// </java-name> [Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetName(string name) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the test at the given index </para> /// </summary> /// <java-name> /// testAt /// </java-name> [Dot42.DexImport("testAt", "(I)Ljunit/framework/Test;", AccessFlags = 1)] public virtual global::Junit.Framework.ITest TestAt(int index) /* MethodBuilder.Create */ { return default(global::Junit.Framework.ITest); } /// <summary> /// <para>Returns the number of tests in this suite </para> /// </summary> /// <java-name> /// testCount /// </java-name> [Dot42.DexImport("testCount", "()I", AccessFlags = 1)] public virtual int TestCount() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns the tests as an enumeration </para> /// </summary> /// <java-name> /// tests /// </java-name> [Dot42.DexImport("tests", "()Ljava/util/Enumeration;", AccessFlags = 1, Signature = "()Ljava/util/Enumeration<Ljunit/framework/Test;>;")] public virtual global::Java.Util.IEnumeration<global::Junit.Framework.ITest> Tests() /* MethodBuilder.Create */ { return default(global::Java.Util.IEnumeration<global::Junit.Framework.ITest>); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the name of the suite. Not all test suites have a name and this method can return null. </para> /// </summary> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetName(); } [Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetName(value); } } } /// <summary> /// <para>A test case defines the fixture to run multiple tests. To define a test case<br></br> <ol><li><para>implement a subclass of <code>TestCase</code> </para></li><li><para>define instance variables that store the state of the fixture </para></li><li><para>initialize the fixture state by overriding setUp() </para></li><li><para>clean-up after a test by overriding tearDown(). </para></li></ol>Each test runs in its own fixture so there can be no side effects among test runs. Here is an example: <pre> /// public class MathTest extends TestCase { /// protected double fValue1; /// protected double fValue2; /// /// protected void setUp() { /// fValue1= 2.0; /// fValue2= 3.0; /// } /// } /// </pre></para><para>For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling junit.framework.Assert#assertTrue(String, boolean) with a boolean. <pre> /// public void testAdd() { /// double result= fValue1 + fValue2; /// assertTrue(result == 5.0); /// } /// </pre></para><para>Once the methods are defined you can run them. The framework supports both a static type safe and more dynamic way to run a test. In the static way you override the runTest method and define the method to be invoked. A convenient way to do so is with an anonymous inner class. <pre> /// TestCase test= new MathTest("add") { /// public void runTest() { /// testAdd(); /// } /// }; /// test.run(); /// </pre></para><para>The dynamic way uses reflection to implement runTest(). It dynamically finds and invokes a method. In this case the name of the test case has to correspond to the test method to be run. <pre> /// TestCase test= new MathTest("testAdd"); /// test.run(); /// </pre></para><para>The tests to be run can be collected into a TestSuite. JUnit provides different <b>test runners</b> which can run a test suite and collect the results. A test runner either expects a static method <code>suite</code> as the entry point to get a test to run or it will extract the suite automatically. <pre> /// public static Test suite() { /// suite.addTest(new MathTest("testAdd")); /// suite.addTest(new MathTest("testDivideByZero")); /// return suite; /// } /// </pre> <para>TestResult </para><simplesectsep></simplesectsep><para>TestSuite </para></para> /// </summary> /// <java-name> /// junit/framework/TestCase /// </java-name> [Dot42.DexImport("junit/framework/TestCase", AccessFlags = 1057)] public abstract partial class TestCase : global::Junit.Framework.Assert, global::Junit.Framework.ITest /* scope: __dot42__ */ { /// <summary> /// <para>No-arg constructor to enable serialization. This method is not intended to be used by mere mortals without calling setName(). </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public TestCase() /* MethodBuilder.Create */ { } /// <summary> /// <para>Constructs a test case with the given name. </para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public TestCase(string name) /* MethodBuilder.Create */ { } /// <summary> /// <para>Counts the number of test cases executed by run(TestResult result). </para> /// </summary> /// <java-name> /// countTestCases /// </java-name> [Dot42.DexImport("countTestCases", "()I", AccessFlags = 1)] public virtual int CountTestCases() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Creates a default TestResult object</para><para><para>TestResult </para></para> /// </summary> /// <java-name> /// createResult /// </java-name> [Dot42.DexImport("createResult", "()Ljunit/framework/TestResult;", AccessFlags = 4)] protected internal virtual global::Junit.Framework.TestResult CreateResult() /* MethodBuilder.Create */ { return default(global::Junit.Framework.TestResult); } /// <summary> /// <para>A convenience method to run this test, collecting the results with a default TestResult object.</para><para><para>TestResult </para></para> /// </summary> /// <java-name> /// run /// </java-name> [Dot42.DexImport("run", "()Ljunit/framework/TestResult;", AccessFlags = 1)] public virtual global::Junit.Framework.TestResult Run() /* MethodBuilder.Create */ { return default(global::Junit.Framework.TestResult); } /// <summary> /// <para>Runs the test case and collects the results in TestResult. </para> /// </summary> /// <java-name> /// run /// </java-name> [Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)] public virtual void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */ { } /// <summary> /// <para>Runs the bare test sequence. </para> /// </summary> /// <java-name> /// runBare /// </java-name> [Dot42.DexImport("runBare", "()V", AccessFlags = 1)] public virtual void RunBare() /* MethodBuilder.Create */ { } /// <summary> /// <para>Override to run the test and assert its state. </para> /// </summary> /// <java-name> /// runTest /// </java-name> [Dot42.DexImport("runTest", "()V", AccessFlags = 4)] protected internal virtual void RunTest() /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para> /// </summary> /// <java-name> /// setUp /// </java-name> [Dot42.DexImport("setUp", "()V", AccessFlags = 4)] protected internal virtual void SetUp() /* MethodBuilder.Create */ { } /// <summary> /// <para>Tears down the fixture, for example, close a network connection. This method is called after a test is executed. </para> /// </summary> /// <java-name> /// tearDown /// </java-name> [Dot42.DexImport("tearDown", "()V", AccessFlags = 4)] protected internal virtual void TearDown() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns a string representation of the test case </para> /// </summary> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Gets the name of a TestCase </para> /// </summary> /// <returns> /// <para>the name of the TestCase </para> /// </returns> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the name of a TestCase </para> /// </summary> /// <java-name> /// setName /// </java-name> [Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetName(string name) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the name of a TestCase </para> /// </summary> /// <returns> /// <para>the name of the TestCase </para> /// </returns> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetName(); } [Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetName(value); } } } /// <summary> /// <para>A <b>Protectable</b> can be run and can throw a Throwable.</para><para><para>TestResult </para></para> /// </summary> /// <java-name> /// junit/framework/Protectable /// </java-name> [Dot42.DexImport("junit/framework/Protectable", AccessFlags = 1537)] public partial interface IProtectable /* scope: __dot42__ */ { /// <summary> /// <para>Run the the following method protected. </para> /// </summary> /// <java-name> /// protect /// </java-name> [Dot42.DexImport("protect", "()V", AccessFlags = 1025)] void Protect() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Thrown when an assertion failed. </para> /// </summary> /// <java-name> /// junit/framework/AssertionFailedError /// </java-name> [Dot42.DexImport("junit/framework/AssertionFailedError", AccessFlags = 33)] public partial class AssertionFailedError : global::Java.Lang.AssertionError /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public AssertionFailedError() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public AssertionFailedError(string message) /* MethodBuilder.Create */ { } } /// <summary> /// <para>A <b>Test</b> can be run and collect its results.</para><para><para>TestResult </para></para> /// </summary> /// <java-name> /// junit/framework/Test /// </java-name> [Dot42.DexImport("junit/framework/Test", AccessFlags = 1537)] public partial interface ITest /* scope: __dot42__ */ { /// <summary> /// <para>Counts the number of test cases that will be run by this test. </para> /// </summary> /// <java-name> /// countTestCases /// </java-name> [Dot42.DexImport("countTestCases", "()I", AccessFlags = 1025)] int CountTestCases() /* MethodBuilder.Create */ ; /// <summary> /// <para>Runs a test and collects its result in a TestResult instance. </para> /// </summary> /// <java-name> /// run /// </java-name> [Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1025)] void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A set of assert methods. Messages are only displayed when an assert fails. </para> /// </summary> /// <java-name> /// junit/framework/Assert /// </java-name> [Dot42.DexImport("junit/framework/Assert", AccessFlags = 33)] public partial class Assert /* scope: __dot42__ */ { /// <summary> /// <para>Protect constructor since it is a static only class </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal Assert() /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that a condition is true. If it isn't it throws an AssertionFailedError with the given message. </para> /// </summary> /// <java-name> /// assertTrue /// </java-name> [Dot42.DexImport("assertTrue", "(Ljava/lang/String;Z)V", AccessFlags = 9)] public static void AssertTrue(string message, bool condition) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that a condition is true. If it isn't it throws an AssertionFailedError. </para> /// </summary> /// <java-name> /// assertTrue /// </java-name> [Dot42.DexImport("assertTrue", "(Z)V", AccessFlags = 9)] public static void AssertTrue(bool condition) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that a condition is false. If it isn't it throws an AssertionFailedError with the given message. </para> /// </summary> /// <java-name> /// assertFalse /// </java-name> [Dot42.DexImport("assertFalse", "(Ljava/lang/String;Z)V", AccessFlags = 9)] public static void AssertFalse(string message, bool condition) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that a condition is false. If it isn't it throws an AssertionFailedError. </para> /// </summary> /// <java-name> /// assertFalse /// </java-name> [Dot42.DexImport("assertFalse", "(Z)V", AccessFlags = 9)] public static void AssertFalse(bool condition) /* MethodBuilder.Create */ { } /// <summary> /// <para>Fails a test with the given message. </para> /// </summary> /// <java-name> /// fail /// </java-name> [Dot42.DexImport("fail", "(Ljava/lang/String;)V", AccessFlags = 9)] public static void Fail(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Fails a test with no message. </para> /// </summary> /// <java-name> /// fail /// </java-name> [Dot42.DexImport("fail", "()V", AccessFlags = 9)] public static void Fail() /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertEquals(string @string, object @object, object object1) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertEquals(object expected, object actual) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)] public static void AssertEquals(string @string, string string1, string string2) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)] public static void AssertEquals(string expected, string actual) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;DDD)V", AccessFlags = 9)] public static void AssertEquals(string @string, double @double, double double1, double double2) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(DDD)V", AccessFlags = 9)] public static void AssertEquals(double @double, double double1, double double2) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;FFF)V", AccessFlags = 9)] public static void AssertEquals(string @string, float single, float single1, float single2) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(FFF)V", AccessFlags = 9)] public static void AssertEquals(float single, float single1, float single2) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;JJ)V", AccessFlags = 9)] public static void AssertEquals(string @string, long int64, long int641) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(JJ)V", AccessFlags = 9)] public static void AssertEquals(long expected, long actual) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;ZZ)V", AccessFlags = 9)] public static void AssertEquals(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(ZZ)V", AccessFlags = 9)] public static void AssertEquals(bool expected, bool actual) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;BB)V", AccessFlags = 9)] public static void AssertEquals(string @string, sbyte sByte, sbyte sByte1) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;BB)V", AccessFlags = 9, IgnoreFromJava = true)] public static void AssertEquals(string @string, byte @byte, byte byte1) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(BB)V", AccessFlags = 9)] public static void AssertEquals(sbyte expected, sbyte actual) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(BB)V", AccessFlags = 9, IgnoreFromJava = true)] public static void AssertEquals(byte expected, byte actual) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;CC)V", AccessFlags = 9)] public static void AssertEquals(string @string, char @char, char char1) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(CC)V", AccessFlags = 9)] public static void AssertEquals(char expected, char actual) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;SS)V", AccessFlags = 9)] public static void AssertEquals(string @string, short int16, short int161) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(SS)V", AccessFlags = 9)] public static void AssertEquals(short expected, short actual) /* MethodBuilder.Create */ { } /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(Ljava/lang/String;II)V", AccessFlags = 9)] public static void AssertEquals(string @string, int int32, int int321) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two ints are equal. </para> /// </summary> /// <java-name> /// assertEquals /// </java-name> [Dot42.DexImport("assertEquals", "(II)V", AccessFlags = 9)] public static void AssertEquals(int expected, int actual) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that an object isn't null. </para> /// </summary> /// <java-name> /// assertNotNull /// </java-name> [Dot42.DexImport("assertNotNull", "(Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertNotNull(object @object) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that an object isn't null. If it is an AssertionFailedError is thrown with the given message. </para> /// </summary> /// <java-name> /// assertNotNull /// </java-name> [Dot42.DexImport("assertNotNull", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertNotNull(string message, object @object) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that an object is null. If it isn't an AssertionError is thrown. Message contains: Expected: &lt;null&gt; but was: object</para><para></para> /// </summary> /// <java-name> /// assertNull /// </java-name> [Dot42.DexImport("assertNull", "(Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertNull(object @object) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that an object is null. If it is not an AssertionFailedError is thrown with the given message. </para> /// </summary> /// <java-name> /// assertNull /// </java-name> [Dot42.DexImport("assertNull", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertNull(string message, object @object) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two objects refer to the same object. If they are not an AssertionFailedError is thrown with the given message. </para> /// </summary> /// <java-name> /// assertSame /// </java-name> [Dot42.DexImport("assertSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertSame(string message, object expected, object actual) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two objects refer to the same object. If they are not the same an AssertionFailedError is thrown. </para> /// </summary> /// <java-name> /// assertSame /// </java-name> [Dot42.DexImport("assertSame", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertSame(object expected, object actual) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown with the given message. </para> /// </summary> /// <java-name> /// assertNotSame /// </java-name> [Dot42.DexImport("assertNotSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertNotSame(string message, object expected, object actual) /* MethodBuilder.Create */ { } /// <summary> /// <para>Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown. </para> /// </summary> /// <java-name> /// assertNotSame /// </java-name> [Dot42.DexImport("assertNotSame", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)] public static void AssertNotSame(object expected, object actual) /* MethodBuilder.Create */ { } /// <java-name> /// failSame /// </java-name> [Dot42.DexImport("failSame", "(Ljava/lang/String;)V", AccessFlags = 9)] public static void FailSame(string message) /* MethodBuilder.Create */ { } /// <java-name> /// failNotSame /// </java-name> [Dot42.DexImport("failNotSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)] public static void FailNotSame(string message, object expected, object actual) /* MethodBuilder.Create */ { } /// <java-name> /// failNotEquals /// </java-name> [Dot42.DexImport("failNotEquals", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)] public static void FailNotEquals(string message, object expected, object actual) /* MethodBuilder.Create */ { } /// <java-name> /// format /// </java-name> [Dot42.DexImport("format", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/String;", AccessFlags = 9)] public static string Format(string message, object expected, object actual) /* MethodBuilder.Create */ { return default(string); } } /// <summary> /// <para>A Listener for test progress </para> /// </summary> /// <java-name> /// junit/framework/TestListener /// </java-name> [Dot42.DexImport("junit/framework/TestListener", AccessFlags = 1537)] public partial interface ITestListener /* scope: __dot42__ */ { /// <summary> /// <para>An error occurred. </para> /// </summary> /// <java-name> /// addError /// </java-name> [Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1025)] void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>A failure occurred. </para> /// </summary> /// <java-name> /// addFailure /// </java-name> [Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 1025)] void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */ ; /// <summary> /// <para>A test ended. </para> /// </summary> /// <java-name> /// endTest /// </java-name> [Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 1025)] void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ ; /// <summary> /// <para>A test started. </para> /// </summary> /// <java-name> /// startTest /// </java-name> [Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 1025)] void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A <code>TestFailure</code> collects a failed test together with the caught exception. <para>TestResult </para></para> /// </summary> /// <java-name> /// junit/framework/TestFailure /// </java-name> [Dot42.DexImport("junit/framework/TestFailure", AccessFlags = 33)] public partial class TestFailure /* scope: __dot42__ */ { /// <java-name> /// fFailedTest /// </java-name> [Dot42.DexImport("fFailedTest", "Ljunit/framework/Test;", AccessFlags = 4)] protected internal global::Junit.Framework.ITest FFailedTest; /// <java-name> /// fThrownException /// </java-name> [Dot42.DexImport("fThrownException", "Ljava/lang/Throwable;", AccessFlags = 4)] protected internal global::System.Exception FThrownException; /// <summary> /// <para>Constructs a TestFailure with the given test and exception. </para> /// </summary> [Dot42.DexImport("<init>", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1)] public TestFailure(global::Junit.Framework.ITest failedTest, global::System.Exception thrownException) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the failed test. </para> /// </summary> /// <java-name> /// failedTest /// </java-name> [Dot42.DexImport("failedTest", "()Ljunit/framework/Test;", AccessFlags = 1)] public virtual global::Junit.Framework.ITest FailedTest() /* MethodBuilder.Create */ { return default(global::Junit.Framework.ITest); } /// <summary> /// <para>Gets the thrown exception. </para> /// </summary> /// <java-name> /// thrownException /// </java-name> [Dot42.DexImport("thrownException", "()Ljava/lang/Throwable;", AccessFlags = 1)] public virtual global::System.Exception ThrownException() /* MethodBuilder.Create */ { return default(global::System.Exception); } /// <summary> /// <para>Returns a short description of the failure. </para> /// </summary> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// trace /// </java-name> [Dot42.DexImport("trace", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string Trace() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// exceptionMessage /// </java-name> [Dot42.DexImport("exceptionMessage", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string ExceptionMessage() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// isFailure /// </java-name> [Dot42.DexImport("isFailure", "()Z", AccessFlags = 1)] public virtual bool IsFailure() /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal TestFailure() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>A <code>TestResult</code> collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between <b>failures</b> and <b>errors</b>. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException.</para><para><para>Test </para></para> /// </summary> /// <java-name> /// junit/framework/TestResult /// </java-name> [Dot42.DexImport("junit/framework/TestResult", AccessFlags = 33)] public partial class TestResult /* scope: __dot42__ */ { /// <java-name> /// fFailures /// </java-name> [Dot42.DexImport("fFailures", "Ljava/util/Vector;", AccessFlags = 4)] protected internal global::Java.Util.Vector<global::Junit.Framework.TestFailure> FFailures; /// <java-name> /// fErrors /// </java-name> [Dot42.DexImport("fErrors", "Ljava/util/Vector;", AccessFlags = 4)] protected internal global::Java.Util.Vector<global::Junit.Framework.TestFailure> FErrors; /// <java-name> /// fListeners /// </java-name> [Dot42.DexImport("fListeners", "Ljava/util/Vector;", AccessFlags = 4)] protected internal global::Java.Util.Vector<global::Junit.Framework.ITestListener> FListeners; /// <java-name> /// fRunTests /// </java-name> [Dot42.DexImport("fRunTests", "I", AccessFlags = 4)] protected internal int FRunTests; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public TestResult() /* MethodBuilder.Create */ { } /// <summary> /// <para>Adds an error to the list of errors. The passed in exception caused the error. </para> /// </summary> /// <java-name> /// addError /// </java-name> [Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 33)] public virtual void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ { } /// <summary> /// <para>Adds a failure to the list of failures. The passed in exception caused the failure. </para> /// </summary> /// <java-name> /// addFailure /// </java-name> [Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 33)] public virtual void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */ { } /// <summary> /// <para>Registers a TestListener </para> /// </summary> /// <java-name> /// addListener /// </java-name> [Dot42.DexImport("addListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 33)] public virtual void AddListener(global::Junit.Framework.ITestListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Unregisters a TestListener </para> /// </summary> /// <java-name> /// removeListener /// </java-name> [Dot42.DexImport("removeListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 33)] public virtual void RemoveListener(global::Junit.Framework.ITestListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Informs the result that a test was completed. </para> /// </summary> /// <java-name> /// endTest /// </java-name> [Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)] public virtual void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the number of detected errors. </para> /// </summary> /// <java-name> /// errorCount /// </java-name> [Dot42.DexImport("errorCount", "()I", AccessFlags = 33)] public virtual int ErrorCount() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns an Enumeration for the errors </para> /// </summary> /// <java-name> /// errors /// </java-name> [Dot42.DexImport("errors", "()Ljava/util/Enumeration;", AccessFlags = 33, Signature = "()Ljava/util/Enumeration<Ljunit/framework/TestFailure;>;")] public virtual global::Java.Util.IEnumeration<global::Junit.Framework.TestFailure> Errors() /* MethodBuilder.Create */ { return default(global::Java.Util.IEnumeration<global::Junit.Framework.TestFailure>); } /// <summary> /// <para>Gets the number of detected failures. </para> /// </summary> /// <java-name> /// failureCount /// </java-name> [Dot42.DexImport("failureCount", "()I", AccessFlags = 33)] public virtual int FailureCount() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns an Enumeration for the failures </para> /// </summary> /// <java-name> /// failures /// </java-name> [Dot42.DexImport("failures", "()Ljava/util/Enumeration;", AccessFlags = 33, Signature = "()Ljava/util/Enumeration<Ljunit/framework/TestFailure;>;")] public virtual global::Java.Util.IEnumeration<global::Junit.Framework.TestFailure> Failures() /* MethodBuilder.Create */ { return default(global::Java.Util.IEnumeration<global::Junit.Framework.TestFailure>); } /// <summary> /// <para>Runs a TestCase. </para> /// </summary> /// <java-name> /// run /// </java-name> [Dot42.DexImport("run", "(Ljunit/framework/TestCase;)V", AccessFlags = 4)] protected internal virtual void Run(global::Junit.Framework.TestCase test) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the number of run tests. </para> /// </summary> /// <java-name> /// runCount /// </java-name> [Dot42.DexImport("runCount", "()I", AccessFlags = 33)] public virtual int RunCount() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Runs a TestCase. </para> /// </summary> /// <java-name> /// runProtected /// </java-name> [Dot42.DexImport("runProtected", "(Ljunit/framework/Test;Ljunit/framework/Protectable;)V", AccessFlags = 1)] public virtual void RunProtected(global::Junit.Framework.ITest test, global::Junit.Framework.IProtectable p) /* MethodBuilder.Create */ { } /// <summary> /// <para>Checks whether the test run should stop </para> /// </summary> /// <java-name> /// shouldStop /// </java-name> [Dot42.DexImport("shouldStop", "()Z", AccessFlags = 33)] public virtual bool ShouldStop() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Informs the result that a test will be started. </para> /// </summary> /// <java-name> /// startTest /// </java-name> [Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)] public virtual void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <summary> /// <para>Marks that the test run should stop. </para> /// </summary> /// <java-name> /// stop /// </java-name> [Dot42.DexImport("stop", "()V", AccessFlags = 33)] public virtual void Stop() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns whether the entire test was successful or not. </para> /// </summary> /// <java-name> /// wasSuccessful /// </java-name> [Dot42.DexImport("wasSuccessful", "()Z", AccessFlags = 33)] public virtual bool WasSuccessful() /* MethodBuilder.Create */ { return default(bool); } } }
using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; using Java.Lang; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace CustomBalloon { public class MyBalloonView : View { private readonly Regex re = new Regex(@"\:(\w+)\:", RegexOptions.Compiled); private readonly Dictionary<string, int> _emojis = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) { { "grin", 0x1F601 }, { "joy", 0x1F602 }, { "smile", 0x1F603 }, { "smiling", 0x1F604 }, { "sweat_smile", 0x1F605 }, { "laugh", 0x1F606 } }; private readonly List<string> monkeyPhrases = new List<string>() { "Xamarin Evolve rocks my rainbow socks!", "Have you visited the Darwin Lounge?", "Is Woz in the house?", "What's in your swag bag?", "I learned a lot this week!", "Did you get a selfie with James?", "How much coffee did you drink today?", "I'm ready to create awesome apps!", "A banana split would be good right now" }; private Paint _textPaint; private Paint _backgroundPaint; private bool _showEmojis; private string _text; private float _textSize; private int _triangleHeight; private Color _balloonColor; private Color _textColor; private Color _accentColor; private bool _useAccentColor; //at a minimum you must provide a constructor that takes a Context and an AttributeSet object as parameters public MyBalloonView(Context context, IAttributeSet attrs) : base(context, attrs) { InitializePaint(); } public string Text { get { return _text; } set { _text = FormatText(value); InvalidateAndRedraw(); } } public float TextSize { get { return _textSize; } set { _textSize = value; _textPaint.TextSize = _textSize; InvalidateAndRedraw(); } } public bool ShowEmojis { get { return _showEmojis; } set { _showEmojis = value; InvalidateAndRedraw(); } } public Color AccentColor { get { return _accentColor; } set { _accentColor = value; InvalidateAndRedraw(); } } public Color BalloonColor { get { return _balloonColor; } set { _balloonColor = value; InvalidateAndRedraw(); } } public Color TextColor { get { return _textColor; } set { _textColor = value; _textPaint.Color = _textColor; InvalidateAndRedraw(); } } public int TriangleHeight { get { return _triangleHeight; } set { _triangleHeight = value; InvalidateAndRedraw(); } } public override bool OnTouchEvent(MotionEvent e) { _useAccentColor = (e.Action == MotionEventActions.Down); if (e.Action == MotionEventActions.Up) { this.Text = GetRandomPhrase(); } InvalidateAndRedraw(); return true; } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); float textMeasurement = _textPaint.MeasureText(this.Text); SetMeasuredDimension((int)textMeasurement + 50, MeasuredHeight); } protected override void OnDraw(Canvas canvas) { _backgroundPaint.Color = (_useAccentColor) ? AccentColor : BalloonColor; float textMeasurement = _textPaint.MeasureText(this.Text); float balloonCenterX = MeasuredWidth / 2; int triangleStart = 80; RectF r = new RectF(0, 0, MeasuredWidth, MeasuredHeight - TriangleHeight); canvas.DrawRoundRect(r, 30f, 30f, _backgroundPaint); Point startingPoint = new Point(triangleStart, (int)r.Bottom); Point firstLine = new Point(triangleStart, MeasuredHeight); Point secondLine = new Point(triangleStart - (TriangleHeight / 2), MeasuredHeight - TriangleHeight); Path path = new Path(); path.MoveTo(startingPoint.X, startingPoint.Y); path.LineTo(firstLine.X, firstLine.Y); path.LineTo(secondLine.X, secondLine.Y); float textX = balloonCenterX - textMeasurement / 2; float textY = MeasuredHeight / 2; canvas.DrawPath(path, _backgroundPaint); canvas.DrawText(this.Text, textX, textY, _textPaint); } private void InvalidateAndRedraw() { Invalidate(); RequestLayout(); } private string FormatText(string text) { string formattedText = text; if (ShowEmojis && !string.IsNullOrEmpty(text)) { formattedText = re.Replace(text, match => GetEmoji(match.Groups[1].Value, match.Value)); } return formattedText; } private string GetEmoji(string key, string originalText) { string emojified = _emojis.ContainsKey(key) ? new string(Character.ToChars(_emojis[key])) : originalText; return emojified; } private string GetRandomPhrase() { int maxValue = monkeyPhrases.Count - 1; int maxEmojiValue = _emojis.Count - 1; Random randomPhrase = new Random(); int randomIndex = randomPhrase.Next(0, maxValue); string phrase = monkeyPhrases.ElementAt(randomIndex); Random randomEmoji = new Random(); int randomEmojiIndex = randomEmoji.Next(0, maxEmojiValue); string emoji = _emojis.Keys.ElementAt(randomEmojiIndex); return $"{phrase} :{emoji}:"; } private void InitializePaint() { _textPaint = new Paint(); _backgroundPaint = new Paint(); } } }
#if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2) #define SupportCustomYieldInstruction #endif using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using UniRx.InternalUtil; using UnityEngine; namespace UniRx { public sealed class MainThreadDispatcher : MonoBehaviour { public enum CullingMode { /// <summary> /// Won't remove any MainThreadDispatchers. /// </summary> Disabled, /// <summary> /// Checks if there is an existing MainThreadDispatcher on Awake(). If so, the new dispatcher removes itself. /// </summary> Self, /// <summary> /// Search for excess MainThreadDispatchers and removes them all on Awake(). /// </summary> All } public static CullingMode cullingMode = CullingMode.Self; #if UNITY_EDITOR // In UnityEditor's EditorMode can't instantiate and work MonoBehaviour.Update. // EditorThreadDispatcher use EditorApplication.update instead of MonoBehaviour.Update. class EditorThreadDispatcher { static object gate = new object(); static EditorThreadDispatcher instance; public static EditorThreadDispatcher Instance { get { // Activate EditorThreadDispatcher is dangerous, completely Lazy. lock (gate) { if (instance == null) { instance = new EditorThreadDispatcher(); } return instance; } } } ThreadSafeQueueWorker editorQueueWorker = new ThreadSafeQueueWorker(); EditorThreadDispatcher() { UnityEditor.EditorApplication.update += Update; } public void Enqueue(Action<object> action, object state) { editorQueueWorker.Enqueue(action, state); } public void UnsafeInvoke(Action action) { try { action(); } catch (Exception ex) { Debug.LogException(ex); } } public void UnsafeInvoke<T>(Action<T> action, T state) { try { action(state); } catch (Exception ex) { Debug.LogException(ex); } } public void PseudoStartCoroutine(IEnumerator routine) { editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); } void Update() { editorQueueWorker.ExecuteAll(x => Debug.LogException(x)); } void ConsumeEnumerator(IEnumerator routine) { if (routine.MoveNext()) { var current = routine.Current; if (current == null) { goto ENQUEUE; } var type = current.GetType(); if (type == typeof(WWW)) { var www = (WWW)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitWWW(www, routine)), null); return; } else if (type == typeof(AsyncOperation)) { var asyncOperation = (AsyncOperation)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitAsyncOperation(asyncOperation, routine)), null); return; } else if (type == typeof(WaitForSeconds)) { var waitForSeconds = (WaitForSeconds)current; var accessor = typeof(WaitForSeconds).GetField("m_Seconds", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic); var second = (float)accessor.GetValue(waitForSeconds); editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitForSeconds(second, routine)), null); return; } else if (type == typeof(Coroutine)) { Debug.Log("Can't wait coroutine on UnityEditor"); goto ENQUEUE; } #if SupportCustomYieldInstruction else if (current is IEnumerator) { var enumerator = (IEnumerator)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapEnumerator(enumerator, routine)), null); return; } #endif ENQUEUE: editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); // next update } } IEnumerator UnwrapWaitWWW(WWW www, IEnumerator continuation) { while (!www.isDone) { yield return null; } ConsumeEnumerator(continuation); } IEnumerator UnwrapWaitAsyncOperation(AsyncOperation asyncOperation, IEnumerator continuation) { while (!asyncOperation.isDone) { yield return null; } ConsumeEnumerator(continuation); } IEnumerator UnwrapWaitForSeconds(float second, IEnumerator continuation) { var startTime = DateTimeOffset.UtcNow; while (true) { yield return null; var elapsed = (DateTimeOffset.UtcNow - startTime).TotalSeconds; if (elapsed >= second) { break; } }; ConsumeEnumerator(continuation); } IEnumerator UnwrapEnumerator(IEnumerator enumerator, IEnumerator continuation) { while (enumerator.MoveNext()) { yield return null; } ConsumeEnumerator(continuation); } } #endif /// <summary>Dispatch Asyncrhonous action.</summary> public static void Post(Action<object> action, object state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; } #endif var dispatcher = Instance; if (!isQuitting && !object.ReferenceEquals(dispatcher, null)) { dispatcher.queueWorker.Enqueue(action, state); } } /// <summary>Dispatch Synchronous action if possible.</summary> public static void Send(Action<object> action, object state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; } #endif if (mainThreadToken != null) { try { action(state); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } else { Post(action, state); } } /// <summary>Run Synchronous action.</summary> public static void UnsafeSend(Action action) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action); return; } #endif try { action(); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } /// <summary>Run Synchronous action.</summary> public static void UnsafeSend<T>(Action<T> action, T state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action, state); return; } #endif try { action(state); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } /// <summary>ThreadSafe StartCoroutine.</summary> public static void SendStartCoroutine(IEnumerator routine) { if (mainThreadToken != null) { StartCoroutine(routine); } else { #if UNITY_EDITOR // call from other thread if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (!isQuitting && !object.ReferenceEquals(dispatcher, null)) { dispatcher.queueWorker.Enqueue(_ => { var dispacher2 = Instance; if (dispacher2 != null) { (dispacher2 as MonoBehaviour).StartCoroutine(routine); } }, null); } } } public static void StartUpdateMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.updateMicroCoroutine.AddCoroutine(routine); } } public static void StartFixedUpdateMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.fixedUpdateMicroCoroutine.AddCoroutine(routine); } } public static void StartEndOfFrameMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.endOfFrameMicroCoroutine.AddCoroutine(routine); } } new public static Coroutine StartCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return null; } #endif var dispatcher = Instance; if (dispatcher != null) { return (dispatcher as MonoBehaviour).StartCoroutine(routine); } else { return null; } } public static void RegisterUnhandledExceptionCallback(Action<Exception> exceptionCallback) { if (exceptionCallback == null) { // do nothing Instance.unhandledExceptionCallback = Stubs<Exception>.Ignore; } else { Instance.unhandledExceptionCallback = exceptionCallback; } } ThreadSafeQueueWorker queueWorker = new ThreadSafeQueueWorker(); Action<Exception> unhandledExceptionCallback = ex => Debug.LogException(ex); // default MicroCoroutine updateMicroCoroutine = null; MicroCoroutine fixedUpdateMicroCoroutine = null; MicroCoroutine endOfFrameMicroCoroutine = null; static MainThreadDispatcher instance; static bool initialized; static bool isQuitting = false; public static string InstanceName { get { if (instance == null) { throw new NullReferenceException("MainThreadDispatcher is not initialized."); } return instance.name; } } public static bool IsInitialized { get { return initialized && instance != null; } } [ThreadStatic] static object mainThreadToken; static MainThreadDispatcher Instance { get { Initialize(); return instance; } } public static void Initialize() { if (!initialized) { #if UNITY_EDITOR // Don't try to add a GameObject when the scene is not playing. Only valid in the Editor, EditorView. if (!ScenePlaybackDetector.IsPlaying) return; #endif MainThreadDispatcher dispatcher = null; try { dispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>(); } catch { // Throw exception when calling from a worker thread. var ex = new Exception("UniRx requires a MainThreadDispatcher component created on the main thread. Make sure it is added to the scene before calling UniRx from a worker thread."); UnityEngine.Debug.LogException(ex); throw ex; } if (isQuitting) { // don't create new instance after quitting // avoid "Some objects were not cleaned up when closing the scene find target" error. return; } if (dispatcher == null) { // awake call immediately from UnityEngine new GameObject("MainThreadDispatcher").AddComponent<MainThreadDispatcher>(); } else { dispatcher.Awake(); // force awake } } } public static bool IsInMainThread { get { return (mainThreadToken != null); } } void Awake() { if (instance == null) { instance = this; mainThreadToken = new object(); initialized = true; #if (ENABLE_MONO_BLEEDING_EDGE_EDITOR || ENABLE_MONO_BLEEDING_EDGE_STANDALONE) if (UniRxSynchronizationContext.AutoInstall) { SynchronizationContext.SetSynchronizationContext(new UniRxSynchronizationContext()); } #endif updateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex)); fixedUpdateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex)); endOfFrameMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex)); StartCoroutine(RunUpdateMicroCoroutine()); StartCoroutine(RunFixedUpdateMicroCoroutine()); StartCoroutine(RunEndOfFrameMicroCoroutine()); DontDestroyOnLoad(gameObject); } else { if (this != instance) { if (cullingMode == CullingMode.Self) { // Try to destroy this dispatcher if there's already one in the scene. Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Removing myself..."); DestroyDispatcher(this); } else if (cullingMode == CullingMode.All) { Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Cleaning up all excess dispatchers..."); CullAllExcessDispatchers(); } else { Debug.LogWarning("There is already a MainThreadDispatcher in the scene."); } } } } IEnumerator RunUpdateMicroCoroutine() { while (true) { yield return null; updateMicroCoroutine.Run(); } } IEnumerator RunFixedUpdateMicroCoroutine() { while (true) { yield return YieldInstructionCache.WaitForFixedUpdate; fixedUpdateMicroCoroutine.Run(); } } IEnumerator RunEndOfFrameMicroCoroutine() { while (true) { yield return YieldInstructionCache.WaitForEndOfFrame; endOfFrameMicroCoroutine.Run(); } } static void DestroyDispatcher(MainThreadDispatcher aDispatcher) { if (aDispatcher != instance) { // Try to remove game object if it's empty var components = aDispatcher.gameObject.GetComponents<Component>(); if (aDispatcher.gameObject.transform.childCount == 0 && components.Length == 2) { if (components[0] is Transform && components[1] is MainThreadDispatcher) { Destroy(aDispatcher.gameObject); } } else { // Remove component MonoBehaviour.Destroy(aDispatcher); } } } public static void CullAllExcessDispatchers() { var dispatchers = GameObject.FindObjectsOfType<MainThreadDispatcher>(); for (int i = 0; i < dispatchers.Length; i++) { DestroyDispatcher(dispatchers[i]); } } void OnDestroy() { if (instance == this) { instance = GameObject.FindObjectOfType<MainThreadDispatcher>(); initialized = instance != null; /* // Although `this` still refers to a gameObject, it won't be found. var foundDispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>(); if (foundDispatcher != null) { // select another game object Debug.Log("new instance: " + foundDispatcher.name); instance = foundDispatcher; initialized = true; } */ } } void Update() { if (update != null) { try { update.OnNext(Unit.Default); } catch (Exception ex) { unhandledExceptionCallback(ex); } } queueWorker.ExecuteAll(unhandledExceptionCallback); } // for Lifecycle Management Subject<Unit> update; public static IObservable<Unit> UpdateAsObservable() { return Instance.update ?? (Instance.update = new Subject<Unit>()); } Subject<Unit> lateUpdate; void LateUpdate() { if (lateUpdate != null) lateUpdate.OnNext(Unit.Default); } public static IObservable<Unit> LateUpdateAsObservable() { return Instance.lateUpdate ?? (Instance.lateUpdate = new Subject<Unit>()); } Subject<bool> onApplicationFocus; void OnApplicationFocus(bool focus) { if (onApplicationFocus != null) onApplicationFocus.OnNext(focus); } public static IObservable<bool> OnApplicationFocusAsObservable() { return Instance.onApplicationFocus ?? (Instance.onApplicationFocus = new Subject<bool>()); } Subject<bool> onApplicationPause; void OnApplicationPause(bool pause) { if (onApplicationPause != null) onApplicationPause.OnNext(pause); } public static IObservable<bool> OnApplicationPauseAsObservable() { return Instance.onApplicationPause ?? (Instance.onApplicationPause = new Subject<bool>()); } Subject<Unit> onApplicationQuit; void OnApplicationQuit() { isQuitting = true; if (onApplicationQuit != null) onApplicationQuit.OnNext(Unit.Default); } public static IObservable<Unit> OnApplicationQuitAsObservable() { return Instance.onApplicationQuit ?? (Instance.onApplicationQuit = new Subject<Unit>()); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedDeploymentsClientSnippets { /// <summary>Snippet for ListDeployments</summary> public void ListDeploymentsRequestObject() { // Snippet: ListDeployments(ListDeploymentsRequest, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) ListDeploymentsRequest request = new ListDeploymentsRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request PagedEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeployments(request); // Iterate over all response items, lazily performing RPCs as required foreach (Deployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeploymentsAsync</summary> public async Task ListDeploymentsRequestObjectAsync() { // Snippet: ListDeploymentsAsync(ListDeploymentsRequest, CallSettings) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) ListDeploymentsRequest request = new ListDeploymentsRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request PagedAsyncEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeploymentsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Deployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeployments</summary> public void ListDeployments() { // Snippet: ListDeployments(string, string, int?, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; // Make the request PagedEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeployments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Deployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeploymentsAsync</summary> public async Task ListDeploymentsAsync() { // Snippet: ListDeploymentsAsync(string, string, int?, CallSettings) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; // Make the request PagedAsyncEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeploymentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Deployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeployments</summary> public void ListDeploymentsResourceNames() { // Snippet: ListDeployments(EnvironmentName, string, int?, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); // Make the request PagedEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeployments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Deployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeploymentsAsync</summary> public async Task ListDeploymentsResourceNamesAsync() { // Snippet: ListDeploymentsAsync(EnvironmentName, string, int?, CallSettings) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); // Make the request PagedAsyncEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeploymentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Deployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetDeployment</summary> public void GetDeploymentRequestObject() { // Snippet: GetDeployment(GetDeploymentRequest, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) GetDeploymentRequest request = new GetDeploymentRequest { DeploymentName = DeploymentName.FromProjectLocationAgentEnvironmentDeployment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"), }; // Make the request Deployment response = deploymentsClient.GetDeployment(request); // End snippet } /// <summary>Snippet for GetDeploymentAsync</summary> public async Task GetDeploymentRequestObjectAsync() { // Snippet: GetDeploymentAsync(GetDeploymentRequest, CallSettings) // Additional: GetDeploymentAsync(GetDeploymentRequest, CancellationToken) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) GetDeploymentRequest request = new GetDeploymentRequest { DeploymentName = DeploymentName.FromProjectLocationAgentEnvironmentDeployment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"), }; // Make the request Deployment response = await deploymentsClient.GetDeploymentAsync(request); // End snippet } /// <summary>Snippet for GetDeployment</summary> public void GetDeployment() { // Snippet: GetDeployment(string, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/deployments/[DEPLOYMENT]"; // Make the request Deployment response = deploymentsClient.GetDeployment(name); // End snippet } /// <summary>Snippet for GetDeploymentAsync</summary> public async Task GetDeploymentAsync() { // Snippet: GetDeploymentAsync(string, CallSettings) // Additional: GetDeploymentAsync(string, CancellationToken) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/deployments/[DEPLOYMENT]"; // Make the request Deployment response = await deploymentsClient.GetDeploymentAsync(name); // End snippet } /// <summary>Snippet for GetDeployment</summary> public void GetDeploymentResourceNames() { // Snippet: GetDeployment(DeploymentName, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) DeploymentName name = DeploymentName.FromProjectLocationAgentEnvironmentDeployment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"); // Make the request Deployment response = deploymentsClient.GetDeployment(name); // End snippet } /// <summary>Snippet for GetDeploymentAsync</summary> public async Task GetDeploymentResourceNamesAsync() { // Snippet: GetDeploymentAsync(DeploymentName, CallSettings) // Additional: GetDeploymentAsync(DeploymentName, CancellationToken) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) DeploymentName name = DeploymentName.FromProjectLocationAgentEnvironmentDeployment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"); // Make the request Deployment response = await deploymentsClient.GetDeploymentAsync(name); // End snippet } } }
// Copyright 2021 Jacob Trimble // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using ModMaker.Lua; using ModMaker.Lua.Runtime; using ModMaker.Lua.Runtime.LuaValues; using NUnit.Framework; using Choice = ModMaker.Lua.OverloadSelector.Choice; using CompareResult = ModMaker.Lua.OverloadSelector.CompareResult; #nullable enable namespace UnitTests { [TestFixture] class OverloadSelectorTest { class Base { } class Derived : Base { } class Other { } Tuple<Type, Type?>?[] _mapValues(Type?[] values) { return values.Select(t => t == null ? null : new Tuple<Type, Type?>(t, null)).ToArray(); } void _runTest(Choice a, Choice b, Type?[] values, bool bValid = true) { _runTest(a, b, _mapValues(values), bValid); } void _runTest(Choice a, Choice b, Tuple<Type, Type?>?[] values, bool bValid = true) { // Verify both are valid when compared with something that won't match. var other = new Choice(new[] { typeof(int), typeof(int), typeof(int) }); Assert.AreEqual(CompareResult.A, OverloadSelector.Compare(a, other, values)); Assert.AreEqual(bValid ? CompareResult.A : CompareResult.Neither, OverloadSelector.Compare(b, other, values)); Assert.AreEqual(CompareResult.A, OverloadSelector.Compare(a, b, values)); Assert.AreEqual(CompareResult.B, OverloadSelector.Compare(b, a, values)); } void _runNeither(Choice a, Choice b, Type?[] values) { _runNeither(a, b, _mapValues(values)); } void _runNeither(Choice a, Choice b, Tuple<Type, Type?>?[] values) { Assert.AreEqual(CompareResult.Neither, OverloadSelector.Compare(a, b, values)); Assert.AreEqual(CompareResult.Neither, OverloadSelector.Compare(b, a, values)); } delegate void TestDelegate(ref int x); #if NETCOREAPP3_1 static void _withNotNull([NotNull] object _) { } #endif static void _withParams(params string[] _) { } static void _withParamsPrimitive(params int[] _) { } static void _withParamsNullablePrimitive(params int?[] _) { } static void _withOptional(string a, int b = 1, long c = 2) { } [Test] public void Choice_MethodInfo_Empty() { Action func = () => { }; var choice = new Choice(func.GetMethodInfo()!); Assert.AreEqual(choice.FormalArguments, new Type[0]); Assert.AreEqual(choice.Nullable, new bool[0]); Assert.AreEqual(choice.OptionalValues, new object[0]); Assert.IsFalse(choice.HasParams); Assert.IsFalse(choice.ParamsNullable); } [Test] public void Choice_MethodInfo_Args() { Func<int, bool, Base, int> func = (int a, bool b, Base c) => 0; var choice = new Choice(func.GetMethodInfo()!); Assert.AreEqual(choice.FormalArguments, new[] { typeof(int), typeof(bool), typeof(Base) }); Assert.AreEqual(choice.Nullable, new[] { false, false, true }); Assert.AreEqual(choice.OptionalValues, new object[0]); Assert.IsFalse(choice.HasParams); Assert.IsFalse(choice.ParamsNullable); } #if NETCOREAPP3_1_OR_GREATER [Test] public void Choice_MethodInfo_NonNullAttribute() { var flags = BindingFlags.Static | BindingFlags.NonPublic; var choice = new Choice(typeof(OverloadSelectorTest).GetMethod(nameof(_withNotNull), flags)!); Assert.AreEqual(choice.FormalArguments, new[] { typeof(object) }); Assert.AreEqual(choice.Nullable, new[] { false }); Assert.AreEqual(choice.OptionalValues, new object[0]); Assert.IsFalse(choice.HasParams); Assert.IsFalse(choice.ParamsNullable); } #endif [Test] public void Choice_MethodInfo_Params() { var flags = BindingFlags.Static | BindingFlags.NonPublic; var choice = new Choice(typeof(OverloadSelectorTest).GetMethod(nameof(_withParams), flags)!); Assert.AreEqual(choice.FormalArguments, new[] { typeof(string[]) }); Assert.AreEqual(choice.Nullable, new[] { true }); Assert.AreEqual(choice.OptionalValues, new object[0]); Assert.IsTrue(choice.HasParams); Assert.IsTrue(choice.ParamsNullable); } [Test] public void Choice_MethodInfo_ParamsPrimitive() { var flags = BindingFlags.Static | BindingFlags.NonPublic; var choice = new Choice(typeof(OverloadSelectorTest).GetMethod(nameof(_withParamsPrimitive), flags)!); Assert.AreEqual(choice.FormalArguments, new[] { typeof(int[]) }); Assert.AreEqual(choice.Nullable, new[] { true }); Assert.AreEqual(choice.OptionalValues, new object[0]); Assert.IsTrue(choice.HasParams); Assert.IsFalse(choice.ParamsNullable); } [Test] public void Choice_MethodInfo_ParamsNullablePrimitive() { var flags = BindingFlags.Static | BindingFlags.NonPublic; var choice = new Choice(typeof(OverloadSelectorTest).GetMethod( nameof(_withParamsNullablePrimitive), flags)!); Assert.AreEqual(choice.FormalArguments, new[] { typeof(int?[]) }); Assert.AreEqual(choice.Nullable, new[] { true }); Assert.AreEqual(choice.OptionalValues, new object[0]); Assert.IsTrue(choice.HasParams); Assert.IsTrue(choice.ParamsNullable); } [Test] public void Choice_MethodInfo_ByRef() { TestDelegate func = (ref int a) => { }; var choice = new Choice(func.GetMethodInfo()!); Assert.AreEqual(choice.FormalArguments, new[] { typeof(int) }); Assert.AreEqual(choice.Nullable, new[] { false }); Assert.AreEqual(choice.OptionalValues, new object[0]); Assert.IsFalse(choice.HasParams); Assert.IsFalse(choice.ParamsNullable); } [Test] public void Choice_MethodInfo_Optional() { var flags = BindingFlags.Static | BindingFlags.NonPublic; var choice = new Choice( typeof(OverloadSelectorTest).GetMethod(nameof(_withOptional), flags)!); Assert.AreEqual(choice.FormalArguments, new[] { typeof(string), typeof(int), typeof(long) }); Assert.AreEqual(choice.Nullable, new[] { true, false, false}); Assert.AreEqual(choice.OptionalValues, new object[] { (int)1, (long)2 }); Assert.IsFalse(choice.HasParams); Assert.IsFalse(choice.ParamsNullable); } [Test] public void Compare_BasicFlow() { var a = new Choice(new[] { typeof(Derived) }); var b = new Choice(new[] { typeof(Other) }); var values = new[] { typeof(Derived) }; Assert.AreEqual(CompareResult.A, OverloadSelector.Compare(a, b, _mapValues(values))); } [Test] public void Compare_BasicAmbiguous() { var a = new Choice(new[] { typeof(Derived) }); var b = new Choice(new[] { typeof(Derived) }); var values = new[] { typeof(Derived) }; Assert.AreEqual(CompareResult.Both, OverloadSelector.Compare(a, b, _mapValues(values))); } [Test] public void Compare_Number() { var a = new Choice(new[] { typeof(double) }); var b = new Choice(new[] { typeof(int) }); _runTest(a, b, new[] { typeof(double) }); } [Test] public void Compare_NumberAmbiguous() { var a = new Choice(new[] { typeof(int) }); var b = new Choice(new[] { typeof(long) }); var values = new[] { typeof(double) }; Assert.AreEqual(CompareResult.Both, OverloadSelector.Compare(a, b, _mapValues(values))); } [Test] public void Compare_IgnoresExtraArgs() { var a = new Choice(new[] { typeof(Derived) }); var b = new Choice(new[] { typeof(Other) }); var values = new[] { typeof(Derived), typeof(Derived), typeof(Derived) }; _runTest(a, b, values, bValid: false); } [Test] public void Compare_ChecksExtraArgs() { var a = new Choice(new[] { typeof(Base) }); var b = new Choice(new[] { typeof(Derived), typeof(Other) }); var values = new[] { typeof(Derived), typeof(Derived) }; _runTest(a, b, values, bValid: false); } [Test] public void Compare_NotEnoughArgs() { var a = new Choice(new[] { typeof(Derived) }); var b = new Choice(new[] { typeof(Derived), typeof(Derived) }); var values = new[] { typeof(Derived) }; _runTest(a, b, values, bValid: false); } [Test] public void Compare_NotEnoughArgsBoth() { var a = new Choice(new[] { typeof(Derived), typeof(Derived) }); var b = new Choice(new[] { typeof(Derived), typeof(Other) }); _runNeither(a, b, new[] { typeof(Derived) }); } [Test] public void Compare_Invalid() { var a = new Choice(new[] { typeof(Derived) }); var b = new Choice(new[] { typeof(Other) }); var values = new[] { typeof(Derived) }; _runTest(a, b, values, bValid: false); } [Test] public void Compare_InvalidBoth() { var a = new Choice(new[] { typeof(Derived) }); var b = new Choice(new[] { typeof(Derived) }); _runNeither(a, b, new[] { typeof(Other) }); } [Test] public void Compare_Inherit_Better() { var a = new Choice(new[] { typeof(Derived) }); var b = new Choice(new[] { typeof(Base) }); _runTest(a, b, new[] { typeof(Derived) }); a = new Choice(new[] { typeof(Derived), typeof(Derived) }); b = new Choice(new[] { typeof(Base), typeof(Derived) }); _runTest(a, b, new[] { typeof(Derived), typeof(Derived) }); a = new Choice(new[] { typeof(Derived), typeof(Derived) }); b = new Choice(new[] { typeof(Base), typeof(Base) }); _runTest(a, b, new[] { typeof(Derived), typeof(Derived) }); } [Test] public void Compare_Inherit_Ambiguous() { var a = new Choice(new[] { typeof(Base), typeof(Derived) }); var b = new Choice(new[] { typeof(Derived), typeof(Base) }); var values = new[] { typeof(Derived), typeof(Derived) }; Assert.AreEqual(CompareResult.Both, OverloadSelector.Compare(a, b, _mapValues(values))); Assert.AreEqual(CompareResult.Both, OverloadSelector.Compare(b, a, _mapValues(values))); } [Test] public void Compare_Params_Success() { var a = new Choice(new[] { typeof(Derived[]) }, hasParams: true); var b = new Choice(new[] { typeof(Other) }); _runTest(a, b, new[] { typeof(Derived), typeof(Derived), typeof(Derived) }, bValid: false); } [Test] public void Compare_Params_Ambiguous() { var a = new Choice(new[] { typeof(Derived[]) }, hasParams: true); var b = new Choice(new[] { typeof(Derived[]) }, hasParams: true); var values = new[] { typeof(Derived) }; Assert.AreEqual(CompareResult.Both, OverloadSelector.Compare(a, b, _mapValues(values))); } [Test] public void Compare_Params_AcceptsZeroValues() { var a = new Choice(new[] { typeof(Derived[]) }, hasParams: true); var b = new Choice(new[] { typeof(Other) }); _runTest(a, b, new Type[0], bValid: false); } [Test] public void Compare_Params_CantUseNormalForm() { var a = new Choice(new[] { typeof(Derived[]) }, hasParams: true); var b = new Choice(new[] { typeof(Other[]) }, hasParams: true); _runNeither(a, b, new[] { typeof(Derived[]) }); } [Test] public void Compare_Params_ExpandedFormError() { var a = new Choice(new[] { typeof(Derived[]) }, hasParams: true); var b = new Choice(new[] { typeof(Other[]) }, hasParams: true); _runTest(a, b, new[] { typeof(Derived) }, bValid: false); } [Test] public void Compare_Params_Error() { var a = new Choice(new[] { typeof(Derived[]) }, hasParams: true); var b = new Choice(new[] { typeof(Derived) }); _runNeither(a, b, new[] { typeof(Other) }); } [Test] public void Compare_Params_MoreParamsWins() { var a = new Choice(new[] { typeof(Base), typeof(Base[]) }, hasParams: true); var b = new Choice(new[] { typeof(Base[]) }, hasParams: true); _runTest(a, b, new[] { typeof(Derived), typeof(Derived) }); _runTest(a, b, new[] { typeof(Derived) }); } [Test] public void Compare_Optional_Basic() { var a = new Choice(new[] { typeof(Base), typeof(Base) }, optionals: new object[] { 1 }); var b = new Choice(new[] { typeof(Other) }); _runTest(a, b, new[] { typeof(Derived) }, bValid: false); } [Test] public void Compare_Optional_NotEnough() { var a = new Choice(new[] { typeof(Base), typeof(Base) }, optionals: new object[] { 1 }); var b = new Choice(new[] { typeof(Other) }); _runNeither(a, b, new Type[0]); } [Test] public void Compare_Optional_MoreParamsWins() { var a = new Choice(new[] { typeof(Base), typeof(Base) }, optionals: new object[] { 1 }); var b = new Choice(new[] { typeof(Base) }); _runTest(a, b, new[] { typeof(Base) }); } [Test] public void Compare_Nullable_Success() { var a = new Choice(new[] { typeof(Base) }, nullable: new[] { true }); var b = new Choice(new[] { typeof(Base) }); _runTest(a, b, new Type?[] { null }, bValid: false); } [Test] public void Compare_Nullable_Error() { var a = new Choice(new[] { typeof(Base) }); var b = new Choice(new[] { typeof(Other) }); _runNeither(a, b, new Type?[] { null }); } [Test] public void Compare_Nullable_NonNullWins() { var a = new Choice(new[] { typeof(Derived) }); var b = new Choice(new[] { typeof(Derived) }, nullable: new[] { true }); _runTest(a, b, new[] { typeof(Derived) }); } [Test] public void Compare_Nullable_ParamsSuccess() { var a = new Choice(new[] { typeof(Derived[]) }, hasParams: true, paramsNullable: true); var b = new Choice(new[] { typeof(Other) }); _runTest(a, b, new Type?[] { null }, bValid: false); } [Test] public void Compare_Nullable_ParamsError() { var a = new Choice(new[] { typeof(Derived[]) }, hasParams: true); var b = new Choice(new[] { typeof(Other) }); _runNeither(a, b, new Type?[] { null }); } [Test] public void Compare_Nullable_ParamsNumber() { var a = new Choice(new[] { typeof(int?[]) }, hasParams: true, paramsNullable: true); var b = new Choice(new[] { typeof(Other) }); _runTest(a, b, new[] { typeof(int), null, typeof(long) }, bValid: false); } [Test] public void Compare_DoubleType_Basic() { var a = new Choice(new[] { typeof(string) }); var b = new Choice(new[] { typeof(object) }); _runTest(a, b, new[] { new Tuple<Type, Type?>(typeof(LuaString), typeof(string)) }); } [Test] public void Compare_DoubleType_NumberBase() { // Should favor double since that's the "real" type of the number. var a = new Choice(new[] { typeof(double) }); var b = new Choice(new[] { typeof(int) }); _runTest(a, b, new[] { new Tuple<Type, Type?>(typeof(LuaNumber), typeof(double)) }); } [Test] public void Compare_DoubleType_NumberAmbiguous() { // Other than double, all numbers are "equivalent". var a = new Choice(new[] { typeof(long) }); var b = new Choice(new[] { typeof(int) }); var values = new[] { new Tuple<Type, Type?>(typeof(LuaNumber), typeof(double)) }; Assert.AreEqual(CompareResult.Both, OverloadSelector.Compare(a, b, values)); } [Test] public void Compare_Function() { var a = new Choice(new[] { typeof(Action) }); var b = new Choice(new[] { typeof(int) }); _runTest(a, b, new[] { typeof(LuaFunction) }, bValid: false); } [Test] public void Compare_Function_Inherited() { var a = new Choice(new[] { typeof(Func<int, string>) }); var b = new Choice(new[] { typeof(int) }); _runTest(a, b, new[] { typeof(LuaDefinedFunction) }, bValid: false); } [Test] public void FindOverload_SingleValue() { var choices = new[] { new Choice(new[] { typeof(Base) }), }; var values = new[] { typeof(Base) }; Assert.AreEqual(0, OverloadSelector.FindOverload(choices, _mapValues(values))); } [Test] public void FindOverload_SingleValueError() { var choices = new[] { new Choice(new[] { typeof(Other) }), }; var values = new[] { typeof(Base) }; Assert.AreEqual(-1, OverloadSelector.FindOverload(choices, _mapValues(values))); } [Test] public void FindOverload_Ambiguous() { var choices = new[] { new Choice(new[] { typeof(Base) }), new Choice(new[] { typeof(Base) }), }; var values = new[] { typeof(Derived) }; Assert.Throws<AmbiguousMatchException>( () => OverloadSelector.FindOverload(choices, _mapValues(values))); } [Test] public void FindOverload_ClearsAmbiguous() { var choices = new[] { new Choice(new[] { typeof(Base) }), new Choice(new[] { typeof(Base) }), new Choice(new[] { typeof(Derived) }), }; var values = new[] { typeof(Derived) }; Assert.AreEqual(2, OverloadSelector.FindOverload(choices, _mapValues(values))); } [Test] public void FindOverload_HandlesNeither() { var choices = new[] { new Choice(new[] { typeof(Base), typeof(Derived) }), new Choice(new[] { typeof(Derived), typeof(Base) }), }; var values = new[] { typeof(Other), typeof(Other) }; Assert.AreEqual(-1, OverloadSelector.FindOverload(choices, _mapValues(values))); } [Test] public void FindOverload_HandlesNeitherWithMore() { var choices = new[] { new Choice(new[] { typeof(Base), typeof(Derived) }), new Choice(new[] { typeof(Derived), typeof(Base) }), new Choice(new[] { typeof(Other), typeof(Other) }), }; var values = new[] { typeof(Other), typeof(Other) }; Assert.AreEqual(2, OverloadSelector.FindOverload(choices, _mapValues(values))); } class CastableFrom { public static explicit operator Base?(CastableFrom _) { return null; } } class CastableFromDerived : CastableFrom { } class CastableTo { public static implicit operator CastableTo?(Base _) { return null; } } class CastableToDerived : CastableTo { } class OtherCastable { public static implicit operator Other?(OtherCastable _) { return null; } } [LuaIgnore] class NonVisibleCastable { public static explicit operator Base?(NonVisibleCastable _) { return null; } } class NonVisibleCastable2 { [LuaIgnore] public static explicit operator Base?(NonVisibleCastable2 _) { return null; } } class NonVisibleCastableTo { [LuaIgnore] public static explicit operator NonVisibleCastableTo?(Base _) { return null; } } [Test] public void TypesCompatible_SameType() { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(Derived), typeof(Derived), out info)); Assert.IsNull(info); } [Test] public void TypesCompatible_BaseType() { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(Derived), typeof(Base), out info)); Assert.IsNull(info); } [Test] public void TypesCompatible_DerivedTypeError() { Assert.IsFalse(OverloadSelector.TypesCompatible(typeof(Base), typeof(Derived), out _)); } [Test] public void TypesCompatible_NullableSource() { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(int?), typeof(int), out info)); Assert.IsNull(info); } [Test] public void TypesCompatible_NullableDest() { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(int), typeof(int?), out info)); Assert.IsNull(info); } [Test] public void TypesCompatible_CompatiblePrimitives() { Type[] types = new[] { // Note that bool and (U)IntPtr aren't considered the compatible. // Also, don't include char since there are cases where it won't work. typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal), }; foreach (Type a in types) { foreach (Type b in types) { if (a == b) continue; MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(a, b, out info)); Assert.IsNotNull(info); object? obj = Helpers.DynamicInvoke(info!, null, new[] { Activator.CreateInstance(a) }); Assert.IsInstanceOf(b, obj); } } } [Test] public void TypesCompatible_Char() { Type[] badTypes = new[] { typeof(float), typeof(double), typeof(decimal), }; foreach (Type a in badTypes) { Assert.IsFalse(OverloadSelector.TypesCompatible(a, typeof(char), out _)); Assert.IsFalse(OverloadSelector.TypesCompatible(typeof(char), a, out _)); } Type[] goodTypes = new[] { typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), }; foreach (Type a in goodTypes) { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(a, typeof(char), out info)); Assert.IsNotNull(info); object? obj = Helpers.DynamicInvoke(info!, null, new[] { Activator.CreateInstance(a) }); Assert.IsInstanceOf<char>(obj); Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(char), a, out info)); Assert.IsNotNull(info); obj = Helpers.DynamicInvoke(info!, null, new[] { (object)'\0' }); Assert.IsInstanceOf(a, obj); } } [Test] public void TypesCompatible_OtherPrimitives() { Type[] types = new[] { typeof(int), typeof(bool), typeof(IntPtr), typeof(UIntPtr) }; foreach (Type a in types) { foreach (Type b in types) { if (a == b) continue; Assert.IsFalse(OverloadSelector.TypesCompatible(a, b, out _)); } } } [Test] public void TypesCompatible_UserCastFrom() { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(CastableFrom), typeof(Base), out info)); Assert.IsNotNull(info); } [Test] public void TypesCompatible_UserCastFromInBaseClass() { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(CastableFromDerived), typeof(Base), out info)); Assert.IsNotNull(info); } [Test] public void TypesCompatible_UserCastFromDerivedObject() { Assert.IsFalse(OverloadSelector.TypesCompatible(typeof(CastableFromDerived), typeof(Derived), out _)); } [Test] public void TypesCompatible_UserCastOther() { Assert.IsFalse(OverloadSelector.TypesCompatible(typeof(OtherCastable), typeof(Base), out _)); } [Test] public void TypesCompatible_UserCastTo() { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(Base), typeof(CastableTo), out info)); Assert.IsNotNull(info); } [Test] public void TypesCompatible_UserCastToInBaseClass() { Assert.IsFalse(OverloadSelector.TypesCompatible(typeof(Base), typeof(CastableToDerived), out _)); } [Test] public void TypesCompatible_UserCastToDerivedObject() { MethodInfo? info; Assert.IsTrue(OverloadSelector.TypesCompatible(typeof(Derived), typeof(CastableTo), out info)); Assert.IsNotNull(info); } [Test] public void TypesCompatible_UserCastNotVisible() { Assert.IsFalse(OverloadSelector.TypesCompatible(typeof(NonVisibleCastable), typeof(Base), out _)); Assert.IsFalse(OverloadSelector.TypesCompatible(typeof(NonVisibleCastable2), typeof(Base), out _)); Assert.IsFalse(OverloadSelector.TypesCompatible(typeof(Base), typeof(NonVisibleCastableTo), out _)); } [Test] public void ConvertArguments_MultiValueArg() { var choice = new Choice(new[] { typeof(LuaMultiValue) }); var args = new LuaMultiValue(); var converted = OverloadSelector.ConvertArguments(args, choice); Assert.AreEqual(new[] { args }, converted); } [Test] public void ConvertArguments_FormalArgs() { var choice = new Choice(new[] { typeof(int), typeof(string) }); var args = new LuaMultiValue(LuaNumber.Create(0), new LuaString("foo")); var converted = OverloadSelector.ConvertArguments(args, choice); Assert.AreEqual(new object[] { 0, "foo" }, converted); } [Test] public void ConvertArguments_AddsOptionals() { var choice = new Choice(new[] { typeof(string), typeof(int), typeof(int) }, optionals: new object[] { 1, 2 }); var args = new LuaMultiValue(new LuaString("a")); var converted = OverloadSelector.ConvertArguments(args, choice); Assert.AreEqual(new object[] { "a", 1, 2 }, converted); args = new LuaMultiValue(new LuaString("a"), LuaNumber.Create(9)); converted = OverloadSelector.ConvertArguments(args, choice); Assert.AreEqual(new object[] { "a", 9, 2 }, converted); args = new LuaMultiValue(new LuaString("a"), LuaNumber.Create(9), LuaNumber.Create(10)); converted = OverloadSelector.ConvertArguments(args, choice); Assert.AreEqual(new object[] { "a", 9, 10 }, converted); } [Test] public void ConvertArguments_AddsParams() { var choice = new Choice(new[] { typeof(string), typeof(int[]) }, hasParams: true); var args = new LuaMultiValue(new LuaString("a"), LuaNumber.Create(1), LuaNumber.Create(2)); var converted = OverloadSelector.ConvertArguments(args, choice); Assert.AreEqual(new object[] { "a", new int[] { 1, 2 } }, converted); args = new LuaMultiValue(new LuaString("a"), LuaNumber.Create(1)); converted = OverloadSelector.ConvertArguments(args, choice); Assert.AreEqual(new object[] { "a", new int[] { 1 } }, converted); args = new LuaMultiValue(new LuaString("a")); converted = OverloadSelector.ConvertArguments(args, choice); Assert.AreEqual(new object[] { "a", new int[0] }, converted); } } }
#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; using Kodestruct.Common.Entities; using Kodestruct.Common.Section.Interfaces; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Steel.AISC.AISC360v10.General.Compactness; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Common.Exceptions; namespace Kodestruct.Steel.AISC.AISC360v10.Flexure { public partial class BeamRectangularHss : FlexuralMemberRhsBase, ISteelBeamFlexure { private double GetEffectiveSectionModulusX(MomentAxis MomentAxis) { double Se=0.0; double be = GetEffectiveFlangeWidth_beff(MomentAxis); double b = GetCompressionFlangeWidth_b(MomentAxis); double AOriginal = Section.Shape.A; double t_f = GetFlangeThickness(MomentAxis); double bRemoved = (b - be); double ADeducted = bRemoved * t_f; double h = GetSectionHeight(MomentAxis); //Find I reduced double I_Reduced = GetReducedMomentOfInertiaX(MomentAxis, ADeducted, bRemoved, t_f); double yCentroidModifiedFromBottom = h / 2.0 - ADeducted / AOriginal; double yCentroidModifiedFromTop = h / 2.0 + ADeducted / AOriginal; Se = I_Reduced / yCentroidModifiedFromTop; return Se; } private double GetSectionHeight(MomentAxis MomentAxis) { double h = 0.0; if (ShapeTube != null) { if (MomentAxis == Common.Entities.MomentAxis.XAxis) { h = ShapeTube.H; } else if (MomentAxis == Common.Entities.MomentAxis.YAxis) { h = ShapeTube.B; } else { throw new Exception("Principal flexure calculation not supported. Select X-axis and Y-axis"); } } else if (ShapeBox != null) { if (MomentAxis == Common.Entities.MomentAxis.XAxis) { h = ShapeBox.H; } else if (MomentAxis == Common.Entities.MomentAxis.YAxis) { h = ShapeBox.B; } else { throw new Exception("Principal flexure calculation not supported. Select X-axis and Y-axis"); } } else { throw new ShapeTypeNotSupportedException(" effective moment of interia calculation for hollow section"); } return h; } private double GetSectionWidth(MomentAxis MomentAxis) { double b = 0.0; if (ShapeTube != null) { if (MomentAxis == Common.Entities.MomentAxis.XAxis) { b = ShapeTube.B; } else if (MomentAxis == Common.Entities.MomentAxis.YAxis) { b = ShapeTube.H; } else { throw new Exception("Principal flexure calculation not supported. Select X-axis and Y-axis"); } } else if (ShapeBox != null) { if (MomentAxis == Common.Entities.MomentAxis.XAxis) { b = ShapeBox.B; } else if (MomentAxis == Common.Entities.MomentAxis.YAxis) { b = ShapeBox.H; } else { throw new Exception("Principal flexure calculation not supported. Select X-axis and Y-axis"); } } else { throw new ShapeTypeNotSupportedException(" effective moment of interia calculation for hollow section"); } return b; } private double GetMomentOfInertia(MomentAxis MomentAxis) { double I; if (MomentAxis == Common.Entities.MomentAxis.XAxis) { I = Section.Shape.I_x; } else if (MomentAxis == Common.Entities.MomentAxis.YAxis) { I = Section.Shape.I_y; } else { throw new Exception("Principal flexure calculation not supported. Select X-axis and Y-axis"); } return I; } private double GetReducedMomentOfInertiaX(MomentAxis MomentAxis, double ADeducted, double bRemoved, double tdes) { double IOriginal = GetMomentOfInertia(MomentAxis); //Section.Shape.I_x; double h = GetSectionHeight(MomentAxis); double yDeducted = (h - tdes) / 2.0; double Ideducted = bRemoved * Math.Pow(tdes, 3) / 12.0; //Use parallel axis theorem: double IFinal = IOriginal - (ADeducted * Math.Pow(yDeducted, 2) + Ideducted); return IFinal; } private double GetFlangeThickness(MomentAxis MomentAxis ) { double t_flange = 0.0; if (ShapeTube!=null) { t_flange = ShapeTube.t_des; } else if (ShapeBox!=null) { if (MomentAxis == Common.Entities.MomentAxis.XAxis) { t_flange = ShapeBox.t_f; } else if (MomentAxis == Common.Entities.MomentAxis.YAxis) { t_flange = ShapeBox.t_w; } else { throw new Exception("Principal flexure calculation not supported. Select X-axis and Y-axis"); } } else { throw new ShapeTypeNotSupportedException(" effective moment of interia calculation for hollow section"); } return t_flange; } protected virtual double GetCompressionFlangeWidth_b(MomentAxis MomentAxis) { // since section is symmetrical the location of compression fiber // does not matter double b_c = 0.0; double B = 0.0; B = GetSectionWidth(MomentAxis); if (ShapeTube != null) { if (ShapeTube.CornerRadiusOutside == -1.0) { b_c = ShapeTube.B - 3.0 * ShapeTube.t_des; } else { b_c = ShapeTube.B - 2.0 * ShapeTube.CornerRadiusOutside; } } else if (ShapeBox != null) { b_c = ShapeBox.B; } else { throw new ShapeTypeNotSupportedException(" effective moment of interia calculation for hollow section"); } return b_c; return b_c; } protected double GetEffectiveFlangeWidth_beff(MomentAxis MomentAxis) { double b = GetCompressionFlangeWidth_b(MomentAxis); double tf = GetFlangeThickness(MomentAxis); double be = 1.92*tf*SqrtE_Fy()*(1.0-0.38/(b/tf)*SqrtE_Fy()-0.738); //(F7-4) be = be > b? b :be; be= be<0? 0 : be; return be; } } }
namespace System.Workflow.ComponentModel.Design { using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Reflection; using System.Globalization; internal sealed class ReferenceService : IReferenceService, IDisposable { private static readonly Attribute[] Attributes = new Attribute[] { BrowsableAttribute.Yes }; private IServiceProvider provider; // service provider we use to get to other services private ArrayList addedComponents; // list of newly added components private ArrayList removedComponents; // list of newly removed components private ArrayList changedComponents; // list of changed components, we will re-cylcle their references too private ArrayList references; // our current list of references internal ReferenceService(IServiceProvider provider) { this.provider = provider; } ~ReferenceService() { Dispose(false); } private void CreateReferences(IComponent component) { CreateReferences(string.Empty, component, component); } private void CreateReferences(string trailingName, object reference, IComponent sitedComponent) { if (object.ReferenceEquals(reference, null)) return; this.references.Add(new ReferenceHolder(trailingName, reference, sitedComponent)); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(reference, Attributes)) { object value = null; try { value = property.GetValue(reference); } catch { // Work around!!! if an property getter throws exception then we ignore it. } if (value != null) { BrowsableAttribute[] browsableAttrs = (BrowsableAttribute[])(value.GetType().GetCustomAttributes(typeof(BrowsableAttribute), true)); if (browsableAttrs.Length > 0 && browsableAttrs[0].Browsable) { CreateReferences(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { trailingName, property.Name }), property.GetValue(reference), sitedComponent); } } } } private void EnsureReferences() { // If the references are null, create them for the first time and connect // up our events to listen to changes to the container. Otherwise, check to // see if the added or removed lists contain anything for us to [....] up. // if (this.references == null) { if (this.provider == null) { throw new ObjectDisposedException("IReferenceService"); } IComponentChangeService cs = this.provider.GetService(typeof(IComponentChangeService)) as IComponentChangeService; Debug.Assert(cs != null, "Reference service relies on IComponentChangeService"); if (cs != null) { cs.ComponentAdded += new ComponentEventHandler(this.OnComponentAdded); cs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); cs.ComponentRename += new ComponentRenameEventHandler(this.OnComponentRename); cs.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged); } TypeDescriptor.Refreshed += new RefreshEventHandler(OnComponentRefreshed); IContainer container = this.provider.GetService(typeof(IContainer)) as IContainer; if (container == null) { Debug.Fail("Reference service cannot operate without IContainer"); throw new InvalidOperationException(); } this.references = new ArrayList(container.Components.Count); foreach (IComponent component in container.Components) { CreateReferences(component); } } else { if (this.addedComponents != null && this.addedComponents.Count > 0) { // There is a possibility that this component already exists. // If it does, just remove it first and then re-add it. // ArrayList clonedAddedComponents = new ArrayList(this.addedComponents); foreach (IComponent ic in clonedAddedComponents) { RemoveReferences(ic); CreateReferences(ic); } this.addedComponents.Clear(); } if (this.removedComponents != null && this.removedComponents.Count > 0) { ArrayList clonedRemovedComponents = new ArrayList(this.removedComponents); foreach (IComponent ic in clonedRemovedComponents) RemoveReferences(ic); this.removedComponents.Clear(); } if (this.changedComponents != null && this.changedComponents.Count > 0) { ArrayList clonedChangedComponents = new ArrayList(this.changedComponents); foreach (IComponent ic in clonedChangedComponents) { RemoveReferences(ic); CreateReferences(ic); } this.changedComponents.Clear(); } } } private void OnComponentChanged(object sender, ComponentChangedEventArgs cevent) { IComponent comp = ((IReferenceService)this).GetComponent(cevent.Component); if (comp != null) { if ((this.addedComponents == null || !this.addedComponents.Contains(comp)) && (this.removedComponents == null || !this.removedComponents.Contains(comp))) { if (this.changedComponents == null) { this.changedComponents = new ArrayList(); this.changedComponents.Add(comp); } else if (!this.changedComponents.Contains(comp)) { this.changedComponents.Add(comp); } } } } private void OnComponentAdded(object sender, ComponentEventArgs cevent) { if (this.addedComponents == null) this.addedComponents = new ArrayList(); this.addedComponents.Add(cevent.Component); if (this.removedComponents != null) this.removedComponents.Remove(cevent.Component); if (this.changedComponents != null) this.changedComponents.Remove(cevent.Component); } private void OnComponentRemoved(object sender, ComponentEventArgs cevent) { if (this.removedComponents == null) this.removedComponents = new ArrayList(); this.removedComponents.Add(cevent.Component); if (this.addedComponents != null) this.addedComponents.Remove(cevent.Component); if (this.changedComponents != null) this.changedComponents.Remove(cevent.Component); } private void OnComponentRename(object sender, ComponentRenameEventArgs cevent) { foreach (ReferenceHolder reference in this.references) { if (object.ReferenceEquals(reference.SitedComponent, cevent.Component)) { reference.ResetName(); return; } } } private void OnComponentRefreshed(RefreshEventArgs e) { if (e.ComponentChanged != null) OnComponentChanged(this, new ComponentChangedEventArgs(e.ComponentChanged, null, null, null)); } private void RemoveReferences(IComponent component) { if (this.references != null) { int size = this.references.Count; for (int i = size - 1; i >= 0; i--) { if (object.ReferenceEquals(((ReferenceHolder)this.references[i]).SitedComponent, component)) this.references.RemoveAt(i); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (this.references != null && this.provider != null) { IComponentChangeService cs = this.provider.GetService(typeof(IComponentChangeService)) as IComponentChangeService; if (cs != null) { cs.ComponentAdded -= new ComponentEventHandler(this.OnComponentAdded); cs.ComponentRemoved -= new ComponentEventHandler(this.OnComponentRemoved); cs.ComponentRename -= new ComponentRenameEventHandler(this.OnComponentRename); cs.ComponentChanged -= new ComponentChangedEventHandler(this.OnComponentChanged); } TypeDescriptor.Refreshed -= new RefreshEventHandler(OnComponentRefreshed); this.references = null; this.provider = null; } } IComponent IReferenceService.GetComponent(object reference) { if (object.ReferenceEquals(reference, null)) throw new ArgumentNullException("reference"); EnsureReferences(); foreach (ReferenceHolder holder in this.references) { if (object.ReferenceEquals(holder.Reference, reference)) return holder.SitedComponent; } return null; } string IReferenceService.GetName(object reference) { if (object.ReferenceEquals(reference, null)) throw new ArgumentNullException("reference"); EnsureReferences(); foreach (ReferenceHolder holder in this.references) { if (object.ReferenceEquals(holder.Reference, reference)) return holder.Name; } return null; } object IReferenceService.GetReference(string name) { if (name == null) throw new ArgumentNullException("name"); EnsureReferences(); foreach (ReferenceHolder holder in this.references) { if (string.Equals(holder.Name, name, StringComparison.OrdinalIgnoreCase)) return holder.Reference; } return null; } object[] IReferenceService.GetReferences() { EnsureReferences(); object[] references = new object[this.references.Count]; for (int i = 0; i < references.Length; i++) references[i] = ((ReferenceHolder)this.references[i]).Reference; return references; } object[] IReferenceService.GetReferences(Type baseType) { if (baseType == null) throw new ArgumentNullException("baseType"); EnsureReferences(); ArrayList results = new ArrayList(this.references.Count); foreach (ReferenceHolder holder in this.references) { object reference = holder.Reference; if (baseType.IsAssignableFrom(reference.GetType())) results.Add(reference); } object[] references = new object[results.Count]; results.CopyTo(references, 0); return references; } private sealed class ReferenceHolder { private string trailingName; private object reference; private IComponent sitedComponent; private string fullName; internal ReferenceHolder(string trailingName, object reference, IComponent sitedComponent) { this.trailingName = trailingName; this.reference = reference; this.sitedComponent = sitedComponent; Debug.Assert(trailingName != null, "Expected a trailing name"); Debug.Assert(reference != null, "Expected a reference"); #if DEBUG Debug.Assert(sitedComponent != null, "Expected a sited component"); if (sitedComponent != null) Debug.Assert(sitedComponent.Site != null, "Sited component is not really sited: " + sitedComponent.ToString()); if (sitedComponent != null && sitedComponent.Site != null) Debug.Assert(sitedComponent.Site.Name != null, "Sited component has no name: " + sitedComponent.ToString()); #endif // DEBUG } internal void ResetName() { this.fullName = null; } internal string Name { get { if (this.fullName == null) { if (this.sitedComponent != null && this.sitedComponent.Site != null && this.sitedComponent.Site.Name != null) { this.fullName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", new object[] { this.sitedComponent.Site.Name, this.trailingName }); } else { #if DEBUG Debug.Assert(this.sitedComponent != null, "Expected a sited component"); if (this.sitedComponent != null) Debug.Assert(this.sitedComponent.Site != null, "Sited component is not really sited: " + this.sitedComponent.ToString()); if (this.sitedComponent != null && this.sitedComponent.Site != null) Debug.Assert(this.sitedComponent.Site.Name != null, "Sited component has no name: " + this.sitedComponent.ToString()); #endif // DEBUG this.fullName = string.Empty; } } return this.fullName; } } internal object Reference { get { return this.reference; } } internal IComponent SitedComponent { get { return this.sitedComponent; } } } } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // -------------------------------------------------------------------------------------- // // A class that provides a simple, lightweight implementation of lazy initialization, // obviating the need for a developer to implement a custom, thread-safe lazy initialization // solution. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Runtime; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; namespace System { // Lazy<T> is generic, but not all of its state needs to be generic. Avoid creating duplicate // objects per instantiation by putting them here. internal static class LazyHelpers { // Dummy object used as the value of m_threadSafeObj if in PublicationOnly mode. internal static readonly object PUBLICATION_ONLY_SENTINEL = new object(); } /// <summary> /// Provides support for lazy initialization. /// </summary> /// <typeparam name="T">Specifies the type of element being lazily initialized.</typeparam> /// <remarks> /// <para> /// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used /// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance /// using parameters to the type's constructors. /// </para> /// </remarks> #if FEATURE_SERIALIZATION [Serializable] #endif [ComVisible(false)] #if !FEATURE_CORECLR [HostProtection(Synchronization = true, ExternalThreading = true)] #endif [DebuggerTypeProxy(typeof(System_LazyDebugView<>))] [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")] public class Lazy<T> { #region Inner classes /// <summary> /// wrapper class to box the initialized value, this is mainly created to avoid boxing/unboxing the value each time the value is called in case T is /// a value type /// </summary> [Serializable] class Boxed { internal Boxed(T value) { m_value = value; } internal T m_value; } /// <summary> /// Wrapper class to wrap the excpetion thrown by the value factory /// </summary> class LazyInternalExceptionHolder { internal ExceptionDispatchInfo m_edi; internal LazyInternalExceptionHolder(Exception ex) { m_edi = ExceptionDispatchInfo.Capture(ex); } } #endregion // A dummy delegate used as a : // 1- Flag to avoid recursive call to Value in None and ExecutionAndPublication modes in m_valueFactory // 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized static readonly Func<T> ALREADY_INVOKED_SENTINEL = delegate { Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked."); return default(T); }; //null --> value is not created //m_value is Boxed --> the value is created, and m_value holds the value //m_value is LazyExceptionHolder --> it holds an exception private object m_boxed; // The factory delegate that returns the value. // In None and ExecutionAndPublication modes, this will be set to ALREADY_INVOKED_SENTINEL as a flag to avoid recursive calls [NonSerialized] private Func<T> m_valueFactory; // null if it is not thread safe mode // LazyHelpers.PUBLICATION_ONLY_SENTINEL if PublicationOnly mode // object if ExecutionAndPublication mode (may be ALREADY_INVOKED_SENTINEL if the value is already initialized) [NonSerialized] private object m_threadSafeObj; /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that /// uses <typeparamref name="T"/>'s default constructor for lazy initialization. /// </summary> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy() : this(LazyThreadSafetyMode.ExecutionAndPublication) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that /// uses a pre-initialized specified value. /// </summary> /// <remarks> /// An instance created with this constructor should be usable by multiple threads // concurrently. /// </remarks> public Lazy(T value) { m_boxed = new Boxed(value); } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that uses a /// specified initialization function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is /// needed. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy(Func<T> valueFactory) : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> public Lazy(bool isThreadSafe) : this(isThreadSafe? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="mode">The lazy thread-safety mode mode</param> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception> public Lazy(LazyThreadSafetyMode mode) { m_threadSafeObj = GetObjectFromMode(mode); } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="mode">The lazy thread-safety mode.</param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception> public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode) { if (valueFactory == null) throw new ArgumentNullException("valueFactory"); m_threadSafeObj = GetObjectFromMode(mode); m_valueFactory = valueFactory; } /// <summary> /// Static helper function that returns an object based on the given mode. it also throws an exception if the mode is invalid /// </summary> private static object GetObjectFromMode(LazyThreadSafetyMode mode) { if (mode == LazyThreadSafetyMode.ExecutionAndPublication) return new object(); else if (mode == LazyThreadSafetyMode.PublicationOnly) return LazyHelpers.PUBLICATION_ONLY_SENTINEL; else if (mode != LazyThreadSafetyMode.None) throw new ArgumentOutOfRangeException("mode", Environment.GetResourceString("Lazy_ctor_ModeInvalid")); return null; // None mode } /// <summary>Forces initialization during serialization.</summary> /// <param name="context">The StreamingContext for the serialization operation.</param> [OnSerializing] private void OnSerializing(StreamingContext context) { // Force initialization T dummy = Value; } /// <summary>Creates and returns a string representation of this instance.</summary> /// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see /// cref="Value"/>.</returns> /// <exception cref="T:System.NullReferenceException"> /// The <see cref="Value"/> is null. /// </exception> public override string ToString() { return IsValueCreated ? Value.ToString() : Environment.GetResourceString("Lazy_ToString_ValueNotCreated"); } /// <summary>Gets the value of the Lazy&lt;T&gt; for debugging display purposes.</summary> internal T ValueForDebugDisplay { get { if (!IsValueCreated) { return default(T); } return ((Boxed)m_boxed).m_value; } } /// <summary> /// Gets a value indicating whether this instance may be used concurrently from multiple threads. /// </summary> internal LazyThreadSafetyMode Mode { get { if (m_threadSafeObj == null) return LazyThreadSafetyMode.None; if (m_threadSafeObj == (object)LazyHelpers.PUBLICATION_ONLY_SENTINEL) return LazyThreadSafetyMode.PublicationOnly; return LazyThreadSafetyMode.ExecutionAndPublication; } } /// <summary> /// Gets whether the value creation is faulted or not /// </summary> internal bool IsValueFaulted { get { return m_boxed is LazyInternalExceptionHolder; } } /// <summary>Gets a value indicating whether the <see cref="T:System.Lazy{T}"/> has been initialized. /// </summary> /// <value>true if the <see cref="T:System.Lazy{T}"/> instance has been initialized; /// otherwise, false.</value> /// <remarks> /// The initialization of a <see cref="T:System.Lazy{T}"/> instance may result in either /// a value being produced or an exception being thrown. If an exception goes unhandled during initialization, /// <see cref="IsValueCreated"/> will return false. /// </remarks> public bool IsValueCreated { get { return m_boxed != null && m_boxed is Boxed; } } /// <summary>Gets the lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</summary> /// <value>The lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</value> /// <exception cref="T:System.MissingMemberException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and that type does not have a public, parameterless constructor. /// </exception> /// <exception cref="T:System.MemberAccessException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and permissions to access the constructor were missing. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was constructed with the <see cref="T:System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or /// <see cref="T:System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance. /// </exception> /// <remarks> /// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization. /// Please <see cref="System.Threading.LazyThreadSafetyMode"> for more information on how <see cref="T:System.Threading.Lazy{T}"/> will behave if an exception is thrown /// from initialization delegate. /// </remarks> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value { get { Boxed boxed = null; if (m_boxed != null ) { // Do a quick check up front for the fast path. boxed = m_boxed as Boxed; if (boxed != null) { return boxed.m_value; } LazyInternalExceptionHolder exc = m_boxed as LazyInternalExceptionHolder; Contract.Assert(exc != null); exc.m_edi.Throw(); } // Fall through to the slow path. #if !FEATURE_CORECLR // We call NOCTD to abort attempts by the debugger to funceval this property (e.g. on mouseover) // (the debugger proxy is the correct way to look at state/value of this object) Debugger.NotifyOfCrossThreadDependency(); #endif return LazyInitValue(); } } /// <summary> /// local helper method to initialize the value /// </summary> /// <returns>The inititialized T value</returns> private T LazyInitValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (mode == LazyThreadSafetyMode.None) { boxed = CreateValue(); m_boxed = boxed; } else if (mode == LazyThreadSafetyMode.PublicationOnly) { boxed = CreateValue(); if (boxed == null || Interlocked.CompareExchange(ref m_boxed, boxed, null) != null) { // If CreateValue returns null, it means another thread successfully invoked the value factory // and stored the result, so we should just take what was stored. If CreateValue returns non-null // but another thread set the value we should just take what was stored. boxed = (Boxed)m_boxed; } else { // We successfully created and stored the value. At this point, the value factory delegate is // no longer needed, and we don't want to hold onto its resources. m_valueFactory = ALREADY_INVOKED_SENTINEL; } } else { object threadSafeObj = Volatile.Read(ref m_threadSafeObj); bool lockTaken = false; try { if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL) Monitor.Enter(threadSafeObj, ref lockTaken); else Contract.Assert(m_boxed != null); if (m_boxed == null) { boxed = CreateValue(); m_boxed = boxed; Volatile.Write(ref m_threadSafeObj, ALREADY_INVOKED_SENTINEL); } else // got the lock but the value is not null anymore, check if it is created by another thread or faulted and throw if so { boxed = m_boxed as Boxed; if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder { LazyInternalExceptionHolder exHolder = m_boxed as LazyInternalExceptionHolder; Contract.Assert(exHolder != null); exHolder.m_edi.Throw(); } } } finally { if (lockTaken) Monitor.Exit(threadSafeObj); } } Contract.Assert(boxed != null); return boxed.m_value; } /// <summary>Creates an instance of T using m_valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private Boxed CreateValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (m_valueFactory != null) { try { // check for recursion if (mode != LazyThreadSafetyMode.PublicationOnly && m_valueFactory == ALREADY_INVOKED_SENTINEL) throw new InvalidOperationException(Environment.GetResourceString("Lazy_Value_RecursiveCallsToValue")); Func<T> factory = m_valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes { m_valueFactory = ALREADY_INVOKED_SENTINEL; } else if (factory == ALREADY_INVOKED_SENTINEL) { // Another thread raced to successfully invoke the factory. return null; } boxed = new Boxed(factory()); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode m_boxed = new LazyInternalExceptionHolder(ex); throw; } } else { try { boxed = new Boxed((T)Activator.CreateInstance(typeof(T))); } catch (System.MissingMethodException) { Exception ex = new System.MissingMemberException(Environment.GetResourceString("Lazy_CreateValue_NoParameterlessCtorForT")); if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode m_boxed = new LazyInternalExceptionHolder(ex); throw ex; } } return boxed; } } /// <summary>A debugger view of the Lazy&lt;T&gt; to surface additional debugging properties and /// to ensure that the Lazy&lt;T&gt; does not become initialized if it was not already.</summary> internal sealed class System_LazyDebugView<T> { //The Lazy object being viewed. private readonly Lazy<T> m_lazy; /// <summary>Constructs a new debugger view object for the provided Lazy object.</summary> /// <param name="lazy">A Lazy object to browse in the debugger.</param> public System_LazyDebugView(Lazy<T> lazy) { m_lazy = lazy; } /// <summary>Returns whether the Lazy object is initialized or not.</summary> public bool IsValueCreated { get { return m_lazy.IsValueCreated; } } /// <summary>Returns the value of the Lazy object.</summary> public T Value { get { return m_lazy.ValueForDebugDisplay; } } /// <summary>Returns the execution mode of the Lazy object</summary> public LazyThreadSafetyMode Mode { get { return m_lazy.Mode; } } /// <summary>Returns the execution mode of the Lazy object</summary> public bool IsValueFaulted { get { return m_lazy.IsValueFaulted; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Globalization { public partial class ChineseLunisolarCalendar : System.Globalization.EastAsianLunisolarCalendar { public ChineseLunisolarCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int GetEra(System.DateTime time) { return default(int); } } public abstract partial class EastAsianLunisolarCalendar : System.Globalization.Calendar { internal EastAsianLunisolarCalendar() { } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public int GetCelestialStem(int sexagenaryYear) { return default(int); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public virtual int GetSexagenaryYear(System.DateTime time) { return default(int); } public int GetTerrestrialBranch(int sexagenaryYear) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class GregorianCalendar : System.Globalization.Calendar { public GregorianCalendar() { } public GregorianCalendar(System.Globalization.GregorianCalendarTypes type) { } public virtual System.Globalization.GregorianCalendarTypes CalendarType { get { return default(System.Globalization.GregorianCalendarTypes); } set { } } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public enum GregorianCalendarTypes { Arabic = 10, Localized = 1, MiddleEastFrench = 9, TransliteratedEnglish = 11, TransliteratedFrench = 12, USEnglish = 2, } public partial class HebrewCalendar : System.Globalization.Calendar { public HebrewCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class HijriCalendar : System.Globalization.Calendar { public HijriCalendar() { } public override int[] Eras { get { return default(int[]); } } public int HijriAdjustment { get { return default(int); } set { } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class JapaneseCalendar : System.Globalization.Calendar { public JapaneseCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class JapaneseLunisolarCalendar : System.Globalization.EastAsianLunisolarCalendar { public JapaneseLunisolarCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int GetEra(System.DateTime time) { return default(int); } } public partial class JulianCalendar : System.Globalization.Calendar { public JulianCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class KoreanCalendar : System.Globalization.Calendar { public KoreanCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class KoreanLunisolarCalendar : System.Globalization.EastAsianLunisolarCalendar { public KoreanLunisolarCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int GetEra(System.DateTime time) { return default(int); } } public partial class PersianCalendar : System.Globalization.Calendar { public PersianCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class TaiwanCalendar : System.Globalization.Calendar { public TaiwanCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class TaiwanLunisolarCalendar : System.Globalization.EastAsianLunisolarCalendar { public TaiwanLunisolarCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int GetEra(System.DateTime time) { return default(int); } } public partial class ThaiBuddhistCalendar : System.Globalization.Calendar { public ThaiBuddhistCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } public partial class UmAlQuraCalendar : System.Globalization.Calendar { public UmAlQuraCalendar() { } public override int[] Eras { get { return default(int[]); } } public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } } public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } } public override int TwoDigitYearMax { get { return default(int); } set { } } public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); } public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); } public override int GetDayOfMonth(System.DateTime time) { return default(int); } public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); } public override int GetDayOfYear(System.DateTime time) { return default(int); } public override int GetDaysInMonth(int year, int month, int era) { return default(int); } public override int GetDaysInYear(int year, int era) { return default(int); } public override int GetEra(System.DateTime time) { return default(int); } public override int GetLeapMonth(int year, int era) { return default(int); } public override int GetMonth(System.DateTime time) { return default(int); } public override int GetMonthsInYear(int year, int era) { return default(int); } public override int GetYear(System.DateTime time) { return default(int); } public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); } public override bool IsLeapMonth(int year, int month, int era) { return default(bool); } public override bool IsLeapYear(int year, int era) { return default(bool); } public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); } public override int ToFourDigitYear(int year) { return default(int); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Text; using NLog.Config; /// <summary> /// A specialized layout that renders CSV-formatted events. /// </summary> [Layout("CsvLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class CsvLayout : LayoutWithHeaderAndFooter { private string actualColumnDelimiter; private string doubleQuoteChar; private char[] quotableCharacters; /// <summary> /// Initializes a new instance of the <see cref="CsvLayout"/> class. /// </summary> public CsvLayout() { this.Columns = new List<CsvColumn>(); this.WithHeader = true; this.Delimiter = CsvColumnDelimiterMode.Auto; this.Quoting = CsvQuotingMode.Auto; this.QuoteChar = "\""; this.Layout = this; this.Header = new CsvHeaderLayout(this); this.Footer = null; } /// <summary> /// Gets the array of parameters to be passed. /// </summary> /// <docgen category='CSV Options' order='10' /> [ArrayParameter(typeof(CsvColumn), "column")] public IList<CsvColumn> Columns { get; private set; } /// <summary> /// Gets or sets a value indicating whether CVS should include header. /// </summary> /// <value>A value of <c>true</c> if CVS should include header; otherwise, <c>false</c>.</value> /// <docgen category='CSV Options' order='10' /> public bool WithHeader { get; set; } /// <summary> /// Gets or sets the column delimiter. /// </summary> /// <docgen category='CSV Options' order='10' /> [DefaultValue("Auto")] public CsvColumnDelimiterMode Delimiter { get; set; } /// <summary> /// Gets or sets the quoting mode. /// </summary> /// <docgen category='CSV Options' order='10' /> [DefaultValue("Auto")] public CsvQuotingMode Quoting { get; set; } /// <summary> /// Gets or sets the quote Character. /// </summary> /// <docgen category='CSV Options' order='10' /> [DefaultValue("\"")] public string QuoteChar { get; set; } /// <summary> /// Gets or sets the custom column delimiter value (valid when ColumnDelimiter is set to 'Custom'). /// </summary> /// <docgen category='CSV Options' order='10' /> public string CustomColumnDelimiter { get; set; } /// <summary> /// Initializes the layout. /// </summary> protected override void InitializeLayout() { base.InitializeLayout(); if (!this.WithHeader) { this.Header = null; } switch (this.Delimiter) { case CsvColumnDelimiterMode.Auto: this.actualColumnDelimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator; break; case CsvColumnDelimiterMode.Comma: this.actualColumnDelimiter = ","; break; case CsvColumnDelimiterMode.Semicolon: this.actualColumnDelimiter = ";"; break; case CsvColumnDelimiterMode.Pipe: this.actualColumnDelimiter = "|"; break; case CsvColumnDelimiterMode.Tab: this.actualColumnDelimiter = "\t"; break; case CsvColumnDelimiterMode.Space: this.actualColumnDelimiter = " "; break; case CsvColumnDelimiterMode.Custom: this.actualColumnDelimiter = this.CustomColumnDelimiter; break; } this.quotableCharacters = (this.QuoteChar + "\r\n" + this.actualColumnDelimiter).ToCharArray(); this.doubleQuoteChar = this.QuoteChar + this.QuoteChar; } /// <summary> /// Formats the log event for write. /// </summary> /// <param name="logEvent">The log event to be formatted.</param> /// <returns>A string representation of the log event.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { string cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { return cachedValue; } var sb = new StringBuilder(); //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < this.Columns.Count; i++) { CsvColumn col = this.Columns[i]; if (i != 0) { sb.Append(this.actualColumnDelimiter); } bool useQuoting; string text = col.Layout.Render(logEvent); switch (this.Quoting) { case CsvQuotingMode.Nothing: useQuoting = false; break; case CsvQuotingMode.All: useQuoting = true; break; default: case CsvQuotingMode.Auto: if (text.IndexOfAny(this.quotableCharacters) >= 0) { useQuoting = true; } else { useQuoting = false; } break; } if (useQuoting) { sb.Append(this.QuoteChar); } if (useQuoting) { sb.Append(text.Replace(this.QuoteChar, this.doubleQuoteChar)); } else { sb.Append(text); } if (useQuoting) { sb.Append(this.QuoteChar); } } return logEvent.AddCachedLayoutValue(this, sb.ToString()); } private string GetHeader() { var sb = new StringBuilder(); //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < this.Columns.Count; i++) { CsvColumn col = this.Columns[i]; if (i != 0) { sb.Append(this.actualColumnDelimiter); } bool useQuoting; string text = col.Name; switch (this.Quoting) { case CsvQuotingMode.Nothing: useQuoting = false; break; case CsvQuotingMode.All: useQuoting = true; break; default: case CsvQuotingMode.Auto: if (text.IndexOfAny(this.quotableCharacters) >= 0) { useQuoting = true; } else { useQuoting = false; } break; } if (useQuoting) { sb.Append(this.QuoteChar); } if (useQuoting) { sb.Append(text.Replace(this.QuoteChar, this.doubleQuoteChar)); } else { sb.Append(text); } if (useQuoting) { sb.Append(this.QuoteChar); } } return sb.ToString(); } /// <summary> /// Header for CSV layout. /// </summary> [ThreadAgnostic] private class CsvHeaderLayout : Layout { private CsvLayout parent; /// <summary> /// Initializes a new instance of the <see cref="CsvHeaderLayout"/> class. /// </summary> /// <param name="parent">The parent.</param> public CsvHeaderLayout(CsvLayout parent) { this.parent = parent; } /// <summary> /// Renders the layout for the specified logging event by invoking layout renderers. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { string cached; if (logEvent.TryGetCachedLayoutValue(this, out cached)) { return cached; } return logEvent.AddCachedLayoutValue(this, this.parent.GetHeader()); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Reflection; using DotSpatial.Controls; using DotSpatial.Data; using DotSpatial.Symbology; using DotSpatial.Tests.Common; using NUnit.Framework; namespace DotSpatial.Serialization.Tests { public enum TestEnum { Default, One, Two } [TestFixture] public class SerializationTests { private readonly List<string> _filesToRemove = new List<string>(); [TestFixtureTearDown] public void Clear() { foreach (var tempFile in _filesToRemove) { try { File.Delete(tempFile); } catch (Exception) { // ignore exceptions } } } [Test] public void TestSimpleGraph() { Node rootNode = new Node(1); Node intNode = new Node(42); rootNode.Nodes.Add(intNode); intNode.Nodes.Add(rootNode); Graph g = new Graph(rootNode); XmlSerializer s = new XmlSerializer(); string result = s.Serialize(g); XmlDeserializer d = new XmlDeserializer(); Graph newGraph = d.Deserialize<Graph>(result); Assert.IsNotNull(newGraph); Assert.AreEqual(g.Root.Data, newGraph.Root.Data); Assert.AreEqual(g.Root.Nodes[0].Data, newGraph.Root.Nodes[0].Data); Assert.AreEqual(g.Root.Nodes[0].Nodes[0].Data, newGraph.Root.Nodes[0].Nodes[0].Data); Assert.AreSame(newGraph.Root, newGraph.Root.Nodes[0].Nodes[0]); } [Test] public void TestGraphWithEnumNode() { Node rootNode = new Node(1); Node intNode = new Node(42); Node enumNode = new Node(TestEnum.Two); rootNode.Nodes.Add(intNode); rootNode.Nodes.Add(enumNode); intNode.Nodes.Add(rootNode); Graph g = new Graph(rootNode); XmlSerializer s = new XmlSerializer(); string result = s.Serialize(g); XmlDeserializer d = new XmlDeserializer(); Graph newGraph = d.Deserialize<Graph>(result); Assert.IsNotNull(newGraph); Assert.AreEqual(g.Root.Data, newGraph.Root.Data); Assert.AreEqual(g.Root.Nodes[0].Data, newGraph.Root.Nodes[0].Data); Assert.AreEqual(g.Root.Nodes[1].Data, newGraph.Root.Nodes[1].Data); Assert.AreEqual(g.Root.Nodes[0].Nodes[0].Data, newGraph.Root.Nodes[0].Nodes[0].Data); Assert.AreSame(newGraph.Root, newGraph.Root.Nodes[0].Nodes[0]); } [Test] public void TestGraphWithStringNode() { Node rootNode = new Node(1); Node intNode = new Node(42); Node stringNode = new Node("test string with <invalid> characters!"); rootNode.Nodes.Add(intNode); rootNode.Nodes.Add(stringNode); intNode.Nodes.Add(rootNode); Graph g = new Graph(rootNode); XmlSerializer s = new XmlSerializer(); string result = s.Serialize(g); XmlDeserializer d = new XmlDeserializer(); Graph newGraph = d.Deserialize<Graph>(result); Assert.IsNotNull(newGraph); Assert.AreEqual(g.Root.Data, newGraph.Root.Data); Assert.AreEqual(g.Root.Nodes[0].Data, newGraph.Root.Nodes[0].Data); Assert.AreEqual(g.Root.Nodes[1].Data, newGraph.Root.Nodes[1].Data); Assert.AreEqual(g.Root.Nodes[0].Nodes[0].Data, newGraph.Root.Nodes[0].Nodes[0].Data); Assert.AreSame(newGraph.Root, newGraph.Root.Nodes[0].Nodes[0]); } [Test] public void TestDictionary() { Dictionary<int, object> dictionary = new Dictionary<int, object>(); dictionary.Add(1, new Node(42)); dictionary.Add(2, "Hello <insert name here>!"); XmlSerializer s = new XmlSerializer(); string result = s.Serialize(dictionary); XmlDeserializer d = new XmlDeserializer(); Dictionary<int, object> newDictionary = d.Deserialize<Dictionary<int, object>>(result); foreach (var key in dictionary.Keys) { Assert.AreEqual(dictionary[key], newDictionary[key]); } } [Test] public void TestMapPointLayer() { string filename = Path.Combine("Data", "test-RandomPts.shp"); IFeatureSet fs = FeatureSet.Open(filename); MapPointLayer l = new MapPointLayer(fs); XmlSerializer s = new XmlSerializer(); string result = s.Serialize(l); XmlDeserializer d = new XmlDeserializer(); MapPointLayer newPointLayer = d.Deserialize<MapPointLayer>(result); Assert.IsNotNull(newPointLayer); Assert.AreEqual(newPointLayer.DataSet.Filename, Path.GetFullPath(filename)); } /// <summary> /// Test for DotSpatial Issue #254 /// </summary> [Test] public void TestMapFrameIsNotNull() { string filename = Path.Combine("Data", "test-RandomPts.shp"); string projectFileName = FileTools.GetTempFileName(".dspx"); _filesToRemove.Add(projectFileName); AppManager manager = new AppManager(); Map map = new Map(); manager.Map = map; IFeatureSet fs = FeatureSet.Open(filename); MapPointLayer l = new MapPointLayer(fs); map.Layers.Add(l); Assert.Greater(map.Layers.Count, 0); manager.SerializationManager.SaveProject(projectFileName); Assert.True(File.Exists(projectFileName)); //reopen the project map.Layers.Clear(); Assert.AreEqual(map.Layers.Count, 0); manager.SerializationManager.OpenProject(projectFileName); Assert.Greater(map.Layers.Count, 0); Assert.IsNotNull(map.Layers[0].MapFrame); } /// <summary> /// Test for DotSpatial Issue #254 /// </summary> [Test] public void TestMapFrameIsNotNull_Group() { string filename = Path.Combine("Data", "test-RandomPts.shp"); string projectFileName = FileTools.GetTempFileName(".dspx"); _filesToRemove.Add(projectFileName); AppManager manager = new AppManager(); Map map = new Map(); manager.Map = map; //new map group added to map MapGroup grp = new MapGroup(map, "group1"); //new map layer added to group IFeatureSet fs = FeatureSet.Open(filename); MapPointLayer l = new MapPointLayer(fs); //add layer to group grp.Layers.Add(l); Assert.Greater(map.Layers.Count, 0); Assert.IsNotNull(l.MapFrame); manager.SerializationManager.SaveProject(projectFileName); Assert.True(File.Exists(projectFileName)); //reopen the project map.Layers.Clear(); Assert.AreEqual(map.Layers.Count, 0); manager.SerializationManager.OpenProject(projectFileName); List<ILayer> layers = map.GetAllLayers(); Assert.IsNotNull(layers[0].MapFrame); } [Test] public void TestFormatter() { ObjectWithIntMember obj = new ObjectWithIntMember(0xBEEF); XmlSerializer s = new XmlSerializer(); string xml = s.Serialize(obj); XmlDeserializer d = new XmlDeserializer(); ObjectWithIntMember result1 = d.Deserialize<ObjectWithIntMember>(xml); Assert.IsNotNull(result1); Assert.AreEqual(0xBEEF, result1.Number); ObjectWithIntMember result2 = new ObjectWithIntMember(0); d.Deserialize(result2, xml); Assert.IsNotNull(result2); Assert.AreEqual(0xBEEF, result2.Number); } [Test] public void TestPointSerializationMap() { var pt = new Point(1, 2); var s = new XmlSerializer(); var xml = s.Serialize(pt); var d = new XmlDeserializer(); var result = d.Deserialize<Point>(xml); Assert.AreEqual(pt, result); } [Test] public void TestRectangleSerializationMap() { var rectangle = new Rectangle(1, 1, 2, 2); XmlSerializer s = new XmlSerializer(); string xml = s.Serialize(rectangle); XmlDeserializer d = new XmlDeserializer(); Rectangle result = d.Deserialize<Rectangle>(xml); Assert.AreEqual(1, result.X); Assert.AreEqual(1, result.Y); Assert.AreEqual(2, result.Width); Assert.AreEqual(2, result.Height); } } #region SerializationMap classes // ReSharper disable UnusedMember.Global public class PointSerializationMap : SerializationMap // ReSharper restore UnusedMember.Global { public PointSerializationMap() : base(typeof(Point)) { var t = typeof(Point); var x = t.GetField("x", BindingFlags.Instance | BindingFlags.NonPublic); var y = t.GetField("y", BindingFlags.Instance | BindingFlags.NonPublic); Serialize(x, "X").AsConstructorArgument(0); Serialize(y, "Y").AsConstructorArgument(1); } } // ReSharper disable UnusedMember.Global public class RectangleSerializationMap : SerializationMap // ReSharper restore UnusedMember.Global { public RectangleSerializationMap() : base(typeof(Rectangle)) { Type t = typeof(Rectangle); var x = t.GetField("x", BindingFlags.Instance | BindingFlags.NonPublic); var y = t.GetField("y", BindingFlags.Instance | BindingFlags.NonPublic); var width = t.GetField("width", BindingFlags.Instance | BindingFlags.NonPublic); var height = t.GetField("height", BindingFlags.Instance | BindingFlags.NonPublic); Serialize(x, "X").AsConstructorArgument(0); Serialize(y, "Y").AsConstructorArgument(1); Serialize(width, "Width").AsConstructorArgument(2); Serialize(height, "Height").AsConstructorArgument(3); } } #endregion }
// *********************************************************************** // Copyright (c) 2007 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.Generic; #if true #endif namespace NUnit.Framework.Constraints { /// <summary> /// ConstraintBuilder maintains the stacks that are used in /// processing a ConstraintExpression. An OperatorStack /// is used to hold operators that are waiting for their /// operands to be reognized. a ConstraintStack holds /// input constraints as well as the results of each /// operator applied. /// </summary> public class ConstraintBuilder { #region Nested Operator Stack Class /// <summary> /// OperatorStack is a type-safe stack for holding ConstraintOperators /// </summary> public class OperatorStack { #if true private Stack<ConstraintOperator> stack = new Stack<ConstraintOperator>(); #else private Stack stack = new Stack(); #endif /// <summary> /// Initializes a new instance of the <see cref="T:OperatorStack"/> class. /// </summary> /// <param name="builder">The builder.</param> public OperatorStack(ConstraintBuilder builder) { } /// <summary> /// Gets a value indicating whether this <see cref="T:OpStack"/> is empty. /// </summary> /// <value><c>true</c> if empty; otherwise, <c>false</c>.</value> public bool Empty { get { return stack.Count == 0; } } /// <summary> /// Gets the topmost operator without modifying the stack. /// </summary> /// <value>The top.</value> public ConstraintOperator Top { get { return (ConstraintOperator)stack.Peek(); } } /// <summary> /// Pushes the specified operator onto the stack. /// </summary> /// <param name="op">The op.</param> public void Push(ConstraintOperator op) { stack.Push(op); } /// <summary> /// Pops the topmost operator from the stack. /// </summary> /// <returns></returns> public ConstraintOperator Pop() { return (ConstraintOperator)stack.Pop(); } } #endregion #region Nested Constraint Stack Class /// <summary> /// ConstraintStack is a type-safe stack for holding Constraints /// </summary> public class ConstraintStack { #if true private Stack<Constraint> stack = new Stack<Constraint>(); #else private Stack stack = new Stack(); #endif private ConstraintBuilder builder; /// <summary> /// Initializes a new instance of the <see cref="T:ConstraintStack"/> class. /// </summary> /// <param name="builder">The builder.</param> public ConstraintStack(ConstraintBuilder builder) { this.builder = builder; } /// <summary> /// Gets a value indicating whether this <see cref="T:ConstraintStack"/> is empty. /// </summary> /// <value><c>true</c> if empty; otherwise, <c>false</c>.</value> public bool Empty { get { return stack.Count == 0; } } /// <summary> /// Gets the topmost constraint without modifying the stack. /// </summary> /// <value>The topmost constraint</value> public Constraint Top { get { return (Constraint)stack.Peek(); } } /// <summary> /// Pushes the specified constraint. As a side effect, /// the constraint's builder field is set to the /// ConstraintBuilder owning this stack. /// </summary> /// <param name="constraint">The constraint.</param> public void Push(Constraint constraint) { stack.Push(constraint); constraint.SetBuilder( this.builder ); } /// <summary> /// Pops this topmost constrait from the stack. /// As a side effect, the constraint's builder /// field is set to null. /// </summary> /// <returns></returns> public Constraint Pop() { Constraint constraint = (Constraint)stack.Pop(); constraint.SetBuilder( null ); return constraint; } } #endregion #region Instance Fields private readonly OperatorStack ops; private readonly ConstraintStack constraints; private object lastPushed; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:ConstraintBuilder"/> class. /// </summary> public ConstraintBuilder() { this.ops = new OperatorStack(this); this.constraints = new ConstraintStack(this); } #endregion #region Properties /// <summary> /// Gets a value indicating whether this instance is resolvable. /// </summary> /// <value> /// <c>true</c> if this instance is resolvable; otherwise, <c>false</c>. /// </value> public bool IsResolvable { get { return lastPushed is Constraint || lastPushed is SelfResolvingOperator; } } #endregion #region Public Methods /// <summary> /// Appends the specified operator to the expression by first /// reducing the operator stack and then pushing the new /// operator on the stack. /// </summary> /// <param name="op">The operator to push.</param> public void Append(ConstraintOperator op) { op.LeftContext = lastPushed; if (lastPushed is ConstraintOperator) SetTopOperatorRightContext(op); // Reduce any lower precedence operators ReduceOperatorStack(op.LeftPrecedence); ops.Push(op); lastPushed = op; } /// <summary> /// Appends the specified constraint to the expresson by pushing /// it on the constraint stack. /// </summary> /// <param name="constraint">The constraint to push.</param> public void Append(Constraint constraint) { if (lastPushed is ConstraintOperator) SetTopOperatorRightContext(constraint); constraints.Push(constraint); lastPushed = constraint; constraint.SetBuilder( this ); } /// <summary> /// Sets the top operator right context. /// </summary> /// <param name="rightContext">The right context.</param> private void SetTopOperatorRightContext(object rightContext) { // Some operators change their precedence based on // the right context - save current precedence. int oldPrecedence = ops.Top.LeftPrecedence; ops.Top.RightContext = rightContext; // If the precedence increased, we may be able to // reduce the region of the stack below the operator if (ops.Top.LeftPrecedence > oldPrecedence) { ConstraintOperator changedOp = ops.Pop(); ReduceOperatorStack(changedOp.LeftPrecedence); ops.Push(changedOp); } } /// <summary> /// Reduces the operator stack until the topmost item /// precedence is greater than or equal to the target precedence. /// </summary> /// <param name="targetPrecedence">The target precedence.</param> private void ReduceOperatorStack(int targetPrecedence) { while (!ops.Empty && ops.Top.RightPrecedence < targetPrecedence) ops.Pop().Reduce(constraints); } /// <summary> /// Resolves this instance, returning a Constraint. If the builder /// is not currently in a resolvable state, an exception is thrown. /// </summary> /// <returns>The resolved constraint</returns> public Constraint Resolve() { if (!IsResolvable) throw new InvalidOperationException("A partial expression may not be resolved"); while (!ops.Empty) { ConstraintOperator op = ops.Pop(); op.Reduce(constraints); } return constraints.Pop(); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using Orleans.MultiCluster; using Orleans.Runtime.Configuration; using Orleans.Runtime.MembershipService; namespace Orleans.Runtime.Management { /// <summary> /// Implementation class for the Orleans management grain. /// </summary> [OneInstancePerCluster] internal class ManagementGrain : Grain, IManagementGrain { private Logger logger; private IMembershipTable membershipTable; public override Task OnActivateAsync() { logger = LogManager.GetLogger("ManagementGrain", LoggerType.Runtime); return TaskDone.Done; } public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false) { var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); var t = onlyActive ? table.Members.Where(item => item.Item1.Status == SiloStatus.Active).ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status) : table.Members.ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status); return t; } public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false) { logger.Info("GetDetailedHosts onlyActive={0}", onlyActive); var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); if (onlyActive) { return table.Members .Where(item => item.Item1.Status == SiloStatus.Active) .Select(x => x.Item1) .ToArray(); } return table.Members .Select(x => x.Item1) .ToArray(); } public Task SetSystemLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetSystemTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetSystemLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetAppLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetAppTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetAppLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetLogLevel(SiloAddress[] siloAddresses, string logName, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetLogLevel[{1}]={2} {0}", Utils.EnumerableToString(silos), logName, traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetLogLevel(logName, traceLevel)); return Task.WhenAll(actionPromises); } public Task ForceGarbageCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).ForceGarbageCollection()); return Task.WhenAll(actionPromises); } public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit) { var silos = GetSiloAddresses(siloAddresses); return Task.WhenAll(GetSiloAddresses(silos).Select(s => GetSiloControlReference(s).ForceActivationCollection(ageLimit))); } public async Task ForceActivationCollection(TimeSpan ageLimit) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); await ForceActivationCollection(silos, ageLimit); } public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction( silos, s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection()); return Task.WhenAll(actionPromises); } public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); if (logger.IsVerbose) logger.Verbose("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos)); var promises = new List<Task<SiloRuntimeStatistics>>(); foreach (SiloAddress siloAddress in silos) promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics()); return Task.WhenAll(promises); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds) { var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); return await GetSimpleGrainStatistics(silos); } public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); hostsIds = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<int> GetGrainActivationCount(GrainReference grainReference) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> hostsIds = hosts.Keys.ToList(); var tasks = new List<Task<DetailedGrainReport>>(); foreach (var silo in hostsIds) tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId)); await Task.WhenAll(tasks); return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum(); } public async Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing) { var global = new[] { "Globals/", "/Globals/", "OrleansConfiguration/Globals/", "/OrleansConfiguration/Globals/" }; if (hostIds != null && configuration.Keys.Any(k => global.Any(k.StartsWith))) throw new ArgumentException("Must update global configuration settings on all silos"); var silos = GetSiloAddresses(hostIds); if (silos.Length == 0) return; var document = XPathValuesToXml(configuration); if (tracing != null) { AddXPathValue(document, new[] { "OrleansConfiguration", "Defaults", "Tracing" }, null); var parent = document["OrleansConfiguration"]["Defaults"]["Tracing"]; foreach (var trace in tracing) { var child = document.CreateElement("TraceLevelOverride"); child.SetAttribute("LogPrefix", trace.Key); child.SetAttribute("TraceLevel", trace.Value); parent.AppendChild(child); } } using(var sw = new StringWriter()) { using(var xw = XmlWriter.Create(sw)) { document.WriteTo(xw); xw.Flush(); var xml = sw.ToString(); // do first one, then all the rest to avoid spamming all the silos in case of a parameter error await GetSiloControlReference(silos[0]).UpdateConfiguration(xml); await Task.WhenAll(silos.Skip(1).Select(s => GetSiloControlReference(s).UpdateConfiguration(xml))); } } } public async Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations) { SiloAddress[] silos = GetSiloAddresses(hostIds); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).UpdateStreamProviders(streamProviderConfigurations)); await Task.WhenAll(actionPromises); } public async Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetGrainTypeList()).ToArray(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).Distinct().ToArray(); } public async Task<int> GetTotalActivationCount() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> silos = hosts.Keys.ToList(); var tasks = new List<Task<int>>(); foreach (var silo in silos) tasks.Add(GetSiloControlReference(silo).GetActivationCount()); await Task.WhenAll(tasks); int sum = 0; foreach (Task<int> task in tasks) sum += task.Result; return sum; } public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg) { return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg), String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command)); } private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog) { var silos = await GetHosts(true); if(logger.IsVerbose) { logger.Verbose("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys)); } var actionPromises = new List<Task<object>>(); foreach (SiloAddress siloAddress in silos.Keys.ToArray()) actionPromises.Add(action(GetSiloControlReference(siloAddress))); return await Task.WhenAll(actionPromises); } private async Task<IMembershipTable> GetMembershipTable() { if (membershipTable == null) { var factory = new MembershipFactory(); membershipTable = factory.GetMembershipTable(Silo.CurrentSilo.GlobalConfig.LivenessType, Silo.CurrentSilo.GlobalConfig.MembershipTableAssembly); await membershipTable.InitializeMembershipTable(Silo.CurrentSilo.GlobalConfig, false, LogManager.GetLogger(membershipTable.GetType().Name)); } return membershipTable; } private static SiloAddress[] GetSiloAddresses(SiloAddress[] silos) { if (silos != null && silos.Length > 0) return silos; return InsideRuntimeClient.Current.Catalog.SiloStatusOracle .GetApproximateSiloStatuses(true).Select(s => s.Key).ToArray(); } /// <summary> /// Perform an action for each silo. /// </summary> /// <remarks> /// Because SiloControl contains a reference to a system target, each method call using that reference /// will get routed either locally or remotely to the appropriate silo instance auto-magically. /// </remarks> /// <param name="siloAddresses">List of silos to perform the action for</param> /// <param name="perSiloAction">The action functiona to be performed for each silo</param> /// <returns>Array containing one Task for each silo the action was performed for</returns> private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction) { var requestsToSilos = new List<Task>(); foreach (SiloAddress siloAddress in siloAddresses) requestsToSilos.Add( perSiloAction(siloAddress) ); return requestsToSilos; } private static XmlDocument XPathValuesToXml(Dictionary<string,string> values) { var doc = new XmlDocument(); if (values == null) return doc; foreach (var p in values) { var path = p.Key.Split('/').ToList(); if (path[0] == "") path.RemoveAt(0); if (path[0] != "OrleansConfiguration") path.Insert(0, "OrleansConfiguration"); if (!path[path.Count - 1].StartsWith("@")) throw new ArgumentException("XPath " + p.Key + " must end with @attribute"); AddXPathValue(doc, path, p.Value); } return doc; } private static void AddXPathValue(XmlNode xml, IEnumerable<string> path, string value) { if (path == null) return; var first = path.FirstOrDefault(); if (first == null) return; if (first.StartsWith("@")) { first = first.Substring(1); if (path.Count() != 1) throw new ArgumentException("Attribute " + first + " must be last in path"); var e = xml as XmlElement; if (e == null) throw new ArgumentException("Attribute " + first + " must be on XML element"); e.SetAttribute(first, value); return; } foreach (var child in xml.ChildNodes) { var e = child as XmlElement; if (e != null && e.LocalName == first) { AddXPathValue(e, path.Skip(1), value); return; } } var empty = (xml as XmlDocument ?? xml.OwnerDocument).CreateElement(first); xml.AppendChild(empty); AddXPathValue(empty, path.Skip(1), value); } private ISiloControl GetSiloControlReference(SiloAddress silo) { return InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo); } #region MultiCluster private MultiClusterNetwork.IMultiClusterOracle GetMultiClusterOracle() { if (!Silo.CurrentSilo.GlobalConfig.HasMultiClusterNetwork) throw new OrleansException("No multicluster network configured"); return Silo.CurrentSilo.LocalMultiClusterOracle; } public Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways() { return Task.FromResult(GetMultiClusterOracle().GetGateways().Cast<IMultiClusterGatewayInfo>().ToList()); } public Task<MultiClusterConfiguration> GetMultiClusterConfiguration() { return Task.FromResult(GetMultiClusterOracle().GetMultiClusterConfiguration()); } public async Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true) { var multiClusterOracle = GetMultiClusterOracle(); var configuration = new MultiClusterConfiguration(DateTime.UtcNow, clusters.ToList(), comment); if (!MultiClusterConfiguration.OlderThan(multiClusterOracle.GetMultiClusterConfiguration(), configuration)) throw new OrleansException("Could not inject multi-cluster configuration: current configuration is newer than clock"); if (checkForLaggingSilosFirst) { try { var laggingSilos = await multiClusterOracle.FindLaggingSilos(multiClusterOracle.GetMultiClusterConfiguration()); if (laggingSilos.Count > 0) { var msg = string.Format("Found unstable silos {0}", string.Join(",", laggingSilos)); throw new OrleansException(msg); } } catch (Exception e) { throw new OrleansException("Could not inject multi-cluster configuration: stability check failed", e); } } await multiClusterOracle.InjectMultiClusterConfiguration(configuration); return configuration; } public Task<List<SiloAddress>> FindLaggingSilos() { var multiClusterOracle = GetMultiClusterOracle(); var expected = multiClusterOracle.GetMultiClusterConfiguration(); return multiClusterOracle.FindLaggingSilos(expected); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using SIL.Lift.Options; using SIL.ObjectModel; using SIL.Reporting; using SIL.Text; namespace SIL.Lift { public interface IPalasoDataObjectProperty : ICloneable<IPalasoDataObjectProperty>, IEquatable<IPalasoDataObjectProperty> { PalasoDataObject Parent { set; } } public interface IReceivePropertyChangeNotifications { void NotifyPropertyChanged(string property); } public interface IReferenceContainer { string TargetId { get; set; } string Key { get; set; } } public abstract class PalasoDataObject: INotifyPropertyChanged, IReceivePropertyChangeNotifications { [NonSerialized] private ArrayList _listEventHelpers; /// <summary> /// see comment on _parent field of MultiText for an explanation of this field /// </summary> private PalasoDataObject _parent; private List<KeyValuePair<string, IPalasoDataObjectProperty>> _properties; protected PalasoDataObject(PalasoDataObject parent) { _properties = new List<KeyValuePair<string, IPalasoDataObjectProperty>>(); _parent = parent; } public IEnumerable<string> PropertiesInUse { get { return Properties.Select(prop => prop.Key); } } public abstract bool IsEmpty { get; } /// <summary> /// see comment on _parent field of MultiText for an explanation of this field /// </summary> public PalasoDataObject Parent { get { return _parent; } set { Debug.Assert(value != null); _parent = value; } } public List<KeyValuePair<string, IPalasoDataObjectProperty>> Properties { get { if (_properties == null) { _properties = new List<KeyValuePair<string, IPalasoDataObjectProperty>>(); NotifyPropertyChanged("properties dictionary"); } return _properties; } } public bool HasProperties { get { foreach (KeyValuePair<string, IPalasoDataObjectProperty> pair in _properties) { if (!IsPropertyEmpty(pair.Value)) { return true; } } return false; } } public bool HasPropertiesForPurposesOfDeletion { get { return _properties.Any(pair => !IsPropertyEmptyForPurposesOfDeletion(pair.Value)); } } #region INotifyPropertyChanged Members /// <summary> /// For INotifyPropertyChanged /// </summary> public event PropertyChangedEventHandler PropertyChanged = delegate { }; #endregion public event EventHandler EmptyObjectsRemoved = delegate { }; /// <summary> /// Do the non-db40-specific parts of becoming activated /// </summary> public void FinishActivation() { EmptyObjectsRemoved = delegate { }; WireUpEvents(); } protected void WireUpList(IBindingList list, string listName) { _listEventHelpers.Add(new ListEventHelper(this, list, listName)); } protected virtual void WireUpEvents() { _listEventHelpers = new ArrayList(); PropertyChanged += OnPropertyChanged; } private void OnEmptyObjectsRemoved(object sender, EventArgs e) { // perculate up EmptyObjectsRemoved(sender, e); } protected void OnEmptyObjectsRemoved() { EmptyObjectsRemoved(this, new EventArgs()); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { SomethingWasModified(e.PropertyName); } public void WireUpChild(INotifyPropertyChanged child) { child.PropertyChanged -= OnChildObjectPropertyChanged; //prevent the bug where we were acquiring these with each GetProperty<> call child.PropertyChanged += OnChildObjectPropertyChanged; if (child is PalasoDataObject) { ((PalasoDataObject) child).EmptyObjectsRemoved += OnEmptyObjectsRemoved; } } /// <summary> /// called by the binding list when senses are added, removed, reordered, etc. /// Also called when the user types in fields, etc. /// </summary> /// <remarks>The only side effect of this should be to update the dateModified fields</remarks> public virtual void SomethingWasModified(string propertyModified) { //NO: can't do this until really putting the record to bed; //only the display code knows when to do that. RemoveEmptyProperties(); } public virtual void CleanUpAfterEditting() { RemoveEmptyProperties(); } public virtual void CleanUpEmptyObjects() {} /// <summary> /// BE CAREFUL about when this is called. Empty properties *should exist* /// as long as the record is being editted /// </summary> public void RemoveEmptyProperties() { // remove any custom fields that are empty int originalCount = Properties.Count; for (int i = originalCount - 1;i >= 0;i--) // NB: counting backwards { //trying to reproduce ws-564 Debug.Assert(Properties.Count > i, "Likely hit the ws-564 bug."); if (Properties.Count <= i) { ErrorReport.ReportNonFatalMessageWithStackTrace( "The number of properties was orginally {0}, is now {1}, but the index is {2}. PLEASE help us reproduce this bug.", originalCount, Properties.Count, i); } object property = Properties[i].Value; if (property is IReportEmptiness) { ((IReportEmptiness) property).RemoveEmptyStuff(); } if (IsPropertyEmpty(property)) { Logger.WriteMinorEvent("Removing {0} due to emptiness.", property.ToString()); Properties.RemoveAt(i); // don't: this just makes for false modified events: NotifyPropertyChanged(property.ToString()); } } } private static bool IsPropertyEmpty(object property) { if (property is MultiText) { return MultiTextBase.IsEmpty((MultiText) property); } else if (property is OptionRef) { return ((OptionRef) property).IsEmpty; } else if (property is OptionRefCollection) { return ((OptionRefCollection) property).IsEmpty; } else if (property is IReportEmptiness) { return ((IReportEmptiness) property).ShouldBeRemovedFromParentDueToEmptiness; } // Debug.Fail("Unknown property type"); return false; //don't throw it away if you don't know what it is } private static bool IsPropertyEmptyForPurposesOfDeletion(object property) { if (property is MultiText) { return IsPropertyEmpty(property); } else if (property is OptionRef) { return true; } else if (property is OptionRefCollection) { return ((OptionRefCollection) property).ShouldHoldUpDeletionOfParentObject; } else if (property is IReportEmptiness) { return IsPropertyEmpty(property); } return false; //don't throw it away if you don't know what it is } public virtual void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } protected virtual void OnChildObjectPropertyChanged(object sender, PropertyChangedEventArgs e) { NotifyPropertyChanged(e.PropertyName); } public TContents GetOrCreateProperty<TContents>(string fieldName) where TContents : class, IPalasoDataObjectProperty, new() { TContents value = GetProperty<TContents>(fieldName); if (value != null) { return value; } TContents newGuy = new TContents(); //Properties.Add(fieldName, newGuy); Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(fieldName, newGuy)); newGuy.Parent = this; //temp hack until mt's use parents for notification if (newGuy is MultiText) { WireUpChild((INotifyPropertyChanged) newGuy); } return newGuy; } protected void AddProperty(string fieldName, IPalasoDataObjectProperty field) { Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(fieldName, field)); field.Parent = this; //temp hack until mt's use parents for notification if (field is MultiText) { WireUpChild((INotifyPropertyChanged)field); } } /// <summary> /// Will return null if not found /// </summary> /// <typeparam name="TContents"></typeparam> /// <returns>null if not found</returns> public TContents GetProperty<TContents>(string fieldName) where TContents : class //, IParentable { KeyValuePair<string, IPalasoDataObjectProperty> found = Properties.Find(p => p.Key == fieldName); if (found.Key == fieldName) { Debug.Assert(found.Value is TContents, "Currently we assume that there is only a single type of object for a given name."); //temp hack until mt's use parents for notification);on if (found.Value is MultiText) { WireUpChild((INotifyPropertyChanged) found.Value); } return found.Value as TContents; } return null; } /// <summary> /// Merge in a property from some other object, e.g., when merging senses /// </summary> public void MergeProperty(KeyValuePair<string, IPalasoDataObjectProperty> incoming) { KeyValuePair<string, IPalasoDataObjectProperty> existing = Properties.Find( p => p.Key == incoming.Key ); if (existing.Value is OptionRefCollection) { if (existing.Key == incoming.Key) { var optionRefCollection = existing.Value as OptionRefCollection; var incomingRefCollection = incoming.Value as OptionRefCollection; optionRefCollection.MergeByKey(incomingRefCollection); } else { Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(incoming.Key, incoming.Value)); } } else { if (existing.Key == incoming.Key) { Properties.Remove(existing); } Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(incoming.Key, incoming.Value)); } incoming.Value.Parent = this; //temp hack until mt's use parents for notification if (incoming.Value is MultiText) { WireUpChild((INotifyPropertyChanged)incoming.Value); } } public bool GetHasFlag(string propertyName) { FlagState flag = GetProperty<FlagState>(propertyName); if (flag == null) { return false; } return flag.Value; } /// <summary> /// /// </summary> ///<remarks>Seting a flag is represented by creating a property and giving it a "set" /// value, though that is not really meaningful (there are no other possible values).</remarks> /// <param name="propertyName"></param> public void SetFlag(string propertyName) { FlagState f = GetOrCreateProperty<FlagState>(propertyName); f.Value = true; // KeyValuePair<FlagState, object> found = Properties.Find(delegate(KeyValuePair<FlagState, object> p) { return p.Key == propertyName; }); // if (found.Key == propertyName) // { // _properties.Remove(found); // } // // Properties.Add(new KeyValuePair<string, object>(propertyName, "set")); } /// <summary> /// /// </summary> /// <remarks>Clearing a flag is represented by just removing the property, if it exists</remarks> /// <param name="propertyName"></param> public void ClearFlag(string propertyName) { KeyValuePair<string, IPalasoDataObjectProperty> found = Properties.Find(p => p.Key == propertyName); if (found.Key == propertyName) { _properties.Remove(found); } } #region Nested type: WellKnownProperties public class WellKnownProperties { public static string Note = "note"; public static bool Contains(string fieldName) { List<string> list = new List<string>(new string[] {Note}); return list.Contains(fieldName); } } ; #endregion public static string GetEmbeddedXmlNameForProperty(string name) { return name + "-xml"; } public override bool Equals(Object obj) { if (!(obj is PalasoDataObject)) return false; return Equals((PalasoDataObject)obj); } public bool Equals(PalasoDataObject other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!_properties.SequenceEqual(other._properties)) return false; return true; } } public interface IReportEmptiness { bool ShouldHoldUpDeletionOfParentObject { get; } bool ShouldCountAsFilledForPurposesOfConditionalDisplay { get; } bool ShouldBeRemovedFromParentDueToEmptiness { get; } void RemoveEmptyStuff(); } /// <summary> /// This class enables creating the necessary event subscriptions. It was added /// before we were forced to add "parent" fields to everything. I could probably /// be removed now, since that field could be used by children to cause the wiring, /// but we are hoping that the parent field might go away with future version of db4o. /// </summary> public class ListEventHelper { private readonly string _listName; private readonly PalasoDataObject _listOwner; public ListEventHelper(PalasoDataObject listOwner, IBindingList list, string listName) { _listOwner = listOwner; _listName = listName; list.ListChanged += OnListChanged; foreach (INotifyPropertyChanged x in list) { _listOwner.WireUpChild(x); } } private void OnListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { IBindingList list = (IBindingList) sender; INotifyPropertyChanged newGuy = (INotifyPropertyChanged) list[e.NewIndex]; _listOwner.WireUpChild(newGuy); if (newGuy is PalasoDataObject) { ((PalasoDataObject) newGuy).Parent = _listOwner; } } _listOwner.NotifyPropertyChanged(_listName); } } public class EmbeddedXmlCollection: IPalasoDataObjectProperty { private List<string> _values; private PalasoDataObject _parent; public EmbeddedXmlCollection() { _values = new List<string>(); } public PalasoDataObject Parent { set { _parent = value; } } public List<string> Values { get { return _values; } set { _values = value; } } public IPalasoDataObjectProperty Clone() { var clone = new EmbeddedXmlCollection(); clone._values.AddRange(_values); return clone; } public override bool Equals(object other) { return Equals((EmbeddedXmlCollection)other); } public bool Equals(IPalasoDataObjectProperty other) { return Equals((EmbeddedXmlCollection) other); } public bool Equals(EmbeddedXmlCollection other) { if (other == null) return false; if (!_values.SequenceEqual(other._values)) return false; //order is relevant return true; } public override string ToString() { var builder = new StringBuilder(); foreach (var part in Values) { builder.Append(part.ToString() + " "); } return builder.ToString().Trim(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class ToLookupTests : EnumerableTests { private static void AssertMatches<K, T>(IEnumerable<K> keys, IEnumerable<T> elements, System.Linq.ILookup<K, T> lookup) { Assert.NotNull(lookup); Assert.NotNull(keys); Assert.NotNull(elements); int num = 0; using (IEnumerator<K> keyEnumerator = keys.GetEnumerator()) using (IEnumerator<T> elEnumerator = elements.GetEnumerator()) { while (keyEnumerator.MoveNext()) { Assert.True(lookup.Contains(keyEnumerator.Current)); foreach (T e in lookup[keyEnumerator.Current]) { Assert.True(elEnumerator.MoveNext()); Assert.Equal(e, elEnumerator.Current); } ++num; } Assert.False(elEnumerator.MoveNext()); } Assert.Equal(num, lookup.Count); } [Fact] public void SameResultsRepeatCall() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; ; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; Assert.Equal(q.ToLookup(e => e.a1), q.ToLookup(e => e.a1)); } [Fact] public void NullKeyIncluded() { string[] key = { "Chris", "Bob", null, "Tim" }; int[] element = { 50, 95, 55, 90 }; var source = key.Zip(element, (k, e) => new { Name = k, Score = e }); AssertMatches(key, source, source.ToLookup(e => e.Name)); } [Fact] public void OneElementCustomComparer() { string[] key = { "Chris" }; int[] element = { 50 }; var source = new [] { new {Name = "risCh", Score = 50} }; AssertMatches(key, source, source.ToLookup(e => e.Name, new AnagramEqualityComparer())); } [Fact] public void UniqueElementsElementSelector() { string[] key = { "Chris", "Prakash", "Tim", "Robert", "Brian" }; int[] element = { 50, 100, 95, 60, 80 }; var source = new [] { new { Name = key[0], Score = element[0] }, new { Name = key[1], Score = element[1] }, new { Name = key[2], Score = element[2] }, new { Name = key[3], Score = element[3] }, new { Name = key[4], Score = element[4] } }; AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score)); } [Fact] public void DuplicateKeys() { string[] key = { "Chris", "Prakash", "Robert" }; int[] element = { 50, 80, 100, 95, 99, 56 }; var source = new[] { new { Name = key[0], Score = element[0] }, new { Name = key[1], Score = element[2] }, new { Name = key[2], Score = element[5] }, new { Name = key[1], Score = element[3] }, new { Name = key[0], Score = element[1] }, new { Name = key[1], Score = element[4] } }; AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void Count() { string[] key = { "Chris", "Prakash", "Robert" }; int[] element = { 50, 80, 100, 95, 99, 56 }; var source = new[] { new { Name = key[0], Score = element[0] }, new { Name = key[1], Score = element[2] }, new { Name = key[2], Score = element[5] }, new { Name = key[1], Score = element[3] }, new { Name = key[0], Score = element[1] }, new { Name = key[1], Score = element[4] } }; Assert.Equal(3, source.ToLookup(e => e.Name, e => e.Score).Count()); } [Fact] public void EmptySource() { string[] key = { }; int[] element = { }; var source = key.Zip(element, (k, e) => new { Name = k, Score = e }); AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void SingleNullKeyAndElement() { string[] key = { null }; string[] element = { null }; string[] source = new string[] { null }; AssertMatches(key, element, source.ToLookup(e => e, e => e, EqualityComparer<string>.Default)); } [Fact] public void NullSource() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10)); } [Fact] public void NullSourceExplicitComparer() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, EqualityComparer<int>.Default)); } [Fact] public void NullSourceElementSelector() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, i => i + 2)); } [Fact] public void NullSourceElementSelectorExplicitComparer() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, i => i + 2, EqualityComparer<int>.Default)); } [Fact] public void NullKeySelector() { Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector)); } [Fact] public void NullKeySelectorExplicitComparer() { Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, EqualityComparer<int>.Default)); } [Fact] public void NullKeySelectorElementSelector() { Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, i => i + 2)); } [Fact] public void NullKeySelectorElementSelectorExplicitComparer() { Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, i => i + 2, EqualityComparer<int>.Default)); } [Fact] public void NullElementSelector() { Func<int, int> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => Enumerable.Range(0, 1000).ToLookup(i => i / 10, elementSelector)); } [Fact] public void NullElementSelectorExplicitComparer() { Func<int, int> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => Enumerable.Range(0, 1000).ToLookup(i => i / 10, elementSelector, EqualityComparer<int>.Default)); } } }
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ContosoUniversity.Data.Entities; using System; using ContosoUniversity.ViewModels; using ContosoUniversity.Common.Interfaces; using AutoMapper; using ContosoUniversity.Common; using ContosoUniversity.Data.DbContexts; using Microsoft.AspNetCore.Authorization; namespace ContosoUniversity.Web.Controllers { public class DepartmentsController : Controller { private readonly IRepository<Department> _departmentRepo; private readonly IRepository<Instructor> _instructorRepo; private readonly IModelBindingHelperAdaptor _modelBindingHelperAdaptor; private readonly IMapper _mapper; public DepartmentsController(UnitOfWork<ApplicationContext> unitOfWork, IModelBindingHelperAdaptor modelBindingHelperAdaptor, IMapper mapper) { _departmentRepo = unitOfWork.DepartmentRepository; _instructorRepo = unitOfWork.InstructorRepository; _modelBindingHelperAdaptor = modelBindingHelperAdaptor; _mapper = mapper; } public async Task<IActionResult> Index() { var query = _departmentRepo.GetAll() .Include(d => d.Administrator) .Select(d => _mapper.Map<DepartmentDetailsViewModel>(d)); return View(await query.ToListAsync()); } public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var vm = await _departmentRepo.Get(id.Value) .Include(d => d.Administrator) .Select(d => _mapper.Map<DepartmentDetailsViewModel>(d)) .AsGatedNoTracking() .SingleOrDefaultAsync(); if (vm == null) { return NotFound(); } return View(vm); } public IActionResult Create() { ViewData["InstructorID"] = new SelectList(_instructorRepo.GetAll(), "ID", "FullName"); return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(DepartmentCreateViewModel vm) { if (ModelState.IsValid) { var department = _mapper.Map<Department>(vm); await _departmentRepo.AddAsync(department); await _departmentRepo.SaveChangesAsync(); return RedirectToAction("Index", new { newid = department.ID }); } ViewData["InstructorID"] = new SelectList(_instructorRepo.GetAll(), "ID", "FullName", vm.InstructorID); return View(vm); } public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var department = await _departmentRepo.Get(id.Value) .AsGatedNoTracking() .SingleOrDefaultAsync(); if (department == null) { return NotFound(); } var vm = _mapper.Map<DepartmentEditViewModel>(department); ViewData["InstructorID"] = new SelectList(_instructorRepo.GetAll(), "ID", "FullName", department.InstructorID); return View(vm); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(DepartmentEditViewModel vm) { if (!ModelState.IsValid) { return View(vm); } var departmentToUpdate = await _departmentRepo.Get(vm.ID) .Include(i => i.Administrator) .SingleOrDefaultAsync(); if (departmentToUpdate == null) { ModelState.AddModelError(string.Empty, "Unable to save changes. The department was deleted by another user."); ViewData["InstructorID"] = new SelectList(_instructorRepo.GetAll(), "ID", "FullName", vm.InstructorID); return View(vm); } try { departmentToUpdate = _mapper.Map(vm, departmentToUpdate); departmentToUpdate.ModifiedDate = DateTime.UtcNow; await _departmentRepo.SaveChangesAsync(); return RedirectToAction("Index"); } catch (DbUpdateConcurrencyException ex) { var exceptionEntry = ex.Entries.Single(); var clientValues = (Department)exceptionEntry.Entity; var databaseEntry = exceptionEntry.GetDatabaseValues(); if (databaseEntry == null) { ModelState.AddModelError(string.Empty, "Unable to save changes. The department was deleted by another use."); } else { var databaseValues = (Department)databaseEntry.ToObject(); if (databaseValues.Name != clientValues.Name) { ModelState.AddModelError("Name", $"Current value: {databaseValues.Name}"); } if (databaseValues.Budget != clientValues.Budget) { ModelState.AddModelError("Budget", $"Current value: {databaseValues.Budget:c}"); } if (databaseValues.StartDate != clientValues.StartDate) { ModelState.AddModelError("StartDate", $"Current value: {databaseValues.StartDate:d}"); } if (databaseValues.InstructorID != clientValues.InstructorID) { Instructor databaseInstructor = await _instructorRepo.GetAll().SingleOrDefaultAsync(i => i.ID == databaseValues.InstructorID); ModelState.AddModelError("InstructorID", $"Current value: {databaseInstructor?.FullName}"); } ModelState.AddModelError(string.Empty, "The record you attempted to edit was modified by another use after you got the original valued. " + "The edit operation was canceled and the current values in the database have been displayed. If you still want to edit this record, " + "click the Save button again. Otherwise click the back to List hyperlink."); departmentToUpdate.RowVersion = (byte[])databaseValues.RowVersion; ModelState.Remove("RowVersion"); } } ViewData["InstructorID"] = new SelectList(_instructorRepo.GetAll(), "ID", "FullName", vm.InstructorID); return View(vm); } [Authorize(Roles = "Administrator")] public async Task<IActionResult> Delete(int? id, bool? concurrencyError) { if (id == null) { return NotFound(); } var department = await _departmentRepo.Get(id.Value) .Include(d => d.Administrator) .AsGatedNoTracking() .SingleOrDefaultAsync(); if (department == null) { if (concurrencyError.GetValueOrDefault()) { return RedirectToAction("Index"); } return NotFound(); } if (concurrencyError.GetValueOrDefault()) { ViewData["ConcurrencyErrorMessage"] = "The record you attempted to delete was modified by another user after you got the original values. " + "The delete operation was canceled and the current values in the database have been displayed. If you still want to delete this " + "record, click the Delete button again. Otherwise click the Back to List hyperlink."; } return View(department); } [Authorize(Roles = "Administrator")] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Delete(int id) { var department = await _departmentRepo.Get(id).FirstOrDefaultAsync(); if (department == null) { return RedirectToAction("Index"); } try { _departmentRepo.Delete(department); await _departmentRepo.SaveChangesAsync(); return RedirectToAction("Index"); } catch (DbUpdateConcurrencyException) { return RedirectToAction("Delete", new { concurrencyError = true, id = department.ID }); } } private bool DepartmentExists(int id) { return _departmentRepo.GetAll().Any(e => e.ID == id); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using Xunit; namespace System.Reflection.Tests { public static class TypeTests_StructLayoutAttribute { [Fact] public static void Test_UndecoratedClass() { Type t = typeof(UndecoratedClass).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Auto, s.Value); Assert.Equal(CharSet.Ansi, s.CharSet); Assert.Equal(8, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_AutoAnsiEightZero() { Type t = typeof(AutoAnsiEightZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Auto, s.Value); Assert.Equal(CharSet.Ansi, s.CharSet); Assert.Equal(8, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_SequentialAnsiEightZero() { Type t = typeof(SequentialAnsiEightZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Ansi, s.CharSet); Assert.Equal(8, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_ExplicitAnsiEightZero() { Type t = typeof(ExplicitAnsiEightZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Explicit, s.Value); Assert.Equal(CharSet.Ansi, s.CharSet); Assert.Equal(8, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_SequentialUnicodeEightZero() { Type t = typeof(SequentialUnicodeEightZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Unicode, s.CharSet); Assert.Equal(8, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void TestSequentialAutoZeroZero() { Type t = typeof(SequentialAutoZeroZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Auto, s.CharSet); Assert.Equal(8, s.Pack); // Not an error: Pack=0 is treated as if it were Pack=8. Assert.Equal(0, s.Size); } [Fact] public static void Test_SequentialAutoOneZero() { Type t = typeof(SequentialAutoOneZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Auto, s.CharSet); Assert.Equal(1, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_SequentialAutoTwoZero() { Type t = typeof(SequentialAutoTwoZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Auto, s.CharSet); Assert.Equal(2, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_SequentialAutoFourZero() { Type t = typeof(SequentialAutoFourZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Auto, s.CharSet); Assert.Equal(4, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_SequentialAutoEightZero() { Type t = typeof(SequentialAutoEightZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Auto, s.CharSet); Assert.Equal(8, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_SequentialAutoSixteeentZero() { Type t = typeof(SequentialAutoSixteenZero).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Auto, s.CharSet); Assert.Equal(16, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_ExplicitAutoEightFortyTwo() { Type t = typeof(ExplicitAutoEightFortyTwo).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Explicit, s.Value); Assert.Equal(CharSet.Auto, s.CharSet); Assert.Equal(8, s.Pack); Assert.Equal(42, s.Size); } [Fact] public static void Test_Derived() { // Though the layout engine honors StructLayout attributes on base classes, Type.StructLayoutAttribute does not. It only looks at the immediate class. Type t = typeof(Derived).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Auto, s.Value); Assert.Equal(CharSet.Ansi, s.CharSet); Assert.Equal(8, s.Pack); Assert.Equal(0, s.Size); } [Fact] public static void Test_Generic() { // Type.StructLayoutAttribute treats generic instance classes as if they were the generic type definition. (The runtime layout engine, on the other hand // generally doesn't allow these.) Type t = typeof(Generic<int>).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Equal(LayoutKind.Sequential, s.Value); Assert.Equal(CharSet.Auto, s.CharSet); Assert.Equal(4, s.Pack); Assert.Equal(40, s.Size); } [Fact] public static void Test_Array() { // HasElement types always return null for this property. Type t = typeof(SequentialAnsiEightZero[]).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Null(s); } [Fact] public static void Test_GenericParameter() { // GenericParameter types always return null for this property. Type t = typeof(GenericParameterHolder<>).Project().GetTypeInfo().GenericTypeParameters[0]; StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Null(s); } [Fact] public static void Test_Interface() { // Interafces return null for this property. Type t = typeof(IInterface).Project(); StructLayoutAttribute s = t.StructLayoutAttribute; Assert.Null(s); } private class UndecoratedClass { } [StructLayout(LayoutKind.Auto, CharSet = CharSet.Ansi, Pack = 8, Size = 0)] private class AutoAnsiEightZero { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8, Size = 0)] private class SequentialAnsiEightZero { } [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Pack = 8, Size = 0)] private class ExplicitAnsiEightZero { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 8, Size = 0)] private class SequentialUnicodeEightZero { } // A "Pack = 0" emits different IL metadata from "Pack = 8". However, both the runtime layout engine and the Type.StructLayoutAttribute // property treat it as if were "8". [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 0, Size = 0)] private class SequentialAutoZeroZero { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1, Size = 0)] private class SequentialAutoOneZero { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 2, Size = 0)] private class SequentialAutoTwoZero { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4, Size = 0)] private class SequentialAutoFourZero { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 8, Size = 0)] private class SequentialAutoEightZero { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 16, Size = 0)] private class SequentialAutoSixteenZero { } [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto, Pack = 8, Size = 42)] private class ExplicitAutoEightFortyTwo { } [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto, Pack = 4, Size = 42)] private class ExplicitAutoFourFortyTwo { } private class Derived : ExplicitAutoFourFortyTwo { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4, Size = 40)] private class Generic<T> { } private class GenericParameterHolder<T> where T : ExplicitAutoFourFortyTwo { } private interface IInterface { } } }
// 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.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.Providers.Mail; namespace WebsitePanel.Portal { public partial class MailListsEditList : WebsitePanelModuleBase { MailList item = null; private string listName = null; protected void Page_Load(object sender, EventArgs e) { btnDelete.Visible = (PanelRequest.ItemID > 0); // bind item BindItem(); } private void BindItem() { try { if (!IsPostBack) { // load item if required if (PanelRequest.ItemID > 0) { // existing item try { item = ES.Services.MailServers.GetMailList(PanelRequest.ItemID); } catch (Exception ex) { ShowErrorMessage("MAIL_GET_LIST", ex); return; } if (item != null) { // save package info ViewState["PackageId"] = item.PackageId; emailAddress.PackageId = item.PackageId; } else RedirectToBrowsePage(); } else { // new item ViewState["PackageId"] = PanelSecurity.PackageId; emailAddress.PackageId = PanelSecurity.PackageId; } } // load provider control LoadProviderControl((int)ViewState["PackageId"], "Mail", providerControl, "EditList.ascx"); if (!IsPostBack) { // bind item to controls if (item != null) { // bind item to controls emailAddress.Email = item.Name; emailAddress.EditMode = true; // other controls IMailEditListControl ctrl = (IMailEditListControl)providerControl.Controls[0]; ctrl.BindItem(item); } } } catch { ShowWarningMessage("INIT_SERVICE_ITEM_FORM"); DisableFormControls(this, btnCancel); return; } } private void SaveItem() { if (!Page.IsValid) return; //MailList tempitem = ES.Services.MailServers.GetMailList(PanelRequest.ItemID); // get form data MailList item = new MailList(); item.Id = PanelRequest.ItemID; item.PackageId = PanelSecurity.PackageId; if (listName != null) { item.Name = listName; } else { item.Name = emailAddress.Email; } //checking if list name is different from existing e-mail accounts MailAccount[] accounts = ES.Services.MailServers.GetMailAccounts(PanelSecurity.PackageId, true); foreach (MailAccount account in accounts) { if (item.Name == account.Name) { ShowWarningMessage("MAIL_LIST_NAME"); return; } } //checking if list name is different from existing e-mail groups MailGroup[] mailgroups = ES.Services.MailServers.GetMailGroups(PanelSecurity.PackageId, true); foreach (MailGroup group in mailgroups) { if (item.Name == group.Name) { ShowWarningMessage("MAIL_LIST_NAME"); return; } } //checking if list name is different from existing forwardings MailAlias[] forwardings = ES.Services.MailServers.GetMailForwardings(PanelSecurity.PackageId, true); foreach (MailAlias forwarding in forwardings) { if (item.Name == forwarding.Name) { ShowWarningMessage("MAIL_LIST_NAME"); return; } } // get other props IMailEditListControl ctrl = (IMailEditListControl)providerControl.Controls[0]; ctrl.SaveItem(item); if (PanelRequest.ItemID == 0) { // new item try { int result = ES.Services.MailServers.AddMailList(item); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_ADD_LIST", ex); return; } } else { // existing item try { int result = ES.Services.MailServers.UpdateMailList(item); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_UPDATE_LIST", ex); return; } } // return RedirectSpaceHomePage(); } private void DeleteItem() { // delete try { int result = ES.Services.MailServers.DeleteMailList(PanelRequest.ItemID); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_DELETE_LIST", ex); return; } // return RedirectSpaceHomePage(); } private string GetDomainName(string email) { return email.Substring(email.IndexOf("@") + 1); } protected void btnSave_Click(object sender, EventArgs e) { SaveItem(); } protected void btnCancel_Click(object sender, EventArgs e) { // return RedirectSpaceHomePage(); } protected void btnDelete_Click(object sender, EventArgs e) { DeleteItem(); } } }
// 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.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using OpenLiveWriter.BlogClient; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Interop.Windows; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl; using System.Globalization; using System.Threading; namespace OpenLiveWriter.PostEditor.PostPropertyEditing { /// <summary> /// This class has all of the controller logic that's common to both /// PostPropertiesBandControl and PostPropertiesForm. /// </summary> internal class SharedPropertiesController : IBlogPostEditor, INewCategoryContext { private readonly string DATETIME_PICKER_PROMPT; private string _blogId; private Blog _targetBlog; private IBlogClientOptions _clientOptions; private IBlogPostEditingContext editorContext; private delegate void SyncAction(SharedPropertiesController other); private bool isDirty; /// <summary> /// When non-zero, suppress marking ourselves dirty and syncing /// with the "other" controller. /// </summary> private int suspendCount = 0; private readonly IWin32Window parentFrame; private readonly Label labelCategory; private readonly CategoryDropDownControlM1 categoryDropDown; private readonly Label labelTags; private readonly AutoCompleteTextbox textTags; private readonly Label labelPageOrder; private readonly NumericTextBox textPageOrder; private readonly Label labelPageParent; private readonly PageParentComboBox comboPageParent; private readonly Label labelPublishDate; private readonly PublishDateTimePicker datePublishDate; private readonly List<PropertyField> fields; public SharedPropertiesController(IWin32Window parentFrame, Label labelCategory, CategoryDropDownControlM1 categoryDropDown, Label labelTags, AutoCompleteTextbox textTags, Label labelPageOrder, NumericTextBox textPageOrder, Label labelPageParent, PageParentComboBox comboPageParent, Label labelPublishDate, PublishDateTimePicker datePublishDate, List<PropertyField> fields, CategoryContext categoryContext) { this.parentFrame = parentFrame; this.labelCategory = labelCategory; this.categoryDropDown = categoryDropDown; this.labelPublishDate = labelPublishDate; this.datePublishDate = datePublishDate; this.fields = fields; this.labelTags = labelTags; this.textTags = textTags; this.labelPageOrder = labelPageOrder; this.textPageOrder = textPageOrder; this.labelPageParent = labelPageParent; this.comboPageParent = comboPageParent; this.categoryDropDown.AccessibleName = Res.Get(StringId.CategoryControlCategories).Replace("{0}", " ").Trim(); this.datePublishDate.AccessibleName = Res.Get(StringId.PropertiesPublishDate); textTags.TextChanged += MakeDirty; textTags.ButtonClicked += (sender, args) => { _targetBlog.RefreshKeywords(); LoadTagValues(); }; comboPageParent.SelectedIndexChanged += MakeDirty; textPageOrder.TextChanged += MakeDirty; datePublishDate.ValueChanged += MakeDirty; DATETIME_PICKER_PROMPT = "'" + Res.Get(StringId.PublishDatePrompt).Replace("'", "''") + "'"; // HACK ALERT - WinLive 209226: For RTL languages, we need to reverse the string, so it displays in the right direction // when right aligned. We need this hack because we are essentially using the CustomFormat string to display // the cue text. The control assumes this to be a valid format string and does a blind reverse on RTL languages // to mirror the date formatting. Unfortunately we don't need that mirroring for the cue text. // We reverse only if either the system (control panel setting) or UI is RTL, not if both are RTL. bool isUIRightToLeft = BidiHelper.IsRightToLeft; bool isSystemRightToLeft = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.IsRightToLeft; if ((isUIRightToLeft && !isSystemRightToLeft) || (!isUIRightToLeft && isSystemRightToLeft)) { // Reverse the string char[] charArray = DATETIME_PICKER_PROMPT.ToCharArray(); Array.Reverse(charArray); DATETIME_PICKER_PROMPT = new string(charArray); } datePublishDate.CustomFormat = DATETIME_PICKER_PROMPT; categoryDropDown.Initialize(parentFrame, categoryContext); InitializeFields(); InitializeSync(); } public SharedPropertiesController Other { get; set; } private void SyncChange(SyncAction action) { if (suspendCount > 0 || Other == null) return; using (Other.SuspendLogic()) action(Other); } private void InitializeFields() { RegisterField(PropertyType.Page, labelPageOrder, textPageOrder, opts => opts.SupportsPageOrder, post => textPageOrder.Text = post.PageOrder, post => post.PageOrder = textPageOrder.Text); RegisterField2(PropertyType.Page, labelPageParent, comboPageParent, opts => opts.SupportsPageParent, (ctx, opts) => { PostIdAndNameField none = new PostIdAndNameField(Res.Get(StringId.PropertiesNoPageParent)); PostIdAndNameField parent = ctx.BlogPost.PageParent; BlogPageFetcher pageFetcher = new BlogPageFetcher(_blogId, 10000); if (!parent.Equals(PostIdAndNameField.Empty)) { comboPageParent.Initialize(new object[] { none, parent }, parent, pageFetcher); } else { comboPageParent.Initialize(none, pageFetcher); } }, post => post.PageParent = comboPageParent.SelectedItem as PostIdAndNameField); RegisterField(PropertyType.Post, labelCategory, categoryDropDown, opts => opts.SupportsCategories, post => { }, post => { }); RegisterField2(PropertyType.Post, labelTags, textTags, opts => opts.SupportsKeywords, (ctx, opts) => textTags.Text = ctx.BlogPost.Keywords, post => post.Keywords = textTags.TextValue); RegisterField(PropertyType.Post, labelPublishDate, datePublishDate, opts => opts.SupportsCustomDate, post => { if (post.HasDatePublishedOverride) { DatePublishedOverride = post.DatePublishedOverride; HasDatePublishedOverride = true; } else { HasDatePublishedOverride = false; } }, post => post.DatePublishedOverride = HasDatePublishedOverride ? DatePublishedOverride : DateTime.MinValue); } private void InitializeSync() { textPageOrder.TextChanged += (sender, args) => SyncChange(other => other.textPageOrder.Text = textPageOrder.Text); textTags.TextChanged += (sender, args) => SyncChange(other => other.textTags.Text = textTags.TextValue); comboPageParent.SelectedIndexChanged += (sender, args) => { SyncChange(other => { other.comboPageParent.BeginUpdate(); try { other.comboPageParent.Items.Clear(); foreach (object o in comboPageParent.Items) other.comboPageParent.Items.Add(o); other.comboPageParent.SelectedIndex = comboPageParent.SelectedIndex; } finally { other.comboPageParent.EndUpdate(); } }); }; datePublishDate.ValueChanged2 += HandlePublishDateValueChanged; } private void HandlePublishDateValueChanged(object sender, EventArgs args) { SyncChange(other => { UpdateDateTimePickerFormat(); // We are syncing to the 'other' control, don't trigger a ValueChanged2 event on it (to prevent // a reverse sync) other.datePublishDate.SetDateTimeAndChecked(datePublishDate.Checked, datePublishDate.Value); other.UpdateDateTimePickerFormat(); other.datePublishDate.Tag = datePublishDate.Tag; }); } private void RegisterField(PropertyType type, Control label, Control editor, PropertyField.ShouldShow shouldShow, PropertyField.Populate populate, PropertyField.Save save) { PropertyField field = new PropertyField(type, new[] { label, editor }, shouldShow, populate, save); fields.Add(field); } private void RegisterField2(PropertyType type, Control label, Control editor, PropertyField.ShouldShow shouldShow, PropertyField.PopulateFull populate, PropertyField.Save save) { PropertyField field = new PropertyField(type, new[] { label, editor }, shouldShow, populate, save); fields.Add(field); } private void LoadTagValues() { if (_targetBlog != null) { // Get all the keywords for the blog and set it as the source for the autocomplete List<string> keywords = new List<string>(); BlogPostKeyword[] keywordList = _targetBlog.Keywords; if (_clientOptions.SupportsGetKeywords && keywordList != null) { foreach (BlogPostKeyword blogPostKeyword in keywordList) { keywords.Add(blogPostKeyword.Name); } } textTags.TagSource = new SimpleTagSource(keywords); SyncChange(other => other.LoadTagValues()); } } public void Initialize(IBlogPostEditingContext context, IBlogClientOptions clientOptions) { Debug.Assert(_blogId == context.BlogId); using (SuspendLogic()) { editorContext = context; using (Blog blog = new Blog(context.BlogId)) UpdateFieldsForBlog(blog); ((IBlogPostEditor)categoryDropDown).Initialize(context, clientOptions); foreach (PropertyField field in fields) field.Initialize(context, clientOptions); } isDirty = false; } public void OnBlogChanged(Blog newBlog) { using (SuspendLogic()) { _blogId = newBlog.Id; _targetBlog = newBlog; _clientOptions = newBlog.ClientOptions; ((IBlogPostEditor)categoryDropDown).OnBlogChanged(newBlog); UpdateFieldsForBlog(newBlog); // Tag stuff textTags.ShowButton = newBlog.ClientOptions.SupportsGetKeywords; if (newBlog.ClientOptions.SupportsGetKeywords) LoadTagValues(); textTags.DefaultText = newBlog.ClientOptions.KeywordsAsTags ? Res.Get(StringId.TagControlSetTags) : ""; } } private void UpdateFieldsForBlog(Blog newBlog) { if (editorContext != null) { foreach (PropertyField field in fields) field.UpdateControlVisibility(editorContext, newBlog.ClientOptions); } } public void OnBlogSettingsChanged(bool templateChanged) { using (SuspendLogic()) { ((IBlogPostEditor)categoryDropDown).OnBlogSettingsChanged(templateChanged); if (editorContext != null) using (Blog blog = new Blog(_blogId)) UpdateFieldsForBlog(blog); } } public bool IsDirty { get { return isDirty || ((IBlogPostEditor)categoryDropDown).IsDirty; } } public void MakeDirty(object sender, EventArgs args) { if (suspendCount <= 0) isDirty = true; } public IDisposable SuspendLogic() { suspendCount++; return new Unsuspender { Parent = this }; } private class Unsuspender : IDisposable { public SharedPropertiesController Parent; public void Dispose() { Parent.suspendCount--; } } public void SaveChanges(BlogPost post, BlogPostSaveOptions options) { using (SuspendLogic()) { ((IBlogPostEditor)categoryDropDown).SaveChanges(post, options); foreach (PropertyField field in fields) field.SaveChanges(post); } isDirty = false; } public bool ValidatePublish() { if (!((IBlogPostEditor)categoryDropDown).ValidatePublish()) return false; if (datePublishDate.Checked && (DatePublishedOverride > DateTimeHelper.UtcNow) && _clientOptions.FuturePublishDateWarning && PostEditorSettings.FuturePublishDateWarning) { using (FutureDateWarningForm warningForm = new FutureDateWarningForm()) { if (warningForm.ShowDialog(parentFrame) != DialogResult.Yes) return false; } } return true; } public bool HasDatePublishedOverride { get { return datePublishDate.Checked; } set { datePublishDate.Checked = value; UpdateDateTimePickerFormat(); } } public DateTime DatePublishedOverride { get { DateTime dateTime = DateTimeHelper.LocalToUtc(datePublishDate.Value); dateTime = dateTime.Subtract(TimeSpan.FromSeconds(dateTime.Second) + TimeSpan.FromMilliseconds(dateTime.Millisecond)); return dateTime; } set { datePublishDate.Tag = true; // Signal the datetime picker has a value // Set the datetime and checked state without triggering the PublishDateTimePicker.ValueChanged2 event datePublishDate.SetDateTimeAndChecked(datePublishDate.Checked, DateTimeHelper.UtcToLocal(value)); } } private void UpdateDateTimePickerFormat() { if (datePublishDate.Checked) { // if we are transitioning from unchecked to checked then // set the current date-time to Now if ((bool)datePublishDate.Tag == false) DatePublishedOverride = DateTime.UtcNow; datePublishDate.Font = defaultFont; datePublishDate.CustomFormat = CultureHelper.GetDateTimeCombinedPattern(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern, CultureHelper.GetShortDateTimePatternForDateTimePicker()); } else { datePublishDate.CustomFormat = DATETIME_PICKER_PROMPT; datePublishDate.Tag = false; // signal the date time picker no longer has a value datePublishDate.Font = defaultFont; } } private Font defaultFont = Res.DefaultFont; public void OnPublishSucceeded(BlogPost blogPost, PostResult postResult) { ((IBlogPostEditor)categoryDropDown).OnPublishSucceeded(blogPost, postResult); List<BlogPostKeyword> keywords = new List<BlogPostKeyword>(); keywords.AddRange(_targetBlog.Keywords); string[] keywordList = blogPost.Keywords.Split(','); foreach (string str in keywordList) { string name = str.Trim(); if (string.IsNullOrEmpty(name)) continue; keywords.Add(new BlogPostKeyword(name)); } _targetBlog.Keywords = keywords.ToArray(); LoadTagValues(); isDirty = false; } public void OnClosing(CancelEventArgs e) { categoryDropDown.OnPostClosing(e); } public void OnPostClosing(CancelEventArgs e) { categoryDropDown.OnPostClosing(e); } public void OnClosed() { categoryDropDown.OnClosed(); } public void OnPostClosed() { categoryDropDown.OnPostClosed(); } public void NewCategoryAdded(BlogPostCategory category) { ((INewCategoryContext)categoryDropDown).NewCategoryAdded(category); } } [Flags] internal enum PropertyType { Post = 1, Page = 2, Both = Post | Page } internal class PropertyField { public delegate bool ShouldShow(IBlogClientOptions options); public delegate void Populate(BlogPost bp); public delegate void PopulateFull(IBlogPostEditingContext ctx, IBlogClientOptions opts); public delegate void Save(BlogPost bp); private PropertyType propertyType; private Control[] controls; private ShouldShow shouldShow; private PopulateFull populate; private Save save; public PropertyField(PropertyType type, Control[] controls, ShouldShow shouldShow, Populate populate, Save save) : this(type, controls, shouldShow, (ctx, opts) => populate(ctx.BlogPost), save) { } public PropertyField(PropertyType type, Control[] controls, ShouldShow shouldShow, PopulateFull populate, Save save) { this.propertyType = type; this.controls = controls; this.shouldShow = shouldShow; this.populate = populate; this.save = save; } public void Initialize(IBlogPostEditingContext editingContext, IBlogClientOptions options) { PropertyType requiredType = editingContext.BlogPost.IsPage ? PropertyType.Page : PropertyType.Post; bool isCorrectType = (propertyType & requiredType) == requiredType; if (isCorrectType && populate != null) populate(editingContext, options); } public void UpdateControlVisibility(IBlogPostEditingContext editingContext, IBlogClientOptions options) { PropertyType requiredType = editingContext.BlogPost.IsPage ? PropertyType.Page : PropertyType.Post; bool isCorrectType = (propertyType & requiredType) == requiredType; bool visible = isCorrectType && shouldShow(options); foreach (Control c in controls) if (c != null) c.Visible = visible; } public void SaveChanges(BlogPost post) { PropertyType requiredType = post.IsPage ? PropertyType.Page : PropertyType.Post; bool isCorrectType = (propertyType & requiredType) == requiredType; if (isCorrectType && save != null) save(post); } } internal class BlogAuthorFetcher : BlogDelayedFetchHandler { public BlogAuthorFetcher(string blogId, int timeoutMs) : base(blogId, Res.Get(StringId.PropertiesAuthorsFetchingText), timeoutMs) { } protected override object BlogFetchOperation(Blog blog) { // refresh our author list blog.RefreshAuthors(); // return what we've got return ConvertAuthors(blog.Authors); } protected override object[] GetDefaultItems(Blog blog) { return ConvertAuthors(blog.Authors); } private object[] ConvertAuthors(AuthorInfo[] authorList) { ArrayList authors = new ArrayList(); foreach (AuthorInfo author in authorList) { authors.Add(new PostIdAndNameField(author.Id, author.Name)); } return authors.ToArray(); } } internal abstract class BlogDelayedFetchHandler : IDelayedFetchHandler { protected BlogDelayedFetchHandler(string blogId, string fetchingText, int timeoutMs) { _blogId = blogId; _fetchingText = fetchingText; _timeoutMs = timeoutMs; } public object[] FetchItems(IWin32Window owner) { object[] items = BlogClientHelper.PerformBlogOperationWithTimeout(_blogId, new BlogClientOperation(BlogFetchOperation), _timeoutMs) as object[]; if (items != null) { return items; } else { // see if we have default items available object[] defaultItems = new object[0]; try { using (Blog blog = new Blog(_blogId)) defaultItems = GetDefaultItems(blog); } catch { } // if we have default items then return them in preference to showing an error if (defaultItems.Length > 0) { return defaultItems; } else { DisplayMessage.Show(MessageId.UnableToRetrieve, _fetchingText); return null; } } } protected abstract object BlogFetchOperation(Blog blog); protected virtual object[] GetDefaultItems(Blog blog) { return new object[0]; } private readonly string _blogId; private readonly int _timeoutMs; private readonly string _fetchingText; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { // Tests for features of the Expression class, rather than any derived types, // including how it acts with custom derived types. // // Unfortunately there is slightly different internal behaviour depending on whether // a derived Expression uses the new constructor, uses the old constructor, or uses // the new constructor after at least one use of the old constructor has been made, // due to static state being affected. For this reason some tests have to be done // in a particular order, with those for the old constructor coming after most of // the tests, and those affected by this being repeated after that. [TestCaseOrderer("System.Linq.Expressions.Tests.TestOrderer", "System.Linq.Expressions.Tests")] public class ExpressionTests { private static readonly Expression MarkerExtension = Expression.Constant(0); private class IncompleteExpressionOverride : Expression { public class Visitor : ExpressionVisitor { protected override Expression VisitExtension(Expression node) { return MarkerExtension; } } public IncompleteExpressionOverride() : base() { } public Expression VisitChildren() { return VisitChildren(new Visitor()); } } private class ClaimedReducibleOverride : IncompleteExpressionOverride { public override bool CanReduce { get { return true; } } } private class ReducesToSame : ClaimedReducibleOverride { public override Expression Reduce() { return this; } } private class ReducesToNull : ClaimedReducibleOverride { public override Expression Reduce() { return null; } } private class ReducesToLongTyped : ClaimedReducibleOverride { private class ReducedToLongTyped : IncompleteExpressionOverride { public override Type Type { get { return typeof(long); } } } public override Type Type { get { return typeof(int); } } public override Expression Reduce() { return new ReducedToLongTyped(); } } private class Reduces : ClaimedReducibleOverride { public override Type Type { get { return typeof(int); } } public override Expression Reduce() { return new Reduces(); } } private class ObsoleteIncompleteExpressionOverride : Expression { #pragma warning disable 0618 // Testing obsolete behaviour. public ObsoleteIncompleteExpressionOverride(ExpressionType nodeType, Type type) : base(nodeType, type) { } #pragma warning restore 0618 } public static IEnumerable<object[]> AllNodeTypesPlusSomeInvalid { get { foreach (ExpressionType et in Enum.GetValues(typeof(ExpressionType))) yield return new object[] { et }; yield return new object[] { (ExpressionType)(-1) }; yield return new object[] { (ExpressionType)int.MaxValue }; yield return new object[] { (ExpressionType)int.MinValue }; } } public static IEnumerable<object[]> SomeTypes { get { return new[] { typeof(int), typeof(void), typeof(object), typeof(DateTime), typeof(string), typeof(ExpressionTests), typeof(ExpressionType) } .Select(type => new object[] { type }); } } [Fact] public void NodeTypeMustBeOverridden() { var exp = new IncompleteExpressionOverride(); Assert.Throws<InvalidOperationException>(() => exp.NodeType); } [Theory, TestOrder(1), MemberData("AllNodeTypesPlusSomeInvalid")] public void NodeTypeFromConstructor(ExpressionType nodeType) { Assert.Equal(nodeType, new ObsoleteIncompleteExpressionOverride(nodeType, typeof(int)).NodeType); } [Fact, TestOrder(2)] public void NodeTypeMustBeOverriddenAfterObsoleteConstructorUsed() { var exp = new IncompleteExpressionOverride(); Assert.Throws<InvalidOperationException>(() => exp.NodeType); } [Fact] public void TypeMustBeOverridden() { var exp = new IncompleteExpressionOverride(); Assert.Throws<InvalidOperationException>(() => exp.Type); } [Theory, TestOrder(1), MemberData("SomeTypes")] public void TypeFromConstructor(Type type) { Assert.Equal(type, new ObsoleteIncompleteExpressionOverride(ExpressionType.Constant, type).Type); } [Fact, TestOrder(1)] public void TypeMayBeNonNullOnObsoleteConstructedExpression() { // This is probably undesirable, but throwing here would be a breaking change. // Impact must be considered before prohibiting this. Assert.Null(new ObsoleteIncompleteExpressionOverride(ExpressionType.Add, null).Type); } [Fact, TestOrder(2)] public void TypeMustBeOverriddenCheckCorrectAfterObsoleteConstructorUsed() { var exp = new IncompleteExpressionOverride(); Assert.Throws<InvalidOperationException>(() => exp.Type); } [Fact] public void DefaultCannotReduce() { Assert.False(new IncompleteExpressionOverride().CanReduce); } [Fact] public void DefaultReducesToSame() { var exp = new IncompleteExpressionOverride(); Assert.Same(exp, exp.Reduce()); } [Fact] public void VisitChildrenThrowsAsNotReducible() { var exp = new IncompleteExpressionOverride(); Assert.Throws<ArgumentException>(() => exp.VisitChildren()); } [Fact] public void CanVisitChildrenIfReallyReduces() { var exp = new Reduces(); Assert.NotSame(exp, exp.VisitChildren()); } [Fact] public void VisitingCallsVisitExtension() { Assert.Same(MarkerExtension, new IncompleteExpressionOverride.Visitor().Visit(new IncompleteExpressionOverride())); } [Fact] public void ReduceAndCheckThrowsByDefault() { var exp = new IncompleteExpressionOverride(); Assert.Throws<ArgumentException>(() => exp.ReduceAndCheck()); } [Fact] public void ReduceExtensionsThrowsByDefault() { var exp = new IncompleteExpressionOverride(); Assert.Throws<ArgumentException>(() => exp.ReduceAndCheck()); } [Fact] public void IfClaimCanReduceMustReduce() { var exp = new ClaimedReducibleOverride(); Assert.Throws<ArgumentException>(() => exp.Reduce()); } [Fact] public void ReduceAndCheckThrowOnReduceToSame() { var exp = new ReducesToSame(); Assert.Throws<ArgumentException>(() => exp.ReduceAndCheck()); } [Fact] public void ReduceAndCheckThrowOnReduceToNull() { var exp = new ReducesToNull(); Assert.Throws<ArgumentException>(() => exp.ReduceAndCheck()); } [Fact] public void ReduceAndCheckThrowOnReducedTypeNotAssignable() { var exp = new ReducesToLongTyped(); Assert.Throws<ArgumentException>(() => exp.ReduceAndCheck()); } #pragma warning disable 0169, 0414 // Accessed through reflection. private static int TestField; private const int TestConstant = 0; private static readonly int TestInitOnlyField = 0; #pragma warning restore 0169, 0414 private static int Unreadable { set { } } private static int Unwritable { get { return 0; } } private class UnreadableIndexableClass { public int this[int index] { set { } } } private class UnwritableIndexableClass { public int this[int index] { get { return 0; } } } [Fact] public void ConfirmCanRead() { var readableExpressions = new Expression[] { Expression.Constant(0), Expression.Add(Expression.Constant(0), Expression.Constant(0)), Expression.Default(typeof(int)), Expression.Property(Expression.Constant(new List<int>()), "Count"), Expression.ArrayIndex(Expression.Constant(Array.Empty<int>()), Expression.Constant(0)), Expression.Field(null, typeof(ExpressionTests), "TestField"), Expression.Field(null, typeof(ExpressionTests), "TestConstant"), Expression.Field(null, typeof(ExpressionTests), "TestInitOnlyField") }; Expression.Block(typeof(void), readableExpressions); } public static IEnumerable<Expression> UnreadableExpressions { get { yield return Expression.Property(null, typeof(ExpressionTests), "Unreadable"); yield return Expression.Property(Expression.Constant(new UnreadableIndexableClass()), "Item", Expression.Constant(0)); } } public static IEnumerable<object[]> UnreadableExpressionData { get { return UnreadableExpressions.Concat(new Expression[1]).Select(exp => new object[] { exp }); } } public static IEnumerable<Expression> WritableExpressions { get { yield return Expression.Property(null, typeof(ExpressionTests), "Unreadable"); yield return Expression.Property(Expression.Constant(new UnreadableIndexableClass()), "Item", Expression.Constant(0)); yield return Expression.Field(null, typeof(ExpressionTests), "TestField"); yield return Expression.Parameter(typeof(int)); } } public static IEnumerable<Expression> UnwritableExpressions { get { yield return Expression.Property(null, typeof(ExpressionTests), "Unwritable"); yield return Expression.Property(Expression.Constant(new UnwritableIndexableClass()), "Item", Expression.Constant(0)); yield return Expression.Field(null, typeof(ExpressionTests), "TestConstant"); yield return Expression.Field(null, typeof(ExpressionTests), "TestInitOnlyField"); yield return Expression.Call(Expression.Default(typeof(ExpressionTests)), "ConfirmCannotReadSequence", new Type[0]); yield return null; } } public static IEnumerable<object[]> UnwritableExpressionData { get { return UnwritableExpressions.Select(exp => new object[] { exp }); } } public static IEnumerable<object[]> WritableExpressionData { get { return WritableExpressions.Select(exp => new object[] { exp }); } } [Theory, MemberData("UnreadableExpressionData")] public void ConfirmCannotRead(Expression unreadableExpression) { if (unreadableExpression == null) Assert.Throws<ArgumentNullException>("expression", () => Expression.Increment(unreadableExpression)); else Assert.Throws<ArgumentException>("expression", () => Expression.Increment(unreadableExpression)); } [Fact] public void ConfirmCannotReadSequence() { Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(void), UnreadableExpressions)); } [Theory, MemberData("UnwritableExpressionData")] public void ConfirmCannotWrite(Expression unwritableExpression) { if (unwritableExpression == null) Assert.Throws<ArgumentNullException>("left", () => Expression.Assign(unwritableExpression, Expression.Constant(0))); else Assert.Throws<ArgumentException>("left", () => Expression.Assign(unwritableExpression, Expression.Constant(0))); } [Theory, MemberData("WritableExpressionData")] public void ConfirmCanWrite(Expression writableExpression) { Expression.Assign(writableExpression, Expression.Default(writableExpression.Type)); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.Kgsearch.v1 { /// <summary>The Kgsearch Service.</summary> public class KgsearchService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public KgsearchService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public KgsearchService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Entities = new EntitiesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "kgsearch"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://kgsearch.googleapis.com/"; #else "https://kgsearch.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://kgsearch.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Gets the Entities resource.</summary> public virtual EntitiesResource Entities { get; } } /// <summary>A base abstract class for Kgsearch requests.</summary> public abstract class KgsearchBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new KgsearchBaseServiceRequest instance.</summary> protected KgsearchBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Kgsearch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "entities" collection of methods.</summary> public class EntitiesResource { private const string Resource = "entities"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public EntitiesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Searches Knowledge Graph for entities that match the constraints. A list of matched entities will be /// returned in response, which will be in JSON-LD format and compatible with http://schema.org /// </summary> public virtual SearchRequest Search() { return new SearchRequest(service); } /// <summary> /// Searches Knowledge Graph for entities that match the constraints. A list of matched entities will be /// returned in response, which will be in JSON-LD format and compatible with http://schema.org /// </summary> public class SearchRequest : KgsearchBaseServiceRequest<Google.Apis.Kgsearch.v1.Data.SearchResponse> { /// <summary>Constructs a new Search request.</summary> public SearchRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary> /// The list of entity id to be used for search instead of query string. To specify multiple ids in the HTTP /// request, repeat the parameter in the URL as in ...?ids=A&amp;amp;ids=B /// </summary> [Google.Apis.Util.RequestParameterAttribute("ids", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Ids { get; set; } /// <summary>Enables indenting of json results.</summary> [Google.Apis.Util.RequestParameterAttribute("indent", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Indent { get; set; } /// <summary>The list of language codes (defined in ISO 693) to run the query with, e.g. 'en'.</summary> [Google.Apis.Util.RequestParameterAttribute("languages", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Languages { get; set; } /// <summary>Limits the number of entities to be returned.</summary> [Google.Apis.Util.RequestParameterAttribute("limit", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> Limit { get; set; } /// <summary>Enables prefix match against names and aliases of entities</summary> [Google.Apis.Util.RequestParameterAttribute("prefix", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Prefix { get; set; } /// <summary>The literal query string for search.</summary> [Google.Apis.Util.RequestParameterAttribute("query", Google.Apis.Util.RequestParameterType.Query)] public virtual string Query { get; set; } /// <summary> /// Restricts returned entities with these types, e.g. Person (as defined in http://schema.org/Person). If /// multiple types are specified, returned entities will contain one or more of these types. /// </summary> [Google.Apis.Util.RequestParameterAttribute("types", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Types { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "search"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/entities:search"; /// <summary>Initializes Search parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("ids", new Google.Apis.Discovery.Parameter { Name = "ids", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("indent", new Google.Apis.Discovery.Parameter { Name = "indent", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("languages", new Google.Apis.Discovery.Parameter { Name = "languages", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("limit", new Google.Apis.Discovery.Parameter { Name = "limit", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prefix", new Google.Apis.Discovery.Parameter { Name = "prefix", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("query", new Google.Apis.Discovery.Parameter { Name = "query", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("types", new Google.Apis.Discovery.Parameter { Name = "types", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Kgsearch.v1.Data { /// <summary> /// Response message includes the context and a list of matching results which contain the detail of associated /// entities. /// </summary> public class SearchResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The local context applicable for the response. See more details at /// http://www.w3.org/TR/json-ld/#context-definitions. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("@context")] public virtual object Context { get; set; } /// <summary>The schema type of top-level JSON-LD object, e.g. ItemList.</summary> [Newtonsoft.Json.JsonPropertyAttribute("@type")] public virtual object Type { get; set; } /// <summary>The item list of search results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("itemListElement")] public virtual System.Collections.Generic.IList<object> ItemListElement { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using GraphQL.Conversion; using GraphQL.Introspection; using GraphQL.Types; using Shouldly; using Xunit; namespace GraphQL.Tests.Introspection { public class SchemaIntrospectionTests { [Theory] [ClassData(typeof(DocumentWritersTestData))] public async Task validate_core_schema(IDocumentWriter documentWriter) { var documentExecuter = new DocumentExecuter(); var executionResult = await documentExecuter.ExecuteAsync(_ => { _.Schema = new Schema { Query = new TestQuery() }; _.Query = "IntrospectionQuery".ReadGraphQLRequest(); }); var json = await documentWriter.WriteToStringAsync(executionResult); ShouldBe(json, "IntrospectionResult".ReadJsonResult()); } [Theory] [ClassData(typeof(DocumentWritersTestData))] public async Task validate_core_schema_pascal_case(IDocumentWriter documentWriter) { var documentExecuter = new DocumentExecuter(); var executionResult = await documentExecuter.ExecuteAsync(_ => { _.Schema = new Schema { Query = new TestQuery(), NameConverter = PascalCaseNameConverter.Instance, }; _.Query = "IntrospectionQuery".ReadGraphQLRequest(); }); var json = await documentWriter.WriteToStringAsync(executionResult); ShouldBe(json, "IntrospectionResult".ReadJsonResult().Replace("\"test\"", "\"Test\"")); } public class TestQuery : ObjectGraphType { public TestQuery() { Name = "TestQuery"; Field<StringGraphType>("test"); } } [Theory] [ClassData(typeof(DocumentWritersTestData))] public async Task validate_that_default_schema_comparer_gives_original_order_of_fields_and_types(IDocumentWriter documentWriter) { var documentExecuter = new DocumentExecuter(); var executionResult = await documentExecuter.ExecuteAsync(_ => { _.Schema = new Schema { Query = TestQueryType(), }; _.Query = "GetFieldNamesOfTypesQuery".ReadGraphQLRequest(); }); var scalarTypeNames = new[] { "String", "Boolean", "Int" }; static string GetName(JsonElement el) => el.GetProperty("name").GetString(); var json = JsonDocument.Parse(await documentWriter.WriteToStringAsync(executionResult)); var types = json.RootElement .GetProperty("data") .GetProperty("__schema") .GetProperty("types") .EnumerateArray() .Where(el => !GetName(el).StartsWith("__") && !scalarTypeNames.Contains(GetName(el))) // not interested in introspection or scalar types .ToList(); types.Count.ShouldBe(3); ShouldBe(GetName(types[0]), "Query"); types[0].GetProperty("fields").EnumerateArray().Select(GetName).ShouldBe(new[] { "field2", "field1" }); ShouldBe(GetName(types[1]), "Things"); types[1].GetProperty("fields").EnumerateArray().Select(GetName).ShouldBe(new[] { "foo", "bar", "baz" }); ShouldBe(GetName(types[2]), "Letters"); types[2].GetProperty("fields").EnumerateArray().Select(GetName).ShouldBe(new[] { "bravo", "charlie", "alfa", "delta" }); } [Theory] [ClassData(typeof(DocumentWritersTestData))] public async Task validate_that_alphabetical_schema_comparer_gives_ordered_fields_and_types(IDocumentWriter documentWriter) { var documentExecuter = new DocumentExecuter(); var executionResult = await documentExecuter.ExecuteAsync(_ => { _.Schema = new Schema { Query = TestQueryType(), Comparer = new AlphabeticalSchemaComparer() }; _.Query = "GetFieldNamesOfTypesQuery".ReadGraphQLRequest(); }); var scalarTypeNames = new[] { "String", "Boolean", "Int" }; static string GetName(JsonElement el) => el.GetProperty("name").GetString(); var json = JsonDocument.Parse(await documentWriter.WriteToStringAsync(executionResult)); var types = json.RootElement .GetProperty("data") .GetProperty("__schema") .GetProperty("types") .EnumerateArray() .Where(el => !GetName(el).StartsWith("__") && !scalarTypeNames.Contains(GetName(el))) // not interested in introspection or scalar types .ToList(); types.Count.ShouldBe(3); ShouldBe(GetName(types[0]), "Letters"); types[0].GetProperty("fields").EnumerateArray().Select(GetName).ShouldBe(new[] { "alfa", "bravo", "charlie", "delta" }); ShouldBe(GetName(types[1]), "Query"); types[1].GetProperty("fields").EnumerateArray().Select(GetName).ShouldBe(new[] { "field1", "field2" }); ShouldBe(GetName(types[2]), "Things"); types[2].GetProperty("fields").EnumerateArray().Select(GetName).ShouldBe(new[] { "bar", "baz", "foo" }); } private static IObjectGraphType TestQueryType() { var type1 = new ObjectGraphType { Name = "Letters" }; type1.AddField(new FieldType { Name = "bravo", ResolvedType = new StringGraphType() }); type1.AddField(new FieldType { Name = "charlie", ResolvedType = new IntGraphType() }); type1.AddField(new FieldType { Name = "alfa", ResolvedType = new ListGraphType(new IntGraphType()) }); type1.AddField(new FieldType { Name = "delta", ResolvedType = new StringGraphType() }); var type2 = new ObjectGraphType { Name = "Things" }; type2.AddField(new FieldType { Name = "foo", ResolvedType = new IntGraphType() }); type2.AddField(new FieldType { Name = "bar", ResolvedType = new IntGraphType() }); type2.AddField(new FieldType { Name = "baz", ResolvedType = new NonNullGraphType(new IntGraphType()) }); var queryType = new ObjectGraphType { Name = "Query" }; queryType.AddField(new FieldType { Name = "field2", ResolvedType = type2 }); queryType.AddField(new FieldType { Name = "field1", ResolvedType = type1 }); return queryType; } [Theory] [ClassData(typeof(DocumentWritersTestData))] public async Task validate_non_null_schema(IDocumentWriter documentWriter) { var documentExecuter = new DocumentExecuter(); var executionResult = await documentExecuter.ExecuteAsync(_ => { _.Schema = new TestSchema(); _.Query = InputObjectBugQuery; }); var json = await documentWriter.WriteToStringAsync(executionResult); executionResult.Errors.ShouldBeNull(); ShouldBe(json, InputObjectBugResult); } private static void ShouldBe(string actual, string expected) { Assert.Equal( expected.Replace("\\r", "").Replace("\\n", ""), actual.Replace("\\r", "").Replace("\\n", ""), ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); } public static readonly string InputObjectBugQuery = @" query test { __type(name:""SomeInput"") { inputFields { type { name, description ofType { kind, name } } } } }"; public static readonly string InputObjectBugResult = "{\r\n \"data\": {\r\n \"__type\": {\r\n \"inputFields\": [\r\n {\r\n \"type\": {\r\n \"name\": \"String\",\r\n \"description\": null,\r\n \"ofType\": null\r\n }\r\n }\r\n ]\r\n }\r\n }\r\n}"; public class SomeInputType : InputObjectGraphType { public SomeInputType() : base() { Name = "SomeInput"; Description = "Input values for a patient's demographic information"; Field<StringGraphType>("address"); } } public class RootMutation : ObjectGraphType { public RootMutation() { Field<StringGraphType>( "test", arguments: new QueryArguments(new QueryArgument(typeof(SomeInputType)) { Name = "some" })); } } public class TestSchema : Schema { public TestSchema() { Mutation = new RootMutation(); } } } }
//--------------------------------------------------------------------- // <copyright file="ODataJsonLightReaderUtils.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Core.JsonLight { #region Namespaces using System; using System.Diagnostics; using System.Globalization; using Microsoft.OData.Core.Json; using Microsoft.OData.Core.Metadata; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Library; using ODataErrorStrings = Microsoft.OData.Core.Strings; using ODataPlatformHelper = Microsoft.OData.Core.PlatformHelper; #endregion Namespaces /// <summary> /// Helper methods used by the OData reader for the JsonLight format. /// </summary> internal static class ODataJsonLightReaderUtils { /// <summary> /// Enumeration of all properties in error payloads, the value of the enum is the bitmask which identifies /// a bit per property. /// </summary> /// <remarks> /// We only use a single enumeration for both top-level as well as inner errors. /// This means that some bits are never set for top-level (or inner errors). /// </remarks> [Flags] internal enum ErrorPropertyBitMask { /// <summary>No property found yet.</summary> None = 0, /// <summary>The "error" of the top-level object.</summary> Error = 1, /// <summary>The "code" property.</summary> Code = 2, /// <summary>The "message" property of either the error object or the inner error object.</summary> Message = 4, /// <summary>The "value" property of the message object.</summary> MessageValue = 16, /// <summary>The "innererror" or "internalexception" property of the error object or an inner error object.</summary> InnerError = 32, /// <summary>The "type" property of an inner error object.</summary> TypeName = 64, /// <summary>The "stacktrace" property of an inner error object.</summary> StackTrace = 128, } /// <summary> /// Checks whether the specified property has already been found before. /// </summary> /// <param name="propertiesFoundBitField"> /// The bit field which stores which properties of an error or inner error were found so far. /// </param> /// <param name="propertyFoundBitMask">The bit mask for the property to check.</param> /// <returns>true if the property has not been read before; otherwise false.</returns> internal static bool ErrorPropertyNotFound( ref ODataJsonLightReaderUtils.ErrorPropertyBitMask propertiesFoundBitField, ODataJsonLightReaderUtils.ErrorPropertyBitMask propertyFoundBitMask) { Debug.Assert(((int)propertyFoundBitMask & (((int)propertyFoundBitMask) - 1)) == 0, "propertyFoundBitMask is not a power of 2."); if ((propertiesFoundBitField & propertyFoundBitMask) == propertyFoundBitMask) { return false; } propertiesFoundBitField |= propertyFoundBitMask; return true; } /// <summary> /// Converts the given JSON value to the expected type as per OData conversion rules for JSON values. /// </summary> /// <param name="value">Value to the converted.</param> /// <param name="primitiveTypeReference">Type reference to which the value needs to be converted.</param> /// <param name="messageReaderSettings">The message reader settings used for reading.</param> /// <param name="validateNullValue">true to validate null values; otherwise false.</param> /// <param name="propertyName">The name of the property whose value is being read, if applicable (used for error reporting).</param> /// <param name="converter">The payload value converter to convert this value.</param> /// <returns>Object which is in sync with the property type (modulo the V1 exception of converting numbers to non-compatible target types).</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("DataWeb.Usage", "AC0014", Justification = "Throws every time")] internal static object ConvertValue( object value, IEdmPrimitiveTypeReference primitiveTypeReference, ODataMessageReaderSettings messageReaderSettings, bool validateNullValue, string propertyName, ODataPayloadValueConverter converter) { Debug.Assert(primitiveTypeReference != null, "primitiveTypeReference != null"); if (value == null) { // Only primitive type references are validated. Core model is sufficient. ReaderValidationUtils.ValidateNullValue( EdmCoreModel.Instance, primitiveTypeReference, messageReaderSettings, validateNullValue, propertyName); return null; } value = converter.ConvertFromPayloadValue(value, primitiveTypeReference); // otherwise just return the value without doing any conversion return value; } /// <summary> /// Ensure that the <paramref name="instance"/> is not null; if so create a new instance. /// </summary> /// <typeparam name="T">The type of the instance to check.</typeparam> /// <param name="instance">The instance to check for null.</param> internal static void EnsureInstance<T>(ref T instance) where T : class, new() { if (instance == null) { instance = new T(); } } /// <summary> /// Determines if the specified <paramref name="propertyName"/> is an OData annotation property name. /// </summary> /// <param name="propertyName">The property name to test.</param> /// <returns>true if the property name is an OData annotation property name, false otherwise.</returns> internal static bool IsODataAnnotationName(string propertyName) { Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); return propertyName.StartsWith(JsonLightConstants.ODataAnnotationNamespacePrefix, StringComparison.Ordinal); } /// <summary> /// Determines if the specified property name is a name of an annotation property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <returns>true if <paramref name="propertyName"/> is a name of an annotation property, false otherwise.</returns> /// <remarks> /// This method returns true both for normal annotation as well as property annotations. /// </remarks> internal static bool IsAnnotationProperty(string propertyName) { Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); return propertyName.IndexOf('.') >= 0; } /// <summary> /// Validates that the annotation value is valid. /// </summary> /// <param name="propertyValue">The value of the annotation.</param> /// <param name="annotationName">The name of the (instance or property) annotation (used for error reporting).</param> internal static void ValidateAnnotationValue(object propertyValue, string annotationName) { Debug.Assert(!string.IsNullOrEmpty(annotationName), "!string.IsNullOrEmpty(annotationName)"); if (propertyValue == null) { throw new ODataException(ODataErrorStrings.ODataJsonLightReaderUtils_AnnotationWithNullValue(annotationName)); } } /// <summary> /// Gets the payload type name for an OData OM instance for JsonLight. /// </summary> /// <param name="payloadItem">The payload item to get the type name for.</param> /// <returns>The type name as read from the payload item (or constructed for primitive items).</returns> internal static string GetPayloadTypeName(object payloadItem) { if (payloadItem == null) { return null; } TypeCode typeCode = ODataPlatformHelper.GetTypeCode(payloadItem.GetType()); switch (typeCode) { // In JSON only boolean, String, Int32 and Double are recognized as primitive types // (without additional type conversion). So only check for those; if not one of these primitive // types it must be a complex, entity or collection value. case TypeCode.Boolean: return Metadata.EdmConstants.EdmBooleanTypeName; case TypeCode.String: return Metadata.EdmConstants.EdmStringTypeName; case TypeCode.Int32: return Metadata.EdmConstants.EdmInt32TypeName; case TypeCode.Double: return Metadata.EdmConstants.EdmDoubleTypeName; default: Debug.Assert(typeCode == TypeCode.Object, "If not one of the primitive types above, it must be an object in JSON."); break; } ODataComplexValue complexValue = payloadItem as ODataComplexValue; if (complexValue != null) { return complexValue.TypeName; } ODataCollectionValue collectionValue = payloadItem as ODataCollectionValue; if (collectionValue != null) { return EdmLibraryExtensions.GetCollectionTypeFullName(collectionValue.TypeName); } ODataEntry entry = payloadItem as ODataEntry; if (entry != null) { return entry.TypeName; } throw new ODataException(ODataErrorStrings.General_InternalError(InternalErrorCodes.ODataJsonLightReader_ReadEntryStart)); } } }
// // KeyInfoX509Data.cs - KeyInfoX509Data implementation for XML Signature // // Authors: // Sebastien Pouliot <sebastien@ximian.com> // Atsushi Enomoto (atsushi@ximian.com) // Tim Coleman (tim@timcoleman.com) // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) Tim Coleman, 2004 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Xml; namespace System.Security.Cryptography.Xml { public class KeyInfoX509Data : KeyInfoClause { private byte[] x509crl; private ArrayList IssuerSerialList; private ArrayList SubjectKeyIdList; private ArrayList SubjectNameList; private ArrayList X509CertificateList; public KeyInfoX509Data () { } public KeyInfoX509Data (byte[] rgbCert) { AddCertificate (new X509Certificate (rgbCert)); } public KeyInfoX509Data (X509Certificate cert) { AddCertificate (cert); } #if NET_2_0 && SECURITY_DEP public KeyInfoX509Data (X509Certificate cert, X509IncludeOption includeOption) { if (cert == null) throw new ArgumentNullException ("cert"); switch (includeOption) { case X509IncludeOption.None: case X509IncludeOption.EndCertOnly: AddCertificate (cert); break; case X509IncludeOption.ExcludeRoot: AddCertificatesChainFrom (cert, false); break; case X509IncludeOption.WholeChain: AddCertificatesChainFrom (cert, true); break; } } // this gets complicated because we must: // 1. build the chain using a X509Certificate2 class; // 2. test for root using the Mono.Security.X509.X509Certificate class; // 3. add the certificates as X509Certificate instances; private void AddCertificatesChainFrom (X509Certificate cert, bool root) { X509Chain chain = new X509Chain (); chain.Build (new X509Certificate2 (cert)); foreach (X509ChainElement ce in chain.ChainElements) { byte[] rawdata = ce.Certificate.RawData; if (!root) { // exclude root Mono.Security.X509.X509Certificate mx = new Mono.Security.X509.X509Certificate (rawdata); if (mx.IsSelfSigned) rawdata = null; } if (rawdata != null) AddCertificate (new X509Certificate (rawdata)); } } #endif public ArrayList Certificates { get { return X509CertificateList; } } public byte[] CRL { get { return x509crl; } set { x509crl = value; } } public ArrayList IssuerSerials { get { return IssuerSerialList; } } public ArrayList SubjectKeyIds { get { return SubjectKeyIdList; } } public ArrayList SubjectNames { get { return SubjectNameList; } } public void AddCertificate (X509Certificate certificate) { #if NET_2_0 if (certificate == null) throw new ArgumentNullException ("certificate"); #endif if (X509CertificateList == null) X509CertificateList = new ArrayList (); X509CertificateList.Add (certificate); } public void AddIssuerSerial (string issuerName, string serialNumber) { #if NET_2_0 if (issuerName == null) throw new ArgumentException ("issuerName"); #endif if (IssuerSerialList == null) IssuerSerialList = new ArrayList (); X509IssuerSerial xis = new X509IssuerSerial (issuerName, serialNumber); IssuerSerialList.Add (xis); } public void AddSubjectKeyId (byte[] subjectKeyId) { if (SubjectKeyIdList == null) SubjectKeyIdList = new ArrayList (); SubjectKeyIdList.Add (subjectKeyId); } #if NET_2_0 [ComVisible (false)] public void AddSubjectKeyId (string subjectKeyId) { if (SubjectKeyIdList == null) SubjectKeyIdList = new ArrayList (); byte[] id = null; if (subjectKeyId != null) id = Convert.FromBase64String (subjectKeyId); SubjectKeyIdList.Add (id); } #endif public void AddSubjectName (string subjectName) { if (SubjectNameList == null) SubjectNameList = new ArrayList (); SubjectNameList.Add (subjectName); } public override XmlElement GetXml () { #if !NET_2_0 // sanity check int count = 0; if (IssuerSerialList != null) count += IssuerSerialList.Count; if (SubjectKeyIdList != null) count += SubjectKeyIdList.Count; if (SubjectNameList != null) count += SubjectNameList.Count; if (X509CertificateList != null) count += X509CertificateList.Count; if ((x509crl == null) && (count == 0)) throw new CryptographicException ("value"); #endif XmlDocument document = new XmlDocument (); XmlElement xel = document.CreateElement (XmlSignature.ElementNames.X509Data, XmlSignature.NamespaceURI); // FIXME: hack to match MS implementation xel.SetAttribute ("xmlns", XmlSignature.NamespaceURI); // <X509IssuerSerial> if ((IssuerSerialList != null) && (IssuerSerialList.Count > 0)) { foreach (X509IssuerSerial iser in IssuerSerialList) { XmlElement isl = document.CreateElement (XmlSignature.ElementNames.X509IssuerSerial, XmlSignature.NamespaceURI); XmlElement xin = document.CreateElement (XmlSignature.ElementNames.X509IssuerName, XmlSignature.NamespaceURI); xin.InnerText = iser.IssuerName; isl.AppendChild (xin); XmlElement xsn = document.CreateElement (XmlSignature.ElementNames.X509SerialNumber, XmlSignature.NamespaceURI); xsn.InnerText = iser.SerialNumber; isl.AppendChild (xsn); xel.AppendChild (isl); } } // <X509SKI> if ((SubjectKeyIdList != null) && (SubjectKeyIdList.Count > 0)) { foreach (byte[] skid in SubjectKeyIdList) { XmlElement ski = document.CreateElement (XmlSignature.ElementNames.X509SKI, XmlSignature.NamespaceURI); ski.InnerText = Convert.ToBase64String (skid); xel.AppendChild (ski); } } // <X509SubjectName> if ((SubjectNameList != null) && (SubjectNameList.Count > 0)) { foreach (string subject in SubjectNameList) { XmlElement sn = document.CreateElement (XmlSignature.ElementNames.X509SubjectName, XmlSignature.NamespaceURI); sn.InnerText = subject; xel.AppendChild (sn); } } // <X509Certificate> if ((X509CertificateList != null) && (X509CertificateList.Count > 0)) { foreach (X509Certificate x509 in X509CertificateList) { XmlElement cert = document.CreateElement (XmlSignature.ElementNames.X509Certificate, XmlSignature.NamespaceURI); cert.InnerText = Convert.ToBase64String (x509.GetRawCertData ()); xel.AppendChild (cert); } } // only one <X509CRL> if (x509crl != null) { XmlElement crl = document.CreateElement (XmlSignature.ElementNames.X509CRL, XmlSignature.NamespaceURI); crl.InnerText = Convert.ToBase64String (x509crl); xel.AppendChild (crl); } return xel; } public override void LoadXml (XmlElement element) { if (element == null) throw new ArgumentNullException ("element"); if (IssuerSerialList != null) IssuerSerialList.Clear (); if (SubjectKeyIdList != null) SubjectKeyIdList.Clear (); if (SubjectNameList != null) SubjectNameList.Clear (); if (X509CertificateList != null) X509CertificateList.Clear (); x509crl = null; if ((element.LocalName != XmlSignature.ElementNames.X509Data) || (element.NamespaceURI != XmlSignature.NamespaceURI)) throw new CryptographicException ("element"); XmlElement [] xnl = null; // <X509IssuerSerial> xnl = XmlSignature.GetChildElements (element, XmlSignature.ElementNames.X509IssuerSerial); if (xnl != null) { for (int i=0; i < xnl.Length; i++) { XmlElement xel = (XmlElement) xnl[i]; XmlElement issuer = XmlSignature.GetChildElement (xel, XmlSignature.ElementNames.X509IssuerName, XmlSignature.NamespaceURI); XmlElement serial = XmlSignature.GetChildElement (xel, XmlSignature.ElementNames.X509SerialNumber, XmlSignature.NamespaceURI); AddIssuerSerial (issuer.InnerText, serial.InnerText); } } // <X509SKI> xnl = XmlSignature.GetChildElements (element, XmlSignature.ElementNames.X509SKI); if (xnl != null) { for (int i=0; i < xnl.Length; i++) { byte[] skid = Convert.FromBase64String (xnl[i].InnerXml); AddSubjectKeyId (skid); } } // <X509SubjectName> xnl = XmlSignature.GetChildElements (element, XmlSignature.ElementNames.X509SubjectName); if (xnl != null) { for (int i=0; i < xnl.Length; i++) { AddSubjectName (xnl[i].InnerXml); } } // <X509Certificate> xnl = XmlSignature.GetChildElements (element, XmlSignature.ElementNames.X509Certificate); if (xnl != null) { for (int i=0; i < xnl.Length; i++) { byte[] cert = Convert.FromBase64String (xnl[i].InnerXml); AddCertificate (new X509Certificate (cert)); } } // only one <X509CRL> XmlElement x509el = XmlSignature.GetChildElement (element, XmlSignature.ElementNames.X509CRL, XmlSignature.NamespaceURI); if (x509el != null) { x509crl = Convert.FromBase64String (x509el.InnerXml); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Orleans.Configuration; using Orleans.Configuration.Overrides; using Orleans.Persistence.AzureStorage; using Orleans.Providers.Azure; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace Orleans.Storage { /// <summary> /// Simple storage for writing grain state data to Azure table storage. /// </summary> public class AzureTableGrainStorage : IGrainStorage, IRestExceptionDecoder, ILifecycleParticipant<ISiloLifecycle> { private readonly AzureTableStorageOptions options; private readonly ClusterOptions clusterOptions; private readonly Serializer serializer; private readonly IServiceProvider services; private readonly ILogger logger; private GrainStateTableDataManager tableDataManager; private JsonSerializerSettings JsonSettings; // each property can hold 64KB of data and each entity can take 1MB in total, so 15 full properties take // 15 * 64 = 960 KB leaving room for the primary key, timestamp etc private const int MAX_DATA_CHUNK_SIZE = 64 * 1024; private const int MAX_STRING_PROPERTY_LENGTH = 32 * 1024; private const int MAX_DATA_CHUNKS_COUNT = 15; private const string BINARY_DATA_PROPERTY_NAME = "Data"; private const string STRING_DATA_PROPERTY_NAME = "StringData"; private string name; /// <summary> Default constructor </summary> public AzureTableGrainStorage( string name, AzureTableStorageOptions options, IOptions<ClusterOptions> clusterOptions, Serializer serializer, IServiceProvider services, ILogger<AzureTableGrainStorage> logger) { this.options = options; this.clusterOptions = clusterOptions.Value; this.name = name; this.serializer = serializer; this.services = services; this.logger = logger; } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IGrainStorage.ReadStateAsync"/> public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if(logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_ReadingData, "Reading: GrainType={0} Pk={1} Grainid={2} from Table={3}", grainType, pk, grainReference, this.options.TableName); string partitionKey = pk; string rowKey = AzureTableUtils.SanitizeTableProperty(grainType); GrainStateRecord record = await tableDataManager.Read(partitionKey, rowKey).ConfigureAwait(false); if (record != null) { var entity = record.Entity; if (entity != null) { var loadedState = ConvertFromStorageFormat(entity, grainState.Type); grainState.RecordExists = loadedState != null; grainState.State = loadedState ?? Activator.CreateInstance(grainState.Type); grainState.ETag = record.ETag; } } // Else leave grainState in previous default condition } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IGrainStorage.WriteStateAsync"/> public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Writing: GrainType={0} Pk={1} Grainid={2} ETag={3} to Table={4}", grainType, pk, grainReference, grainState.ETag, this.options.TableName); var rowKey = AzureTableUtils.SanitizeTableProperty(grainType); var entity = new DynamicTableEntity(pk, rowKey); ConvertToStorageFormat(grainState.State, entity); var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag }; try { await DoOptimisticUpdate(() => tableDataManager.Write(record), grainType, grainReference.GrainId, this.options.TableName, grainState.ETag).ConfigureAwait(false); grainState.ETag = record.ETag; grainState.RecordExists = true; } catch (Exception exc) { logger.Error((int)AzureProviderErrorCode.AzureTableProvider_WriteError, $"Error Writing: GrainType={grainType} GrainId={grainReference.GrainId} ETag={grainState.ETag} to Table={this.options.TableName} Exception={exc.Message}", exc); throw; } } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <remarks> /// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row /// for this grain will be deleted / removed, otherwise the table row will be /// cleared by overwriting with default / null values. /// </remarks> /// <see cref="IGrainStorage.ClearStateAsync"/> public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Clearing: GrainType={0} Pk={1} Grainid={2} ETag={3} DeleteStateOnClear={4} from Table={5}", grainType, pk, grainReference, grainState.ETag, this.options.DeleteStateOnClear, this.options.TableName); var rowKey = AzureTableUtils.SanitizeTableProperty(grainType); var entity = new DynamicTableEntity(pk, rowKey); var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag }; string operation = "Clearing"; try { if (this.options.DeleteStateOnClear) { operation = "Deleting"; await DoOptimisticUpdate(() => tableDataManager.Delete(record), grainType, grainReference.GrainId, this.options.TableName, grainState.ETag).ConfigureAwait(false); } else { await DoOptimisticUpdate(() => tableDataManager.Write(record), grainType, grainReference.GrainId, this.options.TableName, grainState.ETag).ConfigureAwait(false); } grainState.ETag = record.ETag; // Update in-memory data to the new ETag grainState.RecordExists = false; } catch (Exception exc) { logger.Error((int)AzureProviderErrorCode.AzureTableProvider_DeleteError, string.Format("Error {0}: GrainType={1} Grainid={2} ETag={3} from Table={4} Exception={5}", operation, grainType, grainReference, grainState.ETag, this.options.TableName, exc.Message), exc); throw; } } private static async Task DoOptimisticUpdate(Func<Task> updateOperation, string grainType, GrainId grainId, string tableName, string currentETag) { try { await updateOperation.Invoke().ConfigureAwait(false); } catch (StorageException ex) when (ex.IsPreconditionFailed() || ex.IsConflict() || ex.IsNotFound()) { throw new TableStorageUpdateConditionNotSatisfiedException(grainType, grainId.ToString(), tableName, "Unknown", currentETag, ex); } } /// <summary> /// Serialize to Azure storage format in either binary or JSON format. /// </summary> /// <param name="grainState">The grain state data to be serialized</param> /// <param name="entity">The Azure table entity the data should be stored in</param> /// <remarks> /// See: /// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx /// for more on the JSON serializer. /// </remarks> internal void ConvertToStorageFormat(object grainState, DynamicTableEntity entity) { int dataSize; IEnumerable<EntityProperty> properties; string basePropertyName; if (this.options.UseJson) { // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm string data = Newtonsoft.Json.JsonConvert.SerializeObject(grainState, this.JsonSettings); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); // each Unicode character takes 2 bytes dataSize = data.Length * 2; properties = SplitStringData(data).Select(t => new EntityProperty(t)); basePropertyName = STRING_DATA_PROPERTY_NAME; } else { // Convert to binary format byte[] data = this.serializer.SerializeToArray(grainState); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Writing binary data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); dataSize = data.Length; properties = SplitBinaryData(data).Select(t => new EntityProperty(t)); basePropertyName = BINARY_DATA_PROPERTY_NAME; } CheckMaxDataSize(dataSize, MAX_DATA_CHUNK_SIZE * MAX_DATA_CHUNKS_COUNT); foreach (var keyValuePair in properties.Zip(GetPropertyNames(basePropertyName), (property, name) => new KeyValuePair<string, EntityProperty>(name, property))) { entity.Properties.Add(keyValuePair); } } private void CheckMaxDataSize(int dataSize, int maxDataSize) { if (dataSize > maxDataSize) { var msg = string.Format("Data too large to write to Azure table. Size={0} MaxSize={1}", dataSize, maxDataSize); logger.Error(0, msg); throw new ArgumentOutOfRangeException("GrainState.Size", msg); } } private static IEnumerable<string> SplitStringData(string stringData) { var startIndex = 0; while (startIndex < stringData.Length) { var chunkSize = Math.Min(MAX_STRING_PROPERTY_LENGTH, stringData.Length - startIndex); yield return stringData.Substring(startIndex, chunkSize); startIndex += chunkSize; } } private static IEnumerable<byte[]> SplitBinaryData(byte[] binaryData) { var startIndex = 0; while (startIndex < binaryData.Length) { var chunkSize = Math.Min(MAX_DATA_CHUNK_SIZE, binaryData.Length - startIndex); var chunk = new byte[chunkSize]; Array.Copy(binaryData, startIndex, chunk, 0, chunkSize); yield return chunk; startIndex += chunkSize; } } private static IEnumerable<string> GetPropertyNames(string basePropertyName) { yield return basePropertyName; for (var i = 1; i < MAX_DATA_CHUNKS_COUNT; ++i) { yield return basePropertyName + i; } } private static IEnumerable<byte[]> ReadBinaryDataChunks(DynamicTableEntity entity) { foreach (var binaryDataPropertyName in GetPropertyNames(BINARY_DATA_PROPERTY_NAME)) { EntityProperty dataProperty; if (entity.Properties.TryGetValue(binaryDataPropertyName, out dataProperty)) { switch (dataProperty.PropertyType) { // if TablePayloadFormat.JsonNoMetadata is used case EdmType.String: var stringValue = dataProperty.StringValue; if (!string.IsNullOrEmpty(stringValue)) { yield return Convert.FromBase64String(stringValue); } break; // if any payload type providing metadata is used case EdmType.Binary: var binaryValue = dataProperty.BinaryValue; if (binaryValue != null && binaryValue.Length > 0) { yield return binaryValue; } break; } } } } private static byte[] ReadBinaryData(DynamicTableEntity entity) { var dataChunks = ReadBinaryDataChunks(entity).ToArray(); var dataSize = dataChunks.Select(d => d.Length).Sum(); var result = new byte[dataSize]; var startIndex = 0; foreach (var dataChunk in dataChunks) { Array.Copy(dataChunk, 0, result, startIndex, dataChunk.Length); startIndex += dataChunk.Length; } return result; } private static IEnumerable<string> ReadStringDataChunks(DynamicTableEntity entity) { foreach (var stringDataPropertyName in GetPropertyNames(STRING_DATA_PROPERTY_NAME)) { EntityProperty dataProperty; if (entity.Properties.TryGetValue(stringDataPropertyName, out dataProperty)) { var data = dataProperty.StringValue; if (!string.IsNullOrEmpty(data)) { yield return data; } } } } private static string ReadStringData(DynamicTableEntity entity) { return string.Join(string.Empty, ReadStringDataChunks(entity)); } /// <summary> /// Deserialize from Azure storage format /// </summary> /// <param name="entity">The Azure table entity the stored data</param> /// <param name="stateType">The state type</param> internal object ConvertFromStorageFormat(DynamicTableEntity entity, Type stateType) { var binaryData = ReadBinaryData(entity); var stringData = ReadStringData(entity); object dataValue = null; try { if (binaryData.Length > 0) { // Rehydrate dataValue = this.serializer.Deserialize<object>(binaryData); } else if (!string.IsNullOrEmpty(stringData)) { dataValue = Newtonsoft.Json.JsonConvert.DeserializeObject(stringData, stateType, this.JsonSettings); } // Else, no data found } catch (Exception exc) { var sb = new StringBuilder(); if (binaryData.Length > 0) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", binaryData); } else if (!string.IsNullOrEmpty(stringData)) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", stringData); } if (dataValue != null) { sb.AppendFormat("Data Value={0} Type={1}", dataValue, dataValue.GetType()); } logger.Error(0, sb.ToString(), exc); throw new AggregateException(sb.ToString(), exc); } return dataValue; } private string GetKeyString(GrainReference grainReference) { var key = String.Format("{0}_{1}", this.clusterOptions.ServiceId, grainReference.ToKeyString()); return AzureTableUtils.SanitizeTableProperty(key); } internal class GrainStateRecord { public string ETag { get; set; } public DynamicTableEntity Entity { get; set; } } private class GrainStateTableDataManager { public string TableName { get; private set; } private readonly AzureTableDataManager<DynamicTableEntity> tableManager; private readonly ILogger logger; public GrainStateTableDataManager(AzureStorageOperationOptions options, ILogger logger) { this.logger = logger; TableName = options.TableName; tableManager = new AzureTableDataManager<DynamicTableEntity>(options, logger); } public Task InitTableAsync() { return tableManager.InitTableAsync(); } public async Task<GrainStateRecord> Read(string partitionKey, string rowKey) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Reading, "Reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); try { Tuple<DynamicTableEntity, string> data = await tableManager.ReadSingleTableEntryAsync(partitionKey, rowKey).ConfigureAwait(false); if (data == null || data.Item1 == null) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); return null; } DynamicTableEntity stateEntity = data.Item1; var record = new GrainStateRecord { Entity = stateEntity, ETag = data.Item2 }; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_DataRead, "Read: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", stateEntity.PartitionKey, stateEntity.RowKey, TableName, record.ETag); return record; } catch (Exception exc) { if (AzureTableUtils.TableStorageDataNotFound(exc)) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading (exception): PartitionKey={0} RowKey={1} from Table={2} Exception={3}", partitionKey, rowKey, TableName, LogFormatter.PrintException(exc)); return null; // No data } throw; } } public async Task Write(GrainStateRecord record) { var entity = record.Entity; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Writing: PartitionKey={0} RowKey={1} to Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); string eTag = String.IsNullOrEmpty(record.ETag) ? await tableManager.CreateTableEntryAsync(entity).ConfigureAwait(false) : await tableManager.UpdateTableEntryAsync(entity, record.ETag).ConfigureAwait(false); record.ETag = eTag; } public async Task Delete(GrainStateRecord record) { var entity = record.Entity; if (record.ETag == null) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "Not attempting to delete non-existent persistent state: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); return; } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Deleting: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); await tableManager.DeleteTableEntryAsync(entity, record.ETag).ConfigureAwait(false); record.ETag = null; } } /// <summary> Decodes Storage exceptions.</summary> public bool DecodeException(Exception e, out HttpStatusCode httpStatusCode, out string restStatus, bool getRESTErrors = false) { return AzureTableUtils.EvaluateException(e, out httpStatusCode, out restStatus, getRESTErrors); } private async Task Init(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); try { this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureTableGrainStorage {name} initializing: {this.options.ToString()}"); this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, $"AzureTableGrainStorage {name} is using DataConnectionString: {ConfigUtilities.RedactConnectionStringInfo(this.options.ConnectionString)}"); this.JsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.services), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling); this.options.ConfigureJsonSerializerSettings?.Invoke(this.JsonSettings); this.tableDataManager = new GrainStateTableDataManager(this.options, this.logger); await this.tableDataManager.InitTableAsync(); stopWatch.Stop(); this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds."); } catch (Exception ex) { stopWatch.Stop(); this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex); throw; } } private Task Close(CancellationToken ct) { this.tableDataManager = null; return Task.CompletedTask; } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(OptionFormattingUtilities.Name<AzureTableGrainStorage>(this.name), this.options.InitStage, Init, Close); } } public static class AzureTableGrainStorageFactory { public static IGrainStorage Create(IServiceProvider services, string name) { var optionsSnapshot = services.GetRequiredService<IOptionsMonitor<AzureTableStorageOptions>>(); var clusterOptions = services.GetProviderClusterOptions(name); return ActivatorUtilities.CreateInstance<AzureTableGrainStorage>(services, name, optionsSnapshot.Get(name), clusterOptions); } } }
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Buffers; using System.IO; using System.Threading; using System.Threading.Tasks; using Nerdbank.Streams; namespace MessagePack { /// <summary> /// Reads one or more messagepack data structures from a <see cref="Stream"/>. /// </summary> /// <remarks> /// This class is *not* thread-safe. Do not call more than one member at once and be sure any call completes (including asynchronous tasks) /// before calling the next one. /// </remarks> public partial class MessagePackStreamReader : IDisposable { private readonly Stream stream; private readonly bool leaveOpen; private SequencePool.Rental sequenceRental; private SequencePosition? endOfLastMessage; /// <summary> /// Initializes a new instance of the <see cref="MessagePackStreamReader"/> class. /// </summary> /// <param name="stream">The stream to read from. This stream will be disposed of when this <see cref="MessagePackStreamReader"/> is disposed.</param> public MessagePackStreamReader(Stream stream) : this(stream, leaveOpen: false) { } /// <summary> /// Initializes a new instance of the <see cref="MessagePackStreamReader"/> class. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="leaveOpen">If true, leaves the stream open after this <see cref="MessagePackStreamReader"/> is disposed; otherwise, false.</param> public MessagePackStreamReader(Stream stream, bool leaveOpen) : this(stream, leaveOpen, SequencePool.Shared) { } /// <summary> /// Initializes a new instance of the <see cref="MessagePackStreamReader"/> class. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="leaveOpen">If true, leaves the stream open after this <see cref="MessagePackStreamReader"/> is disposed; otherwise, false.</param> /// <param name="sequencePool">The pool to rent a <see cref="Sequence{T}"/> object from.</param> public MessagePackStreamReader(Stream stream, bool leaveOpen, SequencePool sequencePool) { if (sequencePool == null) { throw new ArgumentNullException(nameof(sequencePool)); } this.stream = stream ?? throw new ArgumentNullException(nameof(stream)); this.leaveOpen = leaveOpen; this.sequenceRental = sequencePool.Rent(); } /// <summary> /// Gets any bytes that have been read since the last complete message returned from <see cref="ReadAsync(CancellationToken)"/>. /// </summary> public ReadOnlySequence<byte> RemainingBytes => this.endOfLastMessage.HasValue ? this.ReadData.AsReadOnlySequence.Slice(this.endOfLastMessage.Value) : this.ReadData.AsReadOnlySequence; /// <summary> /// Gets the sequence that we read data from the <see cref="stream"/> into. /// </summary> private Sequence<byte> ReadData => this.sequenceRental.Value; /// <summary> /// Reads the next whole (top-level) messagepack data structure. /// </summary> /// <param name="cancellationToken">A cancellation token.</param> /// <returns> /// A task whose result is the next whole data structure from the stream, or <c>null</c> if the stream ends. /// The returned sequence is valid until this <see cref="MessagePackStreamReader"/> is disposed or /// until this method is called again, whichever comes first. /// </returns> /// <remarks> /// When <c>null</c> is the result of the returned task, /// any extra bytes read (between the last complete message and the end of the stream) will be available via the <see cref="RemainingBytes"/> property. /// </remarks> public async ValueTask<ReadOnlySequence<byte>?> ReadAsync(CancellationToken cancellationToken) { this.RecycleLastMessage(); while (true) { // Check if we have a complete message and return it if we have it. // We do this before reading anything since a previous read may have brought in several messages. cancellationToken.ThrowIfCancellationRequested(); if (this.TryReadNextMessage(out ReadOnlySequence<byte> completeMessage)) { return completeMessage; } if (!await this.TryReadMoreDataAsync(cancellationToken).ConfigureAwait(false)) { // We've reached the end of the stream. // We already checked for a complete message with what we already had, so evidently it's not a complete message. return null; } } } /// <summary> /// Arranges for the next read operation to start by reading from the underlying <see cref="Stream"/> /// instead of any data buffered from a previous read. /// </summary> /// <remarks> /// This is appropriate if the underlying <see cref="Stream"/> has been repositioned such that /// any previously buffered data is no longer applicable to what the caller wants to read. /// </remarks> public void DiscardBufferedData() { this.sequenceRental.Value.Reset(); this.endOfLastMessage = default; } /// <inheritdoc/> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes of managed and unmanaged resources. /// </summary> /// <param name="disposing"><see langword="true"/> if this instance is being disposed; <see langword="false"/> if it is being finalized.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (!this.leaveOpen) { this.stream.Dispose(); } this.sequenceRental.Dispose(); this.sequenceRental = default; } } /// <summary> /// Recycle memory from a previously returned message. /// </summary> private void RecycleLastMessage() { if (this.endOfLastMessage.HasValue) { // A previously returned message can now be safely recycled since the caller wants more. this.ReadData.AdvanceTo(this.endOfLastMessage.Value); this.endOfLastMessage = null; } } /// <summary> /// Read more data from the stream into the <see cref="ReadData"/> buffer. /// </summary> /// <param name="cancellationToken">A cancellation token.</param> /// <returns><c>true</c> if more data was read; <c>false</c> if the end of the stream had already been reached.</returns> private async Task<bool> TryReadMoreDataAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Memory<byte> buffer = this.ReadData.GetMemory(sizeHint: 0); int bytesRead = 0; try { bytesRead = await this.stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); return bytesRead > 0; } finally { // Keep our state clean in case the caller wants to call us again. this.ReadData.Advance(bytesRead); } } /// <summary> /// Checks whether the content in <see cref="ReadData"/> include a complete messagepack structure. /// </summary> /// <param name="completeMessage">Receives the sequence of the first complete data structure found, if any.</param> /// <returns><c>true</c> if a complete data structure was found; <c>false</c> otherwise.</returns> private bool TryReadNextMessage(out ReadOnlySequence<byte> completeMessage) { if (this.ReadData.Length > 0) { var reader = new MessagePackReader(this.ReadData); // Perf opportunity: instead of skipping from the start each time, we could incrementally skip across tries // possibly as easy as simply keeping a count of how many tokens still need to be skipped (that we know about). if (reader.TrySkip()) { this.endOfLastMessage = reader.Position; completeMessage = reader.Sequence.Slice(0, reader.Position); return true; } } completeMessage = default; return false; } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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.Data; using System.Diagnostics; using System.Reflection; using MindTouch.Xml; namespace MindTouch.Data { /// <summary> /// Provides a a database query/stored procedure command builder. /// </summary> public class DataCommand : IDataCommand { //--- Types --- internal class DataColumnField { //--- Fields --- private readonly PropertyInfo _property; private readonly FieldInfo _field; private readonly Type _type; //--- Constructors --- internal DataColumnField(PropertyInfo info) { if(info == null) { throw new ArgumentNullException("info"); } _property = info; _type = info.PropertyType; } internal DataColumnField(FieldInfo info) { if(info == null) { throw new ArgumentNullException("info"); } _field = info; _type = info.FieldType; } //--- Methods --- internal void SetValue(object instance, object value) { if((value == null) || (value is DBNull)) { if(!_type.IsValueType || (_type.IsGenericType && (_type.GetGenericTypeDefinition() == typeof(Nullable<>)))) { if(_property != null) { _property.SetValue(instance, null, null); } else { _field.SetValue(instance, null); } } } else if(_type.IsEnum) { switch(Convert.GetTypeCode(value)) { case TypeCode.String: if(_property != null) { _property.SetValue(instance, Enum.Parse(_type, (string)value, true), null); } else { _field.SetValue(instance, Enum.Parse(_type, (string)value, true)); } break; case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: string text = Enum.GetName(_type, value); if(text != null) { if(_property != null) { _property.SetValue(instance, text, null); } else { _field.SetValue(instance, text); } } break; } } else if(value.GetType() != _type) { if(_property != null) { _property.SetValue(instance, SysUtil.ChangeType(value, _type), null); } else { _field.SetValue(instance, SysUtil.ChangeType(value, _type)); } } else { if(_property != null) { _property.SetValue(instance, value, null); } else { _field.SetValue(instance, value); } } } } //--- Class Fields --- private static readonly log4net.ILog _log = LogUtils.CreateLog(); private static readonly Dictionary<Type, Dictionary<string, DataColumnField>> _typeCache = new Dictionary<Type, Dictionary<string, DataColumnField>>(); private static readonly TimeSpan SLOW_SQL = TimeSpan.FromSeconds(5); //--- Class Methods --- /// <summary> /// Ensure that string is safe for use in SQL statements. /// </summary> /// <param name="text">String to escape</param> /// <returns>Escaped string</returns> public static string MakeSqlSafe(string text) { if(string.IsNullOrEmpty(text)) { return text; } text = text.ReplaceAll( "\\", "\\\\", "\0", "\\0", "\n", "\\n", "\r", "\\r", "'", "\\'", "\"", "\\\"", "\x1a", "\\x1a" ); return text; } private static Dictionary<string, DataColumnField> GetDataFields(Type type) { Dictionary<string, DataColumnField> result; if(!_typeCache.TryGetValue(type, out result)) { lock(_typeCache) { result = new Dictionary<string, DataColumnField>(StringComparer.OrdinalIgnoreCase); // enumerate all properties of this type foreach(PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { foreach(DataColumnAttribute attribute in property.GetCustomAttributes(typeof(DataColumnAttribute), true)) { result.Add(attribute.Name ?? property.Name, new DataColumnField(property)); } } // enumerate all fields of this type foreach(FieldInfo field in type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { foreach(DataColumnAttribute attribute in field.GetCustomAttributes(typeof(DataColumnAttribute), true)) { result.Add(attribute.Name ?? field.Name, new DataColumnField(field)); } } if(result.Count == 0) { throw new MissingFieldException("Type does not have any properties decorated with DataColumn attribute"); } _typeCache[type] = result; } } return result; } private static T FillObject<T>(T item, Dictionary<string, DataColumnField> fields, IDataReader reader) { for(int i = 0; i < reader.FieldCount; i++) { DataColumnField field; if(fields.TryGetValue(reader.GetName(i), out field)) { field.SetValue(item, reader.GetValue(i)); } } return item; } //--- Fields --- private readonly DataFactory _factory; private readonly IDbCommand _command; private readonly string _connection; private readonly Stopwatch _stopWatch = new Stopwatch(); private readonly DataCatalog _catalog; //--- Constructors --- internal DataCommand(DataFactory factory, DataCatalog catalog, string connection, IDbCommand command) { if(factory == null) { throw new ArgumentNullException("factory"); } if(catalog == null) { throw new ArgumentNullException("catalog"); } if(connection == null) { throw new ArgumentNullException("connection"); } if(command == null) { throw new ArgumentNullException("command"); } _factory = factory; _connection = connection; _command = command; _catalog = catalog; } //--- Properties --- /// <summary> /// <see langword="True"/> if this command is a stored procedure. /// </summary> public bool IsStoredProcedure { get { return _command.CommandType == CommandType.StoredProcedure; } } /// <summary> /// Execution time of the last query /// </summary> public TimeSpan ExecutionTime { get { return _stopWatch.Elapsed; } } //--- Methods --- /// <summary> /// Adds an input parameter to the command. /// </summary> /// <param name="key">Name of the parameter</param> /// <param name="value">Value of the parameter</param> /// <returns>Returns this command</returns> public DataCommand With(string key, object value) { _command.Parameters.Add(_factory.CreateParameter(key, value, ParameterDirection.Input)); return this; } IDataCommand IDataCommand.With(string key, object value) { return With(key, value); } /// <summary> /// Adds an input-output parameter to the command. /// </summary> /// <param name="key">Name of the parameter</param> /// <param name="value">Value of the parameter</param> /// <returns>Returns this command</returns> public DataCommand WithInOut(string key, object value) { _command.Parameters.Add(_factory.CreateParameter(key, value, ParameterDirection.InputOutput)); return this; } IDataCommand IDataCommand.WithInOut(string key, object value) { return WithInOut(key, value); } /// <summary> /// Adds an output parameter to the command. /// </summary> /// <param name="key">Name of the parameter</param> /// <returns>Returns this command</returns> public DataCommand WithOutput(string key) { _command.Parameters.Add(_factory.CreateParameter(key, null, ParameterDirection.Output)); return this; } IDataCommand IDataCommand.WithOutput(string key) { return WithOutput(key); } /// <summary> /// Adds an return parameter to the command. /// </summary> /// <param name="key">Name of the parameter</param> /// <returns>Returns this command</returns> public DataCommand WithReturn(string key) { _command.Parameters.Add(_factory.CreateParameter(key, null, ParameterDirection.ReturnValue)); return this; } IDataCommand IDataCommand.WithReturn(string key) { return WithReturn(key); } /// <summary> /// Retrieve an output/return value from the finished command. /// </summary> /// <typeparam name="T">Returned value type</typeparam> /// <param name="key">Name of returned parameter (provided previously using 'WithOutput()' or 'WithInOut()' or 'WithReturn()'</param> /// <returns>Converted value</returns> public T At<T>(string key) { return At(key, default(T)); } /// <summary> /// Retrieve an output/return value from the finished command. /// </summary> /// <typeparam name="T">Returned value type</typeparam> /// <param name="key">Name of returned parameter (provided previously using 'WithOutput()' or 'WithInOut()' or 'WithReturn()'</param> /// <param name="def">Value to return if returned value is null or DbNull</param> /// <returns>Converted value</returns> public T At<T>(string key, T def) { object value = ((IDataParameter)_command.Parameters[_factory.ParameterChar + key]).Value; if(value == null) { return def; } if(value is DBNull) { return def; } if(value is T) { return (T)value; } return (T)SysUtil.ChangeType(value, typeof(T)); } /// <summary> /// Execute command. /// </summary> public void Execute() { _log.TraceMethodCall("Execute()", _command.CommandText); QueryStart(); using(IDbConnection connection = _factory.OpenConnection(_connection)) { using(IDbCommand command = CreateExecutableCommand(connection)) { try { command.ExecuteNonQuery(); } catch(Exception e) { _log.DebugFormat(e,"Execute(): Text: '{0}', Type: {1}", _command.CommandText, _command.CommandType); throw; } finally { QueryFinished(command); } } } } /// <summary> /// Execute command and call handler with an open IDataReader on the result set. /// IDataReader and connection will be automatically closed upon completion of the handler. /// </summary> /// <param name="handler">Handler to invoke</param> public void Execute(Action<IDataReader> handler) { _log.TraceMethodCall("Execute(Action<IDataReader>)", _command.CommandText); if(handler == null) { throw new ArgumentNullException("handler"); } QueryStart(); using(IDbConnection connection = _factory.OpenConnection(_connection)) { using(IDbCommand command = CreateExecutableCommand(connection)) { try { using(IDataReader reader = command.ExecuteReader()) { handler(reader); } } catch(Exception e) { _log.DebugFormat(e, "Execute(handler): Text: '{0}', Type: {1}", _command.CommandText, _command.CommandType); throw; } finally { QueryFinished(command); } } } } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Read value</returns> public string Read() { _log.TraceMethodCall("Read()", _command.CommandText); QueryStart(); using(IDbConnection connection = _factory.OpenConnection(_connection)) { using(IDbCommand command = CreateExecutableCommand(connection)) { try { object value = command.ExecuteScalar(); if(value == null) { return null; } if(value is DBNull) { return null; } return (string) SysUtil.ChangeType(value, typeof(string)); } catch(Exception e) { _log.DebugFormat(e, "Read(): Text: '{0}', Type: {1}", _command.CommandText, _command.CommandType); throw; } finally { QueryFinished(command); } } } } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public bool? ReadAsBool() { return ReadAs<bool>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public byte? ReadAsByte() { return ReadAs<byte>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public short? ReadAsShort() { return ReadAs<short>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public ushort? ReadAsUShort() { return ReadAs<ushort>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public int? ReadAsInt() { return ReadAs<int>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public long? ReadAsLong() { return ReadAs<long>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public uint? ReadAsUInt() { return ReadAs<uint>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public ulong? ReadAsULong() { return ReadAs<ulong>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <returns>Converted value</returns> public DateTime? ReadAsDateTime() { return ReadAs<DateTime>(); } /// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <typeparam name="T">Returned value type</typeparam> /// <returns>Converted value</returns> private T? ReadAs<T>() where T : struct { _log.TraceMethodCall("ReadAs<T>()", typeof(T).FullName, _command.CommandText); QueryStart(); using(IDbConnection connection = _factory.OpenConnection(_connection)) { using(IDbCommand command = CreateExecutableCommand(connection)) { try { object value = command.ExecuteScalar(); if(value == null) { return null; } if(value is DBNull) { return null; } return (T) SysUtil.ChangeType(value, typeof(T)); } catch(Exception e) { _log.DebugFormat(e, "ReadAs(): Text: '{0}', Type: {1}", _command.CommandText, _command.CommandType); throw; } finally { QueryFinished(command); } } } } private IDbCommand CreateExecutableCommand(IDbConnection connection) { IDbCommand command = _factory.CreateQuery(_command.CommandText); try { command.CommandType = _command.CommandType; command.Connection = connection; foreach(IDataParameter parameter in _command.Parameters) { IDataParameter parameterCopy = command.CreateParameter(); parameterCopy.ParameterName = parameter.ParameterName; parameterCopy.Value = parameter.Value; parameterCopy.Direction = parameter.Direction; command.Parameters.Add(parameterCopy); } } catch { if(command != null) { // must dispose of command in case of failure command.Dispose(); } throw; } return command; } /// <summary> /// Execute command and read result into a DataSet. /// </summary> /// <returns>Read DataSet object</returns> public DataSet ReadAsDataSet() { _log.TraceMethodCall("ReadAsDataSet()", _command.CommandText); DataSet result = new DataSet(); using(IDbConnection connection = _factory.OpenConnection(_connection)) { using(IDbCommand command = CreateExecutableCommand(connection)) { try { _factory.CreateAdapter(command).Fill(result); } catch(Exception e) { _log.DebugFormat(e, "ReadAsDataSet(): Text: '{0}', Type: {1}", _command.CommandText, _command.CommandType); throw; } } } return result; } /// <summary> /// Execute command and read result into an XDoc. /// </summary> /// <param name="table">Name of the root element</param> /// <param name="row">Name of the element created for each row</param> /// <returns>Read DataSet object</returns> public XDoc ReadAsXDoc(string table, string row) { _log.TraceMethodCall("ReadAsXDoc()", _command.CommandText); XDoc result = new XDoc(table); Execute(delegate(IDataReader reader) { // capture row columns int count = reader.FieldCount; string[] columns = new string[count]; bool[] attr = new bool[count]; for(int i = 0; i < count; ++i) { columns[i] = reader.GetName(i); if(columns[i].StartsWith("@")) { attr[i] = true; columns[i] = columns[i].Substring(1); } } // read records while(reader.Read()) { result.Start(row); for(int i = 0; i < count; ++i) { if(!reader.IsDBNull(i)) { string column = columns[i]; if(attr[0]) { result.Attr(column, reader.GetValue(i).ToString()); } else { result.Elem(column, reader.GetValue(i).ToString()); } } } result.End(); } }); return result; } /// <summary> /// Execute command and convert the first row into an object. /// </summary> /// <typeparam name="T">Object type to create</typeparam> /// <returns>Created object</returns> public T ReadAsObject<T>() where T : new() { _log.TraceMethodCall("ReadAsObject()", _command.CommandText); Dictionary<string, DataColumnField> fields = GetDataFields(typeof(T)); // read item from database T result = default(T); Execute(delegate(IDataReader reader) { if(reader.Read()) { result = FillObject(new T(), fields, reader); } }); return result; } /// <summary> /// Execute command and convert all rows into a list of objects. /// </summary> /// <typeparam name="T">Object type to create</typeparam> /// <returns>List of created objects</returns> public List<T> ReadAsObjects<T>() where T : new() { if(_log.IsTraceEnabled()) { _log.TraceMethodCall("ReadAsObject<T>()", typeof(T).FullName, _command.CommandText); } Dictionary<string, DataColumnField> fields = GetDataFields(typeof(T)); // read item from database List<T> result = new List<T>(); Execute(delegate(IDataReader reader) { while(reader.Read()) { result.Add(FillObject(new T(), fields, reader)); } }); return result; } private void QueryStart() { _stopWatch.Reset(); _stopWatch.Start(); } private void QueryFinished(IDbCommand command) { _stopWatch.Stop(); if(_stopWatch.Elapsed > SLOW_SQL) { _log.WarnFormat("SLOW SQL ({0:0.000}s, database: {2}): {1}", _stopWatch.Elapsed.TotalSeconds, command.CommandText, command.Connection.Database); } _catalog.FireQueryFinished(this); } } }
// 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.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DynamicTests : ExpressionCompilerTestBase { [Fact] public void Local_Simple() { var source = @"class C { static void M() { dynamic d = 1; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void Local_Array() { var source = @"class C { static void M() { dynamic[] d = new dynamic[1]; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic[] V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void Local_Generic() { var source = @"class C { static void M() { System.Collections.Generic.List<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Collections.Generic.List<dynamic> V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void LocalConstant_Simple() { var source = @"class C { static void M() { const dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, exeBytes)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void LocalConstant_Array() { var source = @"class C { static void M() { const dynamic[] d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, exeBytes)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void LocalConstant_Generic() { var source = @"class C { static void M() { const Generic<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } } class Generic<T> { } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, exeBytes)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void Parameter_Simple() { var source = @"class C { static void M(dynamic d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void Parameter_Array() { var source = @"class C { static void M(dynamic[] d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void Parameter_Generic() { var source = @"class C { static void M(System.Collections.Generic.List<dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [WorkItem(1087216, "DevDiv")] [Fact] public void ComplexDynamicType() { var source = @"class C { static void M(Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } } public class Outer<T, U> { public class Inner<V, W> { } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); VerifyCustomTypeInfo(locals[0], 0x04, 0x03); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); string error; var result = context.CompileExpression("d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, 0x04, 0x03); // Note that the method produced by CompileAssignment returns void // so there is never custom type info. result = context.CompileAssignment("d", "d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, null); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); result = context.CompileExpression( "var dd = d;", DkmEvaluationFlags.None, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 57 (0x39) .maxstack 7 IL_0000: ldtoken ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""dd"" IL_000f: ldstr ""826d6ec1-dc4b-46af-be05-cd3f1a1fd4ac"" IL_0014: newobj ""System.Guid..ctor(string)"" IL_0019: ldc.i4.2 IL_001a: newarr ""byte"" IL_001f: dup IL_0020: ldc.i4.0 IL_0021: ldc.i4.4 IL_0022: stelem.i1 IL_0023: dup IL_0024: ldc.i4.1 IL_0025: ldc.i4.3 IL_0026: stelem.i1 IL_0027: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_002c: ldstr ""dd"" IL_0031: call ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>>(string)"" IL_0036: ldarg.0 IL_0037: stind.ref IL_0038: ret }"); } [Fact] public void DynamicAliases() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0); var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( Alias( DkmClrAliasKind.Variable, "d1", "d1", typeof(object).AssemblyQualifiedName, MakeCustomTypeInfo(true)), Alias( DkmClrAliasKind.Variable, "d2", "d2", typeof(Dictionary<Dictionary<dynamic, Dictionary<object[], dynamic[]>>, object>).AssemblyQualifiedName, MakeCustomTypeInfo(false, false, true, false, false, false, false, true, false))); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var diagnostics = DiagnosticBag.GetInstance(); var testData = new CompilationTestData(); context.CompileGetLocals( locals, argumentsOnly: false, aliases: aliases, diagnostics: diagnostics, typeName: out typeName, testData: testData); diagnostics.Free(); Assert.Equal(locals.Count, 2); VerifyCustomTypeInfo(locals[0], 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d1", expectedILOpt: @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""d1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: ret }"); VerifyCustomTypeInfo(locals[1], 0x84, 0x00); // Note: read flags right-to-left in each byte: 0010 0001 0(000 0000) VerifyLocal(testData, typeName, locals[1], "<>m1", "d2", expectedILOpt: @"{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""d2"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<dynamic, System.Collections.Generic.Dictionary<object[], dynamic[]>>, object>"" IL_000f: ret }"); locals.Free(); } private static CustomTypeInfo MakeCustomTypeInfo(params bool[] flags) { Assert.NotNull(flags); var dynamicFlagsInfo = DynamicFlagsCustomTypeInfo.Create(ImmutableArray.CreateRange(flags)); return new CustomTypeInfo(DynamicFlagsCustomTypeInfo.PayloadTypeId, dynamicFlagsInfo.GetCustomTypeInfoPayload()); } [Fact] public void DynamicAttribute_NotAvailable() { var source = @"class C { static void M() { dynamic d = 1; } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasNoDynamicAttribute(method); } private static void AssertHasDynamicAttribute(IMethodSymbol method) { Assert.Contains( "System.Runtime.CompilerServices.DynamicAttribute", method.GetSynthesizedAttributes(forReturnType: true).Select(a => a.AttributeClass.ToTestDisplayString())); } private static void AssertHasNoDynamicAttribute(IMethodSymbol method) { Assert.DoesNotContain( "System.Runtime.CompilerServices.DynamicAttribute", method.GetSynthesizedAttributes(forReturnType: true).Select(a => a.AttributeClass.ToTestDisplayString())); } [Fact] public void DynamicCall() { var source = @" class C { void M() { dynamic d = this; d.M(); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("d.M()", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(TypeKind.Dynamic, methodData.Method.ReturnType.TypeKind); methodData.VerifyIL(@" { // Code size 77 (0x4d) .maxstack 9 .locals init (dynamic V_0) //d IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""M"" IL_000d: ldnull IL_000e: ldtoken ""<>x"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldloc.0 IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: ret } "); } [WorkItem(1072296)] [Fact] public void InvokeStaticMemberInLambda() { var source = @" class C { static dynamic x; static void Foo(dynamic y) { System.Action a = () => Foo(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.Foo"); var testData = new CompilationTestData(); string error; var result = context.CompileAssignment("a", "() => Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Foo"" IL_0011: ldnull IL_0012: ldtoken ""<>x"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0055: ldtoken ""<>x"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.x"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0069: ret }"); context = CreateMethodContext(runtime, "C.<>c.<Foo>b__1_0"); testData = new CompilationTestData(); result = context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""<>x"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldsfld ""dynamic C.x"" IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0065: ret }"); } [WorkItem(1095613)] [Fact(Skip = "1095613")] public void HoistedLocalsLoseDynamicAttribute() { var source = @" class C { static void M(dynamic x) { dynamic y = 3; System.Func<dynamic> a = () => x + y; } static void Foo(int x) { M(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>c.<>m0()").VerifyIL(@" { // Code size 166 (0xa6) .maxstack 11 .locals init (System.Func<dynamic> V_0) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Func<dynamic>"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""<>c"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_003f: brtrue.s IL_007c IL_0041: ldc.i4.0 IL_0042: ldstr ""Foo"" IL_0047: ldnull IL_0048: ldtoken ""<>c"" IL_004d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0052: ldc.i4.2 IL_0053: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldc.i4.s 33 IL_005c: ldnull IL_005d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.1 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_008b: ldtoken ""<>c"" IL_0090: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0095: ldsfld ""dynamic C.x"" IL_009a: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_009f: callvirt ""System.Func<dynamic> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a4: stloc.0 IL_00a5: ret }"); result = context.CompileExpression("Foo(y)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>c.<>m0()").VerifyIL(@" { // Code size 166 (0xa6) .maxstack 11 .locals init (System.Func<dynamic> V_0) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Func<dynamic>"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""<>c"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_003f: brtrue.s IL_007c IL_0041: ldc.i4.0 IL_0042: ldstr ""Foo"" IL_0047: ldnull IL_0048: ldtoken ""<>c"" IL_004d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0052: ldc.i4.2 IL_0053: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldc.i4.s 33 IL_005c: ldnull IL_005d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.1 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_008b: ldtoken ""<>c"" IL_0090: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0095: ldsfld ""dynamic C.x"" IL_009a: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_009f: callvirt ""System.Func<dynamic> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a4: stloc.0 IL_00a5: ret }"); } private static void VerifyCustomTypeInfo(LocalAndMethod localAndMethod, params byte[] expectedBytes) { VerifyCustomTypeInfo(localAndMethod.GetCustomTypeInfo(), expectedBytes); } private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes) { VerifyCustomTypeInfo(compileResult.GetCustomTypeInfo(), expectedBytes); } private static void VerifyCustomTypeInfo(CustomTypeInfo customTypeInfo, byte[] expectedBytes) { Assert.Equal(DynamicFlagsCustomTypeInfo.PayloadTypeId, customTypeInfo.PayloadTypeId); Assert.Equal(expectedBytes, customTypeInfo.Payload); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Management.Network { /// <summary> /// The Windows Azure Network management API provides a RESTful set of web /// services that interact with Windows Azure Networks service to manage /// your network resrources. The API has entities that capture the /// relationship between an end user and the Windows Azure Networks /// service. /// </summary> public static partial class VirtualNetworkOperationsExtensions { /// <summary> /// The Put VirtualNetwork operation creates/updates a virtual network /// in the specified resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update Virtual Network /// operation /// </param> /// <returns> /// Response for PutVirtualNetworks API service calls. /// </returns> public static VirtualNetworkPutResponse BeginCreateOrUpdating(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters) { return Task.Factory.StartNew((object s) => { return ((IVirtualNetworkOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, virtualNetworkName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetwork operation creates/updates a virtual network /// in the specified resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update Virtual Network /// operation /// </param> /// <returns> /// Response for PutVirtualNetworks API service calls. /// </returns> public static Task<VirtualNetworkPutResponse> BeginCreateOrUpdatingAsync(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters) { return operations.BeginCreateOrUpdatingAsync(resourceGroupName, virtualNetworkName, parameters, CancellationToken.None); } /// <summary> /// The Delete VirtualNetwork operation deletes the specifed virtual /// network /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public static UpdateOperationResponse BeginDeleting(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((IVirtualNetworkOperations)s).BeginDeletingAsync(resourceGroupName, virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete VirtualNetwork operation deletes the specifed virtual /// network /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public static Task<UpdateOperationResponse> BeginDeletingAsync(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName) { return operations.BeginDeletingAsync(resourceGroupName, virtualNetworkName, CancellationToken.None); } /// <summary> /// The Put VirtualNetwork operation creates/updates a virtual /// networkin the specified resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update Virtual Network /// operation /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse CreateOrUpdate(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters) { return Task.Factory.StartNew((object s) => { return ((IVirtualNetworkOperations)s).CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put VirtualNetwork operation creates/updates a virtual /// networkin the specified resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update Virtual Network /// operation /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, parameters, CancellationToken.None); } /// <summary> /// The Delete VirtualNetwork operation deletes the specifed virtual /// network /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((IVirtualNetworkOperations)s).DeleteAsync(resourceGroupName, virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete VirtualNetwork operation deletes the specifed virtual /// network /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName) { return operations.DeleteAsync(resourceGroupName, virtualNetworkName, CancellationToken.None); } /// <summary> /// The Get VirtualNetwork operation retrieves information about the /// specified virtual network. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <returns> /// Response for GetVirtualNetworks API service calls. /// </returns> public static VirtualNetworkGetResponse Get(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((IVirtualNetworkOperations)s).GetAsync(resourceGroupName, virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get VirtualNetwork operation retrieves information about the /// specified virtual network. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// Required. The name of the virtual network. /// </param> /// <returns> /// Response for GetVirtualNetworks API service calls. /// </returns> public static Task<VirtualNetworkGetResponse> GetAsync(this IVirtualNetworkOperations operations, string resourceGroupName, string virtualNetworkName) { return operations.GetAsync(resourceGroupName, virtualNetworkName, CancellationToken.None); } /// <summary> /// The list VirtualNetwork returns all Virtual Networks in a resource /// group /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// Response for ListVirtualNetworks Api servive call /// </returns> public static VirtualNetworkListResponse List(this IVirtualNetworkOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IVirtualNetworkOperations)s).ListAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list VirtualNetwork returns all Virtual Networks in a resource /// group /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// Response for ListVirtualNetworks Api servive call /// </returns> public static Task<VirtualNetworkListResponse> ListAsync(this IVirtualNetworkOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// The list VirtualNetwork returns all Virtual Networks in a /// subscription /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <returns> /// Response for ListVirtualNetworks Api servive call /// </returns> public static VirtualNetworkListResponse ListAll(this IVirtualNetworkOperations operations) { return Task.Factory.StartNew((object s) => { return ((IVirtualNetworkOperations)s).ListAllAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list VirtualNetwork returns all Virtual Networks in a /// subscription /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IVirtualNetworkOperations. /// </param> /// <returns> /// Response for ListVirtualNetworks Api servive call /// </returns> public static Task<VirtualNetworkListResponse> ListAllAsync(this IVirtualNetworkOperations operations) { return operations.ListAllAsync(CancellationToken.None); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; #if FEATURE_SECURITY_PERMISSIONS using System.Security.AccessControl; #endif using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Xunit; namespace Microsoft.Build.UnitTests { public sealed class ReadLinesFromFile_Tests { /// <summary> /// Write one line, read one line. /// </summary> [Fact] public void Basic() { var file = FileUtilities.GetTemporaryFile(); try { // Start with a missing file. File.Delete(file); // Append one line to the file. var a = new WriteLinesToFile { File = new TaskItem(file), Lines = new ITaskItem[] { new TaskItem("Line1") } }; Assert.True(a.Execute()); // Read the line from the file. var r = new ReadLinesFromFile { File = new TaskItem(file) }; Assert.True(r.Execute()); Assert.Single(r.Lines); Assert.Equal("Line1", r.Lines[0].ItemSpec); // Write two more lines to the file. a.Lines = new ITaskItem[] { new TaskItem("Line2"), new TaskItem("Line3") }; Assert.True(a.Execute()); // Read all of the lines and verify them. Assert.True(r.Execute()); Assert.Equal(3, r.Lines.Length); Assert.Equal("Line1", r.Lines[0].ItemSpec); Assert.Equal("Line2", r.Lines[1].ItemSpec); Assert.Equal("Line3", r.Lines[2].ItemSpec); } finally { File.Delete(file); } } /// <summary> /// Write one line, read one line, where the line contains MSBuild-escapable characters. /// The file should contain the *unescaped* lines, but no escaping information should be /// lost when read. /// </summary> [Fact] public void Escaping() { var file = FileUtilities.GetTemporaryFile(); try { // Start with a missing file. File.Delete(file); // Append one line to the file. var a = new WriteLinesToFile { File = new TaskItem(file), Lines = new ITaskItem[] { new TaskItem("Line1_%253b_") } }; Assert.True(a.Execute()); // Read the line from the file. var r = new ReadLinesFromFile { File = new TaskItem(file) }; Assert.True(r.Execute()); Assert.Single(r.Lines); Assert.Equal("Line1_%3b_", r.Lines[0].ItemSpec); // Write two more lines to the file. a.Lines = new ITaskItem[] { new TaskItem("Line2"), new TaskItem("Line3") }; Assert.True(a.Execute()); // Read all of the lines and verify them. Assert.True(r.Execute()); Assert.Equal(3, r.Lines.Length); Assert.Equal("Line1_%3b_", r.Lines[0].ItemSpec); Assert.Equal("Line2", r.Lines[1].ItemSpec); Assert.Equal("Line3", r.Lines[2].ItemSpec); } finally { File.Delete(file); } } /// <summary> /// Write a line that contains an ANSI character that is not ASCII. /// </summary> [Fact] public void ANSINonASCII() { var file = FileUtilities.GetTemporaryFile(); try { // Start with a missing file. File.Delete(file); // Append one line to the file. var a = new WriteLinesToFile { File = new TaskItem(file), Lines = new ITaskItem[] { new TaskItem("My special character is \u00C3") } }; Assert.True(a.Execute()); // Read the line from the file. var r = new ReadLinesFromFile { File = new TaskItem(file) }; Assert.True(r.Execute()); Assert.Single(r.Lines); Assert.Equal("My special character is \u00C3", r.Lines[0].ItemSpec); } finally { File.Delete(file); } } /// <summary> /// Reading lines from an missing file should result in the empty list. /// </summary> [Fact] public void ReadMissing() { var file = FileUtilities.GetTemporaryFile(); File.Delete(file); // Read the line from the file. var r = new ReadLinesFromFile { File = new TaskItem(file) }; Assert.True(r.Execute()); Assert.Empty(r.Lines); } /// <summary> /// Reading blank lines from a file should be ignored. /// </summary> [Fact] public void IgnoreBlankLines() { var file = FileUtilities.GetTemporaryFile(); try { // Start with a missing file. File.Delete(file); // Append one line to the file. var a = new WriteLinesToFile { File = new TaskItem(file), Lines = new ITaskItem[] { new TaskItem("Line1"), new TaskItem(" "), new TaskItem("Line2"), new TaskItem(""), new TaskItem("Line3"), new TaskItem("\0\0\0\0\0\0\0\0\0") } }; Assert.True(a.Execute()); // Read the line from the file. var r = new ReadLinesFromFile { File = new TaskItem(file) }; Assert.True(r.Execute()); Assert.Equal(3, r.Lines.Length); Assert.Equal("Line1", r.Lines[0].ItemSpec); Assert.Equal("Line2", r.Lines[1].ItemSpec); Assert.Equal("Line3", r.Lines[2].ItemSpec); } finally { File.Delete(file); } } #if FEATURE_SECURITY_PERMISSIONS /// <summary> /// Reading lines from a file that you have no access to. /// </summary> [Fact] public void ReadNoAccess() { if (NativeMethodsShared.IsUnixLike) { return; // "The security API is not the same under Unix" } var file = FileUtilities.GetTemporaryFile(); try { // Start with a missing file. File.Delete(file); // Append one line to the file. var a = new WriteLinesToFile { File = new TaskItem(file), Lines = new ITaskItem[] { new TaskItem("This is a new line") } }; Assert.True(a.Execute()); // Remove all File access to the file to current user var fSecurity = File.GetAccessControl(file); var userAccount = string.Format(@"{0}\{1}", System.Environment.UserDomainName, System.Environment.UserName); fSecurity.AddAccessRule(new FileSystemAccessRule(userAccount, FileSystemRights.ReadData, AccessControlType.Deny)); File.SetAccessControl(file, fSecurity); // Attempt to Read lines from the file. var r = new ReadLinesFromFile(); var mEngine = new MockEngine(); r.BuildEngine = mEngine; r.File = new TaskItem(file); Assert.False(r.Execute()); } finally { var fSecurity = File.GetAccessControl(file); var userAccount = string.Format(@"{0}\{1}", System.Environment.UserDomainName, System.Environment.UserName); fSecurity.AddAccessRule(new FileSystemAccessRule(userAccount, FileSystemRights.ReadData, AccessControlType.Allow)); File.SetAccessControl(file, fSecurity); // Delete file File.Delete(file); } } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition.ReflectionModel { internal class ReflectionComposablePart : ComposablePart, ICompositionElement { private readonly ReflectionComposablePartDefinition _definition; private volatile Dictionary<ImportDefinition, object> _importValues = null; private volatile Dictionary<ImportDefinition, ImportingItem> _importsCache = null; private volatile Dictionary<int, ExportingMember> _exportsCache = null; private volatile bool _invokeImportsSatisfied = true; private bool _initialCompositionComplete = false; private volatile object _cachedInstance; private object _lock = new object(); public ReflectionComposablePart(ReflectionComposablePartDefinition definition) { Requires.NotNull(definition, nameof(definition)); _definition = definition; } public ReflectionComposablePart(ReflectionComposablePartDefinition definition, object attributedPart) { Requires.NotNull(definition, nameof(definition)); Requires.NotNull(attributedPart, nameof(attributedPart)); _definition = definition; if (attributedPart is ValueType) { throw new ArgumentException(SR.ArgumentValueType, nameof(attributedPart)); } _cachedInstance = attributedPart; } protected virtual void EnsureRunning() { } protected void RequiresRunning() { EnsureRunning(); } protected virtual void ReleaseInstanceIfNecessary(object instance) { } private Dictionary<ImportDefinition, object> ImportValues { get { var value = _importValues; if(value == null) { lock(_lock) { value = _importValues; if(value == null) { value = new Dictionary<ImportDefinition, object>(); _importValues = value; } } } return value; } } private Dictionary<ImportDefinition, ImportingItem> ImportsCache { get { var value = _importsCache; if(value == null) { lock(_lock) { if(value == null) { value = new Dictionary<ImportDefinition, ImportingItem>(); _importsCache = value; } } } return value; } } protected object CachedInstance { get { lock (_lock) { return _cachedInstance; } } } public ReflectionComposablePartDefinition Definition { get { RequiresRunning(); return _definition; } } public override IDictionary<string, object> Metadata { get { RequiresRunning(); return Definition.Metadata; } } public sealed override IEnumerable<ImportDefinition> ImportDefinitions { get { RequiresRunning(); return Definition.ImportDefinitions; } } public sealed override IEnumerable<ExportDefinition> ExportDefinitions { get { RequiresRunning(); return Definition.ExportDefinitions; } } string ICompositionElement.DisplayName { get { return GetDisplayName(); } } ICompositionElement ICompositionElement.Origin { get { return Definition; } } // This is the ONLY method which is not executed under the ImportEngine composition lock. // We need to protect all state that is accesses public override object GetExportedValue(ExportDefinition definition) { RequiresRunning(); // given the implementation of the ImportEngine, this iwll be called under a lock if the part is still being composed // This is only called outside of the lock when the part is fully composed // based on that we only protect: // _exportsCache - and thus all calls to GetExportingMemberFromDefinition // access to _importValues // access to _initialCompositionComplete // access to _instance Requires.NotNull(definition, nameof(definition)); ExportingMember member = null; lock (_lock) { member = GetExportingMemberFromDefinition(definition); if (member == null) { throw ExceptionBuilder.CreateExportDefinitionNotOnThisComposablePart(nameof(definition)); } EnsureGettable(); } return GetExportedValue(member); } public override void SetImport(ImportDefinition definition, IEnumerable<Export> exports) { RequiresRunning(); Requires.NotNull(definition, nameof(definition)); Requires.NotNull(exports, nameof(exports));; ImportingItem item = GetImportingItemFromDefinition(definition); if (item == null) { throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart(nameof(definition)); } EnsureSettable(definition); // Avoid walking over exports many times Export[] exportsAsArray = exports.AsArray(); EnsureCardinality(definition, exportsAsArray); SetImport(item, exportsAsArray); } public override void Activate() { RequiresRunning(); SetNonPrerequisiteImports(); // Whenever we are composed/recomposed notify the instance NotifyImportSatisfied(); lock (_lock) { _initialCompositionComplete = true; _importValues = null; _importsCache = null; } } public override string ToString() { return GetDisplayName(); } private object GetExportedValue(ExportingMember member) { object instance = null; if (member.RequiresInstance) { // Only activate the instance if we actually need to instance = GetInstanceActivatingIfNeeded(); } return member.GetExportedValue(instance, _lock); } private void SetImport(ImportingItem item, Export[] exports) { object value = item.CastExportsToImportType(exports); lock (_lock) { _invokeImportsSatisfied = true; ImportValues[item.Definition] = value; } } private object GetInstanceActivatingIfNeeded() { var cachedInstance = _cachedInstance; if (cachedInstance != null) { return cachedInstance; } else { ConstructorInfo constructor = null; object[] arguments = null; // determine whether activation is required, and collect necessary information for activation // we need to do that under a lock lock (_lock) { if (!RequiresActivation()) { return null; } constructor = Definition.GetConstructor(); if (constructor == null) { throw new ComposablePartException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_PartConstructorMissing, Definition.GetPartType().FullName), Definition.ToElement()); } arguments = GetConstructorArguments(); } // create instance outside of the lock object createdInstance = CreateInstance(constructor, arguments); SetPrerequisiteImports(); // set the created instance if (_cachedInstance == null) { lock (_lock) { if (_cachedInstance == null) { _cachedInstance = createdInstance; createdInstance = null; } } } // if the instance has been already set if (createdInstance == null) { ReleaseInstanceIfNecessary(createdInstance); } } return _cachedInstance; } private object[] GetConstructorArguments() { ReflectionParameterImportDefinition[] parameterImports = ImportDefinitions.OfType<ReflectionParameterImportDefinition>().ToArray(); object[] arguments = new object[parameterImports.Length]; UseImportedValues( parameterImports, (import, definition, value) => { if (definition.Cardinality == ImportCardinality.ZeroOrMore && !import.ImportType.IsAssignableCollectionType) { throw new ComposablePartException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned, Definition.GetPartType().FullName, definition.ImportingLazyParameter.Value.Name), Definition.ToElement()); } arguments[definition.ImportingLazyParameter.Value.Position] = value; }, true); return arguments; } // alwayc called under a lock private bool RequiresActivation() { // If we have any imports then we need activation // (static imports are not supported) if (ImportDefinitions.Any()) { return true; } // If we have any instance exports, then we also // need activation. return ExportDefinitions.Any(definition => { ExportingMember member = GetExportingMemberFromDefinition(definition); return member.RequiresInstance; }); } // this is called under a lock private void EnsureGettable() { // If we're already composed then we know that // all pre-req imports have been satisfied if (_initialCompositionComplete) { return; } // Make sure all pre-req imports have been set foreach (ImportDefinition definition in ImportDefinitions.Where(definition => definition.IsPrerequisite)) { if (_importValues == null || !ImportValues.ContainsKey(definition)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.InvalidOperation_GetExportedValueBeforePrereqImportSet, definition.ToElement().DisplayName)); } } } private void EnsureSettable(ImportDefinition definition) { lock (_lock) { if (_initialCompositionComplete && !definition.IsRecomposable) { throw new InvalidOperationException(SR.InvalidOperation_DefinitionCannotBeRecomposed); } } } private static void EnsureCardinality(ImportDefinition definition, Export[] exports) { Requires.NullOrNotNullElements(exports, nameof(exports)); ExportCardinalityCheckResult result = ExportServices.CheckCardinality(definition, exports); switch (result) { case ExportCardinalityCheckResult.NoExports: throw new ArgumentException(SR.Argument_ExportsEmpty, nameof(exports)); case ExportCardinalityCheckResult.TooManyExports: throw new ArgumentException(SR.Argument_ExportsTooMany, nameof(exports)); default: if(result != ExportCardinalityCheckResult.Match) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } break; } } private object CreateInstance(ConstructorInfo constructor, object[] arguments) { Exception exception = null; object instance = null; try { instance = constructor.SafeInvoke(arguments); } catch (TypeInitializationException ex) { exception = ex; } catch (TargetInvocationException ex) { exception = ex.InnerException; } if (exception != null) { throw new ComposablePartException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_PartConstructorThrewException, Definition.GetPartType().FullName), Definition.ToElement(), exception); } return instance; } private void SetNonPrerequisiteImports() { IEnumerable<ImportDefinition> members = ImportDefinitions.Where(import => !import.IsPrerequisite); // NOTE: Dev10 484204 The validation is turned off for post imports because of it broke declarative composition UseImportedValues(members, SetExportedValueForImport, false); } private void SetPrerequisiteImports() { IEnumerable<ImportDefinition> members = ImportDefinitions.Where(import => import.IsPrerequisite); // NOTE: Dev10 484204 The validation is turned off for post imports because of it broke declarative composition UseImportedValues(members, SetExportedValueForImport, false); } private void SetExportedValueForImport(ImportingItem import, ImportDefinition definition, object value) { ImportingMember importMember = (ImportingMember)import; object instance = GetInstanceActivatingIfNeeded(); importMember.SetExportedValue(instance, value); } private void UseImportedValues<TImportDefinition>(IEnumerable<TImportDefinition> definitions, Action<ImportingItem, TImportDefinition, object> useImportValue, bool errorIfMissing) where TImportDefinition : ImportDefinition { var result = CompositionResult.SucceededResult; foreach (var definition in definitions) { ImportingItem import = GetImportingItemFromDefinition(definition); object value; if (!TryGetImportValue(definition, out value)) { if (!errorIfMissing) { continue; } if (definition.Cardinality == ImportCardinality.ExactlyOne) { var error = CompositionError.Create( CompositionErrorId.ImportNotSetOnPart, SR.ImportNotSetOnPart, Definition.GetPartType().FullName, definition.ToString()); result = result.MergeError(error); continue; } else { value = import.CastExportsToImportType(Array.Empty<Export>()); } } useImportValue(import, definition, value); } result.ThrowOnErrors(); } private bool TryGetImportValue(ImportDefinition definition, out object value) { lock (_lock) { if (_importValues != null && ImportValues.TryGetValue(definition, out value)) { ImportValues.Remove(definition); return true; } } value = null; return false; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void NotifyImportSatisfied() { if (_invokeImportsSatisfied) { IPartImportsSatisfiedNotification notify = GetInstanceActivatingIfNeeded() as IPartImportsSatisfiedNotification; lock (_lock) { if (!_invokeImportsSatisfied) { //Already notified on another thread return; } _invokeImportsSatisfied = false; } if (notify != null) { try { notify.OnImportsSatisfied(); } catch (Exception exception) { throw new ComposablePartException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_PartOnImportsSatisfiedThrewException, Definition.GetPartType().FullName), Definition.ToElement(), exception); } } } } // this is always called under a lock private ExportingMember GetExportingMemberFromDefinition(ExportDefinition definition) { ExportingMember result; ReflectionMemberExportDefinition reflectionExport = definition as ReflectionMemberExportDefinition; if (reflectionExport == null) { return null; } int exportIndex = reflectionExport.GetIndex(); if(_exportsCache == null) { _exportsCache = new Dictionary<int, ExportingMember>(); } if (!_exportsCache.TryGetValue(exportIndex, out result)) { result = GetExportingMember(definition); if (result != null) { _exportsCache[exportIndex] = result; } } return result; } private ImportingItem GetImportingItemFromDefinition(ImportDefinition definition) { ImportingItem result; if (!ImportsCache.TryGetValue(definition, out result)) { result = GetImportingItem(definition); if (result != null) { ImportsCache[definition] = result; } } return result; } private static ImportingItem GetImportingItem(ImportDefinition definition) { ReflectionImportDefinition reflectionDefinition = definition as ReflectionImportDefinition; if (reflectionDefinition != null) { return reflectionDefinition.ToImportingItem(); } // Don't recognize it return null; } private static ExportingMember GetExportingMember(ExportDefinition definition) { ReflectionMemberExportDefinition exportDefinition = definition as ReflectionMemberExportDefinition; if (exportDefinition != null) { return exportDefinition.ToExportingMember(); } // Don't recognize it return null; } private string GetDisplayName() { return _definition.GetPartType().GetDisplayName(); } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Xamarin.Forms.Core.UnitTests { [TestFixture] public class ContentViewUnitTests : BaseTestFixture { [SetUp] public override void Setup() { base.Setup (); Device.PlatformServices = new MockPlatformServices (); } [TearDown] public override void TearDown() { base.TearDown (); Device.PlatformServices = null; } [Test] public void TestConstructor () { var contentView = new ContentView (); Assert.Null (contentView.Content); Assert.AreEqual (Color.Default, contentView.BackgroundColor); Assert.AreEqual (new Thickness (0), contentView.Padding); } [Test] public void TestSetChild () { var contentView = new ContentView (); var child1 = new Label (); bool added = false; contentView.ChildAdded += (sender, e) => added = true; contentView.Content = child1; Assert.True (added); Assert.AreEqual (child1, contentView.Content); added = false; contentView.Content = child1; Assert.False (added); } [Test] public void TestReplaceChild () { var contentView = new ContentView (); var child1 = new Label (); var child2 = new Label (); contentView.Content = child1; bool removed = false; bool added = false; contentView.ChildRemoved += (sender, e) => removed = true; contentView.ChildAdded += (sender, e) => added = true; contentView.Content = child2; Assert.True (removed); Assert.True (added); Assert.AreEqual (child2, contentView.Content); } [Test] public void TestFrameLayout () { View child; var contentView = new ContentView { Padding = new Thickness (10), Content = child = new View { WidthRequest = 100, HeightRequest = 200, IsPlatformEnabled = true }, IsPlatformEnabled = true, Platform = new UnitPlatform () }; Assert.AreEqual (new Size (120, 220), contentView.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity).Request); contentView.Layout (new Rectangle (0, 0, 300, 300)); Assert.AreEqual (new Rectangle (10, 10, 280, 280), child.Bounds); } [Test] public void WidthRequest () { View child; var contentView = new ContentView { Padding = new Thickness (10), Content = child = new View { WidthRequest = 100, HeightRequest = 200, IsPlatformEnabled = true }, IsPlatformEnabled = true, Platform = new UnitPlatform (), WidthRequest = 20 }; Assert.AreEqual (new Size (40, 220), contentView.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity).Request); } [Test] public void HeightRequest () { View child; var contentView = new ContentView { Padding = new Thickness (10), Content = child = new View { WidthRequest = 100, HeightRequest = 200, IsPlatformEnabled = true, Platform = new UnitPlatform () }, IsPlatformEnabled = true, Platform = new UnitPlatform (), HeightRequest = 20 }; Assert.AreEqual (new Size (120, 40), contentView.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity).Request); } [Test] public void LayoutVerticallyCenter() { View child; var contentView = new ContentView { Content = child = new View { WidthRequest = 100, HeightRequest = 100, IsPlatformEnabled = true, VerticalOptions = LayoutOptions.Center }, IsPlatformEnabled = true, Platform = new UnitPlatform () }; contentView.Layout (new Rectangle(0,0, 200, 200)); Assert.AreEqual (new Rectangle (0, 50, 200, 100), child.Bounds); } [Test] public void LayoutVerticallyBegin() { View child; var contentView = new ContentView { Content = child = new View { WidthRequest = 100, HeightRequest = 100, IsPlatformEnabled = true, VerticalOptions = LayoutOptions.Start }, IsPlatformEnabled = true, Platform = new UnitPlatform () }; contentView.Layout (new Rectangle(0,0, 200, 200)); Assert.AreEqual (new Rectangle (0, 0, 200, 100), child.Bounds); } [Test] public void LayoutVerticallyEnd() { View child; var contentView = new ContentView { Content = child = new View { WidthRequest = 100, HeightRequest = 100, IsPlatformEnabled = true, VerticalOptions = LayoutOptions.End }, IsPlatformEnabled = true, Platform = new UnitPlatform () }; contentView.Layout (new Rectangle(0,0, 200, 200)); Assert.AreEqual (new Rectangle (0, 100, 200, 100), child.Bounds); } [Test] public void LayoutHorizontallyCenter() { View child; var contentView = new ContentView { Content = child = new View { WidthRequest = 100, HeightRequest = 100, IsPlatformEnabled = true, HorizontalOptions = LayoutOptions.Center }, IsPlatformEnabled = true, Platform = new UnitPlatform () }; contentView.Layout (new Rectangle(0,0, 200, 200)); Assert.AreEqual (new Rectangle (50, 0, 100, 200), child.Bounds); } [Test] public void LayoutHorizontallyBegin() { View child; var contentView = new ContentView { Content = child = new View { WidthRequest = 100, HeightRequest = 100, IsPlatformEnabled = true, HorizontalOptions = LayoutOptions.Start }, IsPlatformEnabled = true, Platform = new UnitPlatform () }; contentView.Layout (new Rectangle(0,0, 200, 200)); Assert.AreEqual (new Rectangle (0, 0, 100, 200), child.Bounds); } [Test] public void LayoutHorizontallyEnd() { View child; var contentView = new ContentView { Content = child = new View { WidthRequest = 100, HeightRequest = 100, IsPlatformEnabled = true, HorizontalOptions = LayoutOptions.End }, IsPlatformEnabled = true, Platform = new UnitPlatform () }; contentView.Layout (new Rectangle(0,0, 200, 200)); Assert.AreEqual (new Rectangle (100, 0, 100, 200), child.Bounds); } [Test] public void NullTemplateDirectlyHosts () { // order of setting properties carefully picked to emulate running on real backend var platform = new UnitPlatform (); var contentView = new ContentView (); var child = new View (); contentView.Content = child; contentView.Platform = platform; Assert.AreEqual (child, contentView.LogicalChildren[0]); } class SimpleTemplate : StackLayout { public SimpleTemplate () { Children.Add (new Label ()); Children.Add (new ContentPresenter ()); } } [Test] public void TemplateInflates () { var platform = new UnitPlatform (); var contentView = new ContentView (); contentView.ControlTemplate = new ControlTemplate (typeof (SimpleTemplate)); contentView.Platform = platform; Assert.That (contentView.LogicalChildren[0], Is.TypeOf<SimpleTemplate> ()); } [Test] public void PacksContent () { var platform = new UnitPlatform (); var contentView = new ContentView (); var child = new View (); contentView.ControlTemplate = new ControlTemplate (typeof (SimpleTemplate)); contentView.Content = child; contentView.Platform = platform; Assume.That (contentView.LogicalChildren[0], Is.TypeOf<SimpleTemplate> ()); Assert.That (contentView.Descendants (), Contains.Item (child)); } [Test] public void DoesNotInheritBindingContextToTemplate () { var platform = new UnitPlatform (); var contentView = new ContentView (); var child = new View (); contentView.ControlTemplate = new ControlTemplate (typeof (SimpleTemplate)); contentView.Content = child; contentView.Platform = platform; var bc = "Test"; contentView.BindingContext = bc; Assert.AreNotEqual (bc, contentView.LogicalChildren[0].BindingContext); Assert.IsNull (contentView.LogicalChildren[0].BindingContext); } [Test] public void ContentDoesGetBindingContext () { var platform = new UnitPlatform (); var contentView = new ContentView (); var child = new View (); contentView.ControlTemplate = new ControlTemplate (typeof (SimpleTemplate)); contentView.Content = child; contentView.Platform = platform; var bc = "Test"; contentView.BindingContext = bc; Assert.AreEqual (bc, child.BindingContext); } [Test] public void ContentParentIsNotInsideTempalte () { var platform = new UnitPlatform (); var contentView = new ContentView (); var child = new View (); contentView.ControlTemplate = new ControlTemplate (typeof (SimpleTemplate)); contentView.Content = child; contentView.Platform = platform; Assert.AreEqual (contentView, child.Parent); } [Test] public void NonTemplatedContentInheritsBindingContext () { var platform = new UnitPlatform (); var contentView = new ContentView (); var child = new View (); contentView.Content = child; contentView.Platform = platform; contentView.BindingContext = "Foo"; Assert.AreEqual ("Foo", child.BindingContext); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System.Collections.Generic; namespace OpenSim.Region.CoreModules.World.Land { public class LandChannel : ILandChannel { #region Constants //Land types set with flags in ParcelOverlay. //Only one of these can be used. public const float BAN_LINE_SAFETY_HIEGHT = 100; public const byte LAND_FLAG_PROPERTY_BORDER_SOUTH = 128; //Equals 10000000 public const byte LAND_FLAG_PROPERTY_BORDER_WEST = 64; //Equals 01000000 //RequestResults (I think these are right, they seem to work): public const int LAND_RESULT_MULTIPLE = 1; // The request they made contained more than a single peice of land public const int LAND_RESULT_SINGLE = 0; // The request they made contained only a single piece of land //ParcelSelectObjects public const int LAND_SELECT_OBJECTS_GROUP = 4; public const int LAND_SELECT_OBJECTS_OTHER = 8; public const int LAND_SELECT_OBJECTS_OWNER = 2; public const byte LAND_TYPE_IS_BEING_AUCTIONED = 5; //Equals 00000101 public const byte LAND_TYPE_IS_FOR_SALE = 4; //Equals 00000100 public const byte LAND_TYPE_OWNED_BY_GROUP = 2; //Equals 00000010 public const byte LAND_TYPE_OWNED_BY_OTHER = 1; //Equals 00000001 public const byte LAND_TYPE_OWNED_BY_REQUESTER = 3; //Equals 00000011 public const byte LAND_TYPE_PUBLIC = 0; //Equals 00000000 //These are other constants. Yay! public const int START_LAND_LOCAL_ID = 1; #endregion private readonly Scene m_scene; private readonly LandManagementModule m_landManagementModule; public LandChannel(Scene scene, LandManagementModule landManagementMod) { m_scene = scene; m_landManagementModule = landManagementMod; } #region ILandChannel Members public ILandObject GetLandObject(float x_float, float y_float) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x_float, y_float); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.LandData.Name = "NO LAND"; return obj; } public ILandObject GetLandObject(int localID) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(localID); } return null; } public ILandObject GetLandObject(Vector3 position) { return GetLandObject(position.X, position.Y); } public ILandObject GetLandObject(int x, int y) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x, y); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.LandData.Name = "NO LAND"; return obj; } public List<ILandObject> AllParcels() { if (m_landManagementModule != null) { return m_landManagementModule.AllParcels(); } return new List<ILandObject>(); } public void Clear(bool setupDefaultParcel) { if (m_landManagementModule != null) m_landManagementModule.Clear(setupDefaultParcel); } public List<ILandObject> ParcelsNearPoint(Vector3 position) { if (m_landManagementModule != null) { return m_landManagementModule.ParcelsNearPoint(position); } return new List<ILandObject>(); } public bool IsForcefulBansAllowed() { if (m_landManagementModule != null) { return m_landManagementModule.AllowedForcefulBans; } return false; } public void UpdateLandObject(int localID, LandData data) { if (m_landManagementModule != null) { m_landManagementModule.UpdateLandObject(localID, data); } } public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { if (m_landManagementModule != null) { m_landManagementModule.Join(start_x, start_y, end_x, end_y, attempting_user_id); } } public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { if (m_landManagementModule != null) { m_landManagementModule.Subdivide(start_x, start_y, end_x, end_y, attempting_user_id); } } public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) { if (m_landManagementModule != null) { m_landManagementModule.ReturnObjectsInParcel(localID, returnType, agentIDs, taskIDs, remoteClient); } } public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setParcelObjectMaxOverride(overrideDel); } } public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setSimulatorObjectMaxOverride(overrideDel); } } public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) { if (m_landManagementModule != null) { m_landManagementModule.setParcelOtherCleanTime(remoteClient, localID, otherCleanTime); } } #endregion } }
// EasyTouch library is copyright (c) of Hedgehog Team // Please send feedback or bug reports to the.hedgehog.team@gmail.com using UnityEngine; using System.Collections; /// <summary> /// Release notes: /// /// V1.0 November 2012 /// ============================= /// - First release [ExecuteInEditMode] /// <summary> /// Easy joystick allow to quickly create a virtual joystick /// </summary> public class EasyJoystick : MonoBehaviour { #region Delegate /// <summary> /// Joystick move handler. /// </summary> public delegate void JoystickMoveHandler(MovingJoystick move); /// <summary> /// Joystick move end handler. /// </summary> public delegate void JoystickMoveEndHandler(MovingJoystick move); #endregion #region Event /// <summary> /// Occurs when on_ joystick move. /// </summary> public static event JoystickMoveHandler On_JoystickMove; /// <summary> /// Occurs when on_ joystick move. /// </summary> public static event JoystickMoveEndHandler On_JoystickMoveEnd; #endregion #region Enumeration /// <summary> /// Properties influenced by the joystick /// </summary> public enum PropertiesInfluenced {Rotate, RotateLocal,Translate, TranslateLocal, Scale} /// <summary> /// Axis influenced by the joystick /// </summary> public enum AxisInfluenced{X,Y,Z,XYZ} /// <summary> /// Dynamic area zone. /// </summary> public enum DynamicArea {FullScreen, Left,Right,Top, Bottom, TopLeft, TopRight, BottomLeft, BottomRight}; /// <summary> /// Interaction type. /// </summary> public enum InteractionType {Direct, Include, EventNotification, DirectAndEvent} /// <summary> /// Broadcast mode for javascript /// </summary> public enum Broadcast {SendMessage,SendMessageUpwards,BroadcastMessage } /// <summary> /// Message name. /// </summary> private enum MessageName{ On_JoystickMove, On_JoystickMoveEnd}; #endregion #region Public Joystick return values read only property private Vector2 joystickAxis; /// <summary> /// Gets the joystick axis value between -1 & 1... /// </summary> /// <value> /// The joystick axis. /// </value> public Vector2 JoystickAxis { get { return this.joystickAxis; } } private Vector2 joystickValue; /// <summary> /// Gets the joystick value = joystic axis value * jostick speed * Time.deltaTime... /// </summary> /// <value> /// The joystick value. /// </value> public Vector2 JoystickValue { get { return this.joystickValue; } } #endregion #region public members /// <summary> /// Enable or disable the joystick. /// </summary> public bool enable = true; /// <summary> /// Use fixed update. /// </summary> public bool useFixedUpdate = false; /// <summary> /// The zone radius size. /// </summary> public float zoneRadius=100f; [SerializeField] private float touchSize = 30; /// <summary> /// Gets or sets the size of the touch. /// /// </summary> /// <value> /// The size of the touch. /// </value> public float TouchSize { get { return this.touchSize; } set { touchSize = value; if (touchSize>zoneRadius/2 && restrictArea){ touchSize =zoneRadius/2; } } } /// <summary> /// The dead zone size. While the touch is in this area, the joystick is considered stalled /// </summary> public float deadZone=20; [SerializeField] private bool dynamicJoystick=false; /// <summary> /// Gets or sets a value indicating whether this is a dynamic joystick. /// When this option is enabled, the joystick will display the location of the touch /// </summary> /// <value> /// <c>true</c> if dynamic joystick; otherwise, <c>false</c>. /// </value> public bool DynamicJoystick { get { return this.dynamicJoystick; } set { joystickIndex=-1; dynamicJoystick = value; if (dynamicJoystick){ virtualJoystick=false; } else{ virtualJoystick=true; joystickCenter = joystickPosition; } } } /// <summary> /// When the joystick is dynamic mode, this value indicates the area authorized for display /// </summary> public DynamicArea area = DynamicArea.FullScreen; /// <summary> /// The joystick position on the screen /// </summary> public Vector2 joystickPosition = new Vector2( 135f,135f); [SerializeField] private bool restrictArea=false; /// <summary> /// Gets or sets a value indicating whether the touch must be in the radius area. /// </summary> /// <value> /// <c>true</c> if restrict area; otherwise, <c>false</c>. /// </value> public bool RestrictArea { get { return this.restrictArea; } set { restrictArea = value; if (restrictArea){ touchSizeCoef = touchSize; } else{ touchSizeCoef=0; } } } // Messaging /// <summary> /// The receiver gameobject when you re in broacast mode for events /// </summary> public GameObject ReceiverObjectGame; /// <summary> /// The message sending mode fro broacast /// </summary> public Broadcast messageMode; /// <summary> /// The enable smoothing.When smoothing is enabled, resets the joystick slowly in the start position /// </summary> public bool enableSmoothing = false; [SerializeField] private Vector2 smoothing = new Vector2(2f,2f); /// <summary> /// Gets or sets the smoothing values /// </summary> /// <value> /// The smoothing. /// </value> public Vector2 Smoothing { get { return this.smoothing; } set { smoothing = value; if (smoothing.x<0.1f){ smoothing.x=0.1f; } if (smoothing.y<0.1){ smoothing.y=0.1f; } } } /// <summary> /// The enable inertia. Inertia simulates sliding movements (like a hovercraft, for example) /// </summary> public bool enableInertia = false; [SerializeField] public Vector2 inertia = new Vector2(100,100); /// <summary> /// Gets or sets the inertia values /// </summary> /// <value> /// The inertia. /// </value> public Vector2 Inertia { get { return this.inertia; } set { inertia = value; if (inertia.x<=0){ inertia.x=1; } if (inertia.y<=0){ inertia.y=1; } } } // Helper public bool showZone = true; public bool showTouch = true; public bool showDeadZone = true; public Texture areaTexture; public Texture touchTexture; public Texture deadTexture; #endregion #region Direct mode properties /// <summary> /// The use broadcast for javascript /// </summary> public bool useBroadcast = false; /// <summary> /// The speed of each joystick axis /// </summary> public Vector2 speed; /// <summary> /// The interaction. /// </summary> public InteractionType interaction = InteractionType.Direct; // X axis [SerializeField] private Transform xAxisTransform; /// <summary> /// Gets or sets the transform influenced by x axis of the joystick. /// </summary> /// <value> /// The X axis transform. /// </value> public Transform XAxisTransform { get { return this.xAxisTransform; } set { xAxisTransform = value; if (xAxisTransform!=null){ xAxisCharacterController = xAxisTransform.GetComponent<CharacterController>(); } else{ xAxisCharacterController=null; xAxisGravity=0; } } } /// <summary> /// The character controller attached to the X axis transform (if exist) /// </summary> public CharacterController xAxisCharacterController; /// <summary> /// The gravity. /// </summary> public float xAxisGravity=0; /// <summary> /// The Property influenced by the x axis joystick /// </summary> public PropertiesInfluenced xTI; /// <summary> /// The axis influenced by the x axis joystick /// </summary> public AxisInfluenced xAI; /// <summary> /// Inverse X axis. /// </summary> public bool inverseXAxis=false; // Y axis [SerializeField] private Transform yAxisTransform; /// <summary> /// Gets or sets the transform influenced by y axis of the joystick. /// </summary> /// <value> /// The Y axis transform. /// </value> public Transform YAxisTransform { get { return this.yAxisTransform; } set { yAxisTransform = value; if (yAxisTransform!=null){ yAxisCharacterController = yAxisTransform.GetComponent<CharacterController>(); } else{ yAxisCharacterController=null; yAxisGravity=0; } } } /// <summary> /// The character controller attached to the X axis transform (if exist) /// </summary> public CharacterController yAxisCharacterController; /// <summary> /// The y axis gravity. /// </summary> public float yAxisGravity=0; /// <summary> /// The Property influenced by the y axis joystick /// </summary> public PropertiesInfluenced yTI; /// <summary> /// The axis influenced by the y axis joystick /// </summary> public AxisInfluenced yAI; /// <summary> /// Inverse Y axis. /// </summary> public bool inverseYAxis=false; #endregion #region private members // Joystick properties private Vector2 joystickCenter; private Vector2 joyTouch; private bool virtualJoystick = true; private int joystickIndex=-1; private float touchSizeCoef=0; private bool sendEnd=false; #endregion #region Inspector public bool showProperties=true; public bool showInteraction=true; public bool showAppearance=true; #endregion #region Monobehaviour methods void OnEnable(){ EasyTouch.On_TouchStart += On_TouchStart; EasyTouch.On_TouchUp += On_TouchUp; EasyTouch.On_TouchDown += On_TouchDown; } void OnDisable(){ EasyTouch.On_TouchStart -= On_TouchStart; EasyTouch.On_TouchUp -= On_TouchUp; EasyTouch.On_TouchDown -= On_TouchDown; } void OnDestroy(){ EasyTouch.On_TouchStart -= On_TouchStart; EasyTouch.On_TouchUp -= On_TouchUp; EasyTouch.On_TouchDown -= On_TouchDown; } void Start(){ if (!dynamicJoystick){ joystickCenter = joystickPosition; virtualJoystick = true; } else{ virtualJoystick = false; } } void Update(){ if (!useFixedUpdate && enable){ UpdateJoystick(); } } void FixedUpdate(){ if (useFixedUpdate && enable){ UpdateJoystick(); } } void UpdateJoystick(){ if (Application.isPlaying){ // Reset to initial position if (joystickIndex==-1){ if (!enableSmoothing){ joyTouch = Vector2.zero; } else{ if (joyTouch.sqrMagnitude>0.1){ joyTouch = new Vector2( joyTouch.x - joyTouch.x*smoothing.x*Time.deltaTime, joyTouch.y - joyTouch.y*smoothing.y*Time.deltaTime); } else{ joyTouch = Vector2.zero; } } } // Joystick Axis if (joyTouch.sqrMagnitude>deadZone*deadZone){ joystickAxis = Vector2.zero; if (Mathf.Abs(joyTouch.x)> deadZone){ joystickAxis = new Vector2( (joyTouch.x -(deadZone*Mathf.Sign(joyTouch.x)))/(zoneRadius-touchSizeCoef-deadZone),joystickAxis.y); } else{ joystickAxis = new Vector2( joyTouch.x /(zoneRadius-touchSizeCoef),joystickAxis.y); } if (Mathf.Abs(joyTouch.y)> deadZone){ joystickAxis = new Vector2( joystickAxis.x,(joyTouch.y-(deadZone*Mathf.Sign(joyTouch.y)))/(zoneRadius-touchSizeCoef-deadZone)); } else{ joystickAxis = new Vector2( joystickAxis.x,joyTouch.y/(zoneRadius-touchSizeCoef)); } } else{ joystickAxis = new Vector2(0,0); } // Inverse axis ? if (inverseXAxis){ joystickAxis.x *= -1; } if (inverseYAxis){ joystickAxis.y *= -1; } // Joystick Value Vector2 realvalue = new Vector2( speed.x*joystickAxis.x,speed.y*joystickAxis.y); if (enableInertia){ Vector2 tmp = (realvalue - joystickValue); tmp.x /= inertia.x; tmp.y /= inertia.y; joystickValue += tmp; } else{ joystickValue = realvalue; } // interaction manager if (joystickAxis != Vector2.zero){ sendEnd = false; switch(interaction){ case InteractionType.Direct: UpdateDirect(); break; case InteractionType.EventNotification: CreateEvent(MessageName.On_JoystickMove); break; case InteractionType.DirectAndEvent: UpdateDirect(); CreateEvent(MessageName.On_JoystickMove); break; } } else{ if (!sendEnd){ CreateEvent(MessageName.On_JoystickMoveEnd); sendEnd = true; } } } } void OnGUI(){ // area zone if ((showZone && areaTexture!=null && !dynamicJoystick && enable) || (showZone && dynamicJoystick && virtualJoystick && areaTexture!=null && enable) ){ GUI.DrawTexture( new Rect(joystickCenter.x -zoneRadius ,Screen.height- joystickCenter.y-zoneRadius,zoneRadius*2,zoneRadius*2), areaTexture,ScaleMode.ScaleToFit,true); } // area touch if ((showTouch && touchTexture!=null && !dynamicJoystick && enable)|| (showTouch && dynamicJoystick && virtualJoystick && touchTexture!=null &enable) ){ GUI.DrawTexture( new Rect(joystickCenter.x+(joyTouch.x -touchSize) ,Screen.height-joystickCenter.y-(joyTouch.y+touchSize),touchSize*2,touchSize*2), touchTexture,ScaleMode.ScaleToFit,true); } // dead zone if ((showDeadZone && deadTexture!=null && !dynamicJoystick && enable)|| (showDeadZone && dynamicJoystick && virtualJoystick && deadTexture!=null && enable) ){ GUI.DrawTexture( new Rect(joystickCenter.x -deadZone,Screen.height-joystickCenter.y-deadZone,deadZone*2,deadZone*2), deadTexture,ScaleMode.ScaleToFit,true); } } void OnDrawGizmos(){ } #endregion #region Private methods void CreateEvent(MessageName message){ MovingJoystick move = new MovingJoystick(); move.joystickName = gameObject.name; move.joystickAxis = joystickAxis; move.joystickValue = joystickValue; // if (!useBroadcast){ switch (message){ case MessageName.On_JoystickMove: if (On_JoystickMove!=null){ On_JoystickMove( move); } break; case MessageName.On_JoystickMoveEnd: if (On_JoystickMoveEnd!=null){ On_JoystickMoveEnd( move); } break; } } else{ switch(messageMode){ case Broadcast.BroadcastMessage: ReceiverObjectGame.BroadcastMessage( message.ToString(),move,SendMessageOptions.DontRequireReceiver); break; case Broadcast.SendMessage: ReceiverObjectGame.SendMessage( message.ToString(),move,SendMessageOptions.DontRequireReceiver); break; case Broadcast.SendMessageUpwards: ReceiverObjectGame.SendMessageUpwards( message.ToString(),move,SendMessageOptions.DontRequireReceiver); break; } } } void UpdateDirect(){ // Gravity if (xAxisCharacterController!=null && xAxisGravity>0){ xAxisCharacterController.Move( Vector3.down*xAxisGravity*Time.deltaTime); } if (yAxisCharacterController!=null && yAxisGravity>0){ yAxisCharacterController.Move( Vector3.down*yAxisGravity*Time.deltaTime); } // X joystick axis if (xAxisTransform !=null){ // Axis influenced Vector3 axis =GetInfluencedAxis( xAI); // Action DoActionDirect( xAxisTransform, xTI, axis, joystickValue.x, xAxisCharacterController); } // y joystick axis if (YAxisTransform !=null){ // Axis Vector3 axis = GetInfluencedAxis(yAI); // Action DoActionDirect( yAxisTransform, yTI, axis,joystickValue.y, yAxisCharacterController); } } Vector3 GetInfluencedAxis(AxisInfluenced axisInfluenced){ Vector3 axis = Vector3.zero; switch(axisInfluenced){ case AxisInfluenced.X: axis = Vector3.right; break; case AxisInfluenced.Y: axis = Vector3.up; break; case AxisInfluenced.Z: axis = Vector3.forward; break; case AxisInfluenced.XYZ: axis = Vector3.one; break; } return axis; } void DoActionDirect(Transform axisTransform, PropertiesInfluenced inlfuencedProperty,Vector3 axis, float sensibility, CharacterController charact){ switch(inlfuencedProperty){ case PropertiesInfluenced.Rotate: axisTransform.Rotate( axis * sensibility * Time.deltaTime,Space.World); break; case PropertiesInfluenced.RotateLocal: axisTransform.Rotate( axis * sensibility * Time.deltaTime,Space.Self); break; case PropertiesInfluenced.Translate: if (charact==null){ axisTransform.Translate(axis * sensibility * Time.deltaTime,Space.World); } else{ charact.Move( axis * sensibility * Time.deltaTime ); } break; case PropertiesInfluenced.TranslateLocal: if (charact==null){ axisTransform.Translate(axis * sensibility * Time.deltaTime,Space.Self); } else{ charact.Move( charact.transform.TransformDirection(axis) * sensibility * Time.deltaTime ); } break; case PropertiesInfluenced.Scale: axisTransform.localScale += axis * sensibility * Time.deltaTime; break; } } #endregion #region EasyTouch events void On_TouchStart(Gesture gesture){ if (!dynamicJoystick){ if ((gesture.position - joystickCenter).sqrMagnitude < (zoneRadius+touchSizeCoef/2)*(zoneRadius+touchSizeCoef/2)){ joystickIndex = gesture.fingerIndex; } } else{ if (!virtualJoystick){ #region area restriction switch (area){ // full case DynamicArea.FullScreen: virtualJoystick = true; ; break; // bottom case DynamicArea.Bottom: if (gesture.position.y< Screen.height/2){ virtualJoystick = true; } break; // top case DynamicArea.Top: if (gesture.position.y> Screen.height/2){ virtualJoystick = true; } break; // Right case DynamicArea.Right: if (gesture.position.x> Screen.width/2){ virtualJoystick = true; } break; // Left case DynamicArea.Left: if (gesture.position.x< Screen.width/2){ virtualJoystick = true; } break; // top Right case DynamicArea.TopRight: if (gesture.position.y> Screen.height/2 && gesture.position.x> Screen.width/2){ virtualJoystick = true; } break; // top Left case DynamicArea.TopLeft: if (gesture.position.y> Screen.height/2 && gesture.position.x< Screen.width/2){ virtualJoystick = true; } break; // bottom Right case DynamicArea.BottomRight: if (gesture.position.y< Screen.height/2 && gesture.position.x> Screen.width/2){ virtualJoystick = true; } break; // bottom left case DynamicArea.BottomLeft: if (gesture.position.y< Screen.height/2 && gesture.position.x< Screen.width/2){ virtualJoystick = true; } break; } #endregion if (virtualJoystick){ joystickCenter = gesture.position; joystickIndex = gesture.fingerIndex; } } } } // Joystick move void On_TouchDown(Gesture gesture){ if (gesture.fingerIndex == joystickIndex){ joyTouch = new Vector2( gesture.position.x, gesture.position.y) - joystickCenter; if ((joyTouch/(zoneRadius-touchSizeCoef)).sqrMagnitude > 1){ joyTouch.Normalize(); joyTouch *= zoneRadius-touchSizeCoef; } } } // Touch end void On_TouchUp( Gesture gesture){ if (gesture.fingerIndex == joystickIndex){ joystickIndex=-1; if (dynamicJoystick){ virtualJoystick=false; } } } #endregion }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2013 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; #if !NETFX_35 && !UNITY && !WINDOWS_PHONE using System.Collections.Concurrent; #endif // !NETFX_35 && !UNITY && !WINDOWS_PHONE using System.Collections.Generic; #if !UNITY using System.Diagnostics.Contracts; #endif // !UNITY using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading; namespace MsgPack.Serialization { /// <summary> /// Holds debugging support information. /// </summary> internal static class SerializerDebugging { #if !XAMIOS && !XAMDROID && !UNITY [ThreadStatic] private static bool _traceEnabled; /// <summary> /// Gets or sets a value indicating whether instruction/expression tracing is enabled or not. /// </summary> /// <value> /// <c>true</c> if instruction/expression tracing is enabled; otherwise, <c>false</c>. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static bool TraceEnabled { get { return _traceEnabled; } set { _traceEnabled = value; } } [ThreadStatic] private static bool _dumpEnabled; /// <summary> /// Gets or sets a value indicating whether IL dump is enabled or not. /// </summary> /// <value> /// <c>true</c> if IL dump is enabled; otherwise, <c>false</c>. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static bool DumpEnabled { get { return _dumpEnabled; } set { _dumpEnabled = value; } } #endif // !XAMIOS && !XAMDROID && !UNITY [ThreadStatic] private static bool _avoidsGenericSerializer; /// <summary> /// Gets or sets a value indicating whether generic serializer for array, <see cref="List{T}"/>, <see cref="Dictionary{TKey,TValue}"/>, /// or <see cref="Nullable{T}"/> is not used. /// </summary> /// <value> /// <c>true</c> if generic serializer is not used; otherwise, <c>false</c>. /// </value> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static bool AvoidsGenericSerializer { get { return _avoidsGenericSerializer; } set { _avoidsGenericSerializer = value; } } #if !XAMIOS && !XAMDROID && !UNITY #if !NETFX_CORE [ThreadStatic] private static StringWriter _ilTraceWriter; #endif // !NETFX_CORE /// <summary> /// Gets the <see cref="TextWriter"/> for IL tracing. /// </summary> /// <value> /// The <see cref="TextWriter"/> for IL tracing. /// This value will not be <c>null</c>. /// </value> public static TextWriter ILTraceWriter { get { #if !NETFX_CORE if ( !_traceEnabled ) { return TextWriter.Null; } if ( _ilTraceWriter == null ) { _ilTraceWriter = new StringWriter( CultureInfo.InvariantCulture ); } return _ilTraceWriter; #else return TextWriter.Null; #endif // !NETFX_CORE } } /// <summary> /// Traces the specific event. /// </summary> /// <param name="format">The format string.</param> /// <param name="args">The args for formatting.</param> #if NETFX_CORE || WINDOWS_PHONE [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "format", Justification = "Used in other platforms" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args", Justification = "Used in other platforms" )] #endif // NETFX_CORE || WINDOWS_PHONE public static void TraceEvent( string format, params object[] args ) { #if !NETFX_CORE && !WINDOWS_PHONE if ( !_traceEnabled ) { return; } Tracer.Emit.TraceEvent( Tracer.EventType.DefineType, Tracer.EventId.DefineType, format, args ); #endif // !NETFX_CORE && !WINDOWS_PHONE } /// <summary> /// Flushes the trace data. /// </summary> public static void FlushTraceData() { #if !NETFX_CORE && !WINDOWS_PHONE if ( !_traceEnabled ) { return; } Tracer.Emit.TraceData( Tracer.EventType.DefineType, Tracer.EventId.DefineType, _ilTraceWriter.ToString() ); #endif // !NETFX_CORE && !WINDOWS_PHONE } #if !NETFX_CORE && !SILVERLIGHT && !NETFX_35 [ThreadStatic] private static AssemblyBuilder _assemblyBuilder; [ThreadStatic] private static ModuleBuilder _moduleBuilder; /// <summary> /// Prepares instruction dump with specified <see cref="AssemblyBuilder"/>. /// </summary> /// <param name="assemblyBuilder">The assembly builder to hold instructions.</param> public static void PrepareDump( AssemblyBuilder assemblyBuilder ) { if ( _dumpEnabled ) { #if DEBUG Contract.Assert( assemblyBuilder != null ); #endif // DEBUG _assemblyBuilder = assemblyBuilder; } } /// <summary> /// Prepares the dump with dedicated internal <see cref="AssemblyBuilder"/>. /// </summary> public static void PrepareDump() { _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName( "ExpressionTreeSerializerLogics" ), AssemblyBuilderAccess.Save, default( IEnumerable<CustomAttributeBuilder> ) ); _moduleBuilder = _assemblyBuilder.DefineDynamicModule( "ExpressionTreeSerializerLogics", "ExpressionTreeSerializerLogics.dll", true ); } #endif // !NETFX_CORE && !SILVERLIGHT && !NETFX_35 // TODO: Cleanup %Temp% to delete temp assemblies generated for on the fly code DOM. #if !NETFX_CORE && !SILVERLIGHT [ThreadStatic] private static IList<string> _runtimeAssemblies; [ThreadStatic] private static IList<string> _compiledCodeDomSerializerAssemblies; public static IEnumerable<string> CodeDomSerializerDependentAssemblies { get { EnsureDependentAssembliesListsInitialized(); #if DEBUG Contract.Assert( _compiledCodeDomSerializerAssemblies != null ); #endif // DEBUG // FCL dependencies and msgpack core libs foreach ( var runtimeAssembly in _runtimeAssemblies ) { yield return runtimeAssembly; } // dependents foreach ( var compiledAssembly in _compiledCodeDomSerializerAssemblies ) { yield return compiledAssembly; } } } #endif // !NETFX_CORE && !SILVERLIGHT #if NETFX_CORE || SILVERLIGHT [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "pathToAssembly", Justification = "For API compatibility" )] #endif // NETFX_CORE || SILVERLIGHT [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static void AddRuntimeAssembly( string pathToAssembly ) { #if !NETFX_CORE && !SILVERLIGHT EnsureDependentAssembliesListsInitialized(); _runtimeAssemblies.Add( pathToAssembly ); #endif // !NETFX_CORE && !SILVERLIGHT } #if NETFX_CORE || SILVERLIGHT [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "pathToAssembly", Justification = "For API compatibility" )] #endif // NETFX_CORE || SILVERLIGHT [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static void AddCompiledCodeDomAssembly( string pathToAssembly ) { #if !NETFX_CORE && !SILVERLIGHT EnsureDependentAssembliesListsInitialized(); _compiledCodeDomSerializerAssemblies.Add( pathToAssembly ); #endif // !NETFX_CORE && !SILVERLIGHT } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static void ResetDependentAssemblies() { #if !NETFX_CORE && !SILVERLIGHT EnsureDependentAssembliesListsInitialized(); #if !NETFX_35 File.AppendAllLines( GetHistoryFilePath(), _compiledCodeDomSerializerAssemblies ); #else File.AppendAllText( GetHistoryFilePath(), String.Join( Environment.NewLine, _compiledCodeDomSerializerAssemblies.ToArray() ) + Environment.NewLine ); #endif // !NETFX_35 _compiledCodeDomSerializerAssemblies.Clear(); ResetRuntimeAssemblies(); #endif // !NETFX_CORE && !SILVERLIGHT } #if !NETFX_CORE && !SILVERLIGHT private static int _wasDeleted; private const string HistoryFile = "MsgPack.Serialization.SerializationGenerationDebugging.CodeDOM.History.txt"; [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" , Justification = "For unit testing")] public static void DeletePastTemporaries() { if ( Interlocked.CompareExchange( ref _wasDeleted, 1, 0 ) != 0 ) { return; } try { var historyFilePath = GetHistoryFilePath(); if ( !File.Exists( historyFilePath ) ) { return; } foreach ( var pastAssembly in File.ReadAllLines( historyFilePath ) ) { if ( !String.IsNullOrEmpty( pastAssembly ) ) { File.Delete( pastAssembly ); } } new FileStream( historyFilePath, FileMode.Truncate ).Close(); } catch ( IOException ) { } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" , Justification = "For unit testing")] private static string GetHistoryFilePath() { return Path.Combine( Path.GetTempPath(), HistoryFile ); } private static void EnsureDependentAssembliesListsInitialized() { if ( _runtimeAssemblies == null ) { _runtimeAssemblies = new List<string>(); ResetRuntimeAssemblies(); } if ( _compiledCodeDomSerializerAssemblies == null ) { _compiledCodeDomSerializerAssemblies = new List<string>(); } } private static void ResetRuntimeAssemblies() { _runtimeAssemblies.Add( "System.dll" ); #if NETFX_35 _runtimeAssemblies.Add( typeof( Enumerable ).Assembly.Location ); #else _runtimeAssemblies.Add( "System.Core.dll" ); _runtimeAssemblies.Add( "System.Numerics.dll" ); #endif // NETFX_35 _runtimeAssemblies.Add( typeof( SerializerDebugging ).Assembly.Location ); } #endif // !NETFX_CORE && !SILVERLIGHT [ThreadStatic] private static bool _onTheFlyCodeDomEnabled; [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static bool OnTheFlyCodeDomEnabled { get { return _onTheFlyCodeDomEnabled; } set { _onTheFlyCodeDomEnabled = value; } } #if !NETFX_CORE && !SILVERLIGHT && !NETFX_35 /// <summary> /// Creates the new type builder for the serializer. /// </summary> /// <param name="targetType">The serialization target type.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">PrepareDump() was not called.</exception> public static TypeBuilder NewTypeBuilder( Type targetType ) { if ( _moduleBuilder == null ) { throw new InvalidOperationException( "PrepareDump() was not called." ); } return _moduleBuilder.DefineType( IdentifierUtility.EscapeTypeName( targetType ) + "SerializerLogics" ); } #endif // !NETFX_CORE && !SILVERLIGHT && !NETFX_35 #if !NETFX_CORE && !SILVERLIGHT /// <summary> /// Takes dump of instructions. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" , Justification = "For unit testing")] public static void Dump() { #if !NETFX_35 if ( _assemblyBuilder != null ) { _assemblyBuilder.Save( _assemblyBuilder.GetName().Name + ".dll" ); } #endif // !NETFX_35 } #endif // !NETFX_CORE && !SILVERLIGHT /// <summary> /// Resets debugging states. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )] public static void Reset() { #if !NETFX_CORE && !SILVERLIGHT && !NETFX_35 _assemblyBuilder = null; _moduleBuilder = null; if ( _ilTraceWriter != null ) { _ilTraceWriter.Dispose(); _ilTraceWriter = null; } #endif // !NETFX_CORE && !SILVERLIGHT && !NETFX_35 _dumpEnabled = false; _traceEnabled = false; ResetDependentAssemblies(); } #endif // !XAMIOS && !XAMDROID && !UNITY } }
using System; using System.Collections.Generic; using WSDL.Models; using WSDL.Models.Schema; namespace WSDL.TypeManagement { public class StaticPrimitiveTypeProvider : IPrimitiveTypeProvider { private const string XmlSchemaNamespace = "http://www.w3.org/2001/XMLSchema"; private const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; #region Simple Types private static readonly SimpleType CharType = new SimpleType("char", new Restriction { Base = new QName("int", XmlSchemaNamespace) }); private static readonly SimpleType DurationType = new SimpleType("duration", new Restriction { Base = new QName("duration", XmlSchemaNamespace), Pattern = @"\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?", MinimumInclusive = "-P10675199DT2H48M5.4775808S", MaximumInclusive = "P10675199DT2H48M5.4775807S" }); private static readonly SimpleType GuidType = new SimpleType("guid", new Restriction { Base = new QName("string", XmlSchemaNamespace), Pattern = @"[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}" }); #endregion #region Elements private static readonly Element AnyType = new Element { Name = "anyType", Nillable = true, Type = new QName("anyType", XmlSchemaNamespace) }; private static readonly Element AnyUri = new Element { Name = "anyURI", Nillable = true, Type = new QName("anyURI", XmlSchemaNamespace) }; private static readonly Element Base64Binary = new Element { Name = "base64Binary", Nillable = true, Type = new QName("base64Binary", XmlSchemaNamespace) }; private static readonly Element Boolean = new Element { Name = "boolean", Nillable = true, Type = new QName("boolean", XmlSchemaNamespace) }; private static readonly Element Byte = new Element { Name = "byte", Nillable = true, Type = new QName("byte", XmlSchemaNamespace) }; private static readonly Element DateTime = new Element { Name = "dateTime", Nillable = true, Type = new QName("dateTime", XmlSchemaNamespace) }; private static readonly Element Decimal = new Element { Name = "decimal", Nillable = true, Type = new QName("decimal", XmlSchemaNamespace) }; private static readonly Element Double = new Element { Name = "double", Nillable = true, Type = new QName("double", XmlSchemaNamespace) }; private static readonly Element Float = new Element { Name = "float", Nillable = true, Type = new QName("float", XmlSchemaNamespace) }; private static readonly Element Int = new Element { Name = "int", Nillable = true, Type = new QName("int", XmlSchemaNamespace) }; private static readonly Element Long = new Element { Name = "long", Nillable = true, Type = new QName("long", XmlSchemaNamespace) }; private static readonly Element QName = new Element { Name = "QName", Nillable = true, Type = new QName("QName", XmlSchemaNamespace) }; private static readonly Element Short = new Element { Name = "short", Nillable = true, Type = new QName("short", XmlSchemaNamespace) }; private static readonly Element String = new Element { Name = "string", Nillable = true, Type = new QName("string", XmlSchemaNamespace) }; private static readonly Element UnsignedByte = new Element { Name = "unsignedByte", Nillable = true, Type = new QName("unsignedByte", XmlSchemaNamespace) }; private static readonly Element UnsignedInt = new Element { Name = "unsignedInt", Nillable = true, Type = new QName("unsignedInt", XmlSchemaNamespace) }; private static readonly Element UnsignedLong = new Element { Name = "unsignedLong", Nillable = true, Type = new QName("unsignedLong", XmlSchemaNamespace) }; private static readonly Element UnsignedShort = new Element { Name = "unsignedShort", Nillable = true, Type = new QName("unsignedShort", XmlSchemaNamespace) }; private static readonly Element Char = new Element { Name = "char", Nillable = true, Type = new QName("char", SerializationNamespace) }; private static readonly Element Duration = new Element { Name = "duration", Nillable = true, Type = new QName("duration", SerializationNamespace) }; private static readonly Element Guid = new Element { Name = "guid", Nillable = true, Type = new QName("guid", SerializationNamespace) }; #endregion private static readonly Schema PrimitiveTypesSchema = new Schema { TargetNamespace = SerializationNamespace, QualifiedNamespaces = new List<QNamespace> { new QNamespace("tns", SerializationNamespace) }, Types = new List<SchemaType> { CharType, DurationType, GuidType }, Elements = new List<Element> { AnyType, AnyUri, Base64Binary, Boolean, Byte, DateTime, Decimal, Double, Float, Int, Long, QName, Short, String, UnsignedByte, UnsignedInt, UnsignedLong, UnsignedShort, Char, Duration, Guid } }; private static readonly IDictionary<Type, QName> TypeMappings = new Dictionary<Type, QName> { {typeof(Int16), Short.Type}, {typeof(Int32), Int.Type}, {typeof(String), String.Type}, {typeof(Char), Char.Type}, {typeof(Guid), Guid.Type}, {typeof(Boolean), Boolean.Type}, {typeof(Byte), Byte.Type}, {typeof(DateTime), DateTime.Type}, {typeof(Decimal), Decimal.Type}, {typeof(Double), Double.Type}, {typeof(float), Float.Type}, {typeof(long), Long.Type}, {typeof(UInt32), UnsignedInt.Type}, {typeof(UInt16), UnsignedShort.Type}, {typeof(UInt64), UnsignedLong.Type} }; public Schema GetPrimitiveTypesSchema() { return PrimitiveTypesSchema; } public QName GetQNameForType(Type type) { return TypeMappings.ContainsKey(type) ? TypeMappings[type] : null; } public bool IsPrimitive(Type type) { return TypeMappings.ContainsKey(type); } } }
using System; using Encoding = System.Text.Encoding; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Contains the information needed to generate tracelogging /// metadata for an event field. /// </summary> internal class FieldMetadata { /// <summary> /// Name of the field /// </summary> private readonly string name; /// <summary> /// The number of bytes in the UTF8 Encoding of 'name' INCLUDING a null terminator. /// </summary> private readonly int nameSize; private readonly EventFieldTags tags; private readonly byte[] custom; /// <summary> /// ETW supports fixed sized arrays. If inType has the InTypeFixedCountFlag then this is the /// statically known count for the array. It is also used to encode the number of bytes of /// custom meta-data if InTypeCustomCountFlag set. /// </summary> private readonly ushort fixedCount; private byte inType; private byte outType; /// <summary> /// Scalar or variable-length array. /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, bool variableCount) : this( name, type, tags, variableCount ? Statics.InTypeVariableCountFlag : (byte)0, 0, null) { return; } /// <summary> /// Fixed-length array. /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, ushort fixedCount) : this( name, type, tags, Statics.InTypeFixedCountFlag, fixedCount, null) { return; } /// <summary> /// Custom serializer /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, byte[] custom) : this( name, type, tags, Statics.InTypeCustomCountFlag, checked((ushort)(custom == null ? 0 : custom.Length)), custom) { return; } private FieldMetadata( string name, TraceLoggingDataType dataType, EventFieldTags tags, byte countFlags, ushort fixedCount = 0, byte[] custom = null) { if (name == null) { throw new ArgumentNullException( "name", "This usually means that the object passed to Write is of a type that" + " does not support being used as the top-level object in an event," + " e.g. a primitive or built-in type."); } Statics.CheckName(name); var coreType = (int)dataType & Statics.InTypeMask; this.name = name; this.nameSize = Encoding.UTF8.GetByteCount(this.name) + 1; this.inType = (byte)(coreType | countFlags); this.outType = (byte)(((int)dataType >> 8) & Statics.OutTypeMask); this.tags = tags; this.fixedCount = fixedCount; this.custom = custom; if (countFlags != 0) { if (coreType == (int)TraceLoggingDataType.Nil) { throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedArrayOfNil")); } if (coreType == (int)TraceLoggingDataType.Binary) { throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedArrayOfBinary")); } #if !BROKEN_UNTIL_M3 if (coreType == (int)TraceLoggingDataType.Utf16String || coreType == (int)TraceLoggingDataType.MbcsString) { throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedArrayOfNullTerminatedString")); } #endif } if (((int)this.tags & 0xfffffff) != 0) { this.outType |= Statics.OutTypeChainFlag; } if (this.outType != 0) { this.inType |= Statics.InTypeChainFlag; } } public void IncrementStructFieldCount() { this.inType |= Statics.InTypeChainFlag; this.outType++; if ((this.outType & Statics.OutTypeMask) == 0) { throw new NotSupportedException(Environment.GetResourceString("EventSource_TooManyFields")); } } /// <summary> /// This is the main routine for FieldMetaData. Basically it will serialize the data in /// this structure as TraceLogging style meta-data into the array 'metaArray' starting at /// 'pos' (pos is updated to reflect the bytes written). /// /// Note that 'metaData' can be null, in which case it only updates 'pos'. This is useful /// for a 'two pass' approach where you figure out how big to make the array, and then you /// fill it in. /// </summary> public void Encode(ref int pos, byte[] metadata) { // Write out the null terminated UTF8 encoded name if (metadata != null) { Encoding.UTF8.GetBytes(this.name, 0, this.name.Length, metadata, pos); } pos += this.nameSize; // Write 1 byte for inType if (metadata != null) { metadata[pos] = this.inType; } pos += 1; // If InTypeChainFlag set, then write out the outType if (0 != (this.inType & Statics.InTypeChainFlag)) { if (metadata != null) { metadata[pos] = this.outType; } pos += 1; // If OutTypeChainFlag set, then write out tags if (0 != (this.outType & Statics.OutTypeChainFlag)) { Statics.EncodeTags((int)this.tags, ref pos, metadata); } } // If InTypeFixedCountFlag set, write out the fixedCount (2 bytes little endian) if (0 != (this.inType & Statics.InTypeFixedCountFlag)) { if (metadata != null) { metadata[pos + 0] = unchecked((byte)this.fixedCount); metadata[pos + 1] = (byte)(this.fixedCount >> 8); } pos += 2; // If InTypeCustomCountFlag set, write out the blob of custom meta-data. if (Statics.InTypeCustomCountFlag == (this.inType & Statics.InTypeCountMask) && this.fixedCount != 0) { if (metadata != null) { Buffer.BlockCopy(this.custom, 0, metadata, pos, this.fixedCount); } pos += this.fixedCount; } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Multiplayer; using osu.Game.Overlays; using osu.Game.Overlays.Mods; using osu.Game.Overlays.Toolbar; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Screens.Menu; using osu.Game.Screens.OnlinePlay.Components; using osu.Game.Screens.OnlinePlay.Lounge; using osu.Game.Screens.Play; using osu.Game.Screens.Ranking; using osu.Game.Screens.Select; using osu.Game.Screens.Select.Options; using osu.Game.Tests.Beatmaps.IO; using osu.Game.Tests.Visual.Multiplayer; using osuTK; using osuTK.Input; namespace osu.Game.Tests.Visual.Navigation { public class TestSceneScreenNavigation : OsuGameTestScene { private const float click_padding = 25; private Vector2 backButtonPosition => Game.ToScreenSpace(new Vector2(click_padding, Game.LayoutRectangle.Bottom - click_padding)); private Vector2 optionsButtonPosition => Game.ToScreenSpace(new Vector2(click_padding, click_padding)); [Test] public void TestExitSongSelectWithEscape() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show()); AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible); pushEscape(); AddAssert("Overlay was hidden", () => songSelect.ModSelectOverlay.State.Value == Visibility.Hidden); exitViaEscapeAndConfirm(); } /// <summary> /// This tests that the F1 key will open the mod select overlay, and not be handled / blocked by the music controller (which has the same default binding /// but should be handled *after* song select). /// </summary> [Test] public void TestOpenModSelectOverlayUsingAction() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show mods overlay", () => InputManager.Key(Key.F1)); AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible); } [Test] public void TestRetryCountIncrements() { Player player = null; PushAndConfirm(() => new TestPlaySongSelect()); AddStep("import beatmap", () => ImportBeatmapTest.LoadQuickOszIntoOsu(Game).Wait()); AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault); AddStep("press enter", () => InputManager.Key(Key.Enter)); AddUntilStep("wait for player", () => { // dismiss any notifications that may appear (ie. muted notification). clickMouseInCentre(); return (player = Game.ScreenStack.CurrentScreen as Player) != null; }); AddAssert("retry count is 0", () => player.RestartCount == 0); AddStep("attempt to retry", () => player.ChildrenOfType<HotkeyRetryOverlay>().First().Action()); AddUntilStep("wait for old player gone", () => Game.ScreenStack.CurrentScreen != player); AddUntilStep("get new player", () => (player = Game.ScreenStack.CurrentScreen as Player) != null); AddAssert("retry count is 1", () => player.RestartCount == 1); } [Test] public void TestRetryFromResults() { Player player = null; ResultsScreen results = null; WorkingBeatmap beatmap() => Game.Beatmap.Value; PushAndConfirm(() => new TestPlaySongSelect()); AddStep("import beatmap", () => ImportBeatmapTest.LoadQuickOszIntoOsu(Game).Wait()); AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault); AddStep("set mods", () => Game.SelectedMods.Value = new Mod[] { new OsuModNoFail(), new OsuModDoubleTime { SpeedChange = { Value = 2 } } }); AddStep("press enter", () => InputManager.Key(Key.Enter)); AddUntilStep("wait for player", () => { // dismiss any notifications that may appear (ie. muted notification). clickMouseInCentre(); return (player = Game.ScreenStack.CurrentScreen as Player) != null; }); AddUntilStep("wait for track playing", () => beatmap().Track.IsRunning); AddStep("seek to near end", () => player.ChildrenOfType<GameplayClockContainer>().First().Seek(beatmap().Beatmap.HitObjects[^1].StartTime - 1000)); AddUntilStep("wait for pass", () => (results = Game.ScreenStack.CurrentScreen as ResultsScreen) != null && results.IsLoaded); AddStep("attempt to retry", () => results.ChildrenOfType<HotkeyRetryOverlay>().First().Action()); AddUntilStep("wait for player", () => Game.ScreenStack.CurrentScreen != player && Game.ScreenStack.CurrentScreen is Player); } [TestCase(true)] [TestCase(false)] public void TestSongContinuesAfterExitPlayer(bool withUserPause) { Player player = null; WorkingBeatmap beatmap() => Game.Beatmap.Value; PushAndConfirm(() => new TestPlaySongSelect()); AddStep("import beatmap", () => ImportBeatmapTest.LoadOszIntoOsu(Game, virtualTrack: true).Wait()); AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault); if (withUserPause) AddStep("pause", () => Game.Dependencies.Get<MusicController>().Stop(true)); AddStep("press enter", () => InputManager.Key(Key.Enter)); AddUntilStep("wait for player", () => { // dismiss any notifications that may appear (ie. muted notification). clickMouseInCentre(); return (player = Game.ScreenStack.CurrentScreen as Player) != null; }); AddUntilStep("wait for fail", () => player.HasFailed); AddUntilStep("wait for track stop", () => !Game.MusicController.IsPlaying); AddAssert("Ensure time before preview point", () => Game.MusicController.CurrentTrack.CurrentTime < beatmap().Metadata.PreviewTime); pushEscape(); AddUntilStep("wait for track playing", () => Game.MusicController.IsPlaying); AddAssert("Ensure time wasn't reset to preview point", () => Game.MusicController.CurrentTrack.CurrentTime < beatmap().Metadata.PreviewTime); } [Test] public void TestMenuMakesMusic() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddUntilStep("wait for no track", () => Game.MusicController.CurrentTrack.IsDummyDevice); AddStep("return to menu", () => songSelect.Exit()); AddUntilStep("wait for track", () => !Game.MusicController.CurrentTrack.IsDummyDevice && Game.MusicController.IsPlaying); } [Test] public void TestPushSongSelectAndPressBackButtonImmediately() { AddStep("push song select", () => Game.ScreenStack.Push(new TestPlaySongSelect())); AddStep("press back button", () => Game.ChildrenOfType<BackButton>().First().Action()); AddWaitStep("wait two frames", 2); } [Test] public void TestExitSongSelectWithClick() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show()); AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible); AddStep("Move mouse to backButton", () => InputManager.MoveMouseTo(backButtonPosition)); // BackButton handles hover using its child button, so this checks whether or not any of BackButton's children are hovered. AddUntilStep("Back button is hovered", () => Game.ChildrenOfType<BackButton>().First().Children.Any(c => c.IsHovered)); AddStep("Click back button", () => InputManager.Click(MouseButton.Left)); AddUntilStep("Overlay was hidden", () => songSelect.ModSelectOverlay.State.Value == Visibility.Hidden); exitViaBackButtonAndConfirm(); } [Test] public void TestExitMultiWithEscape() { PushAndConfirm(() => new Screens.OnlinePlay.Playlists.Playlists()); exitViaEscapeAndConfirm(); } [Test] public void TestExitMultiWithBackButton() { PushAndConfirm(() => new Screens.OnlinePlay.Playlists.Playlists()); exitViaBackButtonAndConfirm(); } [Test] public void TestOpenOptionsAndExitWithEscape() { AddUntilStep("Wait for options to load", () => Game.Settings.IsLoaded); AddStep("Enter menu", () => InputManager.Key(Key.Enter)); AddStep("Move mouse to options overlay", () => InputManager.MoveMouseTo(optionsButtonPosition)); AddStep("Click options overlay", () => InputManager.Click(MouseButton.Left)); AddAssert("Options overlay was opened", () => Game.Settings.State.Value == Visibility.Visible); AddStep("Hide options overlay using escape", () => InputManager.Key(Key.Escape)); AddAssert("Options overlay was closed", () => Game.Settings.State.Value == Visibility.Hidden); } [Test] public void TestWaitForNextTrackInMenu() { bool trackCompleted = false; AddUntilStep("Wait for music controller", () => Game.MusicController.IsLoaded); AddStep("Seek close to end", () => { Game.MusicController.SeekTo(Game.MusicController.CurrentTrack.Length - 1000); Game.MusicController.CurrentTrack.Completed += () => trackCompleted = true; }); AddUntilStep("Track was completed", () => trackCompleted); AddUntilStep("Track was restarted", () => Game.MusicController.IsPlaying); } [Test] public void TestModSelectInput() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show()); AddStep("Change ruleset to osu!taiko", () => { InputManager.PressKey(Key.ControlLeft); InputManager.Key(Key.Number2); InputManager.ReleaseKey(Key.ControlLeft); }); AddAssert("Ruleset changed to osu!taiko", () => Game.Toolbar.ChildrenOfType<ToolbarRulesetSelector>().Single().Current.Value.ID == 1); AddAssert("Mods overlay still visible", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible); } [Test] public void TestBeatmapOptionsInput() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show options overlay", () => songSelect.BeatmapOptionsOverlay.Show()); AddStep("Change ruleset to osu!taiko", () => { InputManager.PressKey(Key.ControlLeft); InputManager.Key(Key.Number2); InputManager.ReleaseKey(Key.ControlLeft); }); AddAssert("Ruleset changed to osu!taiko", () => Game.Toolbar.ChildrenOfType<ToolbarRulesetSelector>().Single().Current.Value.ID == 1); AddAssert("Options overlay still visible", () => songSelect.BeatmapOptionsOverlay.State.Value == Visibility.Visible); } [Test] public void TestSettingsViaHotkeyFromMainMenu() { AddAssert("toolbar not displayed", () => Game.Toolbar.State.Value == Visibility.Hidden); AddStep("press settings hotkey", () => { InputManager.PressKey(Key.ControlLeft); InputManager.Key(Key.O); InputManager.ReleaseKey(Key.ControlLeft); }); AddUntilStep("settings displayed", () => Game.Settings.State.Value == Visibility.Visible); } [Test] public void TestToolbarHiddenByUser() { AddStep("Enter menu", () => InputManager.Key(Key.Enter)); AddUntilStep("Wait for toolbar to load", () => Game.Toolbar.IsLoaded); AddStep("Hide toolbar", () => { InputManager.PressKey(Key.ControlLeft); InputManager.Key(Key.T); InputManager.ReleaseKey(Key.ControlLeft); }); pushEscape(); AddStep("Enter menu", () => InputManager.Key(Key.Enter)); AddAssert("Toolbar is hidden", () => Game.Toolbar.State.Value == Visibility.Hidden); AddStep("Enter song select", () => { InputManager.Key(Key.Enter); InputManager.Key(Key.Enter); }); AddAssert("Toolbar is hidden", () => Game.Toolbar.State.Value == Visibility.Hidden); } [Test] public void TestPushMatchSubScreenAndPressBackButtonImmediately() { TestMultiplayer multiplayer = null; PushAndConfirm(() => multiplayer = new TestMultiplayer()); AddUntilStep("wait for lounge", () => multiplayer.ChildrenOfType<LoungeSubScreen>().SingleOrDefault()?.IsLoaded == true); AddStep("open room", () => multiplayer.ChildrenOfType<LoungeSubScreen>().Single().Open()); AddStep("press back button", () => Game.ChildrenOfType<BackButton>().First().Action()); AddWaitStep("wait two frames", 2); } [Test] public void TestOverlayClosing() { // use now playing overlay for "overlay -> background" drag case // since most overlays use a scroll container that absorbs on mouse down NowPlayingOverlay nowPlayingOverlay = null; AddUntilStep("Wait for now playing load", () => (nowPlayingOverlay = Game.ChildrenOfType<NowPlayingOverlay>().FirstOrDefault()) != null); AddStep("enter menu", () => InputManager.Key(Key.Enter)); AddUntilStep("toolbar displayed", () => Game.Toolbar.State.Value == Visibility.Visible); AddStep("open now playing", () => InputManager.Key(Key.F6)); AddUntilStep("now playing is visible", () => nowPlayingOverlay.State.Value == Visibility.Visible); // drag tests // background -> toolbar AddStep("move cursor to background", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomRight)); AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left)); AddStep("move cursor to toolbar", () => InputManager.MoveMouseTo(Game.Toolbar.ScreenSpaceDrawQuad.Centre)); AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left)); AddAssert("now playing is hidden", () => nowPlayingOverlay.State.Value == Visibility.Hidden); AddStep("press now playing hotkey", () => InputManager.Key(Key.F6)); // toolbar -> background AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left)); AddStep("move cursor to background", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomRight)); AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left)); AddAssert("now playing is still visible", () => nowPlayingOverlay.State.Value == Visibility.Visible); // background -> overlay AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left)); AddStep("move cursor to now playing overlay", () => InputManager.MoveMouseTo(nowPlayingOverlay.ScreenSpaceDrawQuad.Centre)); AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left)); AddAssert("now playing is still visible", () => nowPlayingOverlay.State.Value == Visibility.Visible); // overlay -> background AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left)); AddStep("move cursor to background", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomRight)); AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left)); AddAssert("now playing is still visible", () => nowPlayingOverlay.State.Value == Visibility.Visible); // background -> background AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left)); AddStep("move cursor to left", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomLeft)); AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left)); AddAssert("now playing is hidden", () => nowPlayingOverlay.State.Value == Visibility.Hidden); AddStep("press now playing hotkey", () => InputManager.Key(Key.F6)); // click tests // toolbar AddStep("move cursor to toolbar", () => InputManager.MoveMouseTo(Game.Toolbar.ScreenSpaceDrawQuad.Centre)); AddStep("click left mouse button", () => InputManager.Click(MouseButton.Left)); AddAssert("now playing is still visible", () => nowPlayingOverlay.State.Value == Visibility.Visible); // background AddStep("move cursor to background", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomRight)); AddStep("click left mouse button", () => InputManager.Click(MouseButton.Left)); AddAssert("now playing is hidden", () => nowPlayingOverlay.State.Value == Visibility.Hidden); } [Test] public void TestExitGameFromSongSelect() { PushAndConfirm(() => new TestPlaySongSelect()); exitViaEscapeAndConfirm(); pushEscape(); // returns to osu! logo AddStep("Hold escape", () => InputManager.PressKey(Key.Escape)); AddUntilStep("Wait for intro", () => Game.ScreenStack.CurrentScreen is IntroScreen); AddStep("Release escape", () => InputManager.ReleaseKey(Key.Escape)); AddUntilStep("Wait for game exit", () => Game.ScreenStack.CurrentScreen == null); AddStep("test dispose doesn't crash", () => Game.Dispose()); } private void clickMouseInCentre() { InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.Centre); InputManager.Click(MouseButton.Left); } private void pushEscape() => AddStep("Press escape", () => InputManager.Key(Key.Escape)); private void exitViaEscapeAndConfirm() { pushEscape(); ConfirmAtMainMenu(); } private void exitViaBackButtonAndConfirm() { AddStep("Move mouse to backButton", () => InputManager.MoveMouseTo(backButtonPosition)); AddStep("Click back button", () => InputManager.Click(MouseButton.Left)); ConfirmAtMainMenu(); } public class TestPlaySongSelect : PlaySongSelect { public ModSelectOverlay ModSelectOverlay => ModSelect; public BeatmapOptionsOverlay BeatmapOptionsOverlay => BeatmapOptions; protected override bool DisplayStableImportPrompt => false; } private class TestMultiplayer : Screens.OnlinePlay.Multiplayer.Multiplayer { [Cached(typeof(MultiplayerClient))] public readonly TestMultiplayerClient Client; public TestMultiplayer() { Client = new TestMultiplayerClient((TestRequestHandlingMultiplayerRoomManager)RoomManager); } protected override RoomManager CreateRoomManager() => new TestRequestHandlingMultiplayerRoomManager(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Oranikle.Studio.Controls { [System.Drawing.ToolboxBitmap(typeof(Oranikle.Studio.Controls.CtrlStyledTab))] public class CtrlStyledTab : System.Windows.Forms.TabControl { internal class TabpageExCollectionEditor : System.ComponentModel.Design.CollectionEditor { public TabpageExCollectionEditor(System.Type type) : base(type) { } protected override System.Type CreateCollectionItemType() { return typeof(System.Windows.Forms.TabPage); } } // class TabpageExCollectionEditor private const int nMargin = 5; private System.Drawing.Color _BorderColor; private bool _DontSlantMiddle; private int _LeftSpacing; private System.Drawing.Font _TabFont; private System.Windows.Forms.TabPage[] _TabPageOrder; private int _TabSlant; private System.Drawing.Color _TabTextColor; private System.Drawing.StringAlignment _TabTextHAlignment; private System.Drawing.StringAlignment _TabTextVAlignment; private System.Drawing.Color _TagPageSelectedColor; private System.Drawing.Color _TagPageUnselectedColor; private bool allowNextSelection; private System.ComponentModel.Container components; private System.Drawing.Color mBackColor; private Oranikle.Studio.Controls.NativeUpDown UpDown; public new System.Windows.Forms.TabAlignment Alignment { get { return base.Alignment; } set { System.Windows.Forms.TabAlignment tabAlignment = value; if ((tabAlignment != System.Windows.Forms.TabAlignment.Top) && (tabAlignment != System.Windows.Forms.TabAlignment.Bottom)) tabAlignment = System.Windows.Forms.TabAlignment.Top; base.Alignment = tabAlignment; } } [System.ComponentModel.Category("Appearance")] public System.Drawing.Color BorderColor { get { return _BorderColor; } set { _BorderColor = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Category("Appearance")] public bool DontSlantMiddle { get { return _DontSlantMiddle; } set { _DontSlantMiddle = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Category("Appearance")] public int LeftSpacing { get { return _LeftSpacing; } set { _LeftSpacing = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Browsable(false)] public new bool Multiline { get { return base.Multiline; } set { base.Multiline = false; } } [System.ComponentModel.Category("Appearance")] [System.ComponentModel.Browsable(true)] public System.Drawing.Color myBackColor { get { return mBackColor; } set { mBackColor = value; Invalidate(); } } [System.ComponentModel.Category("Appearance")] public System.Drawing.Font TabFont { get { return _TabFont; } set { _TabFont = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Category("Appearance")] public int TabSlant { get { return _TabSlant; } set { _TabSlant = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Category("Appearance")] public System.Drawing.Color TabTextColor { get { return _TabTextColor; } set { _TabTextColor = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Category("Appearance")] public System.Drawing.StringAlignment TabTextHAlignment { get { return _TabTextHAlignment; } set { _TabTextHAlignment = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Category("Appearance")] public System.Drawing.StringAlignment TabTextVAlignment { get { return _TabTextVAlignment; } set { _TabTextVAlignment = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Category("Appearance")] public System.Drawing.Color TagPageSelectedColor { get { return _TagPageSelectedColor; } set { _TagPageSelectedColor = value; if (DesignMode) Invalidate(); } } [System.ComponentModel.Category("Appearance")] public System.Drawing.Color TagPageUnselectedColor { get { return _TagPageUnselectedColor; } set { _TagPageUnselectedColor = value; if (DesignMode) Invalidate(); } } public CtrlStyledTab() { _TabSlant = 2; _TagPageSelectedColor = System.Drawing.Color.White; _TagPageUnselectedColor = System.Drawing.Color.LightGray; _TabTextVAlignment = System.Drawing.StringAlignment.Center; _BorderColor = System.Drawing.Color.DarkGray; _TabTextColor = System.Drawing.Color.FromArgb(64, 64, 64); _TabFont = new System.Drawing.Font("Tahoma", 9.0F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); mBackColor = System.Drawing.Color.Transparent; InitializeComponent(); SetStyle(System.Windows.Forms.ControlStyles.UserPaint, true); SetStyle(System.Windows.Forms.ControlStyles.AllPaintingInWmPaint, true); SetStyle(System.Windows.Forms.ControlStyles.DoubleBuffer, true); SetStyle(System.Windows.Forms.ControlStyles.ResizeRedraw, true); SetStyle(System.Windows.Forms.ControlStyles.SupportsTransparentBackColor, true); ControlAdded += new System.Windows.Forms.ControlEventHandler(CtrlColourTab_ControlAdded); ControlRemoved += new System.Windows.Forms.ControlEventHandler(CtrlColourTab_ControlRemoved); SelectedIndexChanged += new System.EventHandler(CtrlColourTab_SelectedIndexChanged); SizeMode = System.Windows.Forms.TabSizeMode.Fixed; TabStop = false; } private void CtrlColourTab_ControlAdded(object sender, System.Windows.Forms.ControlEventArgs e) { SetTabsColor(); } private void CtrlColourTab_ControlRemoved(object sender, System.Windows.Forms.ControlEventArgs e) { SetTabsColor(); } private void CtrlColourTab_SelectedIndexChanged(object sender, System.EventArgs e) { Invalidate(); } internal void DrawControl(System.Drawing.Graphics g) { System.Drawing.Brush brush; if (!Visible) return; System.Drawing.Rectangle rectangle1 = ClientRectangle; System.Drawing.Rectangle rectangle2 = DisplayRectangle; if (mBackColor == System.Drawing.Color.Transparent) brush = new System.Drawing.SolidBrush(Parent.BackColor); else brush = new System.Drawing.SolidBrush(mBackColor); g.FillRectangle(brush, rectangle1); brush.Dispose(); System.Drawing.Size size = System.Windows.Forms.SystemInformation.Border3DSize; int i1 = size.Width; System.Drawing.Pen pen = new System.Drawing.Pen(_BorderColor); rectangle2.Inflate(i1, i1); g.DrawRectangle(pen, rectangle2); pen.Dispose(); for (int i2 = 0; i2 < TabCount; i2++) { DrawTab(g, TabPages[i2], i2); } if (SelectedTab != null) { System.Windows.Forms.TabPage tabPage = SelectedTab; //tabPage.BackColor; pen = new System.Drawing.Pen(_TagPageSelectedColor); rectangle2.Offset(1, 1); rectangle2.Width -= 2; rectangle2.Height -= 2; g.DrawRectangle(pen, rectangle2); rectangle2.Width--; rectangle2.Height--; g.DrawRectangle(pen, rectangle2); pen.Dispose(); } } internal void DrawTab(System.Drawing.Graphics g, System.Windows.Forms.TabPage tabPage, int nIndex) { System.Drawing.Brush brush; System.Drawing.Point[] pointArr; System.Drawing.Rectangle rectangle1 = GetTabRect(nIndex); System.Drawing.RectangleF rectangleF = GetTabRect(nIndex); Oranikle.Studio.Controls.CtrlStyledTabPage ctrlStyledTabPage = tabPage as Oranikle.Studio.Controls.CtrlStyledTabPage; if (ctrlStyledTabPage != null) { System.Nullable<int> nullable1 = ctrlStyledTabPage.TabWidth; if (nullable1.HasValue) { System.Nullable<int> nullable = ctrlStyledTabPage.TabWidth; rectangle1.Width = nullable.Value; System.Nullable<int> nullable2 = ctrlStyledTabPage.TabWidth; rectangleF.Width = (float)nullable2.Value; } } if (_LeftSpacing > 0) { rectangle1 = new System.Drawing.Rectangle(rectangle1.X + _LeftSpacing, rectangle1.Y, rectangle1.Width, rectangle1.Height); rectangleF = new System.Drawing.RectangleF(rectangleF.X + (float)_LeftSpacing, rectangleF.Y, rectangleF.Width, rectangleF.Height); } bool flag = SelectedIndex == nIndex; if (Alignment == System.Windows.Forms.TabAlignment.Top) { if (_DontSlantMiddle) { if (nIndex == 0) { pointArr = new System.Drawing.Point[6]; pointArr[0] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); pointArr[1] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top + _TabSlant); pointArr[2] = new System.Drawing.Point(rectangle1.Left + _TabSlant, rectangle1.Top); pointArr[3] = new System.Drawing.Point(rectangle1.Right, rectangle1.Top); pointArr[4] = new System.Drawing.Point(rectangle1.Right, rectangle1.Bottom); pointArr[5] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); } else if (nIndex == (TabCount - 1)) { pointArr = new System.Drawing.Point[6]; pointArr[0] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); pointArr[1] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); pointArr[2] = new System.Drawing.Point(rectangle1.Right - _TabSlant, rectangle1.Top); pointArr[3] = new System.Drawing.Point(rectangle1.Right, rectangle1.Top + _TabSlant); pointArr[4] = new System.Drawing.Point(rectangle1.Right, rectangle1.Bottom); pointArr[5] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); } else { pointArr = new System.Drawing.Point[5]; pointArr[0] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); pointArr[1] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); pointArr[2] = new System.Drawing.Point(rectangle1.Right, rectangle1.Top); pointArr[3] = new System.Drawing.Point(rectangle1.Right, rectangle1.Bottom); pointArr[4] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); } } else { pointArr = new System.Drawing.Point[7]; pointArr[0] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); pointArr[1] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top + _TabSlant); pointArr[2] = new System.Drawing.Point(rectangle1.Left + _TabSlant, rectangle1.Top); pointArr[3] = new System.Drawing.Point(rectangle1.Right - _TabSlant, rectangle1.Top); pointArr[4] = new System.Drawing.Point(rectangle1.Right, rectangle1.Top + _TabSlant); pointArr[5] = new System.Drawing.Point(rectangle1.Right, rectangle1.Bottom); pointArr[6] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); } } else if (_DontSlantMiddle) { if (nIndex == 0) { pointArr = new System.Drawing.Point[6]; pointArr[0] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); pointArr[1] = new System.Drawing.Point(rectangle1.Right, rectangle1.Top); pointArr[2] = new System.Drawing.Point(rectangle1.Right, rectangle1.Bottom); pointArr[3] = new System.Drawing.Point(rectangle1.Left + _TabSlant, rectangle1.Bottom); pointArr[4] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom - _TabSlant); pointArr[5] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); } else if (nIndex == (TabCount - 1)) { pointArr = new System.Drawing.Point[6]; pointArr[0] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); pointArr[1] = new System.Drawing.Point(rectangle1.Right, rectangle1.Top); pointArr[2] = new System.Drawing.Point(rectangle1.Right, rectangle1.Bottom - _TabSlant); pointArr[3] = new System.Drawing.Point(rectangle1.Right - _TabSlant, rectangle1.Bottom); pointArr[4] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); pointArr[5] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); } else { pointArr = new System.Drawing.Point[5]; pointArr[0] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); pointArr[1] = new System.Drawing.Point(rectangle1.Right, rectangle1.Top); pointArr[2] = new System.Drawing.Point(rectangle1.Right, rectangle1.Bottom); pointArr[3] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom); pointArr[4] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); } } else { pointArr = new System.Drawing.Point[7]; pointArr[0] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); pointArr[1] = new System.Drawing.Point(rectangle1.Right, rectangle1.Top); pointArr[2] = new System.Drawing.Point(rectangle1.Right, rectangle1.Bottom - _TabSlant); pointArr[3] = new System.Drawing.Point(rectangle1.Right - _TabSlant, rectangle1.Bottom); pointArr[4] = new System.Drawing.Point(rectangle1.Left + _TabSlant, rectangle1.Bottom); pointArr[5] = new System.Drawing.Point(rectangle1.Left, rectangle1.Bottom - _TabSlant); pointArr[6] = new System.Drawing.Point(rectangle1.Left, rectangle1.Top); } if (nIndex == SelectedIndex) brush = new System.Drawing.SolidBrush(_TagPageSelectedColor); else brush = new System.Drawing.SolidBrush(_TagPageUnselectedColor); g.FillPolygon(brush, pointArr); brush.Dispose(); g.DrawPolygon(new System.Drawing.Pen(_BorderColor), pointArr); if (flag) { System.Drawing.Pen pen = new System.Drawing.Pen(_TagPageSelectedColor); switch (Alignment) { case System.Windows.Forms.TabAlignment.Top: g.DrawLine(pen, rectangle1.Left + 1, rectangle1.Bottom, rectangle1.Right - 1, rectangle1.Bottom); g.DrawLine(pen, rectangle1.Left + 1, rectangle1.Bottom + 1, rectangle1.Right - 1, rectangle1.Bottom + 1); break; case System.Windows.Forms.TabAlignment.Bottom: g.DrawLine(pen, rectangle1.Left + 1, rectangle1.Top, rectangle1.Right - 1, rectangle1.Top); g.DrawLine(pen, rectangle1.Left + 1, rectangle1.Top - 1, rectangle1.Right - 1, rectangle1.Top - 1); g.DrawLine(pen, rectangle1.Left + 1, rectangle1.Top - 2, rectangle1.Right - 1, rectangle1.Top - 2); break; } pen.Dispose(); } if ((tabPage.ImageIndex >= 0) && (ImageList != null) && (ImageList.Images[tabPage.ImageIndex] != null)) { int i1 = 8, i2 = 2; System.Drawing.Image image = ImageList.Images[tabPage.ImageIndex]; System.Drawing.Rectangle rectangle2 = new System.Drawing.Rectangle(rectangle1.X + i1, rectangle1.Y + 1, image.Width, image.Height); float f = (float)(i1 + image.Width + i2); rectangle2.Y += (rectangle1.Height - image.Height) / 2; rectangleF.X += f; rectangleF.Width -= f; g.DrawImage(image, rectangle2); } if (ImageList == null) { int i3 = 12; rectangleF.X += (float)i3; rectangleF.Width -= (float)i3; } System.Drawing.StringFormat stringFormat = new System.Drawing.StringFormat(); if (ctrlStyledTabPage != null) { System.Nullable<System.Drawing.StringAlignment> nullable4 = ctrlStyledTabPage.TabTextAlignment; if (nullable4.HasValue) goto label_1; System.Nullable<System.Drawing.StringAlignment> nullable3 = ctrlStyledTabPage.TabTextAlignment; stringFormat.Alignment = (System.Drawing.StringAlignment)nullable3.Value; } else { goto label_1; } label_1: { stringFormat.Alignment = _TabTextHAlignment; } stringFormat.LineAlignment = _TabTextVAlignment; stringFormat.Trimming = System.Drawing.StringTrimming.EllipsisCharacter; stringFormat.FormatFlags = System.Drawing.StringFormatFlags.NoWrap; brush = new System.Drawing.SolidBrush(_TabTextColor); g.DrawString(tabPage.Text, _TabFont, brush, rectangleF, stringFormat); } private void InitializeComponent() { components = new System.ComponentModel.Container(); } private void InsertTabPage(System.Windows.Forms.TabPage[] originalOrder, System.Windows.Forms.TabPage page) { if (TabPages.Contains(page)) return; if (originalOrder == null) TabPages.Add(page); System.Collections.Generic.Dictionary<System.Windows.Forms.TabPage,int> dictionary = new System.Collections.Generic.Dictionary<System.Windows.Forms.TabPage,int>(); for (int i1 = 0; i1 < originalOrder.Length; i1++) { dictionary.Add(originalOrder[i1], i1); } if (!dictionary.ContainsKey(page)) TabPages.Add(page); int i2 = dictionary[page];// (page); for (int i3 = 0; i3 < TabPages.Count; i3++) { System.Windows.Forms.TabPage tabPage = TabPages[i3]; if (dictionary.ContainsKey(tabPage) && (dictionary[tabPage] > i2)) { TabPages.Insert(i3, page); return; } } TabPages.Add(page); } public void SaveOriginalTabPageOrder() { _TabPageOrder = new System.Windows.Forms.TabPage[TabPages.Count]; for (int i = 0; i < TabPages.Count; i++) { System.Collections.IEnumerator ienumerator = TabPages.GetEnumerator(); try { while (ienumerator.MoveNext()) { _TabPageOrder[i] = TabPages[i]; } } finally { System.IDisposable idisposable = ienumerator as System.IDisposable; if (idisposable != null) idisposable.Dispose(); } } } public new void SelectTab(System.Windows.Forms.TabPage p) { allowNextSelection = true; SelectedTab = p; } private void SetTabsColor() { foreach (System.Windows.Forms.TabPage tabPage in TabPages) { tabPage.BackColor = _TagPageSelectedColor; } } public void ShowTabPage(bool show, System.Windows.Forms.TabPage page) { if (show) { InsertTabPage(_TabPageOrder, page); return; } if (TabPages.Contains(page)) TabPages.Remove(page); } protected override void Dispose(bool disposing) { if (disposing && (components != null)) components.Dispose(); base.Dispose(disposing); } protected override void OnCreateControl() { base.OnCreateControl(); SetTabsColor(); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == (Keys.Control | Keys.Tab)) { if (this.TabCount > this.SelectedIndex + 1) this.SelectTab(this.TabPages[this.SelectedIndex + 1]); else this.SelectTab(this.TabPages[0]); } //if (keyData == Keys.Tab) //{ // if (this.SelectedTab != null) // { // Control found = GetLastControl(null, this.SelectedTab.Controls); // if (found != null && found.Focused) // { // if (this.TabCount > this.SelectedIndex + 1) // this.SelectTab(this.TabPages[this.SelectedIndex + 1]); // else // this.SelectTab(this.TabPages[0]); // } // } //} return base.ProcessCmdKey(ref msg, keyData); } private Control GetLastControl(Control found, Control.ControlCollection controlCollection) { foreach (Control control in controlCollection) { if (control.Enabled && (found == null || control.TabIndex > found.TabIndex)) { if (control.Controls.Count > 0) { found = GetLastControl(control, control.Controls); } else { found = control; } } } return found; } protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e) { System.Drawing.Point point = e.Location; for (int i = 0; i < TabCount; i++) { System.Drawing.Rectangle rectangle = GetTabRect(i); rectangle.Offset(_LeftSpacing, 0); if (rectangle.Contains(point) && (SelectedIndex != i)) { allowNextSelection = true; SelectedIndex = i; return; } } } protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { base.OnPaint(e); DrawControl(e.Graphics); } protected override void OnSelecting(System.Windows.Forms.TabControlCancelEventArgs e) { if (e.Action == System.Windows.Forms.TabControlAction.Selecting) { e.Cancel = !allowNextSelection; allowNextSelection = false; } if (!e.Cancel) base.OnSelecting(e); } protected override void WndProc(ref System.Windows.Forms.Message m) { if (m.Msg == 528) { System.IntPtr intPtr = m.WParam; if ((ushort)(intPtr.ToInt32() & 65535) == 1) { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(16); Oranikle.Studio.Controls.Win32.RealGetWindowClass(m.LParam, stringBuilder, 16); if (stringBuilder.ToString() == "msctls_updown32") { if (UpDown != null) UpDown.ReleaseHandle(); UpDown = new Oranikle.Studio.Controls.NativeUpDown(); UpDown.AssignHandle(m.LParam); } } } base.WndProc(ref m); } } // class CtrlStyledTab }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Reflection; using Internal.Cryptography; namespace System.Security.Cryptography { // The current RSA contracts require that users cast up to RSACryptoServiceProvider. // There is an expectation that Soon there will be some contract changes enabling RSA // to function as a standalone type, and then this wrapper will go away. public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm { private readonly RSAOpenSsl _defer; public RSACryptoServiceProvider() { _defer = new RSAOpenSsl(); } public RSACryptoServiceProvider(int dwKeySize) { _defer = new RSAOpenSsl(dwKeySize); } public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters) { throw new PlatformNotSupportedException(); } public RSACryptoServiceProvider(CspParameters parameters) { throw new PlatformNotSupportedException(); } public override int KeySize { get { return _defer.KeySize; } set { _defer.KeySize = value; } } public byte[] Decrypt(byte[] rgb, bool fOAEP) { return _defer.Decrypt( rgb, fOAEP ? Interop.libcrypto.OpenSslRsaPadding.RSA_PKCS1_OAEP_PADDING : Interop.libcrypto.OpenSslRsaPadding.RSA_PKCS1_PADDING); } public override byte[] DecryptValue(byte[] rgb) { return _defer.DecryptValue(rgb); } protected override void Dispose(bool disposing) { if (disposing) { _defer.Dispose(); } base.Dispose(disposing); } public byte[] Encrypt(byte[] rgb, bool fOAEP) { return _defer.Encrypt( rgb, fOAEP ? Interop.libcrypto.OpenSslRsaPadding.RSA_PKCS1_OAEP_PADDING : Interop.libcrypto.OpenSslRsaPadding.RSA_PKCS1_PADDING); } public override byte[] EncryptValue(byte[] rgb) { return _defer.EncryptValue(rgb); } public override RSAParameters ExportParameters(bool includePrivateParameters) { return _defer.ExportParameters(includePrivateParameters); } public override void ImportParameters(RSAParameters parameters) { _defer.ImportParameters(parameters); } public byte[] SignData(byte[] buffer, int offset, int count, object halg) { if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); HashAlgorithmName hashAlgorithmName = LookupHashAlgorithm(halg); byte[] hash = _defer.HashData(buffer, offset, count, hashAlgorithmName); return _defer.SignHash(hash, hashAlgorithmName); } public byte[] SignData(byte[] buffer, object halg) { if (buffer == null) throw new ArgumentNullException("buffer"); return SignData(buffer, 0, buffer.Length, halg); } public byte[] SignData(Stream inputStream, object halg) { if (inputStream == null) throw new ArgumentNullException("inputStream"); HashAlgorithmName hashAlgorithmName = LookupHashAlgorithm(halg); byte[] hash = _defer.HashData(inputStream, hashAlgorithmName); return _defer.SignHash(hash, hashAlgorithmName); } public byte[] SignHash(byte[] rgbHash, string str) { if (rgbHash == null) throw new ArgumentNullException("rgbHash"); HashAlgorithmName hashAlgorithmName = LookupHashAlgorithm(str); return _defer.SignHash(rgbHash, hashAlgorithmName); } public bool VerifyData(byte[] buffer, object halg, byte[] signature) { if (buffer == null) throw new ArgumentNullException("buffer"); if (signature == null) throw new ArgumentNullException("signature"); HashAlgorithmName hashAlgorithmName = LookupHashAlgorithm(halg); byte[] hash = _defer.HashData(buffer, 0, buffer.Length, hashAlgorithmName); return _defer.VerifyHash(hash, signature, hashAlgorithmName); } public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { if (rgbHash == null) throw new ArgumentNullException("rgbHash"); if (rgbSignature == null) throw new ArgumentNullException("rgbSignature"); HashAlgorithmName hashAlgorithmName = LookupHashAlgorithm(str); return _defer.VerifyHash(rgbHash, rgbSignature, hashAlgorithmName); } public CspKeyContainerInfo CspKeyContainerInfo { get { throw new PlatformNotSupportedException(); } } public void ImportCspBlob(byte[] keyBlob) { throw new PlatformNotSupportedException(); } public byte[] ExportCspBlob(bool includePrivateParameters) { throw new PlatformNotSupportedException(); } public bool PersistKeyInCsp { get { throw new PlatformNotSupportedException(); } set { throw new PlatformNotSupportedException(); } } public bool PublicOnly { get { return true; } } public static bool UseMachineKeyStore { get { throw new PlatformNotSupportedException(); } set { throw new PlatformNotSupportedException(); } } private static HashAlgorithmName LookupHashAlgorithm(object halg) { string algString = halg as string; if (algString != null) { return LookupHashAlgorithm(algString); } HashAlgorithm hashAlgorithmInstance = halg as HashAlgorithm; if (hashAlgorithmInstance != null) { return LookupHashAlgorithm(hashAlgorithmInstance); } Type hashAlgorithmType = halg as Type; if (hashAlgorithmType != null) { return LookupHashAlgorithm(hashAlgorithmType); } throw new ArgumentException(SR.Argument_InvalidValue); } private static HashAlgorithmName LookupHashAlgorithm(Type hashAlgorithmType) { TypeInfo hashAlgTypeInfo = hashAlgorithmType.GetTypeInfo(); if (typeof(MD5).GetTypeInfo().IsAssignableFrom(hashAlgTypeInfo)) { return HashAlgorithmName.MD5; } if (typeof(SHA1).GetTypeInfo().IsAssignableFrom(hashAlgTypeInfo)) { return HashAlgorithmName.SHA1; } if (typeof(SHA256).GetTypeInfo().IsAssignableFrom(hashAlgTypeInfo)) { return HashAlgorithmName.SHA256; } if (typeof(SHA384).GetTypeInfo().IsAssignableFrom(hashAlgTypeInfo)) { return HashAlgorithmName.SHA384; } if (typeof(SHA512).GetTypeInfo().IsAssignableFrom(hashAlgTypeInfo)) { return HashAlgorithmName.SHA512; } throw new ArgumentException(SR.Argument_InvalidValue); } private static HashAlgorithmName LookupHashAlgorithm(HashAlgorithm hashAlgorithm) { if (hashAlgorithm is MD5) { return HashAlgorithmName.MD5; } if (hashAlgorithm is SHA1) { return HashAlgorithmName.SHA1; } if (hashAlgorithm is SHA256) { return HashAlgorithmName.SHA256; } if (hashAlgorithm is SHA384) { return HashAlgorithmName.SHA384; } if (hashAlgorithm is SHA512) { return HashAlgorithmName.SHA512; } throw new ArgumentException(SR.Argument_InvalidValue); } private static HashAlgorithmName LookupHashAlgorithm(string algString) { const string Md5Oid = "1.2.840.113549.2.5"; const string Sha1Oid = "1.3.14.3.2.26"; const string Sha256Oid = "2.16.840.1.101.3.4.2.1"; const string Sha384Oid = "2.16.840.1.101.3.4.2.2"; const string Sha512Oid = "2.16.840.1.101.3.4.2.3"; if (algString.Length > 0 && !char.IsDigit(algString[0])) { // If algString is an understood OID FriendlyName it will become the numeric OID, // otherwise it will remain as it was. algString = new Oid(algString).Value ?? algString; } switch (algString) { case Md5Oid: return HashAlgorithmName.MD5; case Sha1Oid: return HashAlgorithmName.SHA1; case Sha256Oid: return HashAlgorithmName.SHA256; case Sha384Oid: return HashAlgorithmName.SHA384; case Sha512Oid: return HashAlgorithmName.SHA512; } throw new CryptographicException(SR.Cryptography_InvalidOID); } } }
using System.Collections.Generic; using Box2D.Common; using CocosSharp; namespace Box2D.TestBed { public class Box2DView : CCLayer { private TestEntry m_entry; private Test m_test; private int m_entryID; private Settings settings = new Settings(); CCEventListenerTouchOneByOne touchListener; public bool initWithEntryID(int entryId) { // Register Touch Event touchListener = new CCEventListenerTouchOneByOne(); touchListener.IsSwallowTouches = true; touchListener.OnTouchBegan = onTouchBegan; touchListener.OnTouchMoved = onTouchMoved; touchListener.OnTouchEnded = onTouchEnded; AddEventListener(touchListener, -10); var keyboardListener = new CCEventListenerKeyboard (); keyboardListener.OnKeyPressed = onKeyPressed; keyboardListener.OnKeyReleased = onKeyReleased; AddEventListener(keyboardListener); m_entry = TestEntries.TestList[entryId]; m_test = m_entry.CreateFcn(); return true; } protected override void AddedToScene () { base.AddedToScene (); Schedule (); } public string title() { return m_entry.Name; } public override void Update(float dt) { base.Update(dt); } protected override void Draw() { m_test.Step(settings); base.Draw(); m_test.InternalDraw(settings); } public override void OnExit () { if (touchListener != null) RemoveEventListener(touchListener); base.OnExit (); } bool onTouchBegan(CCTouch touch, CCEvent touchEvent) { CCPoint touchLocation = touch.LocationOnScreen; CCPoint nodePosition = Layer.ScreenToWorldspace(touchLocation); // NSLog(@"pos: %f,%f -> %f,%f", touchLocation.x, touchLocation.y, nodePosition.x, nodePosition.y); return m_test.MouseDown(new b2Vec2(nodePosition.X, nodePosition.Y)); } void onTouchMoved(CCTouch touch, CCEvent touchEvent) { CCPoint touchLocation = touch.LocationOnScreen; CCPoint nodePosition = Layer.ScreenToWorldspace(touchLocation); m_test.MouseMove(new b2Vec2(nodePosition.X, nodePosition.Y)); } void onTouchEnded(CCTouch touch, CCEvent touchEvent) { CCPoint touchLocation = touch.LocationOnScreen; CCPoint nodePosition = Layer.ScreenToWorldspace(touchLocation); m_test.MouseUp(new b2Vec2(nodePosition.X, nodePosition.Y)); } //virtual void accelerometer(UIAccelerometer* accelerometer, CCAcceleration* acceleration); void onKeyPressed(CCEventKeyboard keyEvent) { var result = Convert( keyEvent ); if (result.Length > 0) { m_test.Keyboard(result[0]); } } void onKeyReleased(CCEventKeyboard keyEvent) { var result = Convert( keyEvent ); if (result.Length > 0) { m_test.KeyboardUp(result[0]); } } // private KeyboardState _keyboardState; // public override void KeyboardCurrentState(KeyboardState currentState) // { // _keyboardState = currentState; // } public string Convert(CCEventKeyboard keyEvent) { string output = ""; var state = new List<CCKeys>(keyEvent.KeyboardState.GetPressedKeys()); bool usesShift = (state.Contains(CCKeys.LeftShift) || state.Contains(CCKeys.RightShift)); foreach (CCKeys key in state) { if (key >= CCKeys.A && key <= CCKeys.Z) output += key.ToString(); else if (key >= CCKeys.NumPad0 && key <= CCKeys.NumPad9) output += ((int) (key - CCKeys.NumPad0)).ToString(); else if (key >= CCKeys.D0 && key <= CCKeys.D9) { string num = ((int) (key - CCKeys.D0)).ToString(); #region special num chars if (usesShift) { switch (num) { case "1": { num = "!"; } break; case "2": { num = "@"; } break; case "3": { num = "#"; } break; case "4": { num = "$"; } break; case "5": { num = "%"; } break; case "6": { num = "^"; } break; case "7": { num = "&"; } break; case "8": { num = "*"; } break; case "9": { num = "("; } break; case "0": { num = ")"; } break; default: //wtf? break; } } #endregion output += num; } else if (key == CCKeys.OemComma) output += ","; else if (key == CCKeys.OemPeriod) output += "."; else if (key == CCKeys.OemTilde) output += "'"; else if (key == CCKeys.Space) output += " "; else if (key == CCKeys.OemMinus) output += "-"; else if (key == CCKeys.OemPlus) output += "+"; else if (key == CCKeys.OemQuestion && usesShift) output += "?"; else if (key == CCKeys.Back) //backspace output += "\b"; if (!usesShift) //shouldn't need to upper because it's automagically in upper case output = output.ToLower(); } return output; } public static Box2DView viewWithEntryID(int entryId) { var pView = new Box2DView(); pView.initWithEntryID(entryId); return pView; } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using Orleans.Runtime.Configuration; using Orleans.Messaging; namespace Orleans.Runtime.Messaging { internal class Gateway { private static readonly TimeSpan TIME_BEFORE_CLIENT_DROP = TimeSpan.FromSeconds(60); private readonly MessageCenter messageCenter; private readonly GatewayAcceptor acceptor; private readonly Lazy<GatewaySender>[] senders; private readonly GatewayClientCleanupAgent dropper; // clients is the main authorative collection of all connected clients. // Any client currently in the system appears in this collection. // In addition, we use clientSockets and proxiedGrains collections for fast retrival of ClientState. // Anything that appears in those 2 collections should also appear in the main clients collection. private readonly ConcurrentDictionary<Guid, ClientState> clients; private readonly ConcurrentDictionary<Socket, ClientState> clientSockets; private readonly ConcurrentDictionary<GrainId, ClientState> proxiedGrains; private readonly SiloAddress gatewayAddress; private int nextGatewaySenderToUseForRoundRobin; private readonly ClientsReplyRoutingCache clientsReplyRoutingCache; private readonly object lockable; private static readonly TraceLogger logger = TraceLogger.GetLogger("Orleans.Messaging.Gateway"); private IMessagingConfiguration MessagingConfiguration { get { return messageCenter.MessagingConfiguration; } } internal Gateway(MessageCenter msgCtr, IPEndPoint gatewayAddress) { messageCenter = msgCtr; acceptor = new GatewayAcceptor(msgCtr, this, gatewayAddress); senders = new Lazy<GatewaySender>[messageCenter.MessagingConfiguration.GatewaySenderQueues]; nextGatewaySenderToUseForRoundRobin = 0; dropper = new GatewayClientCleanupAgent(this); clients = new ConcurrentDictionary<Guid, ClientState>(); clientSockets = new ConcurrentDictionary<Socket, ClientState>(); proxiedGrains = new ConcurrentDictionary<GrainId, ClientState>(); clientsReplyRoutingCache = new ClientsReplyRoutingCache(messageCenter.MessagingConfiguration); this.gatewayAddress = SiloAddress.New(gatewayAddress, 0); lockable = new object(); } internal void Start() { acceptor.Start(); for (int i = 0; i < senders.Length; i++) { int capture = i; senders[capture] = new Lazy<GatewaySender>(() => { var sender = new GatewaySender("GatewaySiloSender_" + capture, this); sender.Start(); return sender; }, LazyThreadSafetyMode.ExecutionAndPublication); } dropper.Start(); } internal void Stop() { dropper.Stop(); foreach (var sender in senders) { if (sender != null && sender.IsValueCreated) sender.Value.Stop(); } acceptor.Stop(); } internal void RecordOpenedSocket(Socket sock, Guid clientId) { lock (lockable) { logger.Info(ErrorCode.GatewayClientOpenedSocket, "Recorded opened socket from endpoint {0}, client ID {1}.", sock.RemoteEndPoint, clientId); ClientState clientState; if (clients.TryGetValue(clientId, out clientState)) { var oldSocket = clientState.Socket; if (oldSocket != null) { // The old socket will be closed by itself later. ClientState ignore; clientSockets.TryRemove(oldSocket, out ignore); } clientState.RecordConnection(sock); QueueRequest(clientState, null); } else { int gatewayToUse = nextGatewaySenderToUseForRoundRobin % senders.Length; nextGatewaySenderToUseForRoundRobin++; // under Gateway lock clientState = new ClientState(clientId, gatewayToUse); clients[clientId] = clientState; clientState.RecordConnection(sock); MessagingStatisticsGroup.ConnectedClientCount.Increment(); } clientSockets[sock] = clientState; NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket(); } } internal void RecordClosedSocket(Socket sock) { if (sock == null) return; lock (lockable) { ClientState cs = null; if (!clientSockets.TryGetValue(sock, out cs)) return; EndPoint endPoint = null; try { endPoint = sock.RemoteEndPoint; } catch (Exception) { } // guard against ObjectDisposedExceptions logger.Info(ErrorCode.GatewayClientClosedSocket, "Recorded closed socket from endpoint {0}, client ID {1}.", endPoint != null ? endPoint.ToString() : "null", cs.Id); ClientState ignore; clientSockets.TryRemove(sock, out ignore); cs.RecordDisconnection(); } } internal void RecordProxiedGrain(GrainId grainId, Guid clientId) { lock (lockable) { ClientState cs; if (clients.TryGetValue(clientId, out cs)) { // TO DO done: what if we have an older proxiedGrain for this client? // We now support many proxied grains per client, so there's no need to handle it specially here. proxiedGrains.AddOrUpdate(grainId, cs, (k, v) => cs); } } } internal void RecordSendingProxiedGrain(GrainId senderGrainId, Socket clientSocket) { // not taking global lock on the crytical path! ClientState cs; if (clientSockets.TryGetValue(clientSocket, out cs)) { // TO DO done: what if we have an older proxiedGrain for this client? // We now support many proxied grains per client, so there's no need to handle it specially here. proxiedGrains.AddOrUpdate(senderGrainId, cs, (k, v) => cs); } } internal SiloAddress TryToReroute(Message msg) { // for responses from ClientAddressableObject to ClientGrain try to use clientsReplyRoutingCache for sending replies directly back. if (!msg.SendingGrain.IsClientAddressableObject || !msg.TargetGrain.IsClientGrain) return null; if (msg.Direction != Message.Directions.Response) return null; SiloAddress gateway; return clientsReplyRoutingCache.TryFindClientRoute(msg.TargetGrain, out gateway) ? gateway : null; } internal void RecordUnproxiedGrain(GrainId id) { lock (lockable) { ClientState ignore; proxiedGrains.TryRemove(id, out ignore); } } internal void DropDisconnectedClients() { lock (lockable) { List<ClientState> clientsToDrop = clients.Values.Where(cs => cs.ReadyToDrop()).ToList(); foreach (ClientState client in clientsToDrop) DropClient(client); } } internal void DropExpiredRoutingCachedEntries() { lock (lockable) { clientsReplyRoutingCache.DropExpiredEntries(); } } // This function is run under global lock // There is NO need to acquire individual ClientState lock, since we only access client Id (immutable) and close an older socket. private void DropClient(ClientState client) { logger.Info(ErrorCode.GatewayDroppingClient, "Dropping client {0}, {1} after disconnect with no reconnect", client.Id, DateTime.UtcNow.Subtract(client.DisconnectedSince)); ClientState ignore; clients.TryRemove(client.Id, out ignore); Socket oldSocket = client.Socket; if (oldSocket != null) { // this will not happen, since we drop only already disconnected clients, for socket is already null. But leave this code just to be sure. client.RecordDisconnection(); clientSockets.TryRemove(oldSocket, out ignore); SocketManager.CloseSocket(oldSocket); } List<GrainId> proxies = proxiedGrains.Where((KeyValuePair<GrainId, ClientState> pair) => pair.Value.Id.Equals(client.Id)).Select(p => p.Key).ToList(); foreach (GrainId proxy in proxies) proxiedGrains.TryRemove(proxy, out ignore); MessagingStatisticsGroup.ConnectedClientCount.DecrementBy(1); messageCenter.RecordClientDrop(proxies); } /// <summary> /// See if this message is intended for a grain we're proxying, and queue it for delivery if so. /// </summary> /// <param name="msg"></param> /// <returns>true if the message should be delivered to a proxied grain, false if not.</returns> internal bool TryDeliverToProxy(Message msg) { // See if it's a grain we're proxying. ClientState client; // not taking global lock on the crytical path! if (!proxiedGrains.TryGetValue(msg.TargetGrain, out client)) return false; if (!clients.ContainsKey(client.Id)) { lock (lockable) { if (!clients.ContainsKey(client.Id)) { ClientState ignore; // Lazy clean-up for dropped clients proxiedGrains.TryRemove(msg.TargetGrain, out ignore); // I don't think this can ever happen. When we drop the client (the only place we remove the ClientState from clients collection) // we also actively remove all proxiedGrains for this client. So the clean-up will be non lazy. // leaving it for now. return false; } } } // when this Gateway receives a message from client X to client addressale object Y // it needs to record the original Gateway address through which this message came from (the address of the Gateway that X is connected to) // it will use this Gateway to re-route the REPLY from Y back to X. if (msg.SendingGrain.IsClientGrain && msg.TargetGrain.IsClientAddressableObject) { clientsReplyRoutingCache.RecordClientRoute(msg.SendingGrain, msg.SendingSilo); } msg.TargetSilo = null; msg.SendingSilo = gatewayAddress; // This makes sure we don't expose wrong silo addresses to the client. Client will only see silo address of the Gateway it is connected to. QueueRequest(client, msg); return true; } private void QueueRequest(ClientState clientState, Message msg) { //int index = senders.Length == 1 ? 0 : Math.Abs(clientId.GetHashCode()) % senders.Length; int index = clientState.GatewaySenderNumber; senders[index].Value.QueueRequest(new OutgoingClientMessage(clientState.Id, msg)); } internal void SendMessage(Message msg) { messageCenter.SendMessage(msg); } private class ClientState { internal Queue<Message> PendingToSend { get; private set; } internal Queue<List<Message>> PendingBatchesToSend { get; private set; } internal Socket Socket { get; private set; } internal DateTime DisconnectedSince { get; private set; } internal Guid Id { get; private set; } internal int GatewaySenderNumber { get; private set; } internal bool IsConnected { get { return Socket != null; } } internal ClientState(Guid id, int gatewaySenderNumber) { Id = id; GatewaySenderNumber = gatewaySenderNumber; PendingToSend = new Queue<Message>(); PendingBatchesToSend = new Queue<List<Message>>(); } internal void RecordDisconnection() { if (Socket == null) return; DisconnectedSince = DateTime.UtcNow; Socket = null; NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket(); } internal void RecordConnection(Socket sock) { Socket = sock; DisconnectedSince = DateTime.MaxValue; } internal bool ReadyToDrop() { return !IsConnected && (DateTime.UtcNow.Subtract(DisconnectedSince) >= Gateway.TIME_BEFORE_CLIENT_DROP); } } private class GatewayClientCleanupAgent : AsynchAgent { private readonly Gateway gateway; internal GatewayClientCleanupAgent(Gateway gateway) { this.gateway = gateway; } #region Overrides of AsynchAgent protected override void Run() { while (!Cts.IsCancellationRequested) { gateway.DropDisconnectedClients(); gateway.DropExpiredRoutingCachedEntries(); Thread.Sleep(TIME_BEFORE_CLIENT_DROP); } } #endregion } // this cache is used to record the addresses of Gateways from which clients connected to. // it is used to route replies to clients from client addressable objects // without this cache this Gateway will not know how to route the reply back to the client // (since clients are not registered in the directory and this Gateway may not be proxying for the client for whom the reply is destined). private class ClientsReplyRoutingCache { // for every client: the Gateway to use to route repies back to it plus the last time that client connected via this Gateway. private readonly ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>> clientRoutes; private readonly TimeSpan TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES; internal ClientsReplyRoutingCache(IMessagingConfiguration messagingConfiguration) { clientRoutes = new ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>>(); TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES = messagingConfiguration.ResponseTimeout.Multiply(5); } internal void RecordClientRoute(GrainId client, SiloAddress gateway) { var now = DateTime.UtcNow; clientRoutes.AddOrUpdate(client, new Tuple<SiloAddress, DateTime>(gateway, now), (k, v) => new Tuple<SiloAddress, DateTime>(gateway, now)); } internal bool TryFindClientRoute(GrainId client, out SiloAddress gateway) { gateway = null; Tuple<SiloAddress, DateTime> tuple; bool ret = clientRoutes.TryGetValue(client, out tuple); if (ret) gateway = tuple.Item1; return ret; } internal void DropExpiredEntries() { List<GrainId> clientsToDrop = clientRoutes.Where(route => Expired(route.Value.Item2)).Select(kv => kv.Key).ToList(); foreach (GrainId client in clientsToDrop) { Tuple<SiloAddress, DateTime> tuple; clientRoutes.TryRemove(client, out tuple); } } private bool Expired(DateTime lastUsed) { return DateTime.UtcNow.Subtract(lastUsed) >= TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES; } } private class GatewaySender : AsynchQueueAgent<OutgoingClientMessage> { private readonly Gateway gateway; private readonly CounterStatistic gatewaySends; internal GatewaySender(string name, Gateway gateway) : base(name, gateway.MessagingConfiguration) { this.gateway = gateway; gatewaySends = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT); OnFault = FaultBehavior.RestartOnFault; } protected override void Process(OutgoingClientMessage request) { if (Cts.IsCancellationRequested) return; var client = request.Item1; var msg = request.Item2; // Find the client state ClientState clientState; bool found; lock (gateway.lockable) { found = gateway.clients.TryGetValue(client, out clientState); } // This should never happen -- but make sure to handle it reasonably, just in case if (!found || (clientState == null)) { if (msg == null) return; Log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), client); MessagingStatisticsGroup.OnFailedSentMessage(msg); // Message for unrecognized client -- reject it if (msg.Direction == Message.Directions.Request) { MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, "Unknown client " + client); gateway.SendMessage(error); } else { MessagingStatisticsGroup.OnDroppedSentMessage(msg); } return; } // if disconnected - queue for later. if (!clientState.IsConnected) { if (msg == null) return; if (Log.IsVerbose3) Log.Verbose3("Queued message {0} for client {1}", msg, client); clientState.PendingToSend.Enqueue(msg); return; } // if the queue is non empty - drain it first. if (clientState.PendingToSend.Count > 0) { if (msg != null) clientState.PendingToSend.Enqueue(msg); // For now, drain in-line, although in the future this should happen in yet another asynch agent Drain(clientState); return; } // the queue was empty AND we are connected. // If the request includes a message to send, send it (or enqueue it for later) if (msg == null) return; if (!Send(msg, clientState.Socket)) { if (Log.IsVerbose3) Log.Verbose3("Queued message {0} for client {1}", msg, client); clientState.PendingToSend.Enqueue(msg); } else { if (Log.IsVerbose3) Log.Verbose3("Sent message {0} to client {1}", msg, client); } } protected override void ProcessBatch(List<OutgoingClientMessage> requests) { if (Cts.IsCancellationRequested) return; if (requests == null || requests.Count == 0) return; // Every Tuple in requests are guaranteed to have the same client var client = requests[0].Item1; var msgs = requests.Where(r => r != null).Select(r => r.Item2).ToList(); // Find the client state ClientState clientState; bool found; lock (gateway.lockable) { found = gateway.clients.TryGetValue(client, out clientState); } // This should never happen -- but make sure to handle it reasonably, just in case if (!found || (clientState == null)) { if (msgs.Count == 0) return; Log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send {0} messages to an unrecognized client {1}. First msg {0}", msgs.Count, client, msgs[0].ToString()); foreach (var msg in msgs) { MessagingStatisticsGroup.OnFailedSentMessage(msg); // Message for unrecognized client -- reject it if (msg.Direction == Message.Directions.Request) { MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, "Unknown client " + client); gateway.SendMessage(error); } else { MessagingStatisticsGroup.OnDroppedSentMessage(msg); } } return; } // if disconnected - queue for later. if (!clientState.IsConnected) { if (msgs.Count == 0) return; if (Log.IsVerbose3) Log.Verbose3("Queued {0} messages for client {1}", msgs.Count, client); clientState.PendingBatchesToSend.Enqueue(msgs); return; } // if the queue is non empty - drain it first. if (clientState.PendingBatchesToSend.Count > 0) { if (msgs.Count != 0) clientState.PendingBatchesToSend.Enqueue(msgs); // For now, drain in-line, although in the future this should happen in yet another asynch agent DrainBatch(clientState); return; } // the queue was empty AND we are connected. // If the request includes a message to send, send it (or enqueue it for later) if (msgs.Count == 0) return; if (!SendBatch(msgs, clientState.Socket)) { if (Log.IsVerbose3) Log.Verbose3("Queued {0} messages for client {1}", msgs.Count, client); clientState.PendingBatchesToSend.Enqueue(msgs); } else { if (Log.IsVerbose3) Log.Verbose3("Sent {0} message to client {1}", msgs.Count, client); } } private void Drain(ClientState clientState) { // For now, drain in-line, although in the future this should happen in yet another asynch agent while (clientState.PendingToSend.Count > 0) { var m = clientState.PendingToSend.Peek(); if (Send(m, clientState.Socket)) { if (Log.IsVerbose3) Log.Verbose3("Sent queued message {0} to client {1}", m, clientState.Id); clientState.PendingToSend.Dequeue(); } else { return; } } } private void DrainBatch(ClientState clientState) { // For now, drain in-line, although in the future this should happen in yet another asynch agent while (clientState.PendingBatchesToSend.Count > 0) { var m = clientState.PendingBatchesToSend.Peek(); if (SendBatch(m, clientState.Socket)) { if (Log.IsVerbose3) Log.Verbose3("Sent {0} queued messages to client {1}", m.Count, clientState.Id); clientState.PendingBatchesToSend.Dequeue(); } else { return; } } } private bool Send(Message msg, Socket sock) { if (Cts.IsCancellationRequested) return false; if (sock == null) return false; // Send the message List<ArraySegment<byte>> data; int headerLength; try { data = msg.Serialize(out headerLength); } catch (Exception exc) { OnMessageSerializationFailure(msg, exc); return true; } int length = data.Sum(x => x.Count); int bytesSent = 0; bool exceptionSending = false; bool countMismatchSending = false; string sendErrorStr; try { bytesSent = sock.Send(data); if (bytesSent != length) { // The complete message wasn't sent, even though no error was reported; treat this as an error countMismatchSending = true; sendErrorStr = String.Format("Byte count mismatch on send: sent {0}, expected {1}", bytesSent, length); Log.Warn(ErrorCode.GatewayByteCountMismatch, sendErrorStr); } } catch (Exception exc) { exceptionSending = true; string remoteEndpoint = ""; if (!(exc is ObjectDisposedException)) { remoteEndpoint = sock.RemoteEndPoint.ToString(); } sendErrorStr = String.Format("Exception sending to client at {0}: {1}", remoteEndpoint, exc); Log.Warn(ErrorCode.GatewayExceptionSendingToClient, sendErrorStr, exc); } MessagingStatisticsGroup.OnMessageSend(msg.TargetSilo, msg.Direction, bytesSent, headerLength, SocketDirection.GatewayToClient); bool sendError = exceptionSending || countMismatchSending; if (sendError) { gateway.RecordClosedSocket(sock); SocketManager.CloseSocket(sock); } gatewaySends.Increment(); msg.ReleaseBodyAndHeaderBuffers(); return !sendError; } private bool SendBatch(List<Message> msgs, Socket sock) { if (Cts.IsCancellationRequested) return false; if (sock == null) return false; if (msgs == null || msgs.Count == 0) return true; // Send the message List<ArraySegment<byte>> data; int headerLengths; bool continueSend = OutgoingMessageSender.SerializeMessages(msgs, out data, out headerLengths, OnMessageSerializationFailure); if (!continueSend) return false; int length = data.Sum(x => x.Count); int bytesSent = 0; bool exceptionSending = false; bool countMismatchSending = false; string sendErrorStr; try { bytesSent = sock.Send(data); if (bytesSent != length) { // The complete message wasn't sent, even though no error was reported; treat this as an error countMismatchSending = true; sendErrorStr = String.Format("Byte count mismatch on send: sent {0}, expected {1}", bytesSent, length); Log.Warn(ErrorCode.GatewayByteCountMismatch, sendErrorStr); } } catch (Exception exc) { exceptionSending = true; string remoteEndpoint = ""; if (!(exc is ObjectDisposedException)) { remoteEndpoint = sock.RemoteEndPoint.ToString(); } sendErrorStr = String.Format("Exception sending to client at {0}: {1}", remoteEndpoint, exc); Log.Warn(ErrorCode.GatewayExceptionSendingToClient, sendErrorStr, exc); } MessagingStatisticsGroup.OnMessageBatchSend(msgs[0].TargetSilo, msgs[0].Direction, bytesSent, headerLengths, SocketDirection.GatewayToClient, msgs.Count); bool sendError = exceptionSending || countMismatchSending; if (sendError) { gateway.RecordClosedSocket(sock); SocketManager.CloseSocket(sock); } gatewaySends.Increment(); foreach (Message msg in msgs) msg.ReleaseBodyAndHeaderBuffers(); return !sendError; } private void OnMessageSerializationFailure(Message msg, Exception exc) { // we only get here if we failed to serialize the msg (or any other catastrophic failure). // Request msg fails to serialize on the sending silo, so we just enqueue a rejection msg. // Response msg fails to serialize on the responding silo, so we try to send an error response back. Log.Warn(ErrorCode.Messaging_Gateway_SerializationError, String.Format("Unexpected error serializing message {0} on the gateway", msg.ToString()), exc); msg.ReleaseBodyAndHeaderBuffers(); MessagingStatisticsGroup.OnFailedSentMessage(msg); MessagingStatisticsGroup.OnDroppedSentMessage(msg); } } } }
namespace ExportExtensionCommon { partial class Main { /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main)); this.btn_configure = new System.Windows.Forms.Button(); this.btn_capture = new System.Windows.Forms.Button(); this.btn_export = new System.Windows.Forms.Button(); this.lbl_message = new System.Windows.Forms.Label(); this.toolTip_Configure = new System.Windows.Forms.ToolTip(this.components); this.toolTip_Capture = new System.Windows.Forms.ToolTip(this.components); this.toolTip_Export = new System.Windows.Forms.ToolTip(this.components); this.richTextBox_settings = new System.Windows.Forms.RichTextBox(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.preferencesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openLocationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.cbox_extensionSelector = new System.Windows.Forms.ToolStripComboBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.lbl_status = new System.Windows.Forms.ToolStripStatusLabel(); this.chkbox_clear = new System.Windows.Forms.CheckBox(); this.btn_exit = new System.Windows.Forms.Button(); this.btn_font = new System.Windows.Forms.Button(); this.lbl_location = new System.Windows.Forms.Label(); this.pict_Icon = new System.Windows.Forms.PictureBox(); this.chbox_reloadConfiguration = new System.Windows.Forms.CheckBox(); this.chbox_ignoreEmtpyFields = new System.Windows.Forms.CheckBox(); this.menuStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pict_Icon)).BeginInit(); this.SuspendLayout(); // // btn_configure // resources.ApplyResources(this.btn_configure, "btn_configure"); this.btn_configure.Name = "btn_configure"; this.toolTip_Configure.SetToolTip(this.btn_configure, resources.GetString("btn_configure.ToolTip")); this.btn_configure.UseVisualStyleBackColor = true; this.btn_configure.Click += new System.EventHandler(this.btn_configure_Click); // // btn_capture // resources.ApplyResources(this.btn_capture, "btn_capture"); this.btn_capture.Name = "btn_capture"; this.toolTip_Capture.SetToolTip(this.btn_capture, resources.GetString("btn_capture.ToolTip")); this.btn_capture.UseVisualStyleBackColor = true; this.btn_capture.Click += new System.EventHandler(this.btn_capture_Click); // // btn_export // resources.ApplyResources(this.btn_export, "btn_export"); this.btn_export.Name = "btn_export"; this.toolTip_Export.SetToolTip(this.btn_export, resources.GetString("btn_export.ToolTip")); this.btn_export.UseVisualStyleBackColor = true; this.btn_export.Click += new System.EventHandler(this.btn_export_Click); // // lbl_message // resources.ApplyResources(this.lbl_message, "lbl_message"); this.lbl_message.Name = "lbl_message"; // // richTextBox_settings // resources.ApplyResources(this.richTextBox_settings, "richTextBox_settings"); this.richTextBox_settings.Name = "richTextBox_settings"; this.richTextBox_settings.ReadOnly = true; // // menuStrip1 // this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.cbox_extensionSelector}); resources.ApplyResources(this.menuStrip1, "menuStrip1"); this.menuStrip1.Name = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.preferencesToolStripMenuItem, this.openLocationToolStripMenuItem, this.aboutToolStripMenuItem, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem"); // // preferencesToolStripMenuItem // this.preferencesToolStripMenuItem.Name = "preferencesToolStripMenuItem"; resources.ApplyResources(this.preferencesToolStripMenuItem, "preferencesToolStripMenuItem"); this.preferencesToolStripMenuItem.Click += new System.EventHandler(this.preferencesToolStripMenuItem_Click); // // openLocationToolStripMenuItem // this.openLocationToolStripMenuItem.Name = "openLocationToolStripMenuItem"; resources.ApplyResources(this.openLocationToolStripMenuItem, "openLocationToolStripMenuItem"); this.openLocationToolStripMenuItem.Click += new System.EventHandler(this.openLocationToolStripMenuItem_Click); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; resources.ApplyResources(this.aboutToolStripMenuItem, "aboutToolStripMenuItem"); this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem"); this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // cbox_extensionSelector // resources.ApplyResources(this.cbox_extensionSelector, "cbox_extensionSelector"); this.cbox_extensionSelector.Name = "cbox_extensionSelector"; this.cbox_extensionSelector.SelectedIndexChanged += new System.EventHandler(this.cbox_extensionSelector_SelectedIndexChanged); // // statusStrip1 // this.statusStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.lbl_status}); resources.ApplyResources(this.statusStrip1, "statusStrip1"); this.statusStrip1.Name = "statusStrip1"; // // lbl_status // this.lbl_status.Name = "lbl_status"; resources.ApplyResources(this.lbl_status, "lbl_status"); // // chkbox_clear // resources.ApplyResources(this.chkbox_clear, "chkbox_clear"); //this.chkbox_clear.Checked = global::ExportExtensionCommon.Properties.Settings.Default.ClearSetting; this.chkbox_clear.CheckState = System.Windows.Forms.CheckState.Checked; this.chkbox_clear.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::ExportExtensionCommon.Properties.Settings.Default, "ClearSetting", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.chkbox_clear.Name = "chkbox_clear"; this.chkbox_clear.UseVisualStyleBackColor = true; // // btn_exit // resources.ApplyResources(this.btn_exit, "btn_exit"); this.btn_exit.Name = "btn_exit"; this.btn_exit.UseVisualStyleBackColor = true; this.btn_exit.Click += new System.EventHandler(this.btn_exit_Click); // // btn_font // resources.ApplyResources(this.btn_font, "btn_font"); this.btn_font.Name = "btn_font"; this.btn_font.UseVisualStyleBackColor = true; this.btn_font.Click += new System.EventHandler(this.btn_font_Click); // // lbl_location // resources.ApplyResources(this.lbl_location, "lbl_location"); this.lbl_location.Name = "lbl_location"; this.lbl_location.Click += new System.EventHandler(this.lbl_location_Click); // // pict_Icon // resources.ApplyResources(this.pict_Icon, "pict_Icon"); this.pict_Icon.Name = "pict_Icon"; this.pict_Icon.TabStop = false; // // chbox_reloadConfiguration // resources.ApplyResources(this.chbox_reloadConfiguration, "chbox_reloadConfiguration"); //this.chbox_reloadConfiguration.Checked = global::ExportExtensionCommon.Properties.Settings.Default.ReloadConfiguration; this.chbox_reloadConfiguration.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::ExportExtensionCommon.Properties.Settings.Default, "ReloadConfiguration", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.chbox_reloadConfiguration.Name = "chbox_reloadConfiguration"; this.chbox_reloadConfiguration.UseVisualStyleBackColor = true; // // chbox_ignoreEmtpyFields // resources.ApplyResources(this.chbox_ignoreEmtpyFields, "chbox_ignoreEmtpyFields"); this.chbox_ignoreEmtpyFields.Name = "chbox_ignoreEmtpyFields"; this.chbox_ignoreEmtpyFields.UseVisualStyleBackColor = true; // // Main // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.chbox_ignoreEmtpyFields); this.Controls.Add(this.chbox_reloadConfiguration); this.Controls.Add(this.pict_Icon); this.Controls.Add(this.lbl_location); this.Controls.Add(this.btn_font); this.Controls.Add(this.btn_exit); this.Controls.Add(this.chkbox_clear); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.richTextBox_settings); this.Controls.Add(this.lbl_message); this.Controls.Add(this.btn_export); this.Controls.Add(this.btn_capture); this.Controls.Add(this.btn_configure); this.Controls.Add(this.menuStrip1); this.DataBindings.Add(new System.Windows.Forms.Binding("Location", global::ExportExtensionCommon.Properties.Settings.Default, "MainLocation", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); //this.Location = global::ExportExtensionCommon.Properties.Settings.Default.MainLocation; this.MainMenuStrip = this.menuStrip1; this.Name = "Main"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_Closing); this.Load += new System.EventHandler(this.Main_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pict_Icon)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btn_configure; private System.Windows.Forms.Button btn_capture; private System.Windows.Forms.Button btn_export; private System.Windows.Forms.Label lbl_message; private System.Windows.Forms.ToolTip toolTip_Configure; private System.Windows.Forms.ToolTip toolTip_Capture; private System.Windows.Forms.ToolTip toolTip_Export; private System.Windows.Forms.RichTextBox richTextBox_settings; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openLocationToolStripMenuItem; private System.Windows.Forms.ToolStripComboBox cbox_extensionSelector; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel lbl_status; private System.Windows.Forms.CheckBox chkbox_clear; private System.Windows.Forms.ToolStripMenuItem preferencesToolStripMenuItem; private System.Windows.Forms.Button btn_exit; private System.Windows.Forms.Button btn_font; private System.Windows.Forms.Label lbl_location; private System.Windows.Forms.PictureBox pict_Icon; private System.Windows.Forms.CheckBox chbox_reloadConfiguration; private System.Windows.Forms.CheckBox chbox_ignoreEmtpyFields; } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using AutoMoq; using FizzWare.NBuilder; using Moq; using Sample.Core.Models; using Sample.Core.Repositories; using Sample.Core.Services; namespace Sample.Tests.Core.Services { [TestClass] public class RoleServiceTests { #region Helpers/Test Initializers private AutoMoqer Mocker { get; set; } private Mock<IRoleRepository> MockRepo { get; set; } private RoleService SubjectUnderTest { get; set; } [TestInitialize] public void TestInitialize() { Mocker = new AutoMoqer(); SubjectUnderTest = Mocker.Create<RoleService>(); MockRepo = Mocker.GetMock<IRoleRepository>(); } #endregion #region Tests [TestMethod] public void RoleService_Should_GetMany() { // arrange var expected = Builder<Role>.CreateListOfSize(10).Build(); MockRepo.Setup(x => x.Get()).Returns(expected); // act var actual = SubjectUnderTest.Get(); // assert CollectionAssert.AreEqual(expected as ICollection, actual as ICollection); MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_GetOne() { // arrange var expected = Builder<Role>.CreateNew().Build(); MockRepo.Setup(x => x.Get(expected.Id)).Returns(expected); // act var actual = SubjectUnderTest.Get(expected.Id); // assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Id, actual.Id); Assert.AreEqual(expected.Name, actual.Name); Assert.AreEqual(expected.CreatedAt, actual.CreatedAt); Assert.AreEqual(expected.UpdatedAt, actual.UpdatedAt); MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_Save() { // arrange var expected = Builder<Role>.CreateNew().Build(); MockRepo.Setup(x => x.Save(expected)); // act SubjectUnderTest.Save(expected); // assert MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_Save_Many() { // arrange var expected = Builder<Role>.CreateListOfSize(10).Build(); MockRepo.Setup(x => x.Save(expected)); // act SubjectUnderTest.Save(expected); // assert MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_Insert() { // arrange var expected = Builder<Role>.CreateNew().Build(); MockRepo.Setup(x => x.Insert(expected)); // act SubjectUnderTest.Insert(expected); // assert MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_Insert_Many() { // arrange var expected = Builder<Role>.CreateListOfSize(10).Build(); MockRepo.Setup(x => x.Insert(expected)); // act SubjectUnderTest.Insert(expected); // assert MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_Update() { // arrange var expected = Builder<Role>.CreateNew().Build(); MockRepo.Setup(x => x.Update(expected)); // act SubjectUnderTest.Update(expected); // assert MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_Update_Many() { // arrange var expected = Builder<Role>.CreateListOfSize(10).Build(); MockRepo.Setup(x => x.Update(expected)); // act SubjectUnderTest.Update(expected); // assert MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_Delete() { // arrange var expected = Builder<Role>.CreateNew().Build(); MockRepo.Setup(x => x.Delete(expected)); // act SubjectUnderTest.Delete(expected); // assert MockRepo.VerifyAll(); } [TestMethod] public void RoleService_Should_Delete_Many() { // arrange var expected = Builder<Role>.CreateListOfSize(10).Build(); MockRepo.Setup(x => x.Delete(expected)); // act SubjectUnderTest.Delete(expected); // assert MockRepo.VerifyAll(); } #endregion } }
using System; using System.Linq.Expressions; using System.Reflection; namespace AutoMapper { /// <summary> /// Member configuration options /// </summary> /// <typeparam name="TSource">Source type for this member</typeparam> /// <typeparam name="TMember">Type for this member</typeparam> /// <typeparam name="TDestination">Destination type for this map</typeparam> public interface IMemberConfigurationExpression<TSource, TDestination, TMember> : IProjectionMemberConfiguration<TSource, TDestination, TMember> { /// <summary> /// Do not precompute the execution plan for this member, just map it at runtime. /// Simplifies the execution plan by not inlining. /// </summary> void MapAtRuntime(); /// <summary> /// Map destination member using a custom value resolver /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <typeparam name="TValueResolver">Value resolver type</typeparam> void MapFrom<TValueResolver>() where TValueResolver : IValueResolver<TSource, TDestination, TMember>; /// <summary> /// Map destination member using a custom member value resolver supplied with a source member /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <typeparam name="TValueResolver">Value resolver type</typeparam> /// <typeparam name="TSourceMember">Source member to supply</typeparam> void MapFrom<TValueResolver, TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember) where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>; /// <summary> /// Map destination member using a custom member value resolver supplied from a source member name /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <typeparam name="TValueResolver">Value resolver type</typeparam> /// <typeparam name="TSourceMember">Source member to supply</typeparam> /// <param name="sourceMemberName">Source member name</param> void MapFrom<TValueResolver, TSourceMember>(string sourceMemberName) where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>; /// <summary> /// Map destination member using a custom value resolver instance /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="valueResolver">Value resolver instance to use</param> void MapFrom(IValueResolver<TSource, TDestination, TMember> valueResolver); /// <summary> /// Map destination member using a custom value resolver instance /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="valueResolver">Value resolver instance to use</param> /// <param name="sourceMember">Source member to supply to value resolver</param> void MapFrom<TSourceMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember> valueResolver, Expression<Func<TSource, TSourceMember>> sourceMember); /// <summary> /// Map destination member using a custom function. Access both the source and destination object. /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="mappingFunction">Function to map to destination member</param> void MapFrom<TResult>(Func<TSource, TDestination, TResult> mappingFunction); /// <summary> /// Map destination member using a custom function. Access the source, destination object, and destination member. /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="mappingFunction">Function to map to destination member</param> void MapFrom<TResult>(Func<TSource, TDestination, TMember, TResult> mappingFunction); /// <summary> /// Map destination member using a custom function. Access the source, destination object, destination member, and context. /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="mappingFunction">Function to map to destination member</param> void MapFrom<TResult>(Func<TSource, TDestination, TMember, ResolutionContext, TResult> mappingFunction); /// <summary> /// Specify the source member(s) to map from. /// </summary> /// <param name="sourceMembersPath">Property name referencing the source member to map against. Or a dot separated member path.</param> void MapFrom(string sourceMembersPath); /// <summary> /// Supply a custom mapping order instead of what the .NET runtime returns /// </summary> /// <param name="mappingOrder">Mapping order value</param> void SetMappingOrder(int mappingOrder); /// <summary> /// Reset UseDestinationValue. /// </summary> void DoNotUseDestinationValue(); /// <summary> /// Use the destination value instead of mapping from the source value or creating a new instance /// </summary> void UseDestinationValue(); /// <summary> /// Conditionally map this member against the source, destination, source and destination members /// </summary> /// <param name="condition">Condition to evaluate using the source object</param> void Condition(Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool> condition); /// <summary> /// Conditionally map this member /// </summary> /// <param name="condition">Condition to evaluate using the source object</param> void Condition(Func<TSource, TDestination, TMember, TMember, bool> condition); /// <summary> /// Conditionally map this member /// </summary> /// <param name="condition">Condition to evaluate using the source object</param> void Condition(Func<TSource, TDestination, TMember, bool> condition); /// <summary> /// Conditionally map this member /// </summary> /// <param name="condition">Condition to evaluate using the source object</param> void Condition(Func<TSource, TDestination, bool> condition); /// <summary> /// Conditionally map this member /// </summary> /// <param name="condition">Condition to evaluate using the source object</param> void Condition(Func<TSource, bool> condition); /// <summary> /// Conditionally map this member, evaluated before accessing the source value /// </summary> /// <param name="condition">Condition to evaluate using the source object</param> void PreCondition(Func<TSource, bool> condition); /// <summary> /// Conditionally map this member, evaluated before accessing the source value /// </summary> /// <param name="condition">Condition to evaluate using the current resolution context</param> void PreCondition(Func<ResolutionContext, bool> condition); /// <summary> /// Conditionally map this member, evaluated before accessing the source value /// </summary> /// <param name="condition">Condition to evaluate using the source object and the current resolution context</param> void PreCondition(Func<TSource, ResolutionContext, bool> condition); /// <summary> /// Conditionally map this member, evaluated before accessing the source value /// </summary> /// <param name="condition">Condition to evaluate using the source object, the destination object, and the current resolution context</param> void PreCondition(Func<TSource, TDestination, ResolutionContext, bool> condition); /// <summary> /// The destination member being configured. /// </summary> MemberInfo DestinationMember { get; } /// <summary> /// Specify a value converter to convert from the matching source member to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <typeparam name="TValueConverter">Value converter type</typeparam> /// <typeparam name="TSourceMember">Source member type</typeparam> void ConvertUsing<TValueConverter, TSourceMember>() where TValueConverter : IValueConverter<TSourceMember, TMember>; /// <summary> /// Specify a value converter to convert from the specified source member to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <typeparam name="TValueConverter">Value converter type</typeparam> /// <typeparam name="TSourceMember">Source member type</typeparam> /// <param name="sourceMember">Source member to supply to the value converter</param> void ConvertUsing<TValueConverter, TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember) where TValueConverter : IValueConverter<TSourceMember, TMember>; /// <summary> /// Specify a value converter to convert from the specified source member name to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <typeparam name="TValueConverter">Value converter type</typeparam> /// <typeparam name="TSourceMember">Source member type</typeparam> /// <param name="sourceMemberName">Source member name to supply to the value converter</param> void ConvertUsing<TValueConverter, TSourceMember>(string sourceMemberName) where TValueConverter : IValueConverter<TSourceMember, TMember>; /// <summary> /// Specify a value converter instance to convert from the matching source member to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <typeparam name="TSourceMember">Source member type</typeparam> /// <param name="valueConverter">Value converter instance</param> void ConvertUsing<TSourceMember>(IValueConverter<TSourceMember, TMember> valueConverter); /// <summary> /// Specify a value converter instance from the specified source member to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <typeparam name="TSourceMember">Source member type</typeparam> /// <param name="valueConverter">Value converter instance</param> /// <param name="sourceMember">Source member to supply to the value converter</param> void ConvertUsing<TSourceMember>(IValueConverter<TSourceMember, TMember> valueConverter, Expression<Func<TSource, TSourceMember>> sourceMember); /// <summary> /// Specify a value converter instance to convert from the specified source member name to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <typeparam name="TSourceMember">Source member type</typeparam> /// <param name="valueConverter">Value converter instance</param> /// <param name="sourceMemberName">Source member name to supply to the value converter</param> void ConvertUsing<TSourceMember>(IValueConverter<TSourceMember, TMember> valueConverter, string sourceMemberName); } /// <summary> /// Configuration options for an individual member /// </summary> public interface IMemberConfigurationExpression : IMemberConfigurationExpression<object, object, object> { /// <summary> /// Map destination member using a custom value resolver. Used when the value resolver is not known at compile-time /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="valueResolverType">Value resolver type</param> void MapFrom(Type valueResolverType); /// <summary> /// Map destination member using a custom value resolver. Used when the value resolver is not known at compile-time /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="valueResolverType">Value resolver type</param> /// <param name="sourceMemberName">Member to supply to value resolver</param> void MapFrom(Type valueResolverType, string sourceMemberName); /// <summary> /// Map destination member using a custom value resolver instance /// </summary> /// <remarks>Not used for LINQ projection (ProjectTo)</remarks> /// <param name="valueResolver">Value resolver instance to use</param> /// <param name="sourceMemberName">Source member to supply to value resolver</param> void MapFrom<TSource, TDestination, TSourceMember, TDestMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TDestMember> valueResolver, string sourceMemberName); /// <summary> /// Specify a value converter type to convert from the matching source member to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <param name="valueConverterType">Value converter type</param> void ConvertUsing(Type valueConverterType); /// <summary> /// Specify a value converter type to convert from the specified source member name to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <param name="valueConverterType">Value converter type</param> /// <param name="sourceMemberName">Source member name to supply to the value converter</param> void ConvertUsing(Type valueConverterType, string sourceMemberName); /// <summary> /// Specify a value converter instance to convert from the specified source member name to the destination member /// </summary> /// <remarks> /// Value converters are similar to type converters, but scoped to a single member. Value resolvers receive the enclosed source/destination objects as parameters. /// Value converters do not. This makes it possible to reuse value converters across multiple members and multiple maps. /// </remarks> /// <typeparam name="TSourceMember">Source member type</typeparam> /// <typeparam name="TDestinationMember">Destination member type</typeparam> /// <param name="valueConverter">Value converter instance</param> /// <param name="sourceMemberName">Source member name to supply to the value converter</param> void ConvertUsing<TSourceMember, TDestinationMember>(IValueConverter<TSourceMember, TDestinationMember> valueConverter, string sourceMemberName); } /// <summary> /// Member configuration options /// </summary> /// <typeparam name="TSource">Source type for this member</typeparam> /// <typeparam name="TMember">Type for this member</typeparam> /// <typeparam name="TDestination">Destination type for this map</typeparam> public interface IProjectionMemberConfiguration<TSource, TDestination, TMember> { /// <summary> /// Substitute a custom value when the source member resolves as null /// </summary> /// <param name="nullSubstitute">Value to use</param> void NullSubstitute(object nullSubstitute); /// <summary> /// Map destination member using a custom expression. Used in LINQ projection (ProjectTo). /// </summary> /// <typeparam name="TSourceMember">Member type of the source member to use</typeparam> /// <param name="mapExpression">Map expression</param> void MapFrom<TSourceMember>(Expression<Func<TSource, TSourceMember>> mapExpression); /// <summary> /// Ignore this member for configuration validation and skip during mapping /// </summary> void Ignore(); /// <summary> /// Allow this member to be null. Overrides AllowNullDestinationValues/AllowNullCollection. /// </summary> void AllowNull(); /// <summary> /// Don't allow this member to be null. Overrides AllowNullDestinationValues/AllowNullCollection. /// </summary> void DoNotAllowNull(); /// <summary> /// Ignore this member for LINQ projections unless explicitly expanded during projection /// </summary> void ExplicitExpansion(); /// <summary> /// Apply a transformation function after any resolved destination member value with the given type /// </summary> /// <param name="transformer">Transformation expression</param> void AddTransform(Expression<Func<TMember, TMember>> transformer); } /// <summary> /// Converts a source member value to a destination member value /// </summary> /// <typeparam name="TSourceMember">Source member type</typeparam> /// <typeparam name="TDestinationMember">Destination member type</typeparam> public interface IValueConverter<in TSourceMember, out TDestinationMember> { /// <summary> /// Perform conversion from source member value to destination member value /// </summary> /// <param name="sourceMember">Source member object</param> /// <param name="context">Resolution context</param> /// <returns>Destination member value</returns> TDestinationMember Convert(TSourceMember sourceMember, ResolutionContext context); } /// <summary> /// Extension point to provide custom resolution for a destination value /// </summary> public interface IValueResolver<in TSource, in TDestination, TDestMember> { /// <summary> /// Implementors use source object to provide a destination object. /// </summary> /// <param name="source">Source object</param> /// <param name="destination">Destination object, if exists</param> /// <param name="destMember">Destination member</param> /// <param name="context">The context of the mapping</param> /// <returns>Result, typically build from the source resolution result</returns> TDestMember Resolve(TSource source, TDestination destination, TDestMember destMember, ResolutionContext context); } /// <summary> /// Extension point to provide custom resolution for a destination value /// </summary> public interface IMemberValueResolver<in TSource, in TDestination, in TSourceMember, TDestMember> { /// <summary> /// Implementors use source object to provide a destination object. /// </summary> /// <param name="source">Source object</param> /// <param name="destination">Destination object, if exists</param> /// <param name="sourceMember">Source member</param> /// <param name="destMember">Destination member</param> /// <param name="context">The context of the mapping</param> /// <returns>Result, typically build from the source resolution result</returns> TDestMember Resolve(TSource source, TDestination destination, TSourceMember sourceMember, TDestMember destMember, ResolutionContext context); } }
using System; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Paddings; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Macs { /** * DES based CBC Block Cipher MAC according to ISO9797, algorithm 3 (ANSI X9.19 Retail MAC) * * This could as well be derived from CBCBlockCipherMac, but then the property mac in the base * class must be changed to protected */ public class ISO9797Alg3Mac : IMac { private byte[] mac; private byte[] buf; private int bufOff; private IBlockCipher cipher; private IBlockCipherPadding padding; private int macSize; private KeyParameter lastKey2; private KeyParameter lastKey3; /** * create a Retail-MAC based on a CBC block cipher. This will produce an * authentication code of the length of the block size of the cipher. * * @param cipher the cipher to be used as the basis of the MAC generation. This must * be DESEngine. */ public ISO9797Alg3Mac( IBlockCipher cipher) : this(cipher, cipher.GetBlockSize() * 8, null) { } /** * create a Retail-MAC based on a CBC block cipher. This will produce an * authentication code of the length of the block size of the cipher. * * @param cipher the cipher to be used as the basis of the MAC generation. * @param padding the padding to be used to complete the last block. */ public ISO9797Alg3Mac( IBlockCipher cipher, IBlockCipherPadding padding) : this(cipher, cipher.GetBlockSize() * 8, padding) { } /** * create a Retail-MAC based on a block cipher with the size of the * MAC been given in bits. This class uses single DES CBC mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. */ public ISO9797Alg3Mac( IBlockCipher cipher, int macSizeInBits) : this(cipher, macSizeInBits, null) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses single DES CBC mode as the basis for the * MAC generation. The final block is decrypted and then encrypted using the * middle and right part of the key. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding the padding to be used to complete the last block. */ public ISO9797Alg3Mac( IBlockCipher cipher, int macSizeInBits, IBlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) throw new ArgumentException("MAC size must be multiple of 8"); if (!(cipher is DesEngine)) throw new ArgumentException("cipher must be instance of DesEngine"); this.cipher = new CbcBlockCipher(cipher); this.padding = padding; this.macSize = macSizeInBits / 8; mac = new byte[cipher.GetBlockSize()]; buf = new byte[cipher.GetBlockSize()]; bufOff = 0; } public string AlgorithmName { get { return "ISO9797Alg3"; } } public void Init( ICipherParameters parameters) { Reset(); if (!(parameters is KeyParameter || parameters is ParametersWithIV)) throw new ArgumentException("parameters must be an instance of KeyParameter or ParametersWithIV"); // KeyParameter must contain a double or triple length DES key, // however the underlying cipher is a single DES. The middle and // right key are used only in the final step. KeyParameter kp; if (parameters is KeyParameter) { kp = (KeyParameter)parameters; } else { kp = (KeyParameter)((ParametersWithIV)parameters).Parameters; } KeyParameter key1; byte[] keyvalue = kp.GetKey(); if (keyvalue.Length == 16) { // Double length DES key key1 = new KeyParameter(keyvalue, 0, 8); this.lastKey2 = new KeyParameter(keyvalue, 8, 8); this.lastKey3 = key1; } else if (keyvalue.Length == 24) { // Triple length DES key key1 = new KeyParameter(keyvalue, 0, 8); this.lastKey2 = new KeyParameter(keyvalue, 8, 8); this.lastKey3 = new KeyParameter(keyvalue, 16, 8); } else { throw new ArgumentException("Key must be either 112 or 168 bit long"); } if (parameters is ParametersWithIV) { cipher.Init(true, new ParametersWithIV(key1, ((ParametersWithIV)parameters).GetIV())); } else { cipher.Init(true, key1); } } public int GetMacSize() { return macSize; } public void Update( byte input) { if (bufOff == buf.Length) { cipher.ProcessBlock(buf, 0, mac, 0); bufOff = 0; } buf[bufOff++] = input; } public void BlockUpdate( byte[] input, int inOff, int len) { if (len < 0) throw new ArgumentException("Can't have a negative input length!"); int blockSize = cipher.GetBlockSize(); int resultLen = 0; int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; while (len > blockSize) { resultLen += cipher.ProcessBlock(input, inOff, mac, 0); len -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, len); bufOff += len; } public int DoFinal( byte[] output, int outOff) { int blockSize = cipher.GetBlockSize(); if (padding == null) { // pad with zeroes while (bufOff < blockSize) { buf[bufOff++] = 0; } } else { if (bufOff == blockSize) { cipher.ProcessBlock(buf, 0, mac, 0); bufOff = 0; } padding.AddPadding(buf, bufOff); } cipher.ProcessBlock(buf, 0, mac, 0); // Added to code from base class DesEngine deseng = new DesEngine(); deseng.Init(false, this.lastKey2); deseng.ProcessBlock(mac, 0, mac, 0); deseng.Init(true, this.lastKey3); deseng.ProcessBlock(mac, 0, mac, 0); // **** Array.Copy(mac, 0, output, outOff, macSize); Reset(); return macSize; } /** * Reset the mac generator. */ public void Reset() { Array.Clear(buf, 0, buf.Length); bufOff = 0; // reset the underlying cipher. cipher.Reset(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace Isle.DataContracts { [DataContract] public class OrganizationDataContract : BaseContract { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string Notes { get; set; } [DataMember] public int ParentId { get; set; } [DataMember] public int PrimaryContactId { get; set; } [DataMember] public int Lwia { get; set; } [DataMember] public int IwdsOfficeId { get; set; } [DataMember] public bool IsActive { get; set; } [DataMember] public string InactiveExplanation { get; set; } [DataMember] public string MainPhone { get; set; } [DataMember] public string MainExtension { get; set; } [DataMember] public string AltPhone { get; set; } [DataMember] public string AltExtension { get; set; } [DataMember] public string Fax { get; set; } [DataMember] public string TTY { get; set; } [DataMember] public string WebSite { get; set; } [DataMember] public string Email { get; set; } [DataMember] public string Address { get; set; } [DataMember] public string Address2 { get; set; } [DataMember] public string City { get; set; } [DataMember] public string State { get; set; } [DataMember] public string Zipcode { get; set; } [DataMember] public string Services { get; set; } [DataMember] public int AvgWalkin { get; set; } [DataMember] public string DescClientele { get; set; } [DataMember] public int NumStaff { get; set; } [DataMember] public bool TechRequirements { get; set; } [DataMember] public int NumCompInternet { get; set; } [DataMember] public bool HighSpeedInternet { get; set; } [DataMember] public bool IsComprehensive { get; set; } [DataMember] public bool IsSatellite { get; set; } [DataMember] public bool HasBilingual { get; set; } [DataMember] public string BilingualDesc { get; set; } [DataMember] public bool HasSpanish { get; set; } [DataMember] public string SpanishDesc { get; set; } [DataMember] public bool WIAFunded { get; set; } [DataMember] public bool IsEducational { get; set; } [DataMember] public bool IsCBO { get; set; } [DataMember] public bool IsFaithBased { get; set; } [DataMember] public bool IsStateAgency { get; set; } [DataMember] public bool IsLibrary { get; set; } [DataMember] public bool IsCommCenter { get; set; } [DataMember] public bool IsSocialService { get; set; } [DataMember] public bool IsPrivateSector { get; set; } [DataMember] public bool AccessDissem { get; set; } [DataMember] public DateTime Created { get; set; } [DataMember] public string CreatedBy { get; set; } [DataMember] public DateTime LastUpdated { get; set; } [DataMember] public string LastUpdatedBy { get; set; } [DataMember] public int AffiliatesId { get; set; } [DataMember] public DateTime Timestamp { get; set; } [DataMember] public string SiteStatus { get; set; } [DataMember] public string WorknetSetupStatus { get; set; } [DataMember] public string ContentManagementStatus { get; set; } [DataMember] public string AdditionalTrainingReq { get; set; } [DataMember] public string CompSatelliteType { get; set; } [DataMember] public string SiteType { get; set; } [DataMember] public string StaffingDesc { get; set; } [DataMember] public int IwdsOfficeNbr { get; set; } [DataMember] public short IwdsSiteType { get; set; } [DataMember] public bool IsResourceRoom { get; set; } [DataMember] public string ContactEmail { get; set; } [DataMember] public bool IsLwia { get; set; } [DataMember] public int OrgPathwayId { get; set; } [DataMember] public bool IsSiteComplete { get; set; } [DataMember] public int LogoId { get; set; } [DataMember] public bool IsStateAgencyHO { get; set; } [DataMember] public bool IsDigitalDivide { get; set; } [DataMember] public Guid RowId { get; set; } [DataMember] public bool CanIssueEAVouchers { get; set; } [DataMember] public bool IsEAExamProctor { get; set; } [DataMember] public int OrgTypeId { get; set; } [DataMember] public string ExternalIdentifier { get; set; } } }//
using UnityEngine; using System.Collections; /* Detonator - A parametric explosion system for Unity Created by Ben Throop in August 2009 for the Unity Summer of Code Simplest use case: 1) Use a prefab OR 1) Attach a Detonator to a GameObject, either through code or the Unity UI 2) Either set the Detonator's ExplodeOnStart = true or call Explode() yourself when the time is right 3) View explosion :)f Medium Complexity Use Case: 1) Attach a Detonator as above 2) Change parameters, add your own materials, etc 3) Explode() 4) View Explosion Super Fun Use Case: 1) Attach a Detonator as above 2) Drag one or more DetonatorComponents to that same GameObject 3) Tweak those parameters 4) Explode() 5) View Explosion Better documentation is included as a PDF with this package, or is available online. Check the Unity site for a link or visit my site, listed below. Ben Throop @ben_throop */ [AddComponentMenu("Detonator/Detonator")] public class Detonator : MonoBehaviour { public GameObject[] powerUps; public GameObject[] baddies; private static float _baseSize = 30f; private static Color _baseColor = new Color (1f, .423f, 0f, .5f); private static float _baseDuration = 3f; /* _baseSize reflects the size that DetonatorComponents at size 1 match. Yes, this is really big (30m) size below is the default Detonator size, which is more reasonable for typical useage. It wasn't my intention for them to be different, and I may change that, but for now, that's how it is. */ public float size = 10f; public Color color = Detonator._baseColor; public bool explodeOnStart = true; public float duration = Detonator._baseDuration; public float detail = 1f; public float upwardsBias = 0f; public float destroyTime = 7f; //sorry this is not auto calculated... yet. public bool useWorldSpace = true; public Vector3 direction = Vector3.zero; public Material fireballAMaterial; public Material fireballBMaterial; public Material smokeAMaterial; public Material smokeBMaterial; public Material shockwaveMaterial; public Material sparksMaterial; public Material glowMaterial; public Material heatwaveMaterial; private Component[] components; private DetonatorFireball _fireball; private DetonatorSparks _sparks; private DetonatorShockwave _shockwave; private DetonatorSmoke _smoke; private DetonatorGlow _glow; private DetonatorLight _light; private DetonatorForce _force; private DetonatorHeatwave _heatwave; public bool autoCreateFireball = true; public bool autoCreateSparks = true; public bool autoCreateShockwave = true; public bool autoCreateSmoke = true; public bool autoCreateGlow = true; public bool autoCreateLight = true; public bool autoCreateForce = true; public bool autoCreateHeatwave = false; void Awake () { FillDefaultMaterials (); components = this.GetComponents (typeof(DetonatorComponent)); foreach (DetonatorComponent dc in components) { if (dc is DetonatorFireball) { _fireball = dc as DetonatorFireball; } if (dc is DetonatorSparks) { _sparks = dc as DetonatorSparks; } if (dc is DetonatorShockwave) { _shockwave = dc as DetonatorShockwave; } if (dc is DetonatorSmoke) { _smoke = dc as DetonatorSmoke; } if (dc is DetonatorGlow) { _glow = dc as DetonatorGlow; } if (dc is DetonatorLight) { _light = dc as DetonatorLight; } if (dc is DetonatorForce) { _force = dc as DetonatorForce; } if (dc is DetonatorHeatwave) { _heatwave = dc as DetonatorHeatwave; } } if (!_fireball && autoCreateFireball) { _fireball = gameObject.AddComponent<DetonatorFireball> () as DetonatorFireball; _fireball.Reset (); } if (!_smoke && autoCreateSmoke) { _smoke = gameObject.AddComponent<DetonatorSmoke> () as DetonatorSmoke; _smoke.Reset (); } if (!_sparks && autoCreateSparks) { _sparks = gameObject.AddComponent<DetonatorSparks> () as DetonatorSparks; _sparks.Reset (); } if (!_shockwave && autoCreateShockwave) { _shockwave = gameObject.AddComponent<DetonatorShockwave> () as DetonatorShockwave; _shockwave.Reset (); } if (!_glow && autoCreateGlow) { _glow = gameObject.AddComponent<DetonatorGlow> () as DetonatorGlow; _glow.Reset (); } if (!_light && autoCreateLight) { _light = gameObject.AddComponent<DetonatorLight> () as DetonatorLight; _light.Reset (); } if (!_force && autoCreateForce) { _force = gameObject.AddComponent<DetonatorForce> () as DetonatorForce; _force.Reset (); } if (!_heatwave && autoCreateHeatwave && SystemInfo.supportsImageEffects) { _heatwave = gameObject.AddComponent<DetonatorHeatwave> () as DetonatorHeatwave; _heatwave.Reset (); } components = this.GetComponents (typeof(DetonatorComponent)); } void FillDefaultMaterials () { if (!fireballAMaterial) fireballAMaterial = DefaultFireballAMaterial (); if (!fireballBMaterial) fireballBMaterial = DefaultFireballBMaterial (); if (!smokeAMaterial) smokeAMaterial = DefaultSmokeAMaterial (); if (!smokeBMaterial) smokeBMaterial = DefaultSmokeBMaterial (); if (!shockwaveMaterial) shockwaveMaterial = DefaultShockwaveMaterial (); if (!sparksMaterial) sparksMaterial = DefaultSparksMaterial (); if (!glowMaterial) glowMaterial = DefaultGlowMaterial (); if (!heatwaveMaterial) heatwaveMaterial = DefaultHeatwaveMaterial (); } void Start () { if (explodeOnStart) { UpdateComponents (); this.Explode (); } } private float _lastExplosionTime = 1000f; void Update () { if (destroyTime > 0f) { if (_lastExplosionTime + destroyTime <= Time.time) { int random = Random.Range (0, 2); if (random == 0) { int rand = Random.Range (0, powerUps.Length); Object.Instantiate (powerUps [rand], transform.position, transform.rotation); } else { int randBad = Random.Range (0, baddies.Length); Object.Instantiate (baddies [randBad], transform.position, transform.rotation); } Destroy (gameObject); } } } private bool _firstComponentUpdate = true; void UpdateComponents () { if (_firstComponentUpdate) { foreach (DetonatorComponent component in components) { component.Init (); component.SetStartValues (); } _firstComponentUpdate = false; } if (!_firstComponentUpdate) { float s = size / _baseSize; Vector3 sdir = new Vector3 (direction.x * s, direction.y * s, direction.z * s); float d = duration / _baseDuration; foreach (DetonatorComponent component in components) { if (component.detonatorControlled) { component.size = component.startSize * s; component.timeScale = d; component.detail = component.startDetail * detail; component.force = new Vector3 (component.startForce.x * s + sdir.x, component.startForce.y * s + sdir.y, component.startForce.z * s + sdir.z); component.velocity = new Vector3 (component.startVelocity.x * s + sdir.x, component.startVelocity.y * s + sdir.y, component.startVelocity.z * s + sdir.z); //take the alpha of detonator color and consider it a weight - 1=use all detonator, 0=use all components component.color = Color.Lerp (component.startColor, color, color.a); } } } } private Component[] _subDetonators; public void Explode () { _lastExplosionTime = Time.time; foreach (DetonatorComponent component in components) { UpdateComponents (); component.Explode (); } } public void Reset () { size = 10f; //this is hardcoded because _baseSize up top is not really the default as much as what we match to color = _baseColor; duration = _baseDuration; FillDefaultMaterials (); } //Default Materials //The statics are so that even if there are multiple Detonators in the world, they //don't each create their own default materials. Theoretically this will reduce draw calls, but I haven't really //tested that. public static Material defaultFireballAMaterial; public static Material defaultFireballBMaterial; public static Material defaultSmokeAMaterial; public static Material defaultSmokeBMaterial; public static Material defaultShockwaveMaterial; public static Material defaultSparksMaterial; public static Material defaultGlowMaterial; public static Material defaultHeatwaveMaterial; public static Material DefaultFireballAMaterial () { if (defaultFireballAMaterial != null) return defaultFireballAMaterial; defaultFireballAMaterial = new Material (Shader.Find ("Particles/Additive")); defaultFireballAMaterial.name = "FireballA-Default"; Texture2D tex = Resources.Load ("Detonator/Textures/Fireball") as Texture2D; defaultFireballAMaterial.SetColor ("_TintColor", Color.white); defaultFireballAMaterial.mainTexture = tex; defaultFireballAMaterial.mainTextureScale = new Vector2 (0.5f, 1f); return defaultFireballAMaterial; } public static Material DefaultFireballBMaterial () { if (defaultFireballBMaterial != null) return defaultFireballBMaterial; defaultFireballBMaterial = new Material (Shader.Find ("Particles/Additive")); defaultFireballBMaterial.name = "FireballB-Default"; Texture2D tex = Resources.Load ("Detonator/Textures/Fireball") as Texture2D; defaultFireballBMaterial.SetColor ("_TintColor", Color.white); defaultFireballBMaterial.mainTexture = tex; defaultFireballBMaterial.mainTextureScale = new Vector2 (0.5f, 1f); defaultFireballBMaterial.mainTextureOffset = new Vector2 (0.5f, 0f); return defaultFireballBMaterial; } public static Material DefaultSmokeAMaterial () { if (defaultSmokeAMaterial != null) return defaultSmokeAMaterial; defaultSmokeAMaterial = new Material (Shader.Find ("Particles/Alpha Blended")); defaultSmokeAMaterial.name = "SmokeA-Default"; Texture2D tex = Resources.Load ("Detonator/Textures/Smoke") as Texture2D; defaultSmokeAMaterial.SetColor ("_TintColor", Color.white); defaultSmokeAMaterial.mainTexture = tex; defaultSmokeAMaterial.mainTextureScale = new Vector2 (0.5f, 1f); return defaultSmokeAMaterial; } public static Material DefaultSmokeBMaterial () { if (defaultSmokeBMaterial != null) return defaultSmokeBMaterial; defaultSmokeBMaterial = new Material (Shader.Find ("Particles/Alpha Blended")); defaultSmokeBMaterial.name = "SmokeB-Default"; Texture2D tex = Resources.Load ("Detonator/Textures/Smoke") as Texture2D; defaultSmokeBMaterial.SetColor ("_TintColor", Color.white); defaultSmokeBMaterial.mainTexture = tex; defaultSmokeBMaterial.mainTextureScale = new Vector2 (0.5f, 1f); defaultSmokeBMaterial.mainTextureOffset = new Vector2 (0.5f, 0f); return defaultSmokeBMaterial; } public static Material DefaultSparksMaterial () { if (defaultSparksMaterial != null) return defaultSparksMaterial; defaultSparksMaterial = new Material (Shader.Find ("Particles/Additive")); defaultSparksMaterial.name = "Sparks-Default"; Texture2D tex = Resources.Load ("Detonator/Textures/GlowDot") as Texture2D; defaultSparksMaterial.SetColor ("_TintColor", Color.white); defaultSparksMaterial.mainTexture = tex; return defaultSparksMaterial; } public static Material DefaultShockwaveMaterial () { if (defaultShockwaveMaterial != null) return defaultShockwaveMaterial; defaultShockwaveMaterial = new Material (Shader.Find ("Particles/Additive")); defaultShockwaveMaterial.name = "Shockwave-Default"; Texture2D tex = Resources.Load ("Detonator/Textures/Shockwave") as Texture2D; defaultShockwaveMaterial.SetColor ("_TintColor", new Color (0.1f, 0.1f, 0.1f, 1f)); defaultShockwaveMaterial.mainTexture = tex; return defaultShockwaveMaterial; } public static Material DefaultGlowMaterial () { if (defaultGlowMaterial != null) return defaultGlowMaterial; defaultGlowMaterial = new Material (Shader.Find ("Particles/Additive")); defaultGlowMaterial.name = "Glow-Default"; Texture2D tex = Resources.Load ("Detonator/Textures/Glow") as Texture2D; defaultGlowMaterial.SetColor ("_TintColor", Color.white); defaultGlowMaterial.mainTexture = tex; return defaultGlowMaterial; } public static Material DefaultHeatwaveMaterial () { //Unity Pro Only if (SystemInfo.supportsImageEffects) { if (defaultHeatwaveMaterial != null) return defaultHeatwaveMaterial; defaultHeatwaveMaterial = new Material (Shader.Find ("HeatDistort")); defaultHeatwaveMaterial.name = "Heatwave-Default"; Texture2D tex = Resources.Load ("Detonator/Textures/Heatwave") as Texture2D; defaultHeatwaveMaterial.SetTexture ("_BumpMap", tex); return defaultHeatwaveMaterial; } else { return null; } } }
using System; /// <summary> /// ToInt32(System.Object) /// </summary> public class ConvertToInt32_9 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify methos ToInt32((object)random)."); try { object random = TestLibrary.Generator.GetInt32(-55); int actual = Convert.ToInt32(random); int expected = (int)random; if (actual != expected) { TestLibrary.TestFramework.LogError("001.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt32((object)0)"); try { object obj = 0; int actual = Convert.ToInt32(obj); int expected = 0; if (actual != expected) { TestLibrary.TestFramework.LogError("002.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt32((object)int32.max)"); try { object obj = Int32.MaxValue; int actual = Convert.ToInt32(obj); int expected = Int32.MaxValue; if (actual != expected) { TestLibrary.TestFramework.LogError("003.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt32((object)int32.min)"); try { object obj = Int32.MinValue; int actual = Convert.ToInt32(obj); int expected = Int32.MinValue; if (actual != expected) { TestLibrary.TestFramework.LogError("004.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt32(true)"); try { object obj = true; int actual = Convert.ToInt32(obj); int expected = 1; if (actual != expected) { TestLibrary.TestFramework.LogError("005.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest6: Verify method ToInt32(false)"); try { object obj = false; int actual = Convert.ToInt32(obj); int expected = 0; if (actual != expected) { TestLibrary.TestFramework.LogError("006.1", "Method ToInt32 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest7: Verify method ToInt32(null)"); try { object obj = null; int actual = Convert.ToInt32(obj); int expected = 0; if (actual != expected) { TestLibrary.TestFramework.LogError("007.1", "Method ToInt16 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("007.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: InvalidCastException is not thrown."); try { object obj = new object(); int r = Convert.ToInt32(obj); TestLibrary.TestFramework.LogError("101.1", "InvalidCastException is not thrown."); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ConvertToInt32_9 test = new ConvertToInt32_9(); TestLibrary.TestFramework.BeginTestCase("ConvertToInt32_9"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Console; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Mono.Addins; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { /// <summary> /// This module loads and saves OpenSimulator inventory archives /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryArchiverModule")] public class InventoryArchiverModule : ISharedRegionModule, IInventoryArchiverModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <value> /// Enable or disable checking whether the iar user is actually logged in /// </value> // public bool DisablePresenceChecks { get; set; } public event InventoryArchiveSaved OnInventoryArchiveSaved; public event InventoryArchiveLoaded OnInventoryArchiveLoaded; /// <summary> /// The file to load and save inventory if no filename has been specified /// </summary> protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar"; /// <value> /// Pending save and load completions initiated from the console /// </value> protected List<UUID> m_pendingConsoleTasks = new List<UUID>(); /// <value> /// All scenes that this module knows about /// </value> private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); private Scene m_aScene; private IUserAccountService m_UserAccountService; protected IUserAccountService UserAccountService { get { if (m_UserAccountService == null) // What a strange thing to do... foreach (Scene s in m_scenes.Values) { m_UserAccountService = s.RequestModuleInterface<IUserAccountService>(); break; } return m_UserAccountService; } } public InventoryArchiverModule() {} // public InventoryArchiverModule(bool disablePresenceChecks) // { // DisablePresenceChecks = disablePresenceChecks; // } #region ISharedRegionModule public void Initialise(IConfigSource source) { } public void AddRegion(Scene scene) { if (m_scenes.Count == 0) { scene.RegisterModuleInterface<IInventoryArchiverModule>(this); OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted; OnInventoryArchiveLoaded += LoadInvConsoleCommandCompleted; scene.AddCommand( "Archiving", this, "load iar", "load iar [-m|--merge] <first> <last> <inventory path> <password> [<IAR path>]", "Load user inventory archive (IAR).", "-m|--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones" + "<first> is user's first name." + Environment.NewLine + "<last> is user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine + "<password> is the user's password." + Environment.NewLine + "<IAR path> is the filesystem path or URI from which to load the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleLoadInvConsoleCommand); scene.AddCommand( "Archiving", this, "save iar", "save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]", "Save user inventory archive (IAR).", "<first> is the user's first name.\n" + "<last> is the user's last name.\n" + "<inventory path> is the path inside the user's inventory for the folder/item to be saved.\n" + "<IAR path> is the filesystem path at which to save the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used.\n", DEFAULT_INV_BACKUP_FILENAME) + "-h|--home=<url> adds the url of the profile service to the saved user information.\n" + "-c|--creators preserves information about foreign creators.\n" + "-e|--exclude=<name/uuid> don't save the inventory item in archive" + Environment.NewLine + "-f|--excludefolder=<folder/uuid> don't save contents of the folder in archive" + Environment.NewLine + "-v|--verbose extra debug messages.\n" + "--noassets stops assets being saved to the IAR." + "--perm=<permissions> stops items with insufficient permissions from being saved to the IAR.\n" + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer, \"M\" = Modify.\n", HandleSaveInvConsoleCommand); m_aScene = scene; } m_scenes[scene.RegionInfo.RegionID] = scene; } public void RemoveRegion(Scene scene) { } public void Close() {} public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "Inventory Archiver Module"; } } #endregion /// <summary> /// Trigger the inventory archive saved event. /// </summary> protected internal void TriggerInventoryArchiveSaved( UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException, int SaveCount, int FilterCount) { InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved; if (handlerInventoryArchiveSaved != null) handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException, SaveCount , FilterCount); } /// <summary> /// Trigger the inventory archive loaded event. /// </summary> protected internal void TriggerInventoryArchiveLoaded( UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream loadStream, Exception reportedException, int LoadCount) { InventoryArchiveLoaded handlerInventoryArchiveLoaded = OnInventoryArchiveLoaded; if (handlerInventoryArchiveLoaded != null) handlerInventoryArchiveLoaded(id, succeeded, userInfo, invPath, loadStream, reportedException, LoadCount); } public bool ArchiveInventory( UUID id, string firstName, string lastName, string invPath, string pass, Stream saveStream) { return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>()); } public bool ArchiveInventory( UUID id, string firstName, string lastName, string invPath, string pass, Stream saveStream, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { // if (CheckPresence(userInfo.PrincipalID)) // { try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(options, UserAccountService); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } return true; // } // else // { // m_log.ErrorFormat( // "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", // userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); // } } } return false; } public bool ArchiveInventory( UUID id, string firstName, string lastName, string invPath, string pass, string savePath, Dictionary<string, object> options) { // if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, savePath)) // return false; if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { // if (CheckPresence(userInfo.PrincipalID)) // { try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(options, UserAccountService); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } return true; // } // else // { // m_log.ErrorFormat( // "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", // userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); // } } } return false; } public bool DearchiveInventory(UUID id, string firstName, string lastName, string invPath, string pass, Stream loadStream) { return DearchiveInventory(id, firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>()); } public bool DearchiveInventory( UUID id, string firstName, string lastName, string invPath, string pass, Stream loadStream, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { // if (CheckPresence(userInfo.PrincipalID)) // { InventoryArchiveReadRequest request; bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false); try { request = new InventoryArchiveReadRequest(id, this, m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadStream, merge); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; // } // else // { // m_log.ErrorFormat( // "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", // userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); // } } else m_log.ErrorFormat("[INVENTORY ARCHIVER]: User {0} {1} not found", firstName, lastName); } return false; } public bool DearchiveInventory( UUID id, string firstName, string lastName, string invPath, string pass, string loadPath, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { // if (CheckPresence(userInfo.PrincipalID)) // { InventoryArchiveReadRequest request; bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false); try { request = new InventoryArchiveReadRequest(id, this, m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadPath, merge); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; // } // else // { // m_log.ErrorFormat( // "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", // userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); // } } } return false; } /// <summary> /// Load inventory from an inventory file archive /// </summary> /// <param name="cmdparams"></param> protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams) { try { UUID id = UUID.Random(); Dictionary<string, object> options = new Dictionary<string, object>(); OptionSet optionSet = new OptionSet().Add("m|merge", delegate (string v) { options["merge"] = v != null; }); List<string> mainParams = optionSet.Parse(cmdparams); if (mainParams.Count < 6) { m_log.Error( "[INVENTORY ARCHIVER]: usage is load iar [-m|--merge] <first name> <last name> <inventory path> <user password> [<load file path>]"); return; } string firstName = mainParams[2]; string lastName = mainParams[3]; string invPath = mainParams[4]; string pass = mainParams[5]; string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME); m_log.InfoFormat( "[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}", loadPath, invPath, firstName, lastName); lock (m_pendingConsoleTasks) m_pendingConsoleTasks.Add(id); DearchiveInventory(id, firstName, lastName, invPath, pass, loadPath, options); } catch (InventoryArchiverException e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message); } } /// <summary> /// Save inventory to a file archive /// </summary> /// <param name="cmdparams"></param> protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams) { UUID id = UUID.Random(); Dictionary<string, object> options = new Dictionary<string, object>(); OptionSet ops = new OptionSet(); //ops.Add("v|version=", delegate(string v) { options["version"] = v; }); ops.Add("h|home=", delegate(string v) { options["home"] = v; }); ops.Add("v|verbose", delegate(string v) { options["verbose"] = v; }); ops.Add("c|creators", delegate(string v) { options["creators"] = v; }); ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; }); ops.Add("e|exclude=", delegate(string v) { if (!options.ContainsKey("exclude")) options["exclude"] = new List<String>(); ((List<String>)options["exclude"]).Add(v); }); ops.Add("f|excludefolder=", delegate(string v) { if (!options.ContainsKey("excludefolders")) options["excludefolders"] = new List<String>(); ((List<String>)options["excludefolders"]).Add(v); }); ops.Add("perm=", delegate(string v) { options["checkPermissions"] = v; }); List<string> mainParams = ops.Parse(cmdparams); try { if (mainParams.Count < 6) { m_log.Error( "[INVENTORY ARCHIVER]: save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]"); return; } if (options.ContainsKey("home")) m_log.WarnFormat("[INVENTORY ARCHIVER]: Please be aware that inventory archives with creator information are not compatible with OpenSim 0.7.0.2 and earlier. Do not use the -home option if you want to produce a compatible IAR"); string firstName = mainParams[2]; string lastName = mainParams[3]; string invPath = mainParams[4]; string pass = mainParams[5]; string savePath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME); m_log.InfoFormat( "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}", savePath, invPath, firstName, lastName); lock (m_pendingConsoleTasks) m_pendingConsoleTasks.Add(id); ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options); } catch (InventoryArchiverException e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message); } } private void SaveInvConsoleCommandCompleted( UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException, int SaveCount, int FilterCount) { lock (m_pendingConsoleTasks) { if (m_pendingConsoleTasks.Contains(id)) m_pendingConsoleTasks.Remove(id); else return; } if (succeeded) { // Report success and include item count and filter count (Skipped items due to --perm or --exclude switches) if(FilterCount == 0) m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive with {0} items for {1} {2}", SaveCount, userInfo.FirstName, userInfo.LastName); else m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive with {0} items for {1} {2}. Skipped {3} items due to exclude and/or perm switches", SaveCount, userInfo.FirstName, userInfo.LastName, FilterCount); } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}", userInfo.FirstName, userInfo.LastName, reportedException.Message); } } private void LoadInvConsoleCommandCompleted( UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream loadStream, Exception reportedException, int LoadCount) { lock (m_pendingConsoleTasks) { if (m_pendingConsoleTasks.Contains(id)) m_pendingConsoleTasks.Remove(id); else return; } if (succeeded) { m_log.InfoFormat("[INVENTORY ARCHIVER]: Loaded {0} items from archive {1} for {2} {3}", LoadCount, invPath, userInfo.FirstName, userInfo.LastName); } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Archive load for {0} {1} failed - {2}", userInfo.FirstName, userInfo.LastName, reportedException.Message); } } /// <summary> /// Get user information for the given name. /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="pass">User password</param> /// <returns></returns> protected UserAccount GetUserInfo(string firstName, string lastName, string pass) { UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName); if (null == account) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}", firstName, lastName); return null; } try { string encpass = Util.Md5Hash(pass); if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty) { return account; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.", firstName, lastName); return null; } } catch (Exception e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e); return null; } } /// <summary> /// Notify the client of loaded nodes if they are logged in /// </summary> /// <param name="loadedNodes">Can be empty. In which case, nothing happens</param> private void UpdateClientWithLoadedNodes(UserAccount userInfo, HashSet<InventoryNodeBase> loadedNodes) { if (loadedNodes.Count == 0) return; foreach (Scene scene in m_scenes.Values) { ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID); if (user != null && !user.IsChildAgent) { foreach (InventoryNodeBase node in loadedNodes) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}", // user.Name, node.Name); user.ControllingClient.SendBulkUpdateInventory(node); } break; } } } // /// <summary> // /// Check if the given user is present in any of the scenes. // /// </summary> // /// <param name="userId">The user to check</param> // /// <returns>true if the user is in any of the scenes, false otherwise</returns> // protected bool CheckPresence(UUID userId) // { // if (DisablePresenceChecks) // return true; // // foreach (Scene scene in m_scenes.Values) // { // ScenePresence p; // if ((p = scene.GetScenePresence(userId)) != null) // { // p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false); // return true; // } // } // // return false; // } } }
using System; using System.Collections.Generic; using Server.ContextMenus; using Server.Regions; using Server.Items; using BunnyHole = Server.Mobiles.VorpalBunny.BunnyHole; namespace Server.Mobiles { public class BaseTalismanSummon : BaseCreature { public override bool Commandable{ get{ return false; } } public override bool InitialInnocent{ get{ return true; } } //public override bool IsInvulnerable{ get{ return true; } } // TODO: Wailing banshees are NOT invulnerable, are any of the others? public BaseTalismanSummon() : base( AIType.AI_Melee, FightMode.None, 10, 1, 0.2, 0.4 ) { // TODO: Stats/skills } public BaseTalismanSummon( Serial serial ) : base( serial ) { } public override void AddCustomContextEntries( Mobile from, List<ContextMenuEntry> list ) { if ( from.Alive && ControlMaster == from ) list.Add( new TalismanReleaseEntry( this ) ); } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } private class TalismanReleaseEntry : ContextMenuEntry { private Mobile m_Mobile; public TalismanReleaseEntry( Mobile m ) : base( 6118, 3 ) { m_Mobile = m; } public override void OnClick() { Effects.SendLocationParticles( EffectItem.Create( m_Mobile.Location, m_Mobile.Map, EffectItem.DefaultDuration ), 0x3728, 8, 20, 5042 ); Effects.PlaySound( m_Mobile, m_Mobile.Map, 0x201 ); m_Mobile.Delete(); } } } public class SummonedAntLion : BaseTalismanSummon { [Constructable] public SummonedAntLion() : base() { Name = "an ant lion"; Body = 787; BaseSoundID = 1006; } public SummonedAntLion( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedArcticOgreLord : BaseTalismanSummon { [Constructable] public SummonedArcticOgreLord() : base() { Name = "an arctic ogre lord"; Body = 135; BaseSoundID = 427; } public SummonedArcticOgreLord( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedBakeKitsune : BaseTalismanSummon { [Constructable] public SummonedBakeKitsune() : base() { Name = "a bake kitsune"; Body = 246; BaseSoundID = 0x4DD; } public SummonedBakeKitsune( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedBogling : BaseTalismanSummon { [Constructable] public SummonedBogling() : base() { Name = "a bogling"; Body = 779; BaseSoundID = 422; } public SummonedBogling( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedBullFrog : BaseTalismanSummon { [Constructable] public SummonedBullFrog() : base() { Name = "a bull frog"; Body = 81; Hue = Utility.RandomList( 0x5AC, 0x5A3, 0x59A, 0x591, 0x588, 0x57F ); BaseSoundID = 0x266; } public SummonedBullFrog( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedChicken : BaseTalismanSummon { [Constructable] public SummonedChicken() : base() { Name = "a chicken"; Body = 0xD0; BaseSoundID = 0x6E; } public SummonedChicken( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedCow : BaseTalismanSummon { [Constructable] public SummonedCow() : base() { Name = "a cow"; Body = Utility.RandomList( 0xD8, 0xE7 ); BaseSoundID = 0x78; } public SummonedCow( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedDoppleganger : BaseTalismanSummon { [Constructable] public SummonedDoppleganger() : base() { Name = "a doppleganger"; Body = 0x309; BaseSoundID = 0x451; } public SummonedDoppleganger( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedFrostSpider : BaseTalismanSummon { [Constructable] public SummonedFrostSpider() : base() { Name = "a frost spider"; Body = 20; BaseSoundID = 0x388; } public SummonedFrostSpider( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedGreatHart : BaseTalismanSummon { [Constructable] public SummonedGreatHart() : base() { Name = "a great hart"; Body = 0xEA; BaseSoundID = 0x82; } public SummonedGreatHart( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedLavaSerpent : BaseTalismanSummon { [Constructable] public SummonedLavaSerpent() : base() { Name = "a lava serpent"; Body = 90; BaseSoundID = 219; } public SummonedLavaSerpent( Serial serial ) : base( serial ) { } public override void OnThink() { /* if ( m_NextWave < DateTime.Now ) AreaHeatDamage(); */ } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } /* // An area attack that only damages staff, wtf? private DateTime m_NextWave; public void AreaHeatDamage() { Mobile mob = ControlMaster; if ( mob != null ) { if ( mob.InRange( Location, 2 ) ) { if ( mob.AccessLevel != AccessLevel.Player ) { AOS.Damage( mob, Utility.Random( 2, 3 ), 0, 100, 0, 0, 0 ); mob.SendLocalizedMessage( 1008112 ); // The intense heat is damaging you! } } GuardedRegion r = Region as GuardedRegion; if ( r != null && mob.Alive ) { foreach ( Mobile m in GetMobilesInRange( 2 ) ) { if ( !mob.CanBeHarmful( m ) ) mob.CriminalAction( false ); } } } m_NextWave = DateTime.Now + TimeSpan.FromSeconds( 3 ); } */ } public class SummonedOrcBrute : BaseTalismanSummon { [Constructable] public SummonedOrcBrute() : base() { Body = 189; Name = "an orc brute"; BaseSoundID = 0x45A; } public SummonedOrcBrute( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedPanther : BaseTalismanSummon { [Constructable] public SummonedPanther() : base() { Name = "a panther"; Body = 0xD6; Hue = 0x901; BaseSoundID = 0x462; } public SummonedPanther( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedSheep : BaseTalismanSummon { [Constructable] public SummonedSheep() : base() { Name = "a sheep"; Body = 0xCF; BaseSoundID = 0xD6; } public SummonedSheep( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedSkeletalKnight : BaseTalismanSummon { [Constructable] public SummonedSkeletalKnight() : base() { Name = "a skeletal knight"; Body = 147; BaseSoundID = 451; } public SummonedSkeletalKnight( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedVorpalBunny : BaseTalismanSummon { [Constructable] public SummonedVorpalBunny() : base() { Name = "a vorpal bunny"; Body = 205; Hue = 0x480; BaseSoundID = 0xC9; Timer.DelayCall( TimeSpan.FromMinutes( 30.0 ), new TimerCallback( BeginTunnel ) ); } public SummonedVorpalBunny( Serial serial ) : base( serial ) { } public virtual void BeginTunnel() { if ( Deleted ) return; new BunnyHole().MoveToWorld( Location, Map ); Frozen = true; Say( "* The bunny begins to dig a tunnel back to its underground lair *" ); PlaySound( 0x247 ); Timer.DelayCall( TimeSpan.FromSeconds( 5.0 ), new TimerCallback( Delete ) ); } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class SummonedWailingBanshee : BaseTalismanSummon { [Constructable] public SummonedWailingBanshee() : base() { Name = "a wailing banshee"; Body = 310; BaseSoundID = 0x482; } public SummonedWailingBanshee( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/> // <version>$Revision: 3787 $</version> // </file> using System; using System.Collections.Generic; using System.Text; using ICSharpCode.NRefactory.Ast; using ICSharpCode.NRefactory.AstBuilder; using NR = ICSharpCode.NRefactory.Ast; namespace ICSharpCode.SharpDevelop.Dom.Refactoring { /// <summary> /// Provides code generation facilities. /// </summary> public abstract class CodeGenerator { protected CodeGenerator() { HostCallback.InitializeCodeGeneratorOptions(this); } #region Dummy Code Generator public static readonly CodeGenerator DummyCodeGenerator = new DummyCodeGeneratorClass(); private class DummyCodeGeneratorClass : CodeGenerator { public override string GenerateCode(AbstractNode node, string indentation) { return " - there is no code generator for this language - "; } } #endregion #region DOM -> NRefactory conversion (static) public static TypeReference ConvertType(IReturnType returnType, ClassFinder context) { if (returnType == null) return TypeReference.Null; if (returnType is NullReturnType) return TypeReference.Null; TypeReference typeRef; if (IsPrimitiveType(returnType)) typeRef = new TypeReference(returnType.FullyQualifiedName, true); else if (context != null && CanUseShortTypeName(returnType, context)) typeRef = new TypeReference(returnType.Name); else typeRef = new TypeReference(returnType.FullyQualifiedName); while (returnType.IsArrayReturnType) { int[] rank = typeRef.RankSpecifier ?? new int[0]; Array.Resize(ref rank, rank.Length + 1); rank[rank.Length - 1] = returnType.CastToArrayReturnType().ArrayDimensions - 1; typeRef.RankSpecifier = rank; returnType = returnType.CastToArrayReturnType().ArrayElementType; } if (returnType.IsConstructedReturnType) { foreach (IReturnType typeArgument in returnType.CastToConstructedReturnType().TypeArguments) { typeRef.GenericTypes.Add(ConvertType(typeArgument, context)); } } return typeRef; } static bool IsPrimitiveType(IReturnType returnType) { return TypeReference.PrimitiveTypesCSharpReverse.ContainsKey(returnType.FullyQualifiedName); } /// <summary> /// Returns true if the short name of a type is valid in the given context. /// Returns false for primitive types because they should be passed around using their /// fully qualified names to allow the ambience or output visitor to use the intrinsic /// type name. /// </summary> public static bool CanUseShortTypeName(IReturnType returnType, ClassFinder context) { int typeArgumentCount = (returnType.IsConstructedReturnType) ? returnType.CastToConstructedReturnType().TypeArguments.Count : 0; IReturnType typeInTargetContext = context.SearchType(returnType.Name, typeArgumentCount); return typeInTargetContext != null && typeInTargetContext.FullyQualifiedName == returnType.FullyQualifiedName; } public static Modifiers ConvertModifier(ModifierEnum modifiers, ClassFinder targetContext) { if (targetContext != null && targetContext.ProjectContent != null && targetContext.CallingClass != null) { if (targetContext.ProjectContent.Language.IsClassWithImplicitlyStaticMembers(targetContext.CallingClass)) { return ((Modifiers)modifiers) & ~Modifiers.Static; } } return (Modifiers)modifiers; } public static NR.ParameterModifiers ConvertModifier(Dom.ParameterModifiers m) { return (NR.ParameterModifiers)m; } public static UsingDeclaration ConvertUsing(IUsing u) { List<Using> usings = new List<Using>(); foreach (string name in u.Usings) { usings.Add(new Using(name)); } if (u.HasAliases) { foreach (KeyValuePair<string, IReturnType> pair in u.Aliases) { usings.Add(new Using(pair.Key, ConvertType(pair.Value, null))); } } return new UsingDeclaration(usings); } public static List<ParameterDeclarationExpression> ConvertParameters(IList<IParameter> parameters, ClassFinder targetContext) { List<ParameterDeclarationExpression> l = new List<ParameterDeclarationExpression>(parameters.Count); foreach (IParameter p in parameters) { ParameterDeclarationExpression pd = new ParameterDeclarationExpression(ConvertType(p.ReturnType, targetContext), p.Name, ConvertModifier(p.Modifiers)); pd.Attributes = ConvertAttributes(p.Attributes, targetContext); l.Add(pd); } return l; } public static List<AttributeSection> ConvertAttributes(IList<IAttribute> attributes, ClassFinder targetContext) { AttributeSection sec = new AttributeSection(); foreach (IAttribute att in attributes) { sec.Attributes.Add(new ICSharpCode.NRefactory.Ast.Attribute(ConvertType(att.AttributeType, targetContext).Type, null, null)); } List<AttributeSection> resultList = new List<AttributeSection>(1); if (sec.Attributes.Count > 0) resultList.Add(sec); return resultList; } public static List<TemplateDefinition> ConvertTemplates(IList<ITypeParameter> l, ClassFinder targetContext) { List<TemplateDefinition> o = new List<TemplateDefinition>(l.Count); foreach (ITypeParameter p in l) { TemplateDefinition td = new TemplateDefinition(p.Name, ConvertAttributes(p.Attributes, targetContext)); foreach (IReturnType rt in p.Constraints) { td.Bases.Add(ConvertType(rt, targetContext)); } o.Add(td); } return o; } public static BlockStatement CreateNotImplementedBlock() { BlockStatement b = new BlockStatement(); b.Throw(new TypeReference("NotImplementedException").New()); return b; } public static ParametrizedNode ConvertMember(IMethod m, ClassFinder targetContext) { if (m.IsConstructor) { return new ConstructorDeclaration(m.Name, ConvertModifier(m.Modifiers, targetContext), ConvertParameters(m.Parameters, targetContext), ConvertAttributes(m.Attributes, targetContext)); } else { return new MethodDeclaration { Name = m.Name, Modifier = ConvertModifier(m.Modifiers, targetContext), TypeReference = ConvertType(m.ReturnType, targetContext), Parameters = ConvertParameters(m.Parameters, targetContext), Attributes = ConvertAttributes(m.Attributes, targetContext), Templates = ConvertTemplates(m.TypeParameters, targetContext), Body = CreateNotImplementedBlock() }; } } public static AttributedNode ConvertMember(IMember m, ClassFinder targetContext) { if (m == null) throw new ArgumentNullException("m"); if (m is IProperty) return ConvertMember((IProperty)m, targetContext); else if (m is IMethod) return ConvertMember((IMethod)m, targetContext); else if (m is IEvent) return ConvertMember((IEvent)m, targetContext); else if (m is IField) return ConvertMember((IField)m, targetContext); else throw new ArgumentException("Unknown member: " + m.GetType().FullName); } public static AttributedNode ConvertMember(IProperty p, ClassFinder targetContext) { if (p.IsIndexer) { IndexerDeclaration md; md = new IndexerDeclaration(ConvertType(p.ReturnType, targetContext), ConvertParameters(p.Parameters, targetContext), ConvertModifier(p.Modifiers, targetContext), ConvertAttributes(p.Attributes, targetContext)); md.Parameters = ConvertParameters(p.Parameters, targetContext); if (p.CanGet) md.GetRegion = new PropertyGetRegion(CreateNotImplementedBlock(), null); if (p.CanSet) md.SetRegion = new PropertySetRegion(CreateNotImplementedBlock(), null); return md; } else { PropertyDeclaration md; md = new PropertyDeclaration(ConvertModifier(p.Modifiers, targetContext), ConvertAttributes(p.Attributes, targetContext), p.Name, ConvertParameters(p.Parameters, targetContext)); md.TypeReference = ConvertType(p.ReturnType, targetContext); if (p.CanGet) { md.GetRegion = new PropertyGetRegion(CreateNotImplementedBlock(), null); md.GetRegion.Modifier = ConvertModifier(p.GetterModifiers, null); } if (p.CanSet) { md.SetRegion = new PropertySetRegion(CreateNotImplementedBlock(), null); md.SetRegion.Modifier = ConvertModifier(p.SetterModifiers, null); } return md; } } public static FieldDeclaration ConvertMember(IField f, ClassFinder targetContext) { TypeReference type = ConvertType(f.ReturnType, targetContext); FieldDeclaration fd = new FieldDeclaration(ConvertAttributes(f.Attributes, targetContext), type, ConvertModifier(f.Modifiers, targetContext)); fd.Fields.Add(new VariableDeclaration(f.Name, null, type)); return fd; } public static EventDeclaration ConvertMember(IEvent e, ClassFinder targetContext) { return new EventDeclaration { TypeReference = ConvertType(e.ReturnType, targetContext), Name = e.Name, Modifier = ConvertModifier(e.Modifiers, targetContext), Attributes = ConvertAttributes(e.Attributes, targetContext), }; } #endregion readonly CodeGeneratorOptions options = new CodeGeneratorOptions(); public CodeGeneratorOptions Options { get { return options; } } #region Code generation / insertion public virtual void InsertCodeAfter(IMember member, IDocument document, params AbstractNode[] nodes) { if (member is IMethodOrProperty) { InsertCodeAfter(((IMethodOrProperty)member).BodyRegion.EndLine, document, GetIndentation(document, member.Region.BeginLine), nodes); } else { InsertCodeAfter(member.Region.EndLine, document, GetIndentation(document, member.Region.BeginLine), nodes); } } public virtual void InsertCodeAtEnd(DomRegion region, IDocument document, params AbstractNode[] nodes) { InsertCodeAfter(region.EndLine - 1, document, GetIndentation(document, region.BeginLine) + options.IndentString, nodes); } public virtual void InsertCodeInClass(IClass c, IDocument document, int targetLine, params AbstractNode[] nodes) { InsertCodeAfter(targetLine, document, GetIndentation(document, c.Region.BeginLine) + options.IndentString, false, nodes); } protected string GetIndentation(IDocument document, int line) { string lineText = document.GetLine(line).Text; return lineText.Substring(0, lineText.Length - lineText.TrimStart().Length); } /// <summary> /// Generates code for <paramref name="nodes"/> and inserts it into <paramref name="document"/> /// after the line <paramref name="insertLine"/>. /// </summary> protected void InsertCodeAfter(int insertLine, IDocument document, string indentation, params AbstractNode[] nodes) { InsertCodeAfter(insertLine, document, indentation, true, nodes); } /// <summary> /// Generates code for <paramref name="nodes"/> and inserts it into <paramref name="document"/> /// after the line <paramref name="insertLine"/>. /// </summary> protected void InsertCodeAfter(int insertLine, IDocument document, string indentation, bool startWithEmptyLine, params AbstractNode[] nodes) { IDocumentLine lineSegment = document.GetLine(insertLine + 1); StringBuilder b = new StringBuilder(); for (int i = 0; i < nodes.Length; i++) { if (options.EmptyLinesBetweenMembers) { if (startWithEmptyLine || i > 0) { b.AppendLine(indentation); } } b.Append(GenerateCode(nodes[i], indentation)); } document.Insert(lineSegment.Offset, b.ToString()); document.UpdateView(); } /// <summary> /// Generates code for the NRefactory node. /// </summary> public abstract string GenerateCode(AbstractNode node, string indentation); #endregion #region Generate property public virtual string GetPropertyName(string fieldName) { if (fieldName.StartsWith("_") && fieldName.Length > 1) return Char.ToUpper(fieldName[1]) + fieldName.Substring(2); else if (fieldName.StartsWith("m_") && fieldName.Length > 2) return Char.ToUpper(fieldName[2]) + fieldName.Substring(3); else return Char.ToUpper(fieldName[0]) + fieldName.Substring(1); } public virtual string GetParameterName(string fieldName) { if (fieldName.StartsWith("_") && fieldName.Length > 1) return Char.ToLower(fieldName[1]) + fieldName.Substring(2); else if (fieldName.StartsWith("m_") && fieldName.Length > 2) return Char.ToLower(fieldName[2]) + fieldName.Substring(3); else return Char.ToLower(fieldName[0]) + fieldName.Substring(1); } public virtual PropertyDeclaration CreateProperty(IField field, bool createGetter, bool createSetter) { ClassFinder targetContext = new ClassFinder(field); string name = GetPropertyName(field.Name); PropertyDeclaration property = new PropertyDeclaration(ConvertModifier(field.Modifiers, targetContext), null, name, null); property.TypeReference = ConvertType(field.ReturnType, new ClassFinder(field)); if (createGetter) { BlockStatement block = new BlockStatement(); block.Return(new IdentifierExpression(field.Name)); property.GetRegion = new PropertyGetRegion(block, null); } if (createSetter) { BlockStatement block = new BlockStatement(); block.Assign(new IdentifierExpression(field.Name), new IdentifierExpression("value")); property.SetRegion = new PropertySetRegion(block, null); } property.Modifier = Modifiers.Public | (property.Modifier & Modifiers.Static); return property; } #endregion #region Generate Changed Event public virtual void CreateChangedEvent(IProperty property, IDocument document) { ClassFinder targetContext = new ClassFinder(property); string name = property.Name + "Changed"; EventDeclaration ed = new EventDeclaration { TypeReference = new TypeReference("EventHandler"), Name = name, Modifier = ConvertModifier(property.Modifiers & (ModifierEnum.VisibilityMask | ModifierEnum.Static), targetContext), }; InsertCodeAfter(property, document, ed); List<Expression> arguments = new List<Expression>(2); if (property.IsStatic) arguments.Add(new PrimitiveExpression(null, "null")); else arguments.Add(new ThisReferenceExpression()); arguments.Add(new IdentifierExpression("EventArgs").Member("Empty")); InsertCodeAtEnd(property.SetterRegion, document, new RaiseEventStatement(name, arguments)); } #endregion #region Generate OnEventMethod public virtual MethodDeclaration CreateOnEventMethod(IEvent e) { ClassFinder context = new ClassFinder(e); List<ParameterDeclarationExpression> parameters = new List<ParameterDeclarationExpression>(); bool sender = false; if (e.ReturnType != null) { IMethod invoke = e.ReturnType.GetMethods().Find(delegate(IMethod m) { return m.Name=="Invoke"; }); if (invoke != null) { foreach (IParameter param in invoke.Parameters) { parameters.Add(new ParameterDeclarationExpression(ConvertType(param.ReturnType, context), param.Name)); } if (parameters.Count > 0 && string.Equals(parameters[0].ParameterName, "sender", StringComparison.InvariantCultureIgnoreCase)) { sender = true; parameters.RemoveAt(0); } } } ModifierEnum modifier; if (e.IsStatic) modifier = ModifierEnum.Private | ModifierEnum.Static; else if (e.DeclaringType.IsSealed) modifier = ModifierEnum.Protected; else modifier = ModifierEnum.Protected | ModifierEnum.Virtual; MethodDeclaration method = new MethodDeclaration { Name = "On" + e.Name, Modifier = ConvertModifier(modifier, context), TypeReference = new TypeReference("System.Void", true), Parameters = parameters }; List<Expression> arguments = new List<Expression>(); if (sender) { if (e.IsStatic) arguments.Add(new PrimitiveExpression(null, "null")); else arguments.Add(new ThisReferenceExpression()); } foreach (ParameterDeclarationExpression param in parameters) { arguments.Add(new IdentifierExpression(param.ParameterName)); } method.Body = new BlockStatement(); method.Body.AddChild(new RaiseEventStatement(e.Name, arguments)); return method; } #endregion #region Interface implementation protected string GetInterfaceName(IReturnType interf, IMember member, ClassFinder context) { if (CanUseShortTypeName(member.DeclaringType.DefaultReturnType, context)) return member.DeclaringType.Name; else return member.DeclaringType.FullyQualifiedName; } public virtual void ImplementInterface(IReturnType interf, IDocument document, bool explicitImpl, IClass targetClass) { List<AbstractNode> nodes = new List<AbstractNode>(); ImplementInterface(nodes, interf, explicitImpl, targetClass); InsertCodeAtEnd(targetClass.Region, document, nodes.ToArray()); } static bool InterfaceMemberAlreadyImplementedParametersAreIdentical(IMember a, IMember b) { if (a is IMethodOrProperty && b is IMethodOrProperty) { return DiffUtility.Compare(((IMethodOrProperty)a).Parameters, ((IMethodOrProperty)b).Parameters) == 0; } else { return true; } } static T CloneAndAddExplicitImpl<T>(T member, IClass targetClass) where T : class, IMember { T copy = (T)member.Clone(); copy.DeclaringTypeReference = targetClass.DefaultReturnType; copy.InterfaceImplementations.Add(new ExplicitInterfaceImplementation(member.DeclaringTypeReference, member.Name)); return copy; } static bool InterfaceMemberAlreadyImplemented<T>(IEnumerable<T> existingMembers, T interfaceMember, out bool requireAlternativeImplementation) where T : class, IMember { IReturnType interf = interfaceMember.DeclaringTypeReference; requireAlternativeImplementation = false; foreach (T existing in existingMembers) { StringComparer nameComparer = existing.DeclaringType.ProjectContent.Language.NameComparer; // if existing has same name as interfaceMember, and for methods the parameter list must also be identical: if (nameComparer.Equals(existing.Name, interfaceMember.Name)) { if (InterfaceMemberAlreadyImplementedParametersAreIdentical(existing, interfaceMember)) { // implicit implementation found if (object.Equals(existing.ReturnType, interfaceMember.ReturnType)) { return true; } else { requireAlternativeImplementation = true; } } } else { foreach (ExplicitInterfaceImplementation eii in existing.InterfaceImplementations) { if (object.Equals(eii.InterfaceReference, interf) && nameComparer.Equals(eii.MemberName, interfaceMember.Name)) { if (InterfaceMemberAlreadyImplementedParametersAreIdentical(existing, interfaceMember)) { // explicit implementation found if (object.Equals(existing.ReturnType, interfaceMember.ReturnType)) { return true; } else { requireAlternativeImplementation = true; } } } } } } return false; } static InterfaceImplementation CreateInterfaceImplementation(IMember interfaceMember, ClassFinder context) { return new InterfaceImplementation(ConvertType(interfaceMember.DeclaringTypeReference, context), interfaceMember.Name); } /// <summary> /// Adds the methods implementing the <paramref name="interf"/> to the list /// <paramref name="nodes"/>. /// </summary> public virtual void ImplementInterface(IList<AbstractNode> nodes, IReturnType interf, bool explicitImpl, IClass targetClass) { ClassFinder context = new ClassFinder(targetClass, targetClass.Region.BeginLine + 1, 0); Modifiers implicitImplModifier = ConvertModifier(ModifierEnum.Public, context); Modifiers explicitImplModifier = ConvertModifier(context.Language.ExplicitInterfaceImplementationIsPrivateScope ? ModifierEnum.None : ModifierEnum.Public, context); List<IEvent> targetClassEvents = targetClass.DefaultReturnType.GetEvents(); bool requireAlternativeImplementation; foreach (IEvent e in interf.GetEvents()) { if (!InterfaceMemberAlreadyImplemented(targetClassEvents, e, out requireAlternativeImplementation)) { EventDeclaration ed = ConvertMember(e, context); ed.Attributes.Clear(); if (explicitImpl || requireAlternativeImplementation) { ed.InterfaceImplementations.Add(CreateInterfaceImplementation(e, context)); if (context.Language.RequiresAddRemoveRegionInExplicitInterfaceImplementation) { ed.AddRegion = new EventAddRegion(null); ed.AddRegion.Block = CreateNotImplementedBlock(); ed.RemoveRegion = new EventRemoveRegion(null); ed.RemoveRegion.Block = CreateNotImplementedBlock(); } targetClassEvents.Add(CloneAndAddExplicitImpl(e, targetClass)); ed.Modifier = explicitImplModifier; } else { targetClassEvents.Add(e); ed.Modifier = implicitImplModifier; } nodes.Add(ed); } } List<IProperty> targetClassProperties = targetClass.DefaultReturnType.GetProperties(); foreach (IProperty p in interf.GetProperties()) { if (!InterfaceMemberAlreadyImplemented(targetClassProperties, p, out requireAlternativeImplementation)) { AttributedNode pd = ConvertMember(p, context); pd.Attributes.Clear(); if (explicitImpl || requireAlternativeImplementation) { InterfaceImplementation impl = CreateInterfaceImplementation(p, context); if (pd is IndexerDeclaration) { ((IndexerDeclaration)pd).InterfaceImplementations.Add(impl); } else { ((PropertyDeclaration)pd).InterfaceImplementations.Add(impl); } targetClassProperties.Add(CloneAndAddExplicitImpl(p, targetClass)); pd.Modifier = explicitImplModifier; } else { targetClassProperties.Add(p); pd.Modifier = implicitImplModifier; } nodes.Add(pd); } } List<IMethod> targetClassMethods = targetClass.DefaultReturnType.GetMethods(); foreach (IMethod m in interf.GetMethods()) { if (!InterfaceMemberAlreadyImplemented(targetClassMethods, m, out requireAlternativeImplementation)) { MethodDeclaration md = ConvertMember(m, context) as MethodDeclaration; md.Attributes.Clear(); if (md != null) { if (explicitImpl || requireAlternativeImplementation) { md.InterfaceImplementations.Add(CreateInterfaceImplementation(m, context)); targetClassMethods.Add(CloneAndAddExplicitImpl(m, targetClass)); md.Modifier = explicitImplModifier; } else { targetClassMethods.Add(m); md.Modifier = implicitImplModifier; } nodes.Add(md); } } } } #endregion #region Override member public virtual AttributedNode GetOverridingMethod(IMember baseMember, ClassFinder targetContext) { AttributedNode node = ConvertMember(baseMember, targetContext); node.Modifier &= ~(Modifiers.Virtual | Modifiers.Abstract); node.Modifier |= Modifiers.Override; if (!baseMember.IsAbstract) { // replace the method/property body with a call to the base method/property MethodDeclaration method = node as MethodDeclaration; if (method != null) { method.Body.Children.Clear(); if (method.TypeReference.Type == "System.Void") { method.Body.AddChild(new ExpressionStatement(CreateForwardingMethodCall(method))); } else { method.Body.AddChild(new ReturnStatement(CreateForwardingMethodCall(method))); } } PropertyDeclaration property = node as PropertyDeclaration; if (property != null) { Expression field = new BaseReferenceExpression().Member(property.Name); if (!property.GetRegion.Block.IsNull) { property.GetRegion.Block.Children.Clear(); property.GetRegion.Block.Return(field); } if (!property.SetRegion.Block.IsNull) { property.SetRegion.Block.Children.Clear(); property.SetRegion.Block.Assign(field, new IdentifierExpression("value")); } } } return node; } static InvocationExpression CreateForwardingMethodCall(MethodDeclaration method) { Expression methodName = new MemberReferenceExpression(new BaseReferenceExpression(), method.Name); InvocationExpression ie = new InvocationExpression(methodName, null); foreach (ParameterDeclarationExpression param in method.Parameters) { Expression expr = new IdentifierExpression(param.ParameterName); if (param.ParamModifier == NR.ParameterModifiers.Ref) { expr = new DirectionExpression(FieldDirection.Ref, expr); } else if (param.ParamModifier == NR.ParameterModifiers.Out) { expr = new DirectionExpression(FieldDirection.Out, expr); } ie.Arguments.Add(expr); } return ie; } #endregion #region Using statements public virtual void ReplaceUsings(IDocument document, IList<IUsing> oldUsings, IList<IUsing> newUsings) { if (oldUsings.Count == newUsings.Count) { bool identical = true; for (int i = 0; i < oldUsings.Count; i++) { if (oldUsings[i] != newUsings[i]) { identical = false; break; } } if (identical) return; } int firstLine = int.MaxValue; List<KeyValuePair<int, int>> regions = new List<KeyValuePair<int, int>>(); foreach (IUsing u in oldUsings) { if (u.Region.BeginLine < firstLine) firstLine = u.Region.BeginLine; int st = document.PositionToOffset(u.Region.BeginLine, u.Region.BeginColumn); int en = document.PositionToOffset(u.Region.EndLine, u.Region.EndColumn); regions.Add(new KeyValuePair<int, int>(st, en - st)); } regions.Sort(delegate(KeyValuePair<int, int> a, KeyValuePair<int, int> b) { return a.Key.CompareTo(b.Key); }); int insertionOffset = regions.Count == 0 ? 0 : regions[0].Key; string indentation; if (firstLine != int.MaxValue) { indentation = GetIndentation(document, firstLine); insertionOffset -= indentation.Length; } else { indentation = ""; } document.StartUndoableAction(); for (int i = regions.Count - 1; i >= 0; i--) { document.Remove(regions[i].Key, regions[i].Value); } int lastNewLine = insertionOffset; for (int i = insertionOffset; i < document.TextLength; i++) { char c = document.GetCharAt(i); if (!char.IsWhiteSpace(c)) break; if (c == '\n') { if (i > 0 && document.GetCharAt(i - 1) == '\r') lastNewLine = i - 1; else lastNewLine = i; } } if (lastNewLine != insertionOffset) { document.Remove(insertionOffset, lastNewLine - insertionOffset); } StringBuilder txt = new StringBuilder(); foreach (IUsing us in newUsings) { if (us == null) txt.AppendLine(indentation); else txt.Append(GenerateCode(ConvertUsing(us), indentation)); } document.Insert(insertionOffset, txt.ToString()); document.EndUndoableAction(); } #endregion } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Specialized; using System.Net; using System.Web; using Microsoft.Xrm.Client.Diagnostics; using Microsoft.Xrm.Portal.Cms; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Portal.Runtime; using Microsoft.Xrm.Portal.Web.Providers; using Microsoft.Security.Application; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Client; using Microsoft.Xrm.Sdk.Client; namespace Microsoft.Xrm.Portal.Web { /// <summary> /// Abstract base class for XRM <see cref="SiteMapProvider"/>s, containing shared configuration and /// security validation logic. /// </summary> public abstract class CrmSiteMapProviderBase : SiteMapProvider { public string PortalName { get; private set; } protected IPortalContext PortalContext { get { return PortalCrmConfigurationManager.CreatePortalContext(PortalName); } } protected virtual ICrmSiteMapNodeValidator ChildNodeValidator { get; private set; } protected virtual ICrmSiteMapNodeValidator NodeValidator { get; private set; } protected virtual ICrmSiteMapNodeValidator SecurityTrimmingValidator { get; private set; } public override void Initialize(string name, NameValueCollection attributes) { TraceInfo(@"Initialize(""{0}"", attributes)", name); // Enable security trimming by default. attributes["securityTrimmingEnabled"] = attributes["securityTrimmingEnabled"] ?? "true"; foreach (var key in attributes.AllKeys) { TraceInfo(@"{0}=""{1}""", key, attributes[key]); } base.Initialize(name, attributes); var nodeValidatorProvider = GetNodeValidatorProvider(); NodeValidator = nodeValidatorProvider.GetValidator(this); var securityTrimmingValidatorProvider = GetSecurityTrimmingValidatorProvider(); SecurityTrimmingValidator = securityTrimmingValidatorProvider.GetValidator(this); var childNodeValidatorProvider = GetChildNodeValidatorProvider(); ChildNodeValidator = childNodeValidatorProvider.GetValidator(this); PortalName = attributes["portalName"]; } public override bool IsAccessibleToUser(HttpContext context, SiteMapNode node) { node.ThrowOnNull("node"); context.ThrowOnNull("context"); if (!SecurityTrimmingEnabled) { return true; } var crmNode = node as CrmSiteMapNode; if (crmNode == null) { return base.IsAccessibleToUser(context, node); } return SecurityTrimmingValidator.Validate(PortalContext.ServiceContext, crmNode); } protected void TraceInfo(string messageFormat, params object[] args) { Tracing.FrameworkInformation(GetType().Name, string.Empty, messageFormat, args); } protected static bool TryParseGuid(string value, out Guid guid) { guid = default(Guid); try { if (string.IsNullOrEmpty(value)) { return false; } guid = new Guid(value); return true; } catch (FormatException) { return false; } } protected CrmSiteMapNode ReturnNodeIfAccessible(CrmSiteMapNode node, Func<CrmSiteMapNode> getFallbackNode) { return node != null && node.IsAccessibleToUser(HttpContext.Current) ? node : getFallbackNode(); } protected abstract CrmSiteMapNode GetNode(OrganizationServiceContext context, Entity entity); protected CrmSiteMapNode GetAccessibleNodeOrAccessDeniedNode(OrganizationServiceContext context, Entity entity) { entity.ThrowOnNull("entity"); return ReturnNodeIfAccessible(GetNode(context, entity), GetAccessDeniedNode); } protected CrmSiteMapNode GetAccessDeniedNode() { var portal = PortalContext; var context = portal.ServiceContext; var website = portal.Website; if (HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated) { var loginPage = context.GetPageBySiteMarkerName(website, "Login"); if (loginPage != null) { return ReturnNodeIfAccessible(GetWebPageNodeWithReturnUrl(context, loginPage, HttpStatusCode.Forbidden), GetNotFoundNode); } } var accessDeniedPage = context.GetPageBySiteMarkerName(website, "Access Denied"); if (accessDeniedPage != null) { return ReturnNodeIfAccessible(GetWebPageNodeWithReturnUrl(context, accessDeniedPage, HttpStatusCode.Forbidden), GetNotFoundNode); } return GetNotFoundNode(); } protected CrmSiteMapNode GetNotFoundNode() { var portal = PortalContext; var context = portal.ServiceContext; var website = portal.Website; var notFoundPage = context.GetPageBySiteMarkerName(website, "Page Not Found"); if (notFoundPage == null) { return null; } var notFoundNode = GetWebPageNode(context, notFoundPage, HttpStatusCode.NotFound); return ReturnNodeIfAccessible(notFoundNode, () => null); } protected CrmSiteMapNode GetWebPageNode(OrganizationServiceContext context, Entity page, HttpStatusCode statusCode) { return GetWebPageNode(context, page, statusCode, p => { var pageTemplate = p.GetRelatedEntity(context, "adx_pagetemplate_webpage"); var webPageID = p.GetAttributeValue<Guid>("adx_webpageid"); if (pageTemplate == null) { return null; } // MSBug #120133: Can't URL encode--used for URL rewrite. return "{0}?pageid={1}".FormatWith(pageTemplate.GetAttributeValue<string>("adx_rewriteurl"), webPageID); }); } protected CrmSiteMapNode GetWebPageNode(OrganizationServiceContext context, Entity page, HttpStatusCode statusCode, Func<Entity, string> getRewriteUrl) { var contentFormatter = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<ICrmEntityContentFormatter>(GetType().FullName) ?? new PassthroughCrmEntityContentFormatter(); var rewriteUrl = getRewriteUrl(page); var url = context.GetUrl(page); var title = page.GetAttributeValue<string>("adx_title"); // apply a detached clone of the entity since the SiteMapNode is out of the scope of the current OrganizationServiceContext var pageClone = page.Clone(false); return new CrmSiteMapNode( this, url, url, contentFormatter.Format(string.IsNullOrEmpty(title) ? page.GetAttributeValue<string>("adx_name") : title, page, this), contentFormatter.Format(page.GetAttributeValue<string>("adx_summary"), page, this), rewriteUrl, page.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow), pageClone, statusCode); } protected CrmSiteMapNode GetWebPageNodeWithReturnUrl(OrganizationServiceContext context, Entity page, HttpStatusCode statusCode) { return GetWebPageNode(context, page, statusCode, p => { var pageTemplate = p.GetRelatedEntity(context, "adx_pagetemplate_webpage"); var webPageID = p.GetAttributeValue<Guid>("adx_webpageid"); if (pageTemplate == null) { return null; } return "{0}?pageid={1}&ReturnUrl={2}".FormatWith( pageTemplate.GetAttributeValue<string>("adx_rewriteurl"), webPageID, Encoder.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery)); }); } private INodeValidatorProvider GetNodeValidatorProvider() { return PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<INodeValidatorProvider>("node"); } private INodeValidatorProvider GetSecurityTrimmingValidatorProvider() { return PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<INodeValidatorProvider>("securityTrimming"); } private INodeValidatorProvider GetChildNodeValidatorProvider() { return PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<INodeValidatorProvider>("childNode"); } } }
// 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.Diagnostics; using System.Runtime.InteropServices; namespace Internal.Cryptography.Pal.Native { internal enum CertQueryObjectType : int { CERT_QUERY_OBJECT_FILE = 0x00000001, CERT_QUERY_OBJECT_BLOB = 0x00000002, } [Flags] internal enum ExpectedContentTypeFlags : int { //encoded single certificate CERT_QUERY_CONTENT_FLAG_CERT = 1 << ContentType.CERT_QUERY_CONTENT_CERT, //encoded single CTL CERT_QUERY_CONTENT_FLAG_CTL = 1 << ContentType.CERT_QUERY_CONTENT_CTL, //encoded single CRL CERT_QUERY_CONTENT_FLAG_CRL = 1 << ContentType.CERT_QUERY_CONTENT_CRL, //serialized store CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_STORE, //serialized single certificate CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CERT, //serialized single CTL CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CTL, //serialized single CRL CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CRL, //an encoded PKCS#7 signed message CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED, //an encoded PKCS#7 message. But it is not a signed message CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_UNSIGNED, //the content includes an embedded PKCS7 signed message CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED, //an encoded PKCS#10 CERT_QUERY_CONTENT_FLAG_PKCS10 = 1 << ContentType.CERT_QUERY_CONTENT_PKCS10, //an encoded PFX BLOB CERT_QUERY_CONTENT_FLAG_PFX = 1 << ContentType.CERT_QUERY_CONTENT_PFX, //an encoded CertificatePair (contains forward and/or reverse cross certs) CERT_QUERY_CONTENT_FLAG_CERT_PAIR = 1 << ContentType.CERT_QUERY_CONTENT_CERT_PAIR, //an encoded PFX BLOB, and we do want to load it (not included in //CERT_QUERY_CONTENT_FLAG_ALL) CERT_QUERY_CONTENT_FLAG_PFX_AND_LOAD = 1 << ContentType.CERT_QUERY_CONTENT_PFX_AND_LOAD, CERT_QUERY_CONTENT_FLAG_ALL = CERT_QUERY_CONTENT_FLAG_CERT | CERT_QUERY_CONTENT_FLAG_CTL | CERT_QUERY_CONTENT_FLAG_CRL | CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | CERT_QUERY_CONTENT_FLAG_PKCS10 | CERT_QUERY_CONTENT_FLAG_PFX | CERT_QUERY_CONTENT_FLAG_CERT_PAIR, } [Flags] internal enum ExpectedFormatTypeFlags : int { CERT_QUERY_FORMAT_FLAG_BINARY = 1 << FormatType.CERT_QUERY_FORMAT_BINARY, CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_BASE64_ENCODED, CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED, CERT_QUERY_FORMAT_FLAG_ALL = CERT_QUERY_FORMAT_FLAG_BINARY | CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED | CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED, } internal enum CertEncodingType : int { PKCS_7_ASN_ENCODING = 0x10000, X509_ASN_ENCODING = 0x00001, All = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, } internal enum ContentType : int { //encoded single certificate CERT_QUERY_CONTENT_CERT = 1, //encoded single CTL CERT_QUERY_CONTENT_CTL = 2, //encoded single CRL CERT_QUERY_CONTENT_CRL = 3, //serialized store CERT_QUERY_CONTENT_SERIALIZED_STORE = 4, //serialized single certificate CERT_QUERY_CONTENT_SERIALIZED_CERT = 5, //serialized single CTL CERT_QUERY_CONTENT_SERIALIZED_CTL = 6, //serialized single CRL CERT_QUERY_CONTENT_SERIALIZED_CRL = 7, //a PKCS#7 signed message CERT_QUERY_CONTENT_PKCS7_SIGNED = 8, //a PKCS#7 message, such as enveloped message. But it is not a signed message, CERT_QUERY_CONTENT_PKCS7_UNSIGNED = 9, //a PKCS7 signed message embedded in a file CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED = 10, //an encoded PKCS#10 CERT_QUERY_CONTENT_PKCS10 = 11, //an encoded PFX BLOB CERT_QUERY_CONTENT_PFX = 12, //an encoded CertificatePair (contains forward and/or reverse cross certs) CERT_QUERY_CONTENT_CERT_PAIR = 13, //an encoded PFX BLOB, which was loaded to phCertStore CERT_QUERY_CONTENT_PFX_AND_LOAD = 14, } internal enum FormatType : int { CERT_QUERY_FORMAT_BINARY = 1, CERT_QUERY_FORMAT_BASE64_ENCODED = 2, CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED = 3, } // CRYPTOAPI_BLOB has many typedef aliases in the C++ world (CERT_BLOB, DATA_BLOB, etc.) We'll just stick to one name here. [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPTOAPI_BLOB { public CRYPTOAPI_BLOB(int cbData, byte* pbData) { this.cbData = cbData; this.pbData = pbData; } public int cbData; public byte* pbData; public byte[] ToByteArray() { byte[] array = new byte[cbData]; Marshal.Copy((IntPtr)pbData, array, 0, cbData); return array; } } internal enum CertContextPropId : int { CERT_KEY_PROV_INFO_PROP_ID = 2, CERT_SHA1_HASH_PROP_ID = 3, CERT_FRIENDLY_NAME_PROP_ID = 11, CERT_ARCHIVED_PROP_ID = 19, CERT_KEY_IDENTIFIER_PROP_ID = 20, CERT_PUBKEY_ALG_PARA_PROP_ID = 22, CERT_DELETE_KEYSET_PROP_ID = 101, } [Flags] internal enum CertSetPropertyFlags : int { CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG = 0x40000000, None = 0x00000000, } internal enum CertNameType : int { CERT_NAME_EMAIL_TYPE = 1, CERT_NAME_RDN_TYPE = 2, CERT_NAME_ATTR_TYPE = 3, CERT_NAME_SIMPLE_DISPLAY_TYPE = 4, CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5, CERT_NAME_DNS_TYPE = 6, CERT_NAME_URL_TYPE = 7, CERT_NAME_UPN_TYPE = 8, } [Flags] internal enum CertNameFlags : int { None = 0x00000000, CERT_NAME_ISSUER_FLAG = 0x00000001, } internal enum CertNameStringType : int { CERT_X500_NAME_STR = 3, CERT_NAME_STR_REVERSE_FLAG = 0x02000000, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CONTEXT { public CertEncodingType dwCertEncodingType; public byte* pbCertEncoded; public int cbCertEncoded; public CERT_INFO* pCertInfo; public IntPtr hCertStore; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_INFO { public int dwVersion; public CRYPTOAPI_BLOB SerialNumber; public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; public CRYPTOAPI_BLOB Issuer; public FILETIME NotBefore; public FILETIME NotAfter; public CRYPTOAPI_BLOB Subject; public CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; public CRYPT_BIT_BLOB IssuerUniqueId; public CRYPT_BIT_BLOB SubjectUniqueId; public int cExtension; public CERT_EXTENSION* rgExtension; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_ALGORITHM_IDENTIFIER { public IntPtr pszObjId; public CRYPTOAPI_BLOB Parameters; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_PUBLIC_KEY_INFO { public CRYPT_ALGORITHM_IDENTIFIER Algorithm; public CRYPT_BIT_BLOB PublicKey; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPT_BIT_BLOB { public int cbData; public byte* pbData; public int cUnusedBits; public byte[] ToByteArray() { byte[] array = new byte[cbData]; Marshal.Copy((IntPtr)pbData, array, 0, cbData); return array; } } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_EXTENSION { public IntPtr pszObjId; public int fCritical; public CRYPTOAPI_BLOB Value; } [StructLayout(LayoutKind.Sequential)] internal struct FILETIME { private uint ftTimeLow; private uint ftTimeHigh; public DateTime ToDateTime() { long fileTime = (((long)ftTimeHigh) << 32) + ftTimeLow; return DateTime.FromFileTime(fileTime); } public static FILETIME FromDateTime(DateTime dt) { long fileTime = dt.ToFileTime(); return new FILETIME() { ftTimeLow = (uint)fileTime, ftTimeHigh = (uint)(fileTime >> 32), }; } } internal enum CertStoreProvider : int { CERT_STORE_PROV_MEMORY = 2, CERT_STORE_PROV_SYSTEM_W = 10, } [Flags] internal enum CertStoreFlags : int { CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001, CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004, CERT_STORE_DELETE_FLAG = 0x00000010, CERT_STORE_UNSAFE_PHYSICAL_FLAG = 0x00000020, CERT_STORE_SHARE_STORE_FLAG = 0x00000040, CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080, CERT_STORE_MANIFOLD_FLAG = 0x00000100, CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200, CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400, CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800, CERT_STORE_READONLY_FLAG = 0x00008000, CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000, CERT_STORE_CREATE_NEW_FLAG = 0x00002000, CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000, CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000, CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000, None = 0x00000000, } internal enum CertStoreAddDisposition : int { CERT_STORE_ADD_NEW = 1, CERT_STORE_ADD_USE_EXISTING = 2, CERT_STORE_ADD_REPLACE_EXISTING = 3, CERT_STORE_ADD_ALWAYS = 4, CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES = 5, CERT_STORE_ADD_NEWER = 6, CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7, } [Flags] internal enum PfxCertStoreFlags : int { CRYPT_EXPORTABLE = 0x00000001, CRYPT_USER_PROTECTED = 0x00000002, CRYPT_MACHINE_KEYSET = 0x00000020, CRYPT_USER_KEYSET = 0x00001000, PKCS12_PREFER_CNG_KSP = 0x00000100, PKCS12_ALWAYS_CNG_KSP = 0x00000200, PKCS12_ALLOW_OVERWRITE_KEY = 0x00004000, PKCS12_NO_PERSIST_KEY = 0x00008000, PKCS12_INCLUDE_EXTENDED_PROPERTIES = 0x00000010, None = 0x00000000, } internal enum CryptMessageParameterType : int { CMSG_SIGNER_COUNT_PARAM = 5, CMSG_SIGNER_INFO_PARAM = 6, } [StructLayout(LayoutKind.Sequential)] internal struct CMSG_SIGNER_INFO_Partial // This is not the full definition of CMSG_SIGNER_INFO. Only defining the part we use. { public int dwVersion; public CRYPTOAPI_BLOB Issuer; public CRYPTOAPI_BLOB SerialNumber; //... more fields follow ... } [Flags] internal enum CertFindFlags : int { None = 0x00000000, } internal enum CertFindType : int { CERT_FIND_SUBJECT_CERT = 0x000b0000, CERT_FIND_HASH = 0x00010000, CERT_FIND_SUBJECT_STR = 0x00080007, CERT_FIND_ISSUER_STR = 0x00080004, CERT_FIND_EXISTING = 0x000d0000, CERT_FIND_ANY = 0x00000000, } [Flags] internal enum PFXExportFlags : int { REPORT_NO_PRIVATE_KEY = 0x00000001, REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY = 0x00000002, EXPORT_PRIVATE_KEYS = 0x00000004, None = 0x00000000, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPT_KEY_PROV_INFO { public char* pwszContainerName; public char* pwszProvName; public int dwProvType; public CryptAcquireContextFlags dwFlags; public int cProvParam; public IntPtr rgProvParam; public int dwKeySpec; } [Flags] internal enum CryptAcquireContextFlags : int { CRYPT_DELETEKEYSET = 0x00000010, CRYPT_MACHINE_KEYSET = 0x00000020, None = 0x00000000, } [Flags] internal enum CertNameStrTypeAndFlags : int { CERT_SIMPLE_NAME_STR = 1, CERT_OID_NAME_STR = 2, CERT_X500_NAME_STR = 3, CERT_NAME_STR_SEMICOLON_FLAG = 0x40000000, CERT_NAME_STR_NO_PLUS_FLAG = 0x20000000, CERT_NAME_STR_NO_QUOTING_FLAG = 0x10000000, CERT_NAME_STR_CRLF_FLAG = 0x08000000, CERT_NAME_STR_COMMA_FLAG = 0x04000000, CERT_NAME_STR_REVERSE_FLAG = 0x02000000, CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG = 0x00010000, CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG = 0x00020000, CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG = 0x00040000, CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG = 0x00080000, } internal enum FormatObjectType : int { None = 0, } [Flags] internal enum FormatObjectStringType : int { CRYPT_FORMAT_STR_MULTI_LINE = 0x00000001, CRYPT_FORMAT_STR_NO_HEX = 0x00000010, None = 0x00000000, } internal enum FormatObjectStructType : int { X509_NAME = 7, } internal static class AlgId { public const int CALG_RSA_KEYX = 0xa400; public const int CALG_RSA_SIGN = 0x2400; public const int CALG_DSS_SIGN = 0x2200; public const int CALG_SHA1 = 0x8004; } [Flags] internal enum CryptDecodeObjectFlags : int { None = 0x00000000, } internal enum CryptDecodeObjectStructType : int { CNG_RSA_PUBLIC_KEY_BLOB = 72, X509_DSS_PUBLICKEY = 38, X509_DSS_PARAMETERS = 39, X509_KEY_USAGE = 14, X509_BASIC_CONSTRAINTS = 13, X509_BASIC_CONSTRAINTS2 = 15, X509_ENHANCED_KEY_USAGE = 36, X509_CERT_POLICIES = 16, X509_UNICODE_ANY_STRING = 24, X509_CERTIFICATE_TEMPLATE = 64, } [StructLayout(LayoutKind.Sequential)] internal struct CTL_USAGE { public int cUsageIdentifier; public IntPtr rgpszUsageIdentifier; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_USAGE_MATCH { public CertUsageMatchType dwType; public CTL_USAGE Usage; } internal enum CertUsageMatchType : int { USAGE_MATCH_TYPE_AND = 0x00000000, USAGE_MATCH_TYPE_OR = 0x00000001, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_PARA { public int cbSize; public CERT_USAGE_MATCH RequestedUsage; public CERT_USAGE_MATCH RequestedIssuancePolicy; public int dwUrlRetrievalTimeout; public int fCheckRevocationFreshnessTime; public int dwRevocationFreshnessTime; public FILETIME* pftCacheResync; public int pStrongSignPara; public int dwStrongSignFlags; } [Flags] internal enum CertChainFlags : int { None = 0x00000000, CERT_CHAIN_REVOCATION_CHECK_END_CERT = 0x10000000, CERT_CHAIN_REVOCATION_CHECK_CHAIN = 0x20000000, CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x40000000, CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY = unchecked((int)0x80000000), } internal enum ChainEngine : int { HCCE_CURRENT_USER = 0x0, HCCE_LOCAL_MACHINE = 0x1, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_DSS_PARAMETERS { public CRYPTOAPI_BLOB p; public CRYPTOAPI_BLOB q; public CRYPTOAPI_BLOB g; } internal enum PubKeyMagic : int { DSS_MAGIC = 0x31535344, } [StructLayout(LayoutKind.Sequential)] internal struct BLOBHEADER { public byte bType; public byte bVersion; public short reserved; public uint aiKeyAlg; }; [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_BASIC_CONSTRAINTS_INFO { public CRYPT_BIT_BLOB SubjectType; public int fPathLenConstraint; public int dwPathLenConstraint; public int cSubtreesConstraint; public CRYPTOAPI_BLOB* rgSubtreesConstraint; // PCERT_NAME_BLOB // SubjectType.pbData[0] can contain a CERT_CA_SUBJECT_FLAG that when set indicates that the certificate's subject can act as a CA public const byte CERT_CA_SUBJECT_FLAG = 0x80; }; [StructLayout(LayoutKind.Sequential)] internal struct CERT_BASIC_CONSTRAINTS2_INFO { public int fCA; public int fPathLenConstraint; public int dwPathLenConstraint; }; [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_ENHKEY_USAGE { public int cUsageIdentifier; public IntPtr* rgpszUsageIdentifier; // LPSTR* } internal enum CertStoreSaveAs : int { CERT_STORE_SAVE_AS_STORE = 1, CERT_STORE_SAVE_AS_PKCS7 = 2, } internal enum CertStoreSaveTo : int { CERT_STORE_SAVE_TO_MEMORY = 2, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_POLICY_INFO { public IntPtr pszPolicyIdentifier; public int cPolicyQualifier; public IntPtr rgPolicyQualifier; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_POLICIES_INFO { public int cPolicyInfo; public CERT_POLICY_INFO* rgPolicyInfo; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_NAME_VALUE { public int dwValueType; public CRYPTOAPI_BLOB Value; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_TEMPLATE_EXT { public IntPtr pszObjId; public int dwMajorVersion; public int fMinorVersion; public int dwMinorVersion; } [Flags] internal enum CertControlStoreFlags : int { None = 0x00000000, } internal enum CertControlStoreType : int { CERT_STORE_CTRL_AUTO_RESYNC = 4, } [Flags] internal enum CertTrustErrorStatus : int { CERT_TRUST_NO_ERROR = 0x00000000, CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001, CERT_TRUST_IS_NOT_TIME_NESTED = 0x00000002, CERT_TRUST_IS_REVOKED = 0x00000004, CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008, CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010, CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020, CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040, CERT_TRUST_IS_CYCLIC = 0x00000080, CERT_TRUST_INVALID_EXTENSION = 0x00000100, CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200, CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400, CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800, CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000, CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000, CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000, CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000, CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000, CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000, CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000, CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000, CERT_TRUST_HAS_WEAK_SIGNATURE = 0x00100000, // These can be applied to chains only CERT_TRUST_IS_PARTIAL_CHAIN = 0x00010000, CERT_TRUST_CTL_IS_NOT_TIME_VALID = 0x00020000, CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID = 0x00040000, CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE = 0x00080000, } [Flags] internal enum CertTrustInfoStatus : int { // These can be applied to certificates only CERT_TRUST_HAS_EXACT_MATCH_ISSUER = 0x00000001, CERT_TRUST_HAS_KEY_MATCH_ISSUER = 0x00000002, CERT_TRUST_HAS_NAME_MATCH_ISSUER = 0x00000004, CERT_TRUST_IS_SELF_SIGNED = 0x00000008, // These can be applied to certificates and chains CERT_TRUST_HAS_PREFERRED_ISSUER = 0x00000100, CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY = 0x00000200, CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS = 0x00000400, // These can be applied to chains only CERT_TRUST_IS_COMPLEX_CHAIN = 0x00010000, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_TRUST_STATUS { public CertTrustErrorStatus dwErrorStatus; public CertTrustInfoStatus dwInfoStatus; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_ELEMENT { public int cbSize; public CERT_CONTEXT* pCertContext; public CERT_TRUST_STATUS TrustStatus; public IntPtr pRevocationInfo; public IntPtr pIssuanceUsage; public IntPtr pApplicationUsage; public IntPtr pwszExtendedErrorInfo; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_SIMPLE_CHAIN { public int cbSize; public CERT_TRUST_STATUS TrustStatus; public int cElement; public CERT_CHAIN_ELEMENT** rgpElement; public IntPtr pTrustListInfo; // fHasRevocationFreshnessTime is only set if we are able to retrieve // revocation information for all elements checked for revocation. // For a CRL its CurrentTime - ThisUpdate. // // dwRevocationFreshnessTime is the largest time across all elements // checked. public int fHasRevocationFreshnessTime; public int dwRevocationFreshnessTime; // seconds } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_CONTEXT { public int cbSize; public CERT_TRUST_STATUS TrustStatus; public int cChain; public CERT_SIMPLE_CHAIN** rgpChain; // Following is returned when CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS // is set in dwFlags public int cLowerQualityChainContext; public CERT_CHAIN_CONTEXT** rgpLowerQualityChainContext; // fHasRevocationFreshnessTime is only set if we are able to retrieve // revocation information for all elements checked for revocation. // For a CRL its CurrentTime - ThisUpdate. // // dwRevocationFreshnessTime is the largest time across all elements // checked. public int fHasRevocationFreshnessTime; public int dwRevocationFreshnessTime; // seconds // Flags passed when created via CertGetCertificateChain public int dwCreateFlags; // Following is updated with unique Id when the chain context is logged. public Guid ChainId; } [Flags] internal enum FormatMessageFlags : int { FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_CHAIN_POLICY_PARA { public int cbSize; public int dwFlags; public IntPtr pvExtraPolicyPara; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_CHAIN_POLICY_STATUS { public int cbSize; public int dwError; public IntPtr lChainIndex; public IntPtr lElementIndex; public IntPtr pvExtraPolicyStatus; } internal enum ChainPolicy : int { // Predefined verify chain policies CERT_CHAIN_POLICY_BASE = 1, } internal enum CryptAcquireFlags : int { CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = 0x00040000, } }
using System; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Bot.Connector { /// <summary> /// An Activity is the basic communication type for the Bot Framework 3.0 protocol /// </summary> /// <remarks> /// The Activity class contains all properties that individual, more specific activities /// could contain. It is a superset type. /// </remarks> public partial class Activity : IActivity, IConversationUpdateActivity, IContactRelationUpdateActivity, IInstallationUpdateActivity, IMessageActivity, ITypingActivity, IEndOfConversationActivity, IEventActivity, IInvokeActivity { /// <summary> /// Content-type for an Activity /// </summary> public const string ContentType = "application/vnd.microsoft.activity"; /// <summary> /// Take a message and create a reply message for it with the routing information /// set up to correctly route a reply to the source message /// </summary> /// <param name="text">text you want to reply with</param> /// <param name="locale">language of your reply</param> /// <returns>message set up to route back to the sender</returns> public Activity CreateReply(string text = null, string locale = null) { Activity reply = new Activity(); reply.Type = ActivityTypes.Message; reply.Timestamp = DateTime.UtcNow; reply.From = new ChannelAccount(id: this.Recipient.Id, name: this.Recipient.Name); reply.Recipient = new ChannelAccount(id: this.From.Id, name: this.From.Name); reply.ReplyToId = this.Id; reply.ServiceUrl = this.ServiceUrl; reply.ChannelId = this.ChannelId; reply.Conversation = new ConversationAccount(isGroup: this.Conversation.IsGroup, id: this.Conversation.Id, name: this.Conversation.Name); reply.Text = text ?? String.Empty; reply.Locale = locale ?? this.Locale; return reply; } /// <summary> /// Extension data for overflow of properties /// </summary> [JsonExtensionData(ReadData = true, WriteData = true)] public JObject Properties { get; set; } = new JObject(); /// <summary> /// Create an instance of the Activity class with IMessageActivity masking /// </summary> public static IMessageActivity CreateMessageActivity() { return new Activity(ActivityTypes.Message); } /// <summary> /// Create an instance of the Activity class with IContactRelationUpdateActivity masking /// </summary> public static IContactRelationUpdateActivity CreateContactRelationUpdateActivity() { return new Activity(ActivityTypes.ContactRelationUpdate); } /// <summary> /// Create an instance of the Activity class with IConversationUpdateActivity masking /// </summary> public static IConversationUpdateActivity CreateConversationUpdateActivity() { return new Activity(ActivityTypes.ConversationUpdate); } /// <summary> /// Create an instance of the Activity class with ITypingActivity masking /// </summary> public static ITypingActivity CreateTypingActivity() { return new Activity(ActivityTypes.Typing); } /// <summary> /// Create an instance of the Activity class with IActivity masking /// </summary> public static IActivity CreatePingActivity() { return new Activity(ActivityTypes.Ping); } /// <summary> /// Create an instance of the Activity class with IEndOfConversationActivity masking /// </summary> public static IEndOfConversationActivity CreateEndOfConversationActivity() { return new Activity(ActivityTypes.EndOfConversation); } /// <summary> /// Create an instance of the Activity class with an IEventActivity masking /// </summary> public static IEventActivity CreateEventActivity() { return new Activity(ActivityTypes.Event); } /// <summary> /// Create an instance of the Activity class with IInvokeActivity masking /// </summary> public static IInvokeActivity CreateInvokeActivity() { return new Activity(ActivityTypes.Invoke); } /// <summary> /// True if the Activity is of the specified activity type /// </summary> protected bool IsActivity(string activity) { return string.Compare(this.Type?.Split('/').First(), activity, true) == 0; } /// <summary> /// Return an IMessageActivity mask if this is a message activity /// </summary> public IMessageActivity AsMessageActivity() { return IsActivity(ActivityTypes.Message) ? this : null; } /// <summary> /// Return an IContactRelationUpdateActivity mask if this is a contact relation update activity /// </summary> public IContactRelationUpdateActivity AsContactRelationUpdateActivity() { return IsActivity(ActivityTypes.ContactRelationUpdate) ? this : null; } /// <summary> /// Return an IInstallationUpdateActivity mask if this is a installation update activity /// </summary> public IInstallationUpdateActivity AsInstallationUpdateActivity() { return IsActivity(ActivityTypes.InstallationUpdate) ? this : null; } /// <summary> /// Return an IConversationUpdateActivity mask if this is a conversation update activity /// </summary> public IConversationUpdateActivity AsConversationUpdateActivity() { return IsActivity(ActivityTypes.ConversationUpdate) ? this : null; } /// <summary> /// Return an ITypingActivity mask if this is a typing activity /// </summary> public ITypingActivity AsTypingActivity() { return IsActivity(ActivityTypes.Typing) ? this : null; } /// <summary> /// Return an IEndOfConversationActivity mask if this is an end of conversation activity /// </summary> public IEndOfConversationActivity AsEndOfConversationActivity() { return IsActivity(ActivityTypes.EndOfConversation) ? this : null; } /// <summary> /// Return an IEventActivity mask if this is an event activity /// </summary> public IEventActivity AsEventActivity() { return IsActivity(ActivityTypes.Event) ? this : null; } /// <summary> /// Return an IInvokeActivity mask if this is an invoke activity /// </summary> public IInvokeActivity AsInvokeActivity() { return IsActivity(ActivityTypes.Invoke) ? this : null; } /// <summary> /// Maps type to activity types /// </summary> /// <param name="type"> The type.</param> /// <returns> The activity type.</returns> public static string GetActivityType(string type) { if (String.Equals(type, ActivityTypes.Message, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.Message; if (String.Equals(type, ActivityTypes.ContactRelationUpdate, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.ContactRelationUpdate; if (String.Equals(type, ActivityTypes.ConversationUpdate, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.ConversationUpdate; if (String.Equals(type, ActivityTypes.DeleteUserData, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.DeleteUserData; if (String.Equals(type, ActivityTypes.Typing, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.Typing; if (String.Equals(type, ActivityTypes.Ping, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.Ping; return $"{Char.ToLower(type[0])}{type.Substring(1)}"; } /// <summary> /// Checks if this (message) activity has content. /// </summary> /// <returns>Returns true, if this message has any content to send. False otherwise.</returns> public bool HasContent() { if (!String.IsNullOrWhiteSpace(this.Text)) return true; if (!String.IsNullOrWhiteSpace(this.Summary)) return true; if (this.Attachments != null && this.Attachments.Any()) return true; if (this.ChannelData != null) return true; return false; } /// <summary> /// Resolves the mentions from the entities of this (message) activity. /// </summary> /// <returns>The array of mentions or an empty array, if none found.</returns> public Mention[] GetMentions() { return this.Entities?.Where(entity => String.Compare(entity.Type, "mention", ignoreCase: true) == 0) .Select(e => e.Properties.ToObject<Mention>()).ToArray() ?? new Mention[0]; } } public static class ActivityExtensions { /// <summary> /// Get StateClient appropriate for this activity /// </summary> /// <param name="credentials">credentials for bot to access state api</param> /// <param name="serviceUrl">alternate serviceurl to use for state service</param> /// <param name="handlers"></param> /// <param name="activity"></param> /// <returns></returns> [System.Obsolete("Deprecated: This method will only get the default state client, if you have implemented a custom state client it will not retrieve it")] public static StateClient GetStateClient(this IActivity activity, MicrosoftAppCredentials credentials, string serviceUrl = null, params DelegatingHandler[] handlers) { bool useServiceUrl = (activity.ChannelId == "emulator"); if (useServiceUrl) return new StateClient(new Uri(activity.ServiceUrl), credentials: credentials, handlers: handlers); if (serviceUrl != null) return new StateClient(new Uri(serviceUrl), credentials: credentials, handlers: handlers); return new StateClient(credentials, true, handlers); } /// <summary> /// Get StateClient appropriate for this activity /// </summary> /// <param name="microsoftAppId"></param> /// <param name="microsoftAppPassword"></param> /// <param name="serviceUrl">alternate serviceurl to use for state service</param> /// <param name="handlers"></param> /// <param name="activity"></param> /// <returns></returns> public static StateClient GetStateClient(this IActivity activity, string microsoftAppId = null, string microsoftAppPassword = null, string serviceUrl = null, params DelegatingHandler[] handlers) => GetStateClient(activity, new MicrosoftAppCredentials(microsoftAppId, microsoftAppPassword), serviceUrl, handlers); /// <summary> /// Return the "major" portion of the activity /// </summary> /// <param name="activity"></param> /// <returns>normalized major portion of the activity, aka message/... will return "message"</returns> public static string GetActivityType(this IActivity activity) { var type = activity.Type.Split('/').First(); return Activity.GetActivityType(type); } /// <summary> /// Get channeldata as typed structure /// </summary> /// <param name="activity"></param> /// <typeparam name="TypeT">type to use</typeparam> /// <returns>typed object or default(TypeT)</returns> public static TypeT GetChannelData<TypeT>(this IActivity activity) { if (activity.ChannelData == null) return default(TypeT); return ((JObject)activity.ChannelData).ToObject<TypeT>(); } /// <summary> /// Get channeldata as typed structure /// </summary> /// <param name="activity"></param> /// <typeparam name="TypeT">type to use</typeparam> /// <param name="instance">The resulting instance, if possible</param> /// <returns> /// <c>true</c> if value of <seealso cref="IActivity.ChannelData"/> was coerceable to <typeparamref name="TypeT"/>, <c>false</c> otherwise. /// </returns> public static bool TryGetChannelData<TypeT>(this IActivity activity, out TypeT instance) { instance = default(TypeT); try { if (activity.ChannelData == null) { return false; } instance = GetChannelData<TypeT>(activity); return true; } catch { return false; } } /// <summary> /// Is there a mention of Id in the Text Property /// </summary> /// <param name="id">ChannelAccount.Id</param> /// <param name="activity"></param> /// <returns>true if this id is mentioned in the text</returns> public static bool MentionsId(this IMessageActivity activity, string id) { return activity.GetMentions().Where(mention => mention.Mentioned.Id == id).Any(); } /// <summary> /// Is there a mention of Recipient.Id in the Text Property /// </summary> /// <param name="activity"></param> /// <returns>true if this id is mentioned in the text</returns> public static bool MentionsRecipient(this IMessageActivity activity) { return activity.GetMentions().Where(mention => mention.Mentioned.Id == activity.Recipient.Id).Any(); } /// <summary> /// Remove recipient mention text from Text property /// </summary> /// <param name="activity"></param> /// <returns>new .Text property value</returns> public static string RemoveRecipientMention(this IMessageActivity activity) { return activity.RemoveMentionText(activity.Recipient.Id); } /// <summary> /// Replace any mention text for given id from Text property /// </summary> /// <param name="id">id to match</param> /// <param name="activity"></param> /// <returns>new .Text property value</returns> public static string RemoveMentionText(this IMessageActivity activity, string id) { foreach (var mention in activity.GetMentions().Where(mention => mention.Mentioned.Id == id)) { activity.Text = Regex.Replace(activity.Text, mention.Text, "", RegexOptions.IgnoreCase); } return activity.Text; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using GTInterfacesLibrary; namespace GTMillGameLogic { using TaskReturnType = List<GTGameSpaceInterface<GTMillGameElement, GTMillPosition>>; public class GTMillGameStateGenerator : GTGameStateGeneratorInterface<GTMillGameElement, GTMillPosition> { public Task<TaskReturnType> availableStatesFrom(GTGameSpaceInterface<GTMillGameElement, GTMillPosition> state, GTPlayerInterface<GTMillGameElement, GTMillPosition> player) { return availableStatesFrom(state, player, true); } public Task<TaskReturnType> availableStatesFrom(GTGameSpaceInterface<GTMillGameElement, GTMillPosition> state, GTPlayerInterface<GTMillGameElement, GTMillPosition> player, bool detectMill) { if (player.figuresRemaining > 0) { // first phase return availableStatesFirstPhase(state, player, detectMill); } else if (player.figuresInitial - player.figuresLost > 3) { // second phase return availableStatesSteppingPhase(state, player, detectMill); } else { // third phase return availableStatesThirdPhase(state, player, detectMill); } } private Task<TaskReturnType> availableStatesFirstPhase(GTGameSpaceInterface<GTMillGameElement, GTMillPosition> state, GTPlayerInterface<GTMillGameElement, GTMillPosition> player, bool detectMill) { Task<TaskReturnType> task = Task<TaskReturnType>.Factory.StartNew (() => { TaskReturnType states = new TaskReturnType (); for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { for (int z = 0; z < 3; ++z) { GTMillPosition p = new GTMillPosition(x, y ,z); if (!state.hasElementAt(p)) { int id = player.id * player.figuresLost + 1; GTMillGameElement element = new GTMillGameElement(id, 1, player.id); GTMillGameStep step = new GTMillGameStep(element, GTMillPosition.Nowhere(), p); GTMillGameSpace newState = state.stateWithStep (step) as GTMillGameSpace; if (detectMill && GTMillGameMillDetector.detectMillOnPositionWithStateForUser(step.to, newState, player.id)) { foreach (GTMillGameStep removeStep in removeOppenentFigureSteps(newState, player.id)) { states.Add(newState.stateWithStep(removeStep)); } } else { states.Add (newState); } } } } } return states; }); return task; } private Task<TaskReturnType> availableStatesSteppingPhase(GTGameSpaceInterface<GTMillGameElement, GTMillPosition> state, GTPlayerInterface<GTMillGameElement, GTMillPosition> player, bool detectMill) { Task<TaskReturnType> task = Task<TaskReturnType>.Factory.StartNew (() => { List<GTMillGameStep> steps = new List<GTMillGameStep> (); foreach (KeyValuePair<GTMillPosition, GTMillGameElement> kv in state) { if (kv.Value.owner == player.id) { steps.AddRange(stepsFromPositionWithState(state as GTMillGameSpace, kv.Key)); } } TaskReturnType states = new TaskReturnType (); foreach (GTMillGameStep step in steps) { GTMillGameSpace newState = state.stateWithStep (step) as GTMillGameSpace; if (detectMill && GTMillGameMillDetector.detectMillOnPositionWithStateForUser(step.to, newState, player.id)) { foreach (GTMillGameStep removeStep in removeOppenentFigureSteps(newState, player.id)) { states.Add(newState.stateWithStep(removeStep)); } } else { states.Add (newState); } } return states; }); return task; } private Task<TaskReturnType> availableStatesThirdPhase(GTGameSpaceInterface<GTMillGameElement, GTMillPosition> state, GTPlayerInterface<GTMillGameElement, GTMillPosition> player, bool detectMill) { Task<TaskReturnType> task = Task<TaskReturnType>.Factory.StartNew (() => { TaskReturnType states = new TaskReturnType (); foreach (KeyValuePair<GTMillPosition, GTMillGameElement> kv in state) { if (kv.Value.owner == player.id) { for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { for (int z = 0; z < 3; ++z) { GTMillPosition p = new GTMillPosition(x, y ,z); if (!state.hasElementAt(p)) { GTMillGameElement element = kv.Value; GTMillGameStep step = new GTMillGameStep(element, kv.Key, p); GTMillGameSpace newState = state.stateWithStep (step) as GTMillGameSpace; if (detectMill && GTMillGameMillDetector.detectMillOnPositionWithStateForUser(step.to, newState, player.id)) { foreach (GTMillGameStep removeStep in removeOppenentFigureSteps(newState, player.id)) { states.Add(newState.stateWithStep(removeStep)); } } else { states.Add (newState); } } } } } } } return states; }); return task; } private List<GTMillGameStep> removeOppenentFigureSteps(GTMillGameSpace state, int owner) { List<GTMillGameStep> steps = new List<GTMillGameStep> (); foreach (KeyValuePair<GTMillPosition, GTMillGameElement> kv in state) { if (kv.Value.owner != owner) { steps.Add (new GTMillGameStep(kv.Value, kv.Key, GTMillPosition.Nowhere())); } } return steps; } private List<GTMillGameStep> stepsFromPositionWithState(GTMillGameSpace state, GTMillPosition position) { GTMillPosition[] positions = new GTMillPosition[6]; for (int i = 0; i < 6; i++) { int[] coordinates = position.coordinates(); coordinates [i / 2] += (i % 2 == 0 ? -1 : 1); positions [i] = new GTMillPosition (coordinates[0], coordinates[1], coordinates[2]); } List<GTMillPosition> availablePositions = new List<GTMillPosition> (); foreach (GTMillPosition p in positions) { if (!state.hasElementAt(p) && validPosition(p) && (position.z == p.z || !isCornerPosition (position))) { availablePositions.Add (p); } } List<GTMillGameStep> steps = new List<GTMillGameStep> (availablePositions.Count); foreach (GTMillPosition to in availablePositions) { steps.Add (new GTMillGameStep (state.elementAt (position), position, to)); } return steps; } private bool validPosition(GTMillPosition p) { if (p.x < 0 || p.x > 2 || p.y < 0 || p.y > 2 || p.z < 0 || p.z > 2) { // position out of field return false; } if (p.x == 1 && p.y == 1) { // middle invalid position return false; } return true; } private bool isCornerPosition(GTMillPosition p) { return (p.x + p.y) % 2 == 0; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using Nop.Core.Domain.Orders; namespace Nop.Services.Orders { /// <summary> /// Checkout attribute parser /// </summary> public partial class CheckoutAttributeParser : ICheckoutAttributeParser { private readonly ICheckoutAttributeService _checkoutAttributeService; public CheckoutAttributeParser(ICheckoutAttributeService checkoutAttributeService) { this._checkoutAttributeService = checkoutAttributeService; } /// <summary> /// Gets selected checkout attribute identifiers /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Selected checkout attribute identifiers</returns> protected virtual IList<int> ParseCheckoutAttributeIds(string attributesXml) { var ids = new List<int>(); if (String.IsNullOrEmpty(attributesXml)) return ids; try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); foreach (XmlNode node in xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute")) { if (node.Attributes != null && node.Attributes["ID"] != null) { string str1 = node.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { ids.Add(id); } } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return ids; } /// <summary> /// Gets selected checkout attributes /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Selected checkout attributes</returns> public virtual IList<CheckoutAttribute> ParseCheckoutAttributes(string attributesXml) { var result = new List<CheckoutAttribute>(); var ids = ParseCheckoutAttributeIds(attributesXml); foreach (int id in ids) { var attribute = _checkoutAttributeService.GetCheckoutAttributeById(id); if (attribute != null) { result.Add(attribute); } } return result; } /// <summary> /// Get checkout attribute values /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Checkout attribute values</returns> public virtual IList<CheckoutAttributeValue> ParseCheckoutAttributeValues(string attributesXml) { var values = new List<CheckoutAttributeValue>(); var attributes = ParseCheckoutAttributes(attributesXml); foreach (var attribute in attributes) { if (!attribute.ShouldHaveValues()) continue; var valuesStr = ParseValues(attributesXml, attribute.Id); foreach (string valueStr in valuesStr) { if (!String.IsNullOrEmpty(valueStr)) { int id; if (int.TryParse(valueStr, out id)) { var value = _checkoutAttributeService.GetCheckoutAttributeValueById(id); if (value != null) values.Add(value); } } } } return values; } /// <summary> /// Gets selected checkout attribute value /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="checkoutAttributeId">Checkout attribute identifier</param> /// <returns>Checkout attribute value</returns> public virtual IList<string> ParseValues(string attributesXml, int checkoutAttributeId) { var selectedCheckoutAttributeValues = new List<string>(); try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 = node1.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { if (id == checkoutAttributeId) { var nodeList2 = node1.SelectNodes(@"CheckoutAttributeValue/Value"); foreach (XmlNode node2 in nodeList2) { string value = node2.InnerText.Trim(); selectedCheckoutAttributeValues.Add(value); } } } } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return selectedCheckoutAttributeValues; } /// <summary> /// Adds an attribute /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="ca">Checkout attribute</param> /// <param name="value">Value</param> /// <returns>Attributes</returns> public virtual string AddCheckoutAttribute(string attributesXml, CheckoutAttribute ca, string value) { string result = string.Empty; try { var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); XmlElement attributeElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 = node1.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { if (id == ca.Id) { attributeElement = (XmlElement)node1; break; } } } } //create new one if not found if (attributeElement == null) { attributeElement = xmlDoc.CreateElement("CheckoutAttribute"); attributeElement.SetAttribute("ID", ca.Id.ToString()); rootElement.AppendChild(attributeElement); } var attributeValueElement = xmlDoc.CreateElement("CheckoutAttributeValue"); attributeElement.AppendChild(attributeValueElement); var attributeValueValueElement = xmlDoc.CreateElement("Value"); attributeValueValueElement.InnerText = value; attributeValueElement.AppendChild(attributeValueValueElement); result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return result; } /// <summary> /// Removes checkout attributes which cannot be applied to the current cart and returns an update attributes in XML format /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="cart">Shopping cart items</param> /// <returns>Updated attributes in XML format</returns> public virtual string EnsureOnlyActiveAttributes(string attributesXml, IList<ShoppingCartItem> cart) { if (String.IsNullOrEmpty(attributesXml)) return attributesXml; var result = attributesXml; //removing "shippable" checkout attributes if there's no any shippable products in the cart if (!cart.RequiresShipping()) { //find attribute IDs to remove var checkoutAttributeIdsToRemove = new List<int>(); var attributes = ParseCheckoutAttributes(attributesXml); foreach (var ca in attributes) if (ca.ShippableProductRequired) checkoutAttributeIdsToRemove.Add(ca.Id); //remove them from XML try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var nodesToRemove = new List<XmlNode>(); foreach (XmlNode node in xmlDoc.SelectNodes(@"//Attributes/CheckoutAttribute")) { if (node.Attributes != null && node.Attributes["ID"] != null) { string str1 = node.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { if (checkoutAttributeIdsToRemove.Contains(id)) { nodesToRemove.Add(node); } } } } foreach(var node in nodesToRemove) { node.ParentNode.RemoveChild(node); } result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } } return result; } } }
// -------------------------------------------------------------------------------------------- #region // Copyright (c) 2022, SIL International. All Rights Reserved. // <copyright from='2011' to='2022' company='SIL International'> // Copyright (c) 2022, SIL International. All Rights Reserved. // // Distributable under the terms of the MIT License (https://sil.mit-license.org/) // </copyright> #endregion // -------------------------------------------------------------------------------------------- using System; using System.Drawing; using System.Windows.Forms; using System.Collections.Generic; using System.Linq; using HearThis.Properties; using L10NSharp; namespace HearThis.UI { public enum ColorScheme { Normal, HighContrast } public static class ColorSchemeExtensions { public static string ToLocalizedString(this ColorScheme colorScheme) { switch (colorScheme) { case ColorScheme.Normal: return LocalizationManager.GetString("ColorScheme.Normal", "Normal"); case ColorScheme.HighContrast: return LocalizationManager.GetString("ColorScheme.HighContrast", "High Contrast"); default: return null; } } } public static class AppPalette { public enum ColorSchemeElement { Background, MouseOverButtonBackColor, NavigationTextColor, ScriptFocusTextColor, ScriptContextTextColor, EmptyBoxColor, HilightColor, SecondPartTextColor, SkippedLineColor, Red, Blue, Recording, Titles, ActorCharacterIcon, CharactersIcon, ScriptContextTextColorDuringRecording, } // all toolbar button images need to be this color public static Color CommonMuted = Color.FromArgb(192,192,192); private static Color NormalBackground = Color.FromArgb(65, 65, 65); private static Color NormalHighlight = Color.FromArgb(245,212,17); private static Color HighContrastHighlight = Color.FromArgb(0,255,0); private static readonly Dictionary<ColorScheme, Dictionary<ColorSchemeElement, Color>> ColorSchemes = new Dictionary<ColorScheme, Dictionary<ColorSchemeElement, Color>> { { ColorScheme.Normal, new Dictionary<ColorSchemeElement, Color> { {ColorSchemeElement.Background, NormalBackground }, {ColorSchemeElement.MouseOverButtonBackColor, Color.FromArgb(78,78,78) }, {ColorSchemeElement.NavigationTextColor, CommonMuted }, {ColorSchemeElement.ScriptFocusTextColor, NormalHighlight }, {ColorSchemeElement.ScriptContextTextColor, CommonMuted }, {ColorSchemeElement.EmptyBoxColor, CommonMuted }, {ColorSchemeElement.HilightColor, NormalHighlight }, {ColorSchemeElement.SecondPartTextColor, HighContrastHighlight }, {ColorSchemeElement.SkippedLineColor, Color.FromArgb(166,132,0) }, {ColorSchemeElement.Red, Color.FromArgb(215,2,0) }, {ColorSchemeElement.Blue, Color.FromArgb(00,8,118) }, {ColorSchemeElement.Recording, Color.FromArgb(57,165,0) }, {ColorSchemeElement.Titles, CommonMuted}, {ColorSchemeElement.ScriptContextTextColorDuringRecording, ControlPaint.Light(NormalBackground,(float) .15)}, } }, { ColorScheme.HighContrast, new Dictionary<ColorSchemeElement, Color> { {ColorSchemeElement.Background, Color.FromArgb(0,0,0) }, {ColorSchemeElement.MouseOverButtonBackColor, Color.FromArgb(0,0,0) }, {ColorSchemeElement.NavigationTextColor, CommonMuted }, {ColorSchemeElement.ScriptFocusTextColor, HighContrastHighlight }, {ColorSchemeElement.ScriptContextTextColor, CommonMuted }, {ColorSchemeElement.EmptyBoxColor, CommonMuted }, {ColorSchemeElement.HilightColor, HighContrastHighlight }, {ColorSchemeElement.SecondPartTextColor, NormalHighlight}, {ColorSchemeElement.SkippedLineColor, Color.FromArgb(33, 92, 49) }, {ColorSchemeElement.Red, Color.FromArgb(255,0,0) }, {ColorSchemeElement.Blue, Color.FromArgb(0,0,255) }, {ColorSchemeElement.Recording, Color.FromArgb(0,255,0) }, {ColorSchemeElement.Titles, CommonMuted }, {ColorSchemeElement.ScriptContextTextColorDuringRecording, Color.FromArgb(100,100,100)}, } } }; public static readonly Dictionary<ColorScheme, Dictionary<ColorSchemeElement, Image>> ColorSchemeIcons = new Dictionary<ColorScheme, Dictionary<ColorSchemeElement, Image>> { { ColorScheme.Normal, new Dictionary<ColorSchemeElement, Image> { {ColorSchemeElement.ActorCharacterIcon, Resources.speakIntoMike75x50 }, {ColorSchemeElement.CharactersIcon, Resources.characters } } }, { ColorScheme.HighContrast, new Dictionary<ColorSchemeElement, Image> { {ColorSchemeElement.ActorCharacterIcon, Resources.speakIntoMike75x50HC }, {ColorSchemeElement.CharactersIcon, Resources.charactersHC } } } }; public static ColorScheme CurrentColorScheme { get { var setScheme = Settings.Default.UserColorScheme; if (ColorSchemes.ContainsKey(setScheme)) { return setScheme; } return ColorScheme.Normal; } } public static IEnumerable<KeyValuePair<ColorScheme, string>> AvailableColorSchemes { get { foreach (var colorScheme in Enum.GetValues(typeof(ColorScheme)).Cast<ColorScheme>()) { yield return new KeyValuePair<ColorScheme, string>(colorScheme, colorScheme.ToLocalizedString()); } } } public static Image CharactersImage { get { return ColorSchemeIcons[CurrentColorScheme][ColorSchemeElement.CharactersIcon]; } } public static Image ActorCharacterImage { get { return ColorSchemeIcons[CurrentColorScheme][ColorSchemeElement.ActorCharacterIcon]; } } public static Color Background { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.Background]; } } public static Color MouseOverButtonBackColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.MouseOverButtonBackColor]; } } public static Color NavigationTextColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.NavigationTextColor]; } } public static Color ScriptFocusTextColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.ScriptFocusTextColor]; } } public static Color FaintScriptFocusTextColor { get { var focusColor = ColorSchemes[CurrentColorScheme][ColorSchemeElement.ScriptFocusTextColor]; return Color.FromArgb(128, focusColor.R, focusColor.G, focusColor.B); } } public static Color ScriptContextTextColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.ScriptContextTextColor]; } } public static Color ScriptContextTextColorDuringRecording { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.ScriptContextTextColorDuringRecording]; } } public static Color EmptyBoxColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.EmptyBoxColor]; } } public static Color HilightColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.HilightColor]; } } public static Color SecondPartTextColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.SecondPartTextColor]; } } public static Color SkippedLineColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.SkippedLineColor]; } } public static Color Red { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.Red]; } } public static Color Blue { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.Blue]; } } public static Color Recording { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.Recording]; } } public static Color TitleColor { get { return ColorSchemes[CurrentColorScheme][ColorSchemeElement.Titles]; } } public static Pen CompleteProgressPen = new Pen(HilightColor, 2); public static Brush DisabledBrush = new SolidBrush(EmptyBoxColor); public static Brush BackgroundBrush = new SolidBrush(Background); public static Pen ButtonMouseOverPen = new Pen(ScriptFocusTextColor, 3); public static Pen ButtonSuggestedPen = new Pen(ScriptFocusTextColor, 2); public static Brush ButtonRecordingBrush = new SolidBrush(Recording); public static Brush ButtonWaitingBrush = RedBrush; private static Brush _blueBrush; public static Brush BlueBrush => _blueBrush ?? (_blueBrush = new SolidBrush(Blue)); private static Brush _redBrush; public static Brush RedBrush => _redBrush ?? (_redBrush = new SolidBrush(Red)); private static Brush _emptyBoxBrush; public static Brush EmptyBoxBrush => _emptyBoxBrush ?? (_emptyBoxBrush = new SolidBrush(EmptyBoxColor)); static Brush _highlightBrush; public static Brush HighlightBrush => _highlightBrush ?? (_highlightBrush = new SolidBrush(HilightColor)); private static Brush _skippedBrush; public static Brush SkippedBrush => _skippedBrush ?? (_skippedBrush = new SolidBrush(SkippedLineColor)); } }
/* * 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 Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace OpenSim.Region.OptionalModules.ViewerSupport { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicFloater")] public class DynamicFloaterModule : INonSharedRegionModule, IDynamicFloaterModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private Dictionary<UUID, Dictionary<int, FloaterData>> m_floaters = new Dictionary<UUID, Dictionary<int, FloaterData>>(); public string Name { get { return "DynamicFloaterModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { } public void Close() { } public void AddRegion(Scene scene) { m_scene = scene; scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClientClosed += OnClientClosed; m_scene.RegisterModuleInterface<IDynamicFloaterModule>(this); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { } private void OnNewClient(IClientAPI client) { client.OnChatFromClient += OnChatFromClient; } private void OnClientClosed(UUID agentID, Scene scene) { m_floaters.Remove(agentID); } private void SendToClient(ScenePresence sp, string msg) { sp.ControllingClient.SendChatMessage(msg, (byte)ChatTypeEnum.Owner, sp.AbsolutePosition, "Server", UUID.Zero, UUID.Zero, (byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully); } public void DoUserFloater(UUID agentID, FloaterData dialogData, string configuration) { ScenePresence sp = m_scene.GetScenePresence(agentID); if (sp == null || sp.IsChildAgent) return; if (!m_floaters.ContainsKey(agentID)) m_floaters[agentID] = new Dictionary<int, FloaterData>(); if (m_floaters[agentID].ContainsKey(dialogData.Channel)) return; m_floaters[agentID].Add(dialogData.Channel, dialogData); string xml; if (dialogData.XmlText != null && dialogData.XmlText != String.Empty) { xml = dialogData.XmlText; } else { using (FileStream fs = File.Open(dialogData.XmlName + ".xml", FileMode.Open)) { using (StreamReader sr = new StreamReader(fs)) xml = sr.ReadToEnd().Replace("\n", ""); } } List<string> xparts = new List<string>(); while (xml.Length > 0) { string x = xml; if (x.Length > 600) { x = x.Substring(0, 600); xml = xml.Substring(600); } else { xml = String.Empty; } xparts.Add(x); } for (int i = 0 ; i < xparts.Count ; i++) SendToClient(sp, String.Format("># floater {2} create {0}/{1} " + xparts[i], i + 1, xparts.Count, dialogData.FloaterName)); SendToClient(sp, String.Format("># floater {0} {{notify:1}} {{channel: {1}}} {{node:cancel {{notify:1}}}} {{node:ok {{notify:1}}}} {2}", dialogData.FloaterName, (uint)dialogData.Channel, configuration)); } private void OnChatFromClient(object sender, OSChatMessage msg) { if (msg.Sender == null) return; //m_log.DebugFormat("chan {0} msg {1}", msg.Channel, msg.Message); IClientAPI client = msg.Sender; if (!m_floaters.ContainsKey(client.AgentId)) return; string[] parts = msg.Message.Split(new char[] {':'}); if (parts.Length == 0) return; ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp == null || sp.IsChildAgent) return; Dictionary<int, FloaterData> d = m_floaters[client.AgentId]; // Work around a viewer bug - VALUE from any // dialog can appear on this channel and needs to // be dispatched to ALL open dialogs for the user if (msg.Channel == 427169570) { if (parts[0] == "VALUE") { foreach (FloaterData dd in d.Values) { if(dd.Handler(client, dd, parts)) { m_floaters[client.AgentId].Remove(dd.Channel); SendToClient(sp, String.Format("># floater {0} destroy", dd.FloaterName)); break; } } } return; } if (!d.ContainsKey(msg.Channel)) return; FloaterData data = d[msg.Channel]; if (parts[0] == "NOTIFY") { if (parts[1] == "cancel" || parts[1] == data.FloaterName) { m_floaters[client.AgentId].Remove(data.Channel); SendToClient(sp, String.Format("># floater {0} destroy", data.FloaterName)); } } if (data.Handler != null && data.Handler(client, data, parts)) { m_floaters[client.AgentId].Remove(data.Channel); SendToClient(sp, String.Format("># floater {0} destroy", data.FloaterName)); } } public void FloaterControl(ScenePresence sp, FloaterData d, string msg) { string sendData = String.Format("># floater {0} {1}", d.FloaterName, msg); SendToClient(sp, sendData); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Apache.Geode.Client; namespace PdxTests { public class PositionPdx : IPdxSerializable { #region Private members private long m_avg20DaysVol; private string m_bondRating; private double m_convRatio; private string m_country; private double m_delta; private long m_industry; private long m_issuer; private double m_mktValue; private double m_qty; private string m_secId; private string m_secLinks; private string m_secType; private int m_sharesOutstanding; private string m_underlyer; private long m_volatility; private int m_pid; private static int m_count = 0; #endregion #region Private methods private void Init() { m_avg20DaysVol = 0; m_bondRating = null; m_convRatio = 0.0; m_country = null; m_delta = 0.0; m_industry = 0; m_issuer = 0; m_mktValue = 0.0; m_qty = 0.0; m_secId = null; m_secLinks = null; m_secType = null; m_sharesOutstanding = 0; m_underlyer = null; m_volatility = 0; m_pid = 0; } private UInt64 GetObjectSize(ISerializable obj) { return (obj == null ? 0 : obj.ObjectSize); } #endregion #region Public accessors public string SecId { get { return m_secId; } } public int Id { get { return m_pid; } } public int SharesOutstanding { get { return m_sharesOutstanding; } } public static int Count { get { return m_count; } set { m_count = value; } } public override string ToString() { return "Position [secId="+m_secId+" sharesOutstanding="+m_sharesOutstanding+ " type="+m_secType +" id="+m_pid+"]"; } #endregion #region Constructors public PositionPdx() { Init(); } //This ctor is for a data validation test public PositionPdx(Int32 iForExactVal) { Init(); char[] id = new char[iForExactVal+1]; for (int i = 0; i <= iForExactVal; i++) { id[i] = 'a'; } m_secId = new string(id); m_qty = iForExactVal % 2 == 0 ? 1000 : 100; m_mktValue = m_qty * 2; m_sharesOutstanding = iForExactVal; m_secType = "a"; m_pid = iForExactVal; } public PositionPdx(string id, int shares) { Init(); m_secId = id; m_qty = shares * (m_count % 2 == 0 ? 10.0 : 100.0); m_mktValue = m_qty * 1.2345998; m_sharesOutstanding = shares; m_secType = "a"; m_pid = m_count++; } #endregion public static IPdxSerializable CreateDeserializable() { return new PositionPdx(); } #region IPdxSerializable Members public void FromData(IPdxReader reader) { m_avg20DaysVol = reader.ReadLong("avg20DaysVol"); m_bondRating = reader.ReadString("bondRating"); m_convRatio = reader.ReadDouble("convRatio"); m_country = reader.ReadString("country"); m_delta = reader.ReadDouble("delta"); m_industry = reader.ReadLong("industry"); m_issuer = reader.ReadLong("issuer"); m_mktValue = reader.ReadDouble("mktValue"); m_qty = reader.ReadDouble("qty"); m_secId = reader.ReadString("secId"); m_secLinks = reader.ReadString("secLinks"); m_secType = reader.ReadString("secType"); m_sharesOutstanding = reader.ReadInt("sharesOutstanding"); m_underlyer = reader.ReadString("underlyer"); m_volatility = reader.ReadLong("volatility"); m_pid = reader.ReadInt("pid"); } public void ToData(IPdxWriter writer) { writer.WriteLong("avg20DaysVol", m_avg20DaysVol); writer.WriteString("bondRating", m_bondRating); writer.WriteDouble("convRatio", m_convRatio); writer.WriteString("country", m_country); writer.WriteDouble("delta", m_delta); writer.WriteLong("industry", m_industry); writer.WriteLong("issuer", m_issuer); writer.WriteDouble("mktValue", m_mktValue); writer.WriteDouble("qty", m_qty); writer.WriteString("secId", m_secId); writer.WriteString("secLinks", m_secLinks); writer.WriteString("secType", m_secType); writer.WriteInt("sharesOutstanding", m_sharesOutstanding); writer.WriteString("underlyer", m_underlyer); writer.WriteLong("volatility", m_volatility); writer.WriteInt("pid", m_pid); //identity field writer.MarkIdentityField("pid"); } #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.Diagnostics; using System.Text; using Microsoft.Xml; using Microsoft.Xml.XPath; using Microsoft.Xml.Schema; namespace MS.Internal.Xml.Cache { /// <summary> /// Implementation of a Node in the XPath/XQuery data model. /// 1. All nodes are stored in variable-size pages (max 65536 nodes/page) of XPathNode structures. /// 2. Pages are sequentially numbered. Nodes are allocated in strict document order. /// 3. Node references take the form of a (page, index) pair. /// 4. Each node explicitly stores a parent and a sibling reference. /// 5. If a node has one or more attributes and/or non-collapsed content children, then its first /// child is stored in the next slot. If the node is in the last slot of a page, then its first /// child is stored in the first slot of the next page. /// 6. Attributes are linked together at the start of the child list. /// 7. Namespaces are allocated in totally separate pages. Elements are associated with /// declared namespaces via a hashtable map in the document. /// 8. Name parts are always non-null (string.Empty for nodes without names) /// 9. XPathNodeInfoAtom contains all information that is common to many nodes in a /// document, and therefore is atomized to save space. This includes the document, the name, /// the child, sibling, parent, and value pages, and the schema type. /// 10. The node structure is 20 bytes in length. Out-of-line overhead is typically 2-4 bytes per node. /// </summary> internal struct XPathNode { private XPathNodeInfoAtom _info; // Atomized node information private ushort _idxSibling; // Page index of sibling node private ushort _idxParent; // Page index of parent node private ushort _idxSimilar; // Page index of next node in document order that has local name with same hashcode private ushort _posOffset; // Line position offset of node (added to LinePositionBase) private uint _props; // Node properties (broken down into bits below) private string _value; // String value of node private const uint NodeTypeMask = 0xF; private const uint HasAttributeBit = 0x10; private const uint HasContentChildBit = 0x20; private const uint HasElementChildBit = 0x40; private const uint HasCollapsedTextBit = 0x80; private const uint AllowShortcutTagBit = 0x100; // True if this is an element that allows shortcut tag syntax private const uint HasNmspDeclsBit = 0x200; // True if this is an element with namespace declarations declared on it private const uint LineNumberMask = 0x00FFFC00; // 14 bits for line number offset (0 - 16K) private const int LineNumberShift = 10; private const int CollapsedPositionShift = 24; // 8 bits for collapsed text position offset (0 - 256) #if DEBUG public const int MaxLineNumberOffset = 0x20; public const int MaxLinePositionOffset = 0x20; public const int MaxCollapsedPositionOffset = 0x10; #else public const int MaxLineNumberOffset = 0x3FFF; public const int MaxLinePositionOffset = 0xFFFF; public const int MaxCollapsedPositionOffset = 0xFF; #endif /// <summary> /// Returns the type of this node /// </summary> public XPathNodeType NodeType { get { return (XPathNodeType)(_props & NodeTypeMask); } } /// <summary> /// Returns the namespace prefix of this node. If this node has no prefix, then the empty string /// will be returned (never null). /// </summary> public string Prefix { get { return _info.Prefix; } } /// <summary> /// Returns the local name of this node. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string LocalName { get { return _info.LocalName; } } /// <summary> /// Returns the name of this node. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string Name { get { if (Prefix.Length == 0) { return LocalName; } else { return string.Concat(Prefix, ":", LocalName); } } } /// <summary> /// Returns the namespace part of this node's name. If this node has no name, then the empty string /// will be returned (never null). /// </summary> public string NamespaceUri { get { return _info.NamespaceUri; } } /// <summary> /// Returns this node's document. /// </summary> public XPathDocument Document { get { return _info.Document; } } /// <summary> /// Returns this node's base Uri. This is string.Empty for all node kinds except Element, Root, and PI. /// </summary> public string BaseUri { get { return _info.BaseUri; } } /// <summary> /// Returns this node's source line number. /// </summary> public int LineNumber { get { return _info.LineNumberBase + (int)((_props & LineNumberMask) >> LineNumberShift); } } /// <summary> /// Return this node's source line position. /// </summary> public int LinePosition { get { return _info.LinePositionBase + (int)_posOffset; } } /// <summary> /// If this node is an element with collapsed text, then return the source line position of the node (the /// source line number is the same as LineNumber). /// </summary> public int CollapsedLinePosition { get { Debug.Assert(HasCollapsedText, "Do not call CollapsedLinePosition unless HasCollapsedText is true."); return LinePosition + (int)(_props >> CollapsedPositionShift); } } /// <summary> /// Returns information about the node page. Only the 0th node on each page has this property defined. /// </summary> public XPathNodePageInfo PageInfo { get { return _info.PageInfo; } } /// <summary> /// Returns the root node of the current document. This always succeeds. /// </summary> public int GetRoot(out XPathNode[] pageNode) { return _info.Document.GetRootNode(out pageNode); } /// <summary> /// Returns the parent of this node. If this node has no parent, then 0 is returned. /// </summary> public int GetParent(out XPathNode[] pageNode) { pageNode = _info.ParentPage; return _idxParent; } /// <summary> /// Returns the next sibling of this node. If this node has no next sibling, then 0 is returned. /// </summary> public int GetSibling(out XPathNode[] pageNode) { pageNode = _info.SiblingPage; return _idxSibling; } /// <summary> /// Returns the next element in document order that has the same local name hashcode as this element. /// If there are no similar elements, then 0 is returned. /// </summary> public int GetSimilarElement(out XPathNode[] pageNode) { pageNode = _info.SimilarElementPage; return _idxSimilar; } /// <summary> /// Returns true if this node's name matches the specified localName and namespaceName. Assume /// that localName has been atomized, but namespaceName has not. /// </summary> public bool NameMatch(string localName, string namespaceName) { Debug.Assert(localName == null || (object)Document.NameTable.Get(localName) == (object)localName, "localName must be atomized."); return (object)_info.LocalName == (object)localName && _info.NamespaceUri == namespaceName; } /// <summary> /// Returns true if this is an Element node with a name that matches the specified localName and /// namespaceName. Assume that localName has been atomized, but namespaceName has not. /// </summary> public bool ElementMatch(string localName, string namespaceName) { Debug.Assert(localName == null || (object)Document.NameTable.Get(localName) == (object)localName, "localName must be atomized."); return NodeType == XPathNodeType.Element && (object)_info.LocalName == (object)localName && _info.NamespaceUri == namespaceName; } /// <summary> /// Return true if this node is an xmlns:xml node. /// </summary> public bool IsXmlNamespaceNode { get { string localName = _info.LocalName; return NodeType == XPathNodeType.Namespace && localName.Length == 3 && localName == "xml"; } } /// <summary> /// Returns true if this node has a sibling. /// </summary> public bool HasSibling { get { return _idxSibling != 0; } } /// <summary> /// Returns true if this node has a collapsed text node as its only content-typed child. /// </summary> public bool HasCollapsedText { get { return (_props & HasCollapsedTextBit) != 0; } } /// <summary> /// Returns true if this node has at least one attribute. /// </summary> public bool HasAttribute { get { return (_props & HasAttributeBit) != 0; } } /// <summary> /// Returns true if this node has at least one content-typed child (attributes and namespaces /// don't count). /// </summary> public bool HasContentChild { get { return (_props & HasContentChildBit) != 0; } } /// <summary> /// Returns true if this node has at least one element child. /// </summary> public bool HasElementChild { get { return (_props & HasElementChildBit) != 0; } } /// <summary> /// Returns true if this is an attribute or namespace node. /// </summary> public bool IsAttrNmsp { get { XPathNodeType xptyp = NodeType; return xptyp == XPathNodeType.Attribute || xptyp == XPathNodeType.Namespace; } } /// <summary> /// Returns true if this is a text or whitespace node. /// </summary> public bool IsText { get { return XPathNavigator.IsText(NodeType); } } /// <summary> /// Returns true if this node has local namespace declarations associated with it. Since all /// namespace declarations are stored out-of-line in the owner Document, this property /// can be consulted in order to avoid a lookup in the common case where this node has no /// local namespace declarations. /// </summary> public bool HasNamespaceDecls { get { return (_props & HasNmspDeclsBit) != 0; } set { if (value) _props |= HasNmspDeclsBit; else unchecked { _props &= (byte)~((uint)HasNmspDeclsBit); } } } /// <summary> /// Returns true if this node is an empty element that allows shortcut tag syntax. /// </summary> public bool AllowShortcutTag { get { return (_props & AllowShortcutTagBit) != 0; } } /// <summary> /// Cached hashcode computed over the local name of this element. /// </summary> public int LocalNameHashCode { get { return _info.LocalNameHashCode; } } /// <summary> /// Return the precomputed String value of this node (null if no value exists, i.e. document node, element node with complex content, etc). /// </summary> public string Value { get { return _value; } } //----------------------------------------------- // Node construction //----------------------------------------------- /// <summary> /// Constructs the 0th XPathNode in each page, which contains only page information. /// </summary> public void Create(XPathNodePageInfo pageInfo) { _info = new XPathNodeInfoAtom(pageInfo); } /// <summary> /// Constructs a XPathNode. Later, the idxSibling and value fields may be fixed up. /// </summary> public void Create(XPathNodeInfoAtom info, XPathNodeType xptyp, int idxParent) { Debug.Assert(info != null && idxParent <= UInt16.MaxValue); _info = info; _props = (uint)xptyp; _idxParent = (ushort)idxParent; } /// <summary> /// Set this node's line number information. /// </summary> public void SetLineInfoOffsets(int lineNumOffset, int linePosOffset) { Debug.Assert(lineNumOffset >= 0 && lineNumOffset <= MaxLineNumberOffset, "Line number offset too large or small: " + lineNumOffset); Debug.Assert(linePosOffset >= 0 && linePosOffset <= MaxLinePositionOffset, "Line position offset too large or small: " + linePosOffset); _props |= ((uint)lineNumOffset << LineNumberShift); _posOffset = (ushort)linePosOffset; } /// <summary> /// Set the position offset of this element's collapsed text. /// </summary> public void SetCollapsedLineInfoOffset(int posOffset) { Debug.Assert(posOffset >= 0 && posOffset <= MaxCollapsedPositionOffset, "Collapsed text line position offset too large or small: " + posOffset); _props |= ((uint)posOffset << CollapsedPositionShift); } /// <summary> /// Set this node's value. /// </summary> public void SetValue(string value) { _value = value; } /// <summary> /// Create an empty element value. /// </summary> public void SetEmptyValue(bool allowShortcutTag) { Debug.Assert(NodeType == XPathNodeType.Element); _value = string.Empty; if (allowShortcutTag) _props |= AllowShortcutTagBit; } /// <summary> /// Create a collapsed text node on this element having the specified value. /// </summary> public void SetCollapsedValue(string value) { Debug.Assert(NodeType == XPathNodeType.Element); _value = value; _props |= HasContentChildBit | HasCollapsedTextBit; } /// <summary> /// This method is called when a new child is appended to this node's list of attributes and children. /// The type of the new child is used to determine how various parent properties should be set. /// </summary> public void SetParentProperties(XPathNodeType xptyp) { if (xptyp == XPathNodeType.Attribute) { _props |= HasAttributeBit; } else { _props |= HasContentChildBit; if (xptyp == XPathNodeType.Element) _props |= HasElementChildBit; } } /// <summary> /// Link this node to its next sibling. If "pageSibling" is different than the one stored in the InfoAtom, re-atomize. /// </summary> public void SetSibling(XPathNodeInfoTable infoTable, XPathNode[] pageSibling, int idxSibling) { Debug.Assert(pageSibling != null && idxSibling != 0 && idxSibling <= UInt16.MaxValue, "Bad argument"); Debug.Assert(_idxSibling == 0, "SetSibling should not be called more than once."); _idxSibling = (ushort)idxSibling; if (pageSibling != _info.SiblingPage) { // Re-atomize the InfoAtom _info = infoTable.Create(_info.LocalName, _info.NamespaceUri, _info.Prefix, _info.BaseUri, _info.ParentPage, pageSibling, _info.SimilarElementPage, _info.Document, _info.LineNumberBase, _info.LinePositionBase); } } /// <summary> /// Link this element to the next element in document order that shares a local name having the same hash code. /// If "pageSimilar" is different than the one stored in the InfoAtom, re-atomize. /// </summary> public void SetSimilarElement(XPathNodeInfoTable infoTable, XPathNode[] pageSimilar, int idxSimilar) { Debug.Assert(pageSimilar != null && idxSimilar != 0 && idxSimilar <= UInt16.MaxValue, "Bad argument"); Debug.Assert(_idxSimilar == 0, "SetSimilarElement should not be called more than once."); _idxSimilar = (ushort)idxSimilar; if (pageSimilar != _info.SimilarElementPage) { // Re-atomize the InfoAtom _info = infoTable.Create(_info.LocalName, _info.NamespaceUri, _info.Prefix, _info.BaseUri, _info.ParentPage, _info.SiblingPage, pageSimilar, _info.Document, _info.LineNumberBase, _info.LinePositionBase); } } } /// <summary> /// A reference to a XPathNode is composed of two values: the page on which the node is located, and the node's /// index in the page. /// </summary> internal struct XPathNodeRef { private XPathNode[] _page; private int _idx; public static XPathNodeRef Null { get { return new XPathNodeRef(); } } public XPathNodeRef(XPathNode[] page, int idx) { _page = page; _idx = idx; } public bool IsNull { get { return _page == null; } } public XPathNode[] Page { get { return _page; } } public int Index { get { return _idx; } } public override int GetHashCode() { return XPathNodeHelper.GetLocation(_page, _idx); } } }
using System; using System.Collections.Generic; using System.Net; using System.Runtime.Serialization; using System.Web; using NServiceKit.Common; using NServiceKit.Common.Web; using NServiceKit.Text; using NServiceKit.WebHost.Endpoints; using HttpRequestWrapper = NServiceKit.WebHost.Endpoints.Extensions.HttpRequestWrapper; namespace NServiceKit.ServiceHost { /// <summary>A HTTP request extensions.</summary> public static class HttpRequestExtensions { /// <summary> /// Gets string value from Items[name] then Cookies[name] if exists. /// Useful when *first* setting the users response cookie in the request filter. /// To access the value for this initial request you need to set it in Items[]. /// </summary> /// <returns>string value or null if it doesn't exist</returns> public static string GetItemOrCookie(this IHttpRequest httpReq, string name) { object value; if (httpReq.Items.TryGetValue(name, out value)) return value.ToString(); Cookie cookie; if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value; return null; } /// <summary> /// Gets request paramater string value by looking in the following order: /// - QueryString[name] /// - FormData[name] /// - Cookies[name] /// - Items[name] /// </summary> /// <returns>string value or null if it doesn't exist</returns> public static string GetParam(this IHttpRequest httpReq, string name) { string value; if ((value = httpReq.Headers[HttpHeaders.XParamOverridePrefix + name]) != null) return value; if ((value = httpReq.QueryString[name]) != null) return value; if ((value = httpReq.FormData[name]) != null) return value; //IIS will assign null to params without a name: .../?some_value can be retrieved as req.Params[null] //TryGetValue is not happy with null dictionary keys, so we should bail out here if (string.IsNullOrEmpty(name)) return null; Cookie cookie; if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value; object oValue; if (httpReq.Items.TryGetValue(name, out oValue)) return oValue.ToString(); return null; } /// <summary>An IHttpRequest extension method that gets the parent absolute path.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The parent absolute path.</returns> public static string GetParentAbsolutePath(this IHttpRequest httpReq) { return httpReq.GetAbsolutePath().ToParentPath(); } /// <summary>An IHttpRequest extension method that gets absolute path.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The absolute path.</returns> public static string GetAbsolutePath(this IHttpRequest httpReq) { var resolvedPathInfo = httpReq.PathInfo; var pos = httpReq.RawUrl.IndexOf(resolvedPathInfo, StringComparison.InvariantCultureIgnoreCase); if (pos == -1) throw new ArgumentException( String.Format("PathInfo '{0}' is not in Url '{1}'", resolvedPathInfo, httpReq.RawUrl)); return httpReq.RawUrl.Substring(0, pos + resolvedPathInfo.Length); } /// <summary>An IHttpRequest extension method that gets the parent path URL.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The parent path URL.</returns> public static string GetParentPathUrl(this IHttpRequest httpReq) { return httpReq.GetPathUrl().ToParentPath(); } /// <summary>An IHttpRequest extension method that gets path URL.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The path URL.</returns> public static string GetPathUrl(this IHttpRequest httpReq) { var resolvedPathInfo = httpReq.PathInfo; var pos = resolvedPathInfo == String.Empty ? httpReq.AbsoluteUri.Length : httpReq.AbsoluteUri.IndexOf(resolvedPathInfo, StringComparison.InvariantCultureIgnoreCase); if (pos == -1) throw new ArgumentException( String.Format("PathInfo '{0}' is not in Url '{1}'", resolvedPathInfo, httpReq.RawUrl)); return httpReq.AbsoluteUri.Substring(0, pos + resolvedPathInfo.Length); } /// <summary>An IHttpRequest extension method that gets URL host name.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The URL host name.</returns> public static string GetUrlHostName(this IHttpRequest httpReq) { var aspNetReq = httpReq as HttpRequestWrapper; if (aspNetReq != null) { return aspNetReq.UrlHostName; } var uri = httpReq.AbsoluteUri; var pos = uri.IndexOf("://") + "://".Length; var partialUrl = uri.Substring(pos); var endPos = partialUrl.IndexOf('/'); if (endPos == -1) endPos = partialUrl.Length; var hostName = partialUrl.Substring(0, endPos).Split(':')[0]; return hostName; } /// <summary>An IHttpRequest extension method that gets physical path.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The physical path.</returns> public static string GetPhysicalPath(this IHttpRequest httpReq) { var aspNetReq = httpReq as HttpRequestWrapper; var res = aspNetReq != null ? aspNetReq.Request.PhysicalPath : EndpointHostConfig.Instance.WebHostPhysicalPath.CombineWith(httpReq.PathInfo); return res; } /// <summary>An IHttpRequest extension method that gets application URL.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The application URL.</returns> public static string GetApplicationUrl(this HttpRequest httpReq) { var appPath = httpReq.ApplicationPath; var baseUrl = httpReq.Url.Scheme + "://" + httpReq.Url.Host; if (httpReq.Url.Port != 80) baseUrl += ":" + httpReq.Url.Port; var appUrl = baseUrl.CombineWith(appPath); return appUrl; } /// <summary>An IHttpRequest extension method that gets application URL.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The application URL.</returns> public static string GetApplicationUrl(this IHttpRequest httpReq) { var url = new Uri(httpReq.AbsoluteUri); var baseUrl = url.Scheme + "://" + url.Host; if (url.Port != 80) baseUrl += ":" + url.Port; var appUrl = baseUrl.CombineWith(EndpointHost.Config.NServiceKitHandlerFactoryPath); return appUrl; } /// <summary>An IHttpRequest extension method that gets HTTP method override.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The HTTP method override.</returns> public static string GetHttpMethodOverride(this IHttpRequest httpReq) { var httpMethod = httpReq.HttpMethod; if (httpMethod != HttpMethods.Post) return httpMethod; var overrideHttpMethod = httpReq.Headers[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty() ?? httpReq.FormData[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty() ?? httpReq.QueryString[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty(); if (overrideHttpMethod != null) { if (overrideHttpMethod != HttpMethods.Get && overrideHttpMethod != HttpMethods.Post) httpMethod = overrideHttpMethod; } return httpMethod; } /// <summary>An IHttpRequest extension method that gets format modifier.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The format modifier.</returns> public static string GetFormatModifier(this IHttpRequest httpReq) { var format = httpReq.QueryString["format"]; if (format == null) return null; var parts = format.SplitOnFirst('.'); return parts.Length > 1 ? parts[1] : null; } /// <summary>An IHttpRequest extension method that query if 'httpReq' has not modified since.</summary> /// /// <param name="httpReq"> The httpReq to act on.</param> /// <param name="dateTime">The date time.</param> /// /// <returns>true if not modified since, false if not.</returns> public static bool HasNotModifiedSince(this IHttpRequest httpReq, DateTime? dateTime) { if (!dateTime.HasValue) return false; var strHeader = httpReq.Headers[HttpHeaders.IfModifiedSince]; try { if (strHeader != null) { var dateIfModifiedSince = DateTime.ParseExact(strHeader, "r", null); var utcFromDate = dateTime.Value.ToUniversalTime(); //strip ms utcFromDate = new DateTime( utcFromDate.Ticks - (utcFromDate.Ticks % TimeSpan.TicksPerSecond), utcFromDate.Kind ); return utcFromDate <= dateIfModifiedSince; } return false; } catch { return false; } } /// <summary>An IHttpRequest extension method that did return 304 not modified.</summary> /// /// <param name="httpReq"> The httpReq to act on.</param> /// <param name="dateTime">The date time.</param> /// <param name="httpRes"> The HTTP resource.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> public static bool DidReturn304NotModified(this IHttpRequest httpReq, DateTime? dateTime, IHttpResponse httpRes) { if (httpReq.HasNotModifiedSince(dateTime)) { httpRes.StatusCode = (int) HttpStatusCode.NotModified; return true; } return false; } /// <summary>An IHttpRequest extension method that callback, called when the get jsonp.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>The jsonp callback.</returns> public static string GetJsonpCallback(this IHttpRequest httpReq) { return httpReq == null ? null : httpReq.QueryString["callback"]; } /// <summary>An IHttpRequest extension method that cookies as dictionary.</summary> /// /// <param name="httpReq">The httpReq to act on.</param> /// /// <returns>A Dictionary&lt;string,string&gt;</returns> public static Dictionary<string, string> CookiesAsDictionary(this IHttpRequest httpReq) { var map = new Dictionary<string, string>(); var aspNet = httpReq.OriginalRequest as HttpRequest; if (aspNet != null) { foreach (var name in aspNet.Cookies.AllKeys) { var cookie = aspNet.Cookies[name]; if (cookie == null) continue; map[name] = cookie.Value; } } else { var httpListener = httpReq.OriginalRequest as HttpListenerRequest; if (httpListener != null) { for (var i = 0; i < httpListener.Cookies.Count; i++) { var cookie = httpListener.Cookies[i]; if (cookie == null || cookie.Name == null) continue; map[cookie.Name] = cookie.Value; } } } return map; } /// <summary>An Exception extension method that converts an ex to the status code.</summary> /// /// <param name="ex">The ex to act on.</param> /// /// <returns>ex as an int.</returns> public static int ToStatusCode(this Exception ex) { int errorStatus; if (EndpointHost.Config != null && EndpointHost.Config.MapExceptionToStatusCode.TryGetValue(ex.GetType(), out errorStatus)) { return errorStatus; } if (ex is HttpError) return ((HttpError)ex).Status; if (ex is NotImplementedException || ex is NotSupportedException) return (int)HttpStatusCode.MethodNotAllowed; if (ex is ArgumentException || ex is SerializationException) return (int)HttpStatusCode.BadRequest; if (ex is UnauthorizedAccessException) return (int) HttpStatusCode.Forbidden; return (int)HttpStatusCode.InternalServerError; } /// <summary>An Exception extension method that converts an ex to an error code.</summary> /// /// <param name="ex">The ex to act on.</param> /// /// <returns>ex as a string.</returns> public static string ToErrorCode(this Exception ex) { if (ex is HttpError) return ((HttpError)ex).ErrorCode; return ex.GetType().Name; } } }