context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; using UnityEditor; #if UNITY_5_5_OR_NEWER using UnityEngine.Profiling; #endif using V1=AssetBundleGraph; using Model=UnityEngine.AssetBundles.GraphTool.DataModel.Version2; namespace UnityEngine.AssetBundles.GraphTool { [CustomNode("Group Assets/Group By Size", 41)] public class GroupingBySize : Node { enum GroupingType : int { ByFileSize, ByRuntimeMemorySize }; [SerializeField] private SerializableMultiTargetInt m_groupSizeByte; [SerializeField] private SerializableMultiTargetInt m_groupingType; public override string ActiveStyle { get { return "node 2 on"; } } public override string InactiveStyle { get { return "node 2"; } } public override string Category { get { return "Group"; } } public override void Initialize(Model.NodeData data) { m_groupSizeByte = new SerializableMultiTargetInt(); m_groupingType = new SerializableMultiTargetInt(); data.AddDefaultInputPoint(); data.AddDefaultOutputPoint(); } public override Node Clone(Model.NodeData newData) { var newNode = new GroupingBySize(); newNode.m_groupSizeByte = new SerializableMultiTargetInt(m_groupSizeByte); newNode.m_groupingType = new SerializableMultiTargetInt(m_groupingType); newData.AddDefaultInputPoint(); newData.AddDefaultOutputPoint(); return newNode; } public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) { if (m_groupSizeByte == null) { return; } EditorGUILayout.HelpBox("Grouping by size: Create group of assets by size.", MessageType.Info); editor.UpdateNodeName(node); GUILayout.Space(10f); //Show target configuration tab editor.DrawPlatformSelector(node); using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { var disabledScope = editor.DrawOverrideTargetToggle(node, m_groupSizeByte.ContainsValueOf(editor.CurrentEditingGroup), (bool enabled) => { using(new RecordUndoScope("Remove Target Grouping Size Settings", node, true)){ if(enabled) { m_groupSizeByte[editor.CurrentEditingGroup] = m_groupSizeByte.DefaultValue; m_groupingType[editor.CurrentEditingGroup] = m_groupingType.DefaultValue; } else { m_groupSizeByte.Remove(editor.CurrentEditingGroup); m_groupingType.Remove(editor.CurrentEditingGroup); } onValueChanged(); } }); using (disabledScope) { var newType = (GroupingType)EditorGUILayout.EnumPopup("Grouping Type",(GroupingType)m_groupingType[editor.CurrentEditingGroup]); if (newType != (GroupingType)m_groupingType[editor.CurrentEditingGroup]) { using(new RecordUndoScope("Change Grouping Type", node, true)){ m_groupingType[editor.CurrentEditingGroup] = (int)newType; onValueChanged(); } } var newSizeText = EditorGUILayout.TextField("Size(KB)",m_groupSizeByte[editor.CurrentEditingGroup].ToString()); int newSize = 0; Int32.TryParse (newSizeText, out newSize); if (newSize != m_groupSizeByte[editor.CurrentEditingGroup]) { using(new RecordUndoScope("Change Grouping Size", node, true)){ m_groupSizeByte[editor.CurrentEditingGroup] = newSize; onValueChanged(); } } } } } public override void Prepare (BuildTarget target, Model.NodeData node, IEnumerable<PerformGraph.AssetGroups> incoming, IEnumerable<Model.ConnectionData> connectionsToOutput, PerformGraph.Output Output) { GroupingOutput(target, node, incoming, connectionsToOutput, Output); } private void GroupingOutput (BuildTarget target, Model.NodeData node, IEnumerable<PerformGraph.AssetGroups> incoming, IEnumerable<Model.ConnectionData> connectionsToOutput, PerformGraph.Output Output) { ValidateGroupingKeyword( m_groupSizeByte[target], () => { throw new NodeException("Invalid size.", node.Id); } ); if(connectionsToOutput == null || Output == null) { return; } var outputDict = new Dictionary<string, List<AssetReference>>(); long szGroup = m_groupSizeByte[target] * 1000; int groupCount = 0; long szGroupCount = 0; var groupName = groupCount.ToString(); if(incoming != null) { foreach(var ag in incoming) { foreach (var assets in ag.assetGroups.Values) { foreach(var a in assets) { szGroupCount += GetSizeOfAsset(a, (GroupingType)m_groupingType[target]); if (!outputDict.ContainsKey(groupName)) { outputDict[groupName] = new List<AssetReference>(); } outputDict[groupName].Add(a); if(szGroupCount >= szGroup) { szGroupCount = 0; ++groupCount; groupName = groupCount.ToString(); } } } } } var dst = (connectionsToOutput == null || !connectionsToOutput.Any())? null : connectionsToOutput.First(); Output(dst, outputDict); } public override bool OnAssetsReimported( Model.NodeData nodeData, AssetReferenceStreamManager streamManager, BuildTarget target, string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { return true; } private long GetSizeOfAsset(AssetReference a, GroupingType t) { long size = 0; // You can not read scene and do estimate if (TypeUtility.GetTypeOfAsset (a.importFrom) == typeof(UnityEditor.SceneAsset)) { t = GroupingType.ByFileSize; } if (t == GroupingType.ByRuntimeMemorySize) { var objects = a.allData; foreach (var o in objects) { #if UNITY_5_6_OR_NEWER size += Profiler.GetRuntimeMemorySizeLong (o); #else size += Profiler.GetRuntimeMemorySize(o); #endif } a.ReleaseData (); } else if (t == GroupingType.ByFileSize) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(a.absolutePath); if (fileInfo.Exists) { size = fileInfo.Length; } } return size; } private void ValidateGroupingKeyword (int currentSize, Action InvlaidSize ) { if (currentSize < 0) { InvlaidSize(); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.CompilerServices; using System.Text; namespace ICSharpCode.TextEditor.Document { public class SelectionManager : IDisposable { private TextLocation selectionStart; private IDocument document; private TextArea textArea; internal SelectFrom selectFrom = new SelectFrom(); internal List<ISelection> selectionCollection = new List<ISelection>(); public event EventHandler SelectionChanged; internal TextLocation SelectionStart { get { return this.selectionStart; } set { this.selectionStart = value; } } public List<ISelection> SelectionCollection { get { return this.selectionCollection; } } public bool HasSomethingSelected { get { return this.selectionCollection.Count > 0; } } public bool SelectionIsReadonly { get { if(this.document.ReadOnly) { return true; } foreach(ISelection current in this.selectionCollection) { if(SelectionManager.SelectionIsReadOnly(this.document, current)) { return true; } } return false; } } public string SelectedText { get { StringBuilder stringBuilder = new StringBuilder(); foreach(ISelection current in this.selectionCollection) { stringBuilder.Append(current.SelectedText); } return stringBuilder.ToString(); } } internal static bool SelectionIsReadOnly(IDocument document, ISelection sel) { if(document.TextEditorProperties.SupportReadOnlySegments) { return document.MarkerStrategy.GetMarkers(sel.Offset, sel.Length).Exists((TextMarker m) => m.IsReadOnly); } return false; } public SelectionManager(IDocument document) { this.document = document; document.DocumentChanged += new DocumentEventHandler(this.DocumentChanged); } public SelectionManager(IDocument document, TextArea textArea) { this.document = document; this.textArea = textArea; document.DocumentChanged += new DocumentEventHandler(this.DocumentChanged); } public void Dispose() { if(this.document != null) { this.document.DocumentChanged -= new DocumentEventHandler(this.DocumentChanged); this.document = null; } } private void DocumentChanged(object sender, DocumentEventArgs e) { if(e.Text == null) { this.Remove(e.Offset, e.Length); return; } if(e.Length < 0) { this.Insert(e.Offset, e.Text); return; } this.Replace(e.Offset, e.Length, e.Text); } public void SetSelection(ISelection selection) { if(selection == null) { this.ClearSelection(); return; } if(this.SelectionCollection.Count == 1 && selection.StartPosition == this.SelectionCollection[0].StartPosition && selection.EndPosition == this.SelectionCollection[0].EndPosition) { return; } this.ClearWithoutUpdate(); this.selectionCollection.Add(selection); this.document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.LinesBetween, selection.StartPosition.Y, selection.EndPosition.Y)); this.document.CommitUpdate(); this.OnSelectionChanged(EventArgs.Empty); } public void SetSelection( int startColumn, int endColumn,int line) { this.SetSelection(startColumn, line, endColumn, line); } public void SetSelection(int startColumn, int startLine, int endColumn, int endLine) { this.SetSelection(new TextLocation(startColumn, startLine), new TextLocation(endColumn, endLine)); } public void SetSelection(TextLocation startPosition, TextLocation endPosition) { this.SetSelection(new DefaultSelection(this.document, startPosition, endPosition)); } public bool GreaterEqPos(TextLocation p1, TextLocation p2) { return p1.Y > p2.Y || (p1.Y == p2.Y && p1.X >= p2.X); } public void ExtendSelection(TextLocation oldPosition, TextLocation newPosition) { if(oldPosition == newPosition) { return; } int x = newPosition.X; bool flag = this.GreaterEqPos(oldPosition, newPosition); TextLocation textLocation; TextLocation textLocation2; if(flag) { textLocation = newPosition; textLocation2 = oldPosition; } else { textLocation = oldPosition; textLocation2 = newPosition; } if(textLocation == textLocation2) { return; } if(!this.HasSomethingSelected) { this.SetSelection(new DefaultSelection(this.document, textLocation, textLocation2)); if(this.selectFrom.where == 0) { this.SelectionStart = oldPosition; } return; } ISelection selection = this.selectionCollection[0]; if(textLocation == textLocation2) { return; } if(this.selectFrom.where == 1) { newPosition.X = 0; } if(this.GreaterEqPos(newPosition, this.SelectionStart)) { selection.StartPosition = this.SelectionStart; if(this.selectFrom.where == 1) { selection.EndPosition = new TextLocation(this.textArea.Caret.Column, this.textArea.Caret.Line); } else { newPosition.X = x; selection.EndPosition = newPosition; } } else { if(this.selectFrom.where == 1 && this.selectFrom.first == 1) { selection.EndPosition = this.NextValidPosition(this.SelectionStart.Y); } else { selection.EndPosition = this.SelectionStart; } selection.StartPosition = newPosition; } this.document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.LinesBetween, textLocation.Y, textLocation2.Y)); this.document.CommitUpdate(); this.OnSelectionChanged(EventArgs.Empty); } public TextLocation NextValidPosition(int line) { if(line < this.document.TotalNumberOfLines - 1) { return new TextLocation(0, line + 1); } return new TextLocation(this.document.GetLineSegment(this.document.TotalNumberOfLines - 1).Length + 1, line); } private void ClearWithoutUpdate() { while(this.selectionCollection.Count > 0) { ISelection selection = this.selectionCollection[this.selectionCollection.Count - 1]; this.selectionCollection.RemoveAt(this.selectionCollection.Count - 1); this.document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.LinesBetween, selection.StartPosition.Y, selection.EndPosition.Y)); this.OnSelectionChanged(EventArgs.Empty); } } public void ClearSelection() { Point mousepos = this.textArea.mousepos; this.selectFrom.first = this.selectFrom.where; TextLocation logicalPosition = this.textArea.TextView.GetLogicalPosition(mousepos.X - this.textArea.TextView.DrawingPosition.X, mousepos.Y - this.textArea.TextView.DrawingPosition.Y); if(this.selectFrom.where == 1) { logicalPosition.X = 0; } if(logicalPosition.Line >= this.document.TotalNumberOfLines) { logicalPosition.Line = this.document.TotalNumberOfLines - 1; logicalPosition.Column = this.document.GetLineSegment(this.document.TotalNumberOfLines - 1).Length; } this.SelectionStart = logicalPosition; this.ClearWithoutUpdate(); this.document.CommitUpdate(); } public void RemoveSelectedText() { if(this.SelectionIsReadonly) { this.ClearSelection(); return; } List<int> list = new List<int>(); int num = -1; bool flag = true; foreach(ISelection current in this.selectionCollection) { if(flag) { int y = current.StartPosition.Y; if(y != current.EndPosition.Y) { flag = false; } else { list.Add(y); } } num = current.Offset; this.document.Remove(current.Offset, current.Length); } this.ClearSelection(); if(num != -1) { if(flag) { using(List<int>.Enumerator enumerator2 = list.GetEnumerator()) { while(enumerator2.MoveNext()) { int current2 = enumerator2.Current; this.document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.SingleLine, current2)); } goto IL_FB; } } this.document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea)); IL_FB: this.document.CommitUpdate(); } } private bool SelectionsOverlap(ISelection s1, ISelection s2) { return (s1.Offset <= s2.Offset && s2.Offset <= s1.Offset + s1.Length) || (s1.Offset <= s2.Offset + s2.Length && s2.Offset + s2.Length <= s1.Offset + s1.Length) || (s1.Offset >= s2.Offset && s1.Offset + s1.Length <= s2.Offset + s2.Length); } public bool IsSelected(int offset) { return this.GetSelectionAt(offset) != null; } public ISelection GetSelectionAt(int offset) { foreach(ISelection current in this.selectionCollection) { if(current.ContainsOffset(offset)) { return current; } } return null; } internal void Insert(int offset, string text) { } internal void Remove(int offset, int length) { } internal void Replace(int offset, int length, string text) { } public ColumnRange GetSelectionAtLine(int lineNumber) { foreach(ISelection current in this.selectionCollection) { int y = current.StartPosition.Y; int y2 = current.EndPosition.Y; if(y < lineNumber && lineNumber < y2) { ColumnRange result = ColumnRange.WholeColumn; return result; } if(y == lineNumber) { LineSegment lineSegment = this.document.GetLineSegment(y); int x = current.StartPosition.X; int endColumn = (y2 == lineNumber) ? current.EndPosition.X : (lineSegment.Length + 1); ColumnRange result = new ColumnRange(x, endColumn); return result; } if(y2 == lineNumber) { int x2 = current.EndPosition.X; ColumnRange result = new ColumnRange(0, x2); return result; } } return ColumnRange.NoColumn; } public void FireSelectionChanged() { this.OnSelectionChanged(EventArgs.Empty); } protected virtual void OnSelectionChanged(EventArgs e) { if(this.SelectionChanged != null) { this.SelectionChanged(this, e); } } } }
// // ChangeTrackerTest.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using System.Net; using Couchbase.Lite; using Couchbase.Lite.Replicator; using Couchbase.Lite.Util; using NUnit.Framework; using Sharpen; using Couchbase.Lite.Support; using System.Net.Http; using System.Threading.Tasks; namespace Couchbase.Lite.Replicator { public class ChangeTrackerTest : LiteTestCase { public const string Tag = "ChangeTracker"; /// <exception cref="System.Exception"></exception> public virtual void TestChangeTracker() { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); Uri testURL = GetReplicationURL(); IChangeTrackerClient client = new _ChangeTrackerClient_31(changeTrackerFinishedSignal ); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .OneShot, 0, client); changeTracker.Start(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_31 : IChangeTrackerClient { public _ChangeTrackerClient_31(CountDownLatch changeTrackerFinishedSignal) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change["seq"]; } public HttpClient GetHttpClient() { return CouchbaseLiteHttpClientFactory.Instance.GetHttpClient(); } private readonly CountDownLatch changeTrackerFinishedSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerLongPoll() { ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode.LongPoll); } /// <exception cref="System.Exception"></exception> public virtual void FailingTestChangeTrackerContinuous() { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); CountDownLatch changeReceivedSignal = new CountDownLatch(1); Uri testURL = GetReplicationURL(); IChangeTrackerClient client = new _ChangeTrackerClient_72(changeTrackerFinishedSignal , changeReceivedSignal); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .Continuous, 0, client); changeTracker.Start(); try { bool success = changeReceivedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_72 : IChangeTrackerClient { public _ChangeTrackerClient_72(CountDownLatch changeTrackerFinishedSignal, CountDownLatch changeReceivedSignal) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.changeReceivedSignal = changeReceivedSignal; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change["seq"]; changeReceivedSignal.CountDown(); } public HttpClient GetHttpClient() { return new DefaultHttpClient(); } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly CountDownLatch changeReceivedSignal; } /// <exception cref="System.Exception"></exception> public virtual void ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode mode ) { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); CountDownLatch changeReceivedSignal = new CountDownLatch(1); Uri testURL = GetReplicationURL(); IChangeTrackerClient client = new _ChangeTrackerClient_119(changeTrackerFinishedSignal , changeReceivedSignal); ChangeTracker changeTracker = new ChangeTracker(testURL, mode, 0, client); changeTracker.Start(); try { bool success = changeReceivedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_119 : IChangeTrackerClient { public _ChangeTrackerClient_119(CountDownLatch changeTrackerFinishedSignal, CountDownLatch changeReceivedSignal) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.changeReceivedSignal = changeReceivedSignal; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change["seq"]; NUnit.Framework.Assert.AreEqual("*:1", seq.ToString()); changeReceivedSignal.CountDown(); } public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.SetResponder("_changes", new _Responder_136()); return mockHttpClient; } private sealed class _Responder_136 : CustomizableMockHttpClient.Responder { public _Responder_136() { } /// <exception cref="System.IO.IOException"></exception> public HttpResponse Execute(HttpRequestMessage httpUriRequest) { string json = "{\"results\":[\n" + "{\"seq\":\"*:1\",\"id\":\"doc1-138\",\"changes\":[{\"rev\":\"1-82d\"}]}],\n" + "\"last_seq\":\"*:50\"}"; return CustomizableMockHttpClient.GenerateHttpResponseObject(json); } } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly CountDownLatch changeReceivedSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerWithFilterURL() { Uri testURL = GetReplicationURL(); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, 0, null); // set filter changeTracker.SetFilterName("filter"); // build filter map IDictionary<string, object> filterMap = new Dictionary<string, object>(); filterMap["param"] = "value"; // set filter map changeTracker.SetFilterParams(filterMap); NUnit.Framework.Assert.AreEqual("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=filter&param=value" , changeTracker.GetChangesFeedPath()); } public virtual void TestChangeTrackerWithDocsIds() { Uri testURL = GetReplicationURL(); ChangeTracker changeTrackerDocIds = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, 0, null); IList<string> docIds = new AList<string>(); docIds.AddItem("doc1"); docIds.AddItem("doc2"); changeTrackerDocIds.SetDocIDs(docIds); string docIdsEncoded = URLEncoder.Encode("[\"doc1\",\"doc2\"]"); string expectedFeedPath = string.Format("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=_doc_ids&doc_ids=%s" , docIdsEncoded); string changesFeedPath = changeTrackerDocIds.GetChangesFeedPath(); NUnit.Framework.Assert.AreEqual(expectedFeedPath, changesFeedPath); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerBackoff() { Uri testURL = GetReplicationURL(); CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); IChangeTrackerClient client = new _ChangeTrackerClient_214(mockHttpClient); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, 0, client); BackgroundTask task = new _BackgroundTask_235(changeTracker); task.Execute(); try { // expected behavior: // when: // mockHttpClient throws IOExceptions -> it should start high and then back off and numTimesExecute should be low for (int i = 0; i < 30; i++) { int numTimesExectutedAfter10seconds = 0; try { Sharpen.Thread.Sleep(1000); // take a snapshot of num times the http client was called after 10 seconds if (i == 10) { numTimesExectutedAfter10seconds = mockHttpClient.GetCapturedRequests().Count; } // take another snapshot after 20 seconds have passed if (i == 20) { // by now it should have backed off, so the delta between 10s and 20s should be small int delta = mockHttpClient.GetCapturedRequests().Count - numTimesExectutedAfter10seconds; NUnit.Framework.Assert.IsTrue(delta < 25); } } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } } finally { changeTracker.Stop(); } } private sealed class _ChangeTrackerClient_214 : IChangeTrackerClient { public _ChangeTrackerClient_214(CustomizableMockHttpClient mockHttpClient) { this.mockHttpClient = mockHttpClient; } public void ChangeTrackerStopped(ChangeTracker tracker) { Log.V(ChangeTrackerTest.Tag, "changeTrackerStopped"); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change["seq"]; Log.V(ChangeTrackerTest.Tag, "changeTrackerReceivedChange: " + seq.ToString()); } public HttpClient GetHttpClient() { return mockHttpClient; } private readonly CustomizableMockHttpClient mockHttpClient; } private sealed class _BackgroundTask_235 : Runnable { public _BackgroundTask_235(ChangeTracker changeTracker) { this.changeTracker = changeTracker; } public override void Run() { changeTracker.Start(); } private readonly ChangeTracker changeTracker; } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerInvalidJson() { Uri testURL = GetReplicationURL(); CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); IChangeTrackerClient client = new _ChangeTrackerClient_290(mockHttpClient); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, 0, client); var task = Task.Factory.StartNew(()=> { changeTracker.Start(); }); task.Start(); try { // expected behavior: // when: // mockHttpClient throws IOExceptions -> it should start high and then back off and numTimesExecute should be low for (int i = 0; i < 30; i++) { int numTimesExectutedAfter10seconds = 0; try { Sharpen.Thread.Sleep(1000); // take a snapshot of num times the http client was called after 10 seconds if (i == 10) { numTimesExectutedAfter10seconds = mockHttpClient.GetCapturedRequests().Count; } // take another snapshot after 20 seconds have passed if (i == 20) { // by now it should have backed off, so the delta between 10s and 20s should be small int delta = mockHttpClient.GetCapturedRequests().Count - numTimesExectutedAfter10seconds; NUnit.Framework.Assert.IsTrue(delta < 25); } } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } } finally { changeTracker.Stop(); } } private sealed class _ChangeTrackerClient_290 : IChangeTrackerClient { public _ChangeTrackerClient_290(CustomizableMockHttpClient mockHttpClient) { this.mockHttpClient = mockHttpClient; } public HttpClientHandler HttpHandler { get { throw new NotImplementedException (); } } public void ChangeTrackerStopped(ChangeTracker tracker) { Log.V(ChangeTrackerTest.Tag, "changeTrackerStopped"); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change["seq"]; Log.V(ChangeTrackerTest.Tag, "changeTrackerReceivedChange: " + seq.ToString()); } public HttpClient GetHttpClient() { return mockHttpClient; } private readonly CustomizableMockHttpClient mockHttpClient; } } }
// // Mono.WebServer.XSPApplicationHost // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // Lluis Sanchez Gual (lluis@ximian.com) // // (C) Copyright 2004-2007 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Threading; using Mono.Security.Protocol.Tls; using Mono.WebServer.Log; using SecurityProtocolType = Mono.Security.Protocol.Tls.SecurityProtocolType; namespace Mono.WebServer.XSP { // // XSPWorker: The worker that do the initial processing of XSP // requests. // class XSPWorker: Worker { readonly ApplicationServer server; readonly LingeringNetworkStream netStream; readonly Stream stream; readonly IPEndPoint remoteEP; readonly IPEndPoint localEP; readonly Socket sock; readonly SslInformation ssl; InitialWorkerRequest initial; int requestId = -1; XSPRequestBroker broker; int reuses; public XSPWorker (Socket client, EndPoint localEP, ApplicationServer server, bool secureConnection, SecurityProtocolType securityProtocol, X509Certificate cert, PrivateKeySelectionCallback keyCB, bool allowClientCert, bool requireClientCert) { if (secureConnection) { ssl = new SslInformation { AllowClientCertificate = allowClientCert, RequireClientCertificate = requireClientCert, RawServerCertificate = cert.GetRawCertData () }; netStream = new LingeringNetworkStream (client, true); var s = new SslServerStream (netStream, cert, requireClientCert, false); s.PrivateKeyCertSelectionDelegate += keyCB; s.ClientCertValidationDelegate += ClientCertificateValidation; stream = s; } else { netStream = new LingeringNetworkStream (client, false); stream = netStream; } sock = client; this.server = server; remoteEP = (IPEndPoint) client.RemoteEndPoint; this.localEP = (IPEndPoint) localEP; } public override bool IsAsync { get { return true; } } public override void SetReuseCount (int nreuses) { reuses = nreuses; } public override int GetRemainingReuses () { return 100 - reuses; } public override void Run (object state) { initial = new InitialWorkerRequest (stream); byte [] buffer = InitialWorkerRequest.AllocateBuffer (); stream.BeginRead (buffer, 0, buffer.Length, ReadCB, buffer); } void ReadCB (IAsyncResult ares) { var buffer = (byte []) ares.AsyncState; try { int nread = stream.EndRead (ares); // See if we got at least 1 line initial.SetBuffer (buffer, nread); initial.ReadRequestData (); ThreadPool.QueueUserWorkItem (RunInternal); } catch (Exception e) { InitialWorkerRequest.FreeBuffer (buffer); HandleInitialException (e); } } void HandleInitialException (Exception e) { //bool ignore = ((e is RequestLineException) || (e is IOException)); //if (!ignore) // Console.WriteLine (e); try { if (initial != null && initial.GotSomeInput && sock.Connected) { byte [] error = HttpErrors.ServerError (); Write (error, 0, error.Length); } } catch {} try { Close (); } catch {} if (broker != null && requestId != -1) broker.UnregisterRequest (requestId); } void RunInternal (object state) { RequestData rdata = initial.RequestData; initial.FreeBuffer (); string vhost = null; // TODO: read the headers in InitialWorkerRequest int port = localEP.Port; VPathToHost vapp; try { vapp = server.GetApplicationForPath (vhost, port, rdata.Path, true); } catch (Exception e){ // // This happens if the assembly is not in the GAC, so we report this // error here. // Logger.Write (e); return; } XSPApplicationHost host = null; if (vapp != null) host = (XSPApplicationHost) vapp.AppHost; if (host == null) { byte [] nf = HttpErrors.NotFound (rdata.Path); Write (nf, 0, nf.Length); Close (); return; } broker = (XSPRequestBroker) vapp.RequestBroker; requestId = broker.RegisterRequest (this); if (ssl != null) { var s = (stream as SslServerStream); ssl.KeySize = s.CipherStrength; ssl.SecretKeySize = s.KeyExchangeStrength; } try { string redirect; vapp.Redirect (rdata.Path, out redirect); host.ProcessRequest (requestId, localEP, remoteEP, rdata.Verb, rdata.Path, rdata.QueryString, rdata.Protocol, rdata.InputBuffer, redirect, sock.Handle, ssl); } catch (FileNotFoundException fnf) { // We print this one, as it might be a sign of a bad deployment // once we require the .exe and Mono.WebServer in bin or the GAC. Logger.Write (fnf); } catch (IOException) { // This is ok (including EndOfStreamException) } catch (Exception e) { Logger.Write (e); } } public override int Read (byte[] buffer, int position, int size) { int n = stream.Read (buffer, position, size); return (n >= 0) ? n : -1; } public override void Write (byte[] buffer, int position, int size) { try { stream.Write (buffer, position, size); } catch (Exception ex) { Logger.Write (LogLevel.Error, "Peer unexpectedly closed the connection on write. Closing our end."); Logger.Write (ex); Close (); } } public override void Close () { Close (false); } public void Close (bool keepAlive) { if (!keepAlive || !IsConnected ()) { stream.Close (); if (stream != netStream) { netStream.Close (); } else if (!netStream.OwnsSocket) { try { if (sock.Connected && !(sock.Poll (0, SelectMode.SelectRead) && sock.Available == 0)) sock.Shutdown (SocketShutdown.Both); } catch { // ignore } try { sock.Close (); } catch { // ignore } } return; } netStream.EnableLingering = false; stream.Close (); if (stream != netStream) netStream.Close (); server.ReuseSocket (sock, reuses + 1); } public override bool IsConnected () { return netStream.Connected; } public override void Flush () { if (stream != netStream) stream.Flush (); } bool ClientCertificateValidation (X509Certificate certificate, int [] certificateErrors) { if (certificate != null) ssl.RawClientCertificate = certificate.GetRawCertData (); // to avoid serialization // right now we're accepting any client certificate - i.e. it's up to the // web application to check if the certificate is valid (HttpClientCertificate.IsValid) ssl.ClientCertificateValid = (certificateErrors.Length == 0); return !ssl.RequireClientCertificate || (certificate != null); } } }
// ------------------------------------------------------------------------------ // 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\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GroupSettingTemplateRequest. /// </summary> public partial class GroupSettingTemplateRequest : BaseRequest, IGroupSettingTemplateRequest { /// <summary> /// Constructs a new GroupSettingTemplateRequest. /// </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 GroupSettingTemplateRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified GroupSettingTemplate using POST. /// </summary> /// <param name="groupSettingTemplateToCreate">The GroupSettingTemplate to create.</param> /// <returns>The created GroupSettingTemplate.</returns> public System.Threading.Tasks.Task<GroupSettingTemplate> CreateAsync(GroupSettingTemplate groupSettingTemplateToCreate) { return this.CreateAsync(groupSettingTemplateToCreate, CancellationToken.None); } /// <summary> /// Creates the specified GroupSettingTemplate using POST. /// </summary> /// <param name="groupSettingTemplateToCreate">The GroupSettingTemplate to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created GroupSettingTemplate.</returns> public async System.Threading.Tasks.Task<GroupSettingTemplate> CreateAsync(GroupSettingTemplate groupSettingTemplateToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<GroupSettingTemplate>(groupSettingTemplateToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified GroupSettingTemplate. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified GroupSettingTemplate. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<GroupSettingTemplate>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified GroupSettingTemplate. /// </summary> /// <returns>The GroupSettingTemplate.</returns> public System.Threading.Tasks.Task<GroupSettingTemplate> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified GroupSettingTemplate. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The GroupSettingTemplate.</returns> public async System.Threading.Tasks.Task<GroupSettingTemplate> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<GroupSettingTemplate>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified GroupSettingTemplate using PATCH. /// </summary> /// <param name="groupSettingTemplateToUpdate">The GroupSettingTemplate to update.</param> /// <returns>The updated GroupSettingTemplate.</returns> public System.Threading.Tasks.Task<GroupSettingTemplate> UpdateAsync(GroupSettingTemplate groupSettingTemplateToUpdate) { return this.UpdateAsync(groupSettingTemplateToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified GroupSettingTemplate using PATCH. /// </summary> /// <param name="groupSettingTemplateToUpdate">The GroupSettingTemplate to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated GroupSettingTemplate.</returns> public async System.Threading.Tasks.Task<GroupSettingTemplate> UpdateAsync(GroupSettingTemplate groupSettingTemplateToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<GroupSettingTemplate>(groupSettingTemplateToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <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 IGroupSettingTemplateRequest 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 IGroupSettingTemplateRequest Expand(Expression<Func<GroupSettingTemplate, 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 IGroupSettingTemplateRequest 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 IGroupSettingTemplateRequest Select(Expression<Func<GroupSettingTemplate, 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> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="groupSettingTemplateToInitialize">The <see cref="GroupSettingTemplate"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(GroupSettingTemplate groupSettingTemplateToInitialize) { } } }
/* * 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.Impl.Binary { using System; using System.Collections; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Write action delegate. /// </summary> /// <param name="obj">Target object.</param> /// <param name="writer">Writer.</param> internal delegate void BinaryReflectiveWriteAction(object obj, IBinaryWriter writer); /// <summary> /// Read action delegate. /// </summary> /// <param name="obj">Target object.</param> /// <param name="reader">Reader.</param> internal delegate void BinaryReflectiveReadAction(object obj, IBinaryReader reader); /// <summary> /// Routines for reflective reads and writes. /// </summary> internal static class BinaryReflectiveActions { /** Method: read enum. */ private static readonly MethodInfo MthdReadEnum = typeof(IBinaryReader).GetMethod("ReadEnum", new[] { typeof(string) }); /** Method: read enum. */ private static readonly MethodInfo MthdReadEnumRaw = typeof (IBinaryRawReader).GetMethod("ReadEnum"); /** Method: read enum array. */ private static readonly MethodInfo MthdReadEnumArray = typeof(IBinaryReader).GetMethod("ReadEnumArray", new[] { typeof(string) }); /** Method: read enum array. */ private static readonly MethodInfo MthdReadEnumArrayRaw = typeof(IBinaryRawReader).GetMethod("ReadEnumArray"); /** Method: read array. */ private static readonly MethodInfo MthdReadObjArray = typeof(IBinaryReader).GetMethod("ReadArray", new[] { typeof(string) }); /** Method: read array. */ private static readonly MethodInfo MthdReadObjArrayRaw = typeof(IBinaryRawReader).GetMethod("ReadArray"); /** Method: read object. */ private static readonly MethodInfo MthdReadObj= typeof(IBinaryReader).GetMethod("ReadObject", new[] { typeof(string) }); /** Method: read object. */ private static readonly MethodInfo MthdReadObjRaw = typeof(IBinaryRawReader).GetMethod("ReadObject"); /** Method: write enum array. */ private static readonly MethodInfo MthdWriteEnumArray = typeof(IBinaryWriter).GetMethod("WriteEnumArray"); /** Method: write enum array. */ private static readonly MethodInfo MthdWriteEnumArrayRaw = typeof(IBinaryRawWriter).GetMethod("WriteEnumArray"); /** Method: write array. */ private static readonly MethodInfo MthdWriteObjArray = typeof(IBinaryWriter).GetMethod("WriteArray"); /** Method: write array. */ private static readonly MethodInfo MthdWriteObjArrayRaw = typeof(IBinaryRawWriter).GetMethod("WriteArray"); /** Method: write object. */ private static readonly MethodInfo MthdWriteObj = typeof(IBinaryWriter).GetMethod("WriteObject"); /** Method: write object. */ private static readonly MethodInfo MthdWriteObjRaw = typeof(IBinaryRawWriter).GetMethod("WriteObject"); /** Method: raw writer */ private static readonly MethodInfo MthdGetRawWriter = typeof(IBinaryWriter).GetMethod("GetRawWriter"); /** Method: raw writer */ private static readonly MethodInfo MthdGetRawReader = typeof(IBinaryReader).GetMethod("GetRawReader"); /// <summary> /// Lookup read/write actions for the given type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> public static void GetTypeActions(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { var type = field.FieldType; if (type.IsPrimitive) HandlePrimitive(field, out writeAction, out readAction, raw); else if (type.IsArray) HandleArray(field, out writeAction, out readAction, raw); else HandleOther(field, out writeAction, out readAction, raw); } /// <summary> /// Handle primitive type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> /// <exception cref="IgniteException">Unsupported primitive type: + type.Name</exception> private static void HandlePrimitive(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { var type = field.FieldType; if (type == typeof (bool)) { writeAction = raw ? GetRawWriter<bool>(field, (w, o) => w.WriteBoolean(o)) : GetWriter<bool>(field, (f, w, o) => w.WriteBoolean(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadBoolean()) : GetReader(field, (f, r) => r.ReadBoolean(f)); } else if (type == typeof (sbyte)) { writeAction = raw ? GetRawWriter<sbyte>(field, (w, o) => w.WriteByte(unchecked((byte) o))) : GetWriter<sbyte>(field, (f, w, o) => w.WriteByte(f, unchecked((byte) o))); readAction = raw ? GetRawReader(field, r => unchecked ((sbyte) r.ReadByte())) : GetReader(field, (f, r) => unchecked ((sbyte) r.ReadByte(f))); } else if (type == typeof (byte)) { writeAction = raw ? GetRawWriter<byte>(field, (w, o) => w.WriteByte(o)) : GetWriter<byte>(field, (f, w, o) => w.WriteByte(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadByte()) : GetReader(field, (f, r) => r.ReadByte(f)); } else if (type == typeof (short)) { writeAction = raw ? GetRawWriter<short>(field, (w, o) => w.WriteShort(o)) : GetWriter<short>(field, (f, w, o) => w.WriteShort(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadShort()) : GetReader(field, (f, r) => r.ReadShort(f)); } else if (type == typeof (ushort)) { writeAction = raw ? GetRawWriter<ushort>(field, (w, o) => w.WriteShort(unchecked((short) o))) : GetWriter<ushort>(field, (f, w, o) => w.WriteShort(f, unchecked((short) o))); readAction = raw ? GetRawReader(field, r => unchecked((ushort) r.ReadShort())) : GetReader(field, (f, r) => unchecked((ushort) r.ReadShort(f))); } else if (type == typeof (char)) { writeAction = raw ? GetRawWriter<char>(field, (w, o) => w.WriteChar(o)) : GetWriter<char>(field, (f, w, o) => w.WriteChar(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadChar()) : GetReader(field, (f, r) => r.ReadChar(f)); } else if (type == typeof (int)) { writeAction = raw ? GetRawWriter<int>(field, (w, o) => w.WriteInt(o)) : GetWriter<int>(field, (f, w, o) => w.WriteInt(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadInt()) : GetReader(field, (f, r) => r.ReadInt(f)); } else if (type == typeof (uint)) { writeAction = raw ? GetRawWriter<uint>(field, (w, o) => w.WriteInt(unchecked((int) o))) : GetWriter<uint>(field, (f, w, o) => w.WriteInt(f, unchecked((int) o))); readAction = raw ? GetRawReader(field, r => unchecked((uint) r.ReadInt())) : GetReader(field, (f, r) => unchecked((uint) r.ReadInt(f))); } else if (type == typeof (long)) { writeAction = raw ? GetRawWriter<long>(field, (w, o) => w.WriteLong(o)) : GetWriter<long>(field, (f, w, o) => w.WriteLong(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadLong()) : GetReader(field, (f, r) => r.ReadLong(f)); } else if (type == typeof (ulong)) { writeAction = raw ? GetRawWriter<ulong>(field, (w, o) => w.WriteLong(unchecked((long) o))) : GetWriter<ulong>(field, (f, w, o) => w.WriteLong(f, unchecked((long) o))); readAction = raw ? GetRawReader(field, r => unchecked((ulong) r.ReadLong())) : GetReader(field, (f, r) => unchecked((ulong) r.ReadLong(f))); } else if (type == typeof (float)) { writeAction = raw ? GetRawWriter<float>(field, (w, o) => w.WriteFloat(o)) : GetWriter<float>(field, (f, w, o) => w.WriteFloat(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadFloat()) : GetReader(field, (f, r) => r.ReadFloat(f)); } else if (type == typeof (double)) { writeAction = raw ? GetRawWriter<double>(field, (w, o) => w.WriteDouble(o)) : GetWriter<double>(field, (f, w, o) => w.WriteDouble(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDouble()) : GetReader(field, (f, r) => r.ReadDouble(f)); } else throw new IgniteException("Unsupported primitive type: " + type.Name); } /// <summary> /// Handle array type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> private static void HandleArray(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { Type elemType = field.FieldType.GetElementType(); if (elemType == typeof (bool)) { writeAction = raw ? GetRawWriter<bool[]>(field, (w, o) => w.WriteBooleanArray(o)) : GetWriter<bool[]>(field, (f, w, o) => w.WriteBooleanArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadBooleanArray()) : GetReader(field, (f, r) => r.ReadBooleanArray(f)); } else if (elemType == typeof (byte)) { writeAction = raw ? GetRawWriter<byte[]>(field, (w, o) => w.WriteByteArray(o)) : GetWriter<byte[]>(field, (f, w, o) => w.WriteByteArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadByteArray()) : GetReader(field, (f, r) => r.ReadByteArray(f)); } else if (elemType == typeof (sbyte)) { writeAction = raw ? GetRawWriter<sbyte[]>(field, (w, o) => w.WriteByteArray((byte[]) (Array) o)) : GetWriter<sbyte[]>(field, (f, w, o) => w.WriteByteArray(f, (byte[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (sbyte[]) (Array) r.ReadByteArray()) : GetReader(field, (f, r) => (sbyte[]) (Array) r.ReadByteArray(f)); } else if (elemType == typeof (short)) { writeAction = raw ? GetRawWriter<short[]>(field, (w, o) => w.WriteShortArray(o)) : GetWriter<short[]>(field, (f, w, o) => w.WriteShortArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadShortArray()) : GetReader(field, (f, r) => r.ReadShortArray(f)); } else if (elemType == typeof (ushort)) { writeAction = raw ? GetRawWriter<ushort[]>(field, (w, o) => w.WriteShortArray((short[]) (Array) o)) : GetWriter<ushort[]>(field, (f, w, o) => w.WriteShortArray(f, (short[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (ushort[]) (Array) r.ReadShortArray()) : GetReader(field, (f, r) => (ushort[]) (Array) r.ReadShortArray(f)); } else if (elemType == typeof (char)) { writeAction = raw ? GetRawWriter<char[]>(field, (w, o) => w.WriteCharArray(o)) : GetWriter<char[]>(field, (f, w, o) => w.WriteCharArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadCharArray()) : GetReader(field, (f, r) => r.ReadCharArray(f)); } else if (elemType == typeof (int)) { writeAction = raw ? GetRawWriter<int[]>(field, (w, o) => w.WriteIntArray(o)) : GetWriter<int[]>(field, (f, w, o) => w.WriteIntArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadIntArray()) : GetReader(field, (f, r) => r.ReadIntArray(f)); } else if (elemType == typeof (uint)) { writeAction = raw ? GetRawWriter<uint[]>(field, (w, o) => w.WriteIntArray((int[]) (Array) o)) : GetWriter<uint[]>(field, (f, w, o) => w.WriteIntArray(f, (int[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (uint[]) (Array) r.ReadIntArray()) : GetReader(field, (f, r) => (uint[]) (Array) r.ReadIntArray(f)); } else if (elemType == typeof (long)) { writeAction = raw ? GetRawWriter<long[]>(field, (w, o) => w.WriteLongArray(o)) : GetWriter<long[]>(field, (f, w, o) => w.WriteLongArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadLongArray()) : GetReader(field, (f, r) => r.ReadLongArray(f)); } else if (elemType == typeof (ulong)) { writeAction = raw ? GetRawWriter<ulong[]>(field, (w, o) => w.WriteLongArray((long[]) (Array) o)) : GetWriter<ulong[]>(field, (f, w, o) => w.WriteLongArray(f, (long[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (ulong[]) (Array) r.ReadLongArray()) : GetReader(field, (f, r) => (ulong[]) (Array) r.ReadLongArray(f)); } else if (elemType == typeof (float)) { writeAction = raw ? GetRawWriter<float[]>(field, (w, o) => w.WriteFloatArray(o)) : GetWriter<float[]>(field, (f, w, o) => w.WriteFloatArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadFloatArray()) : GetReader(field, (f, r) => r.ReadFloatArray(f)); } else if (elemType == typeof (double)) { writeAction = raw ? GetRawWriter<double[]>(field, (w, o) => w.WriteDoubleArray(o)) : GetWriter<double[]>(field, (f, w, o) => w.WriteDoubleArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDoubleArray()) : GetReader(field, (f, r) => r.ReadDoubleArray(f)); } else if (elemType == typeof (decimal?)) { writeAction = raw ? GetRawWriter<decimal?[]>(field, (w, o) => w.WriteDecimalArray(o)) : GetWriter<decimal?[]>(field, (f, w, o) => w.WriteDecimalArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDecimalArray()) : GetReader(field, (f, r) => r.ReadDecimalArray(f)); } else if (elemType == typeof (string)) { writeAction = raw ? GetRawWriter<string[]>(field, (w, o) => w.WriteStringArray(o)) : GetWriter<string[]>(field, (f, w, o) => w.WriteStringArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadStringArray()) : GetReader(field, (f, r) => r.ReadStringArray(f)); } else if (elemType == typeof (Guid?)) { writeAction = raw ? GetRawWriter<Guid?[]>(field, (w, o) => w.WriteGuidArray(o)) : GetWriter<Guid?[]>(field, (f, w, o) => w.WriteGuidArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadGuidArray()) : GetReader(field, (f, r) => r.ReadGuidArray(f)); } else if (elemType.IsEnum) { writeAction = raw ? GetRawWriter(field, MthdWriteEnumArrayRaw, elemType) : GetWriter(field, MthdWriteEnumArray, elemType); readAction = raw ? GetRawReader(field, MthdReadEnumArrayRaw, elemType) : GetReader(field, MthdReadEnumArray, elemType); } else { writeAction = raw ? GetRawWriter(field, MthdWriteObjArrayRaw, elemType) : GetWriter(field, MthdWriteObjArray, elemType); readAction = raw ? GetRawReader(field, MthdReadObjArrayRaw, elemType) : GetReader(field, MthdReadObjArray, elemType); } } /// <summary> /// Determines whether specified field is a query field (has QueryFieldAttribute). /// </summary> private static bool IsQueryField(FieldInfo fieldInfo) { Debug.Assert(fieldInfo != null && fieldInfo.DeclaringType != null); var fieldName = BinaryUtils.CleanFieldName(fieldInfo.Name); object[] attrs = null; if (fieldName != fieldInfo.Name) { // Backing field, check corresponding property var prop = fieldInfo.DeclaringType.GetProperty(fieldName, fieldInfo.FieldType); if (prop != null) attrs = prop.GetCustomAttributes(true); } attrs = attrs ?? fieldInfo.GetCustomAttributes(true); return attrs.OfType<QuerySqlFieldAttribute>().Any(); } /// <summary> /// Handle other type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> private static void HandleOther(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { var type = field.FieldType; var genericDef = type.IsGenericType ? type.GetGenericTypeDefinition() : null; bool nullable = genericDef == typeof (Nullable<>); var nullableType = nullable ? type.GetGenericArguments()[0] : null; if (type == typeof (decimal)) { writeAction = raw ? GetRawWriter<decimal>(field, (w, o) => w.WriteDecimal(o)) : GetWriter<decimal>(field, (f, w, o) => w.WriteDecimal(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDecimal()) : GetReader(field, (f, r) => r.ReadDecimal(f)); } else if (type == typeof (string)) { writeAction = raw ? GetRawWriter<string>(field, (w, o) => w.WriteString(o)) : GetWriter<string>(field, (f, w, o) => w.WriteString(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadString()) : GetReader(field, (f, r) => r.ReadString(f)); } else if (type == typeof (Guid)) { writeAction = raw ? GetRawWriter<Guid>(field, (w, o) => w.WriteGuid(o)) : GetWriter<Guid>(field, (f, w, o) => w.WriteGuid(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadObject<Guid>()) : GetReader(field, (f, r) => r.ReadObject<Guid>(f)); } else if (nullable && nullableType == typeof (Guid)) { writeAction = raw ? GetRawWriter<Guid?>(field, (w, o) => w.WriteGuid(o)) : GetWriter<Guid?>(field, (f, w, o) => w.WriteGuid(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadGuid()) : GetReader(field, (f, r) => r.ReadGuid(f)); } else if (type.IsEnum) { writeAction = raw ? GetRawWriter<object>(field, (w, o) => w.WriteEnum(o), true) : GetWriter<object>(field, (f, w, o) => w.WriteEnum(f, o), true); readAction = raw ? GetRawReader(field, MthdReadEnumRaw) : GetReader(field, MthdReadEnum); } else if (type == BinaryUtils.TypDictionary || type.GetInterface(BinaryUtils.TypDictionary.FullName) != null && !type.IsGenericType) { writeAction = raw ? GetRawWriter<IDictionary>(field, (w, o) => w.WriteDictionary(o)) : GetWriter<IDictionary>(field, (f, w, o) => w.WriteDictionary(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDictionary()) : GetReader(field, (f, r) => r.ReadDictionary(f)); } else if (type == BinaryUtils.TypCollection || type.GetInterface(BinaryUtils.TypCollection.FullName) != null && !type.IsGenericType) { writeAction = raw ? GetRawWriter<ICollection>(field, (w, o) => w.WriteCollection(o)) : GetWriter<ICollection>(field, (f, w, o) => w.WriteCollection(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadCollection()) : GetReader(field, (f, r) => r.ReadCollection(f)); } else if (type == typeof (DateTime) && IsQueryField(field) && !raw) { // Special case for DateTime and query fields. // If a field is marked with [QuerySqlField], write it as TimeStamp so that queries work. // This is not needed in raw mode (queries do not work anyway). // It may cause issues when field has attribute, but is used in a cache without queries, and user // may expect non-UTC dates to work. However, such cases are rare, and there are workarounds. writeAction = GetWriter<DateTime>(field, (f, w, o) => w.WriteTimestamp(f, o)); readAction = GetReader(field, (f, r) => r.ReadObject<DateTime>(f)); } else if (nullableType == typeof (DateTime) && IsQueryField(field) && !raw) { writeAction = GetWriter<DateTime?>(field, (f, w, o) => w.WriteTimestamp(f, o)); readAction = GetReader(field, (f, r) => r.ReadTimestamp(f)); } else { writeAction = raw ? GetRawWriter(field, MthdWriteObjRaw) : GetWriter(field, MthdWriteObj); readAction = raw ? GetRawReader(field, MthdReadObjRaw) : GetReader(field, MthdReadObj); } } /// <summary> /// Gets the reader with a specified write action. /// </summary> private static BinaryReflectiveWriteAction GetWriter<T>(FieldInfo field, Expression<Action<string, IBinaryWriter, T>> write, bool convertFieldValToObject = false) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(write != null); // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); Expression fldExpr = Expression.Field(targetParamConverted, field); if (convertFieldValToObject) fldExpr = Expression.Convert(fldExpr, typeof (object)); // Call Writer method var writerParam = Expression.Parameter(typeof(IBinaryWriter)); var fldNameParam = Expression.Constant(BinaryUtils.CleanFieldName(field.Name)); var writeExpr = Expression.Invoke(write, fldNameParam, writerParam, fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the reader with a specified write action. /// </summary> private static BinaryReflectiveWriteAction GetRawWriter<T>(FieldInfo field, Expression<Action<IBinaryRawWriter, T>> write, bool convertFieldValToObject = false) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(write != null); // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); Expression fldExpr = Expression.Field(targetParamConverted, field); if (convertFieldValToObject) fldExpr = Expression.Convert(fldExpr, typeof (object)); // Call Writer method var writerParam = Expression.Parameter(typeof(IBinaryWriter)); var writeExpr = Expression.Invoke(write, Expression.Call(writerParam, MthdGetRawWriter), fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetWriter(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetWriter0(field, method, false, genericArgs); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetRawWriter(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetWriter0(field, method, true, genericArgs); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetWriter0(FieldInfo field, MethodInfo method, bool raw, params Type[] genericArgs) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(method != null); if (genericArgs.Length == 0) genericArgs = new[] {field.FieldType}; // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); var fldExpr = Expression.Field(targetParamConverted, field); // Call Writer method var writerParam = Expression.Parameter(typeof (IBinaryWriter)); var writeMethod = method.MakeGenericMethod(genericArgs); var writeExpr = raw ? Expression.Call(Expression.Call(writerParam, MthdGetRawWriter), writeMethod, fldExpr) : Expression.Call(writerParam, writeMethod, Expression.Constant(BinaryUtils.CleanFieldName(field.Name)), fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the reader with a specified read action. /// </summary> private static BinaryReflectiveReadAction GetReader<T>(FieldInfo field, Expression<Func<string, IBinaryReader, T>> read) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static // Call Reader method var readerParam = Expression.Parameter(typeof(IBinaryReader)); var fldNameParam = Expression.Constant(BinaryUtils.CleanFieldName(field.Name)); Expression readExpr = Expression.Invoke(read, fldNameParam, readerParam); if (typeof(T) != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParam, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } /// <summary> /// Gets the reader with a specified read action. /// </summary> private static BinaryReflectiveReadAction GetRawReader<T>(FieldInfo field, Expression<Func<IBinaryRawReader, T>> read) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static // Call Reader method var readerParam = Expression.Parameter(typeof(IBinaryReader)); Expression readExpr = Expression.Invoke(read, Expression.Call(readerParam, MthdGetRawReader)); if (typeof(T) != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParam, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetReader(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetReader0(field, method, false, genericArgs); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetRawReader(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetReader0(field, method, true, genericArgs); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetReader0(FieldInfo field, MethodInfo method, bool raw, params Type[] genericArgs) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static if (genericArgs.Length == 0) genericArgs = new[] {field.FieldType}; // Call Reader method var readerParam = Expression.Parameter(typeof (IBinaryReader)); var readMethod = method.MakeGenericMethod(genericArgs); Expression readExpr = raw ? Expression.Call(Expression.Call(readerParam, MthdGetRawReader), readMethod) : Expression.Call(readerParam, readMethod, Expression.Constant(BinaryUtils.CleanFieldName(field.Name))); if (readMethod.ReturnType != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, typeof(object)); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParamConverted, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Reflection.Emit.Tests { public class MethodBuilderSetSignature { [Fact] public void SetSignature_GenericMethod_SingleGenericParameter() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder returnType = typeParameters[0]; method.SetSignature(returnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, returnType.AsType()); } [Fact] public void SetSignature_GenericMethod_MultipleGenericParameters() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T", "U"); GenericTypeParameterBuilder desiredReturnType = typeParameters[1]; method.SetSignature(desiredReturnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ReturnType_RequiredCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; method.SetSignature(desiredReturnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ReturnType_RequiredModifier_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; method.SetSignature(desiredReturnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ReturnType_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; method.SetSignature(desiredReturnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ParameterTypes() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int) }; method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_MultipleParameters() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T", "U"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int), typeParameters[1].AsType() }; method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ParameterType_RequiredCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); string[] typeParamNames = new string[] { "T" }; GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters(typeParamNames); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int) }; Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeRequiredCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, parameterTypeRequiredCustomModifiers, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ParameterType_RequiredCustomModifer_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int) }; Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][]; Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeRequiredCustomModifiers[i] = null; parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ParameterType_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int) }; Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, null, parameterTypeOptionalCustomModifiers); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_NonGenericMethod() { Type[] parameterTypes = new Type[] { typeof(string), typeof(object) }; TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), parameterTypes); string[] parameterNames = new string[parameterTypes.Length]; for (int i = 0; i < parameterNames.Length; ++i) { parameterNames[i] = "P" + i.ToString(); method.DefineParameter(i + 1, ParameterAttributes.In, parameterNames[i]); } Type desiredReturnType = typeof(void); Type[] desiredParamType = new Type[] { typeof(int) }; Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][]; Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeRequiredCustomModifiers[i] = null; parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType, null, null, desiredParamType, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } [Fact] public void SetSignature_AllParametersNull() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); method.SetSignature(null, null, null, null, null, null); VerifyMethodSignature(type, method, typeof(void)); } [Fact] public void SetSignature_NullReturnType_CustomModifiersSetToWrongTypes() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; method.SetSignature(null, null, null, null, null, null); VerifyMethodSignature(type, method, typeof(void)); } [Fact] public void SetSignature_NullOnReturnType_CustomModifiersSetCorrectly() { int arraySize = 10; TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = null; Type[][] parameterTypeRequiredCustomModifiers = new Type[arraySize][]; Type[][] parameterTypeOptionalCustomModifiers = new Type[arraySize][]; for (int i = 0; i < arraySize; ++i) { parameterTypeRequiredCustomModifiers[i] = null; parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } [Fact] public void SetSignature_NullReturnType_RequiredCustomModifiers_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(void) }; Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][]; Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeRequiredCustomModifiers[i] = null; parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } private void VerifyMethodSignature(TypeBuilder type, MethodBuilder method, Type desiredReturnType) { Type ret = type.CreateTypeInfo().AsType(); MethodInfo methodInfo = method.GetBaseDefinition(); Type actualReturnType = methodInfo.ReturnType; Assert.NotNull(actualReturnType); Assert.Equal(desiredReturnType.Name, actualReturnType.Name); Assert.Equal(desiredReturnType, actualReturnType); } } }
//! \file ArcMK2.cs //! \date Thu Aug 04 05:11:20 2016 //! \brief MAIKA resource archives. // // Copyright (C) 2016-2018 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using GameRes.Compression; using GameRes.Utility; namespace GameRes.Formats.Maika { [Serializable] public class ScrambleScheme { public uint ScrambledSize; public Tuple<byte, byte>[] ScrambleMap; } internal class MkArchive : ArcFile { public readonly ScrambleScheme Scheme; public MkArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, ScrambleScheme scheme) : base (arc, impl, dir) { Scheme = scheme; } } [Export(typeof(ArchiveFormat))] public class Mk2Opener : ArchiveFormat { public override string Tag { get { return "DAT/MK2"; } } public override string Description { get { return "MAIKA resource archive"; } } public override uint Signature { get { return 0x2E324B4D; } } // 'MK2.0' public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public Mk2Opener () { // 'MK2.0' 'BL2.0'. 'SL1.0', 'LS2.0', 'AR2.0' Signatures = new uint[] { 0x2E324B4D, 0x2E324C42, 0x2E314C53, 0x2E32534C, 0x2E325241 }; } public override ArcFile TryOpen (ArcView file) { if (!file.View.AsciiEqual (4, "0\0")) return null; int count = file.View.ReadInt32 (0x12); if (!IsSaneCount (count)) return null; uint base_offset = file.View.ReadUInt16 (8); uint index_offset = file.View.ReadUInt32 (0xE); if (index_offset >= file.MaxOffset) return null; uint index_size = file.View.ReadUInt32 (0xA); if (index_size > file.View.Reserve (index_offset, index_size)) return null; uint current_offset = index_offset; var dir = new List<Entry> (count); for (int i = 0; i < 512; ++i) { uint entry_offset = index_offset + file.View.ReadUInt32 (current_offset); int n = file.View.ReadUInt16 (current_offset+4); if (n > 0) { for (int j = 0; j < n; ++j) { uint offset = file.View.ReadUInt32 (entry_offset) + base_offset; uint size = file.View.ReadUInt32 (entry_offset+4); uint name_length = file.View.ReadByte (entry_offset+8); if (0 == name_length) return null; var name = file.View.ReadString (entry_offset+9, name_length); entry_offset += 9 + name_length; var entry = FormatCatalog.Instance.Create<Entry> (name); entry.Offset = offset; entry.Size = size; if (!entry.CheckPlacement (index_offset)) return null; dir.Add (entry); } } else if (-1 == file.View.ReadInt32 (entry_offset)) break; current_offset += 6; } return GetArchive (file, dir); } internal ArcFile GetArchive (ArcView file, List<Entry> dir) { if (0 == dir.Count) return null; string arc_id = file.View.ReadString (0, 5); ScrambleScheme scheme; if (!KnownSchemes.TryGetValue (arc_id, out scheme)) scheme = DefaultScheme; return new MkArchive (file, this, dir, scheme); } public override Stream OpenEntry (ArcFile arc, Entry entry) { ushort signature = arc.File.View.ReadUInt16 (entry.Offset); // C1/D1/E1/F1 if (0x3146 != signature && 0x3143 != signature && 0x3144 != signature && 0x3145 != signature) return base.OpenEntry (arc, entry); var mkarc = arc as MkArchive; ScrambleScheme scheme = mkarc != null ? mkarc.Scheme : DefaultScheme; uint packed_size = arc.File.View.ReadUInt32 (entry.Offset+2); if (packed_size < scheme.ScrambledSize || packed_size > entry.Size-10) return base.OpenEntry (arc, entry); Stream input; // XXX scrambling might be applicable for 'E1' signatures only if (scheme.ScrambledSize > 0) { var prefix = arc.File.View.ReadBytes (entry.Offset+10, scheme.ScrambledSize); foreach (var pair in scheme.ScrambleMap) { byte t = prefix[pair.Item1]; prefix[pair.Item1] = prefix[pair.Item2]; prefix[pair.Item2] = t; } input = arc.File.CreateStream (entry.Offset+10+scheme.ScrambledSize, packed_size-scheme.ScrambledSize); input = new PrefixStream (prefix, input); } else { input = arc.File.CreateStream (entry.Offset+10, packed_size); } input = new LzssStream (input); var header = new byte[5]; input.Read (header, 0, 5); if (Binary.AsciiEqual (header, "BPR02")) return new PackedStream<Bpr02Decompressor> (input); if (Binary.AsciiEqual (header, "BPR01")) return new PackedStream<Bpr01Decompressor> (input); return new PrefixStream (header, input); } static readonly ScrambleScheme DefaultScheme = new ScrambleScheme { ScrambledSize = 14, ScrambleMap = new Tuple<byte,byte>[] { new Tuple<byte, byte> (7, 11), new Tuple<byte, byte> (9, 12) } }; static readonly ScrambleScheme ArScheme = new ScrambleScheme { ScrambledSize = 15, ScrambleMap = new Tuple<byte,byte>[] { new Tuple<byte, byte> (7, 13), new Tuple<byte, byte> (9, 14) } }; Dictionary<string, ScrambleScheme> KnownSchemes = new Dictionary<string, ScrambleScheme> { { "AR2.0", ArScheme }, { "USG01", ArScheme }, }; } internal abstract class BprDecompressor : Decompressor { readonly byte m_rle_code; IBinaryStream m_input; protected BprDecompressor (byte rle_code) { m_rle_code = rle_code; } public override void Initialize (Stream input) { m_input = new BinaryStream (input, ""); } protected override IEnumerator<int> Unpack () { for (;;) { int ctl = m_input.ReadByte(); if (-1 == ctl || 0xFF == ctl) yield break; int count = m_input.ReadInt32(); if (m_rle_code == ctl) { byte b = m_input.ReadUInt8(); while (count --> 0) { m_buffer[m_pos++] = b; if (0 == --m_length) yield return m_pos; } } else { while (count > 0) { int chunk = Math.Min (count, m_length); int read = m_input.Read (m_buffer, m_pos, chunk); count -= chunk; m_pos += chunk; m_length -= chunk; if (0 == m_length) yield return m_pos; } } } } bool m_disposed = false; protected override void Dispose (bool disposing) { if (!m_disposed) { if (m_input != null) m_input.Dispose(); m_disposed = true; } } } internal class Bpr02Decompressor : BprDecompressor { public Bpr02Decompressor () : base (3) { } } internal class Bpr01Decompressor : BprDecompressor { public Bpr01Decompressor () : base (1) { } } }
using System; using System.Buffers; using System.Buffers.Text; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using Orleans.Concurrency; namespace Orleans.Runtime { [Serializable, Immutable] public sealed class LegacyGrainId : IEquatable<LegacyGrainId>, IComparable<LegacyGrainId> { private static readonly Interner<UniqueKey, LegacyGrainId> grainIdInternCache = new Interner<UniqueKey, LegacyGrainId>(InternerConstants.SIZE_LARGE); private static readonly Interner<UniqueKey, byte[]> grainTypeInternCache = new Interner<UniqueKey, byte[]>(); private static readonly Interner<UniqueKey, byte[]> grainKeyInternCache = new Interner<UniqueKey, byte[]>(); private static readonly ReadOnlyMemory<byte> ClientPrefixBytes = Encoding.UTF8.GetBytes(GrainTypePrefix.ClientPrefix + "."); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] [DataMember] internal readonly UniqueKey Key; public UniqueKey.Category Category => Key.IdCategory; public bool IsSystemTarget => Key.IsSystemTargetKey; public bool IsGrain => Category == UniqueKey.Category.Grain || Category == UniqueKey.Category.KeyExtGrain; public bool IsClient => Category == UniqueKey.Category.Client; internal LegacyGrainId(UniqueKey key) { this.Key = key; } public static implicit operator GrainId(LegacyGrainId legacy) => legacy.ToGrainId(); public static LegacyGrainId NewId() { return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Grain)); } public static LegacyGrainId NewClientId() { return NewClientId(Guid.NewGuid()); } internal static LegacyGrainId NewClientId(Guid id) { return FindOrCreateGrainId(UniqueKey.NewKey(id, UniqueKey.Category.Client, 0)); } internal static LegacyGrainId GetGrainId(UniqueKey key) { return FindOrCreateGrainId(key); } // For testing only. internal static LegacyGrainId GetGrainIdForTesting(Guid guid) { return FindOrCreateGrainId(UniqueKey.NewKey(guid)); } internal static LegacyGrainId GetSystemTargetGrainId(long typeData) { return FindOrCreateGrainId(UniqueKey.NewEmptySystemTargetKey(typeData)); } internal static GrainType GetGrainType(long typeCode, bool isKeyExt) { return GetGrainType(isKeyExt ? UniqueKey.NewKey(0, UniqueKey.Category.KeyExtGrain, typeCode, "keyext") : UniqueKey.NewKey(0, UniqueKey.Category.Grain, typeCode)); } internal static LegacyGrainId GetGrainId(long typeCode, long primaryKey, string keyExt = null) { return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey, keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain, typeCode, keyExt)); } internal static LegacyGrainId GetGrainId(long typeCode, Guid primaryKey, string keyExt = null) { return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey, keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain, typeCode, keyExt)); } internal static LegacyGrainId GetGrainId(long typeCode, string primaryKey) { return FindOrCreateGrainId(UniqueKey.NewKey(0L, UniqueKey.Category.KeyExtGrain, typeCode, primaryKey)); } internal static LegacyGrainId GetGrainServiceGrainId(short id, int typeData) { return FindOrCreateGrainId(UniqueKey.NewGrainServiceKey(id, typeData)); } internal static LegacyGrainId GetGrainServiceGrainId(int typeData, string systemGrainId) { return FindOrCreateGrainId(UniqueKey.NewGrainServiceKey(systemGrainId, typeData)); } public Guid PrimaryKey { get { return GetPrimaryKey(); } } public long PrimaryKeyLong { get { return GetPrimaryKeyLong(); } } public string PrimaryKeyString { get { return GetPrimaryKeyString(); } } public string IdentityString { get { return ToDetailedString(); } } public bool IsLongKey { get { return Key.IsLongKey; } } public long GetPrimaryKeyLong(out string keyExt) { return Key.PrimaryKeyToLong(out keyExt); } internal long GetPrimaryKeyLong() { return Key.PrimaryKeyToLong(); } public Guid GetPrimaryKey(out string keyExt) { return Key.PrimaryKeyToGuid(out keyExt); } internal Guid GetPrimaryKey() { return Key.PrimaryKeyToGuid(); } internal string GetPrimaryKeyString() { string key; _ = GetPrimaryKey(out key); return key; } public int TypeCode => Key.BaseTypeCode; private static GrainType GetGrainType(UniqueKey key) { return new GrainType(grainTypeInternCache.FindOrCreate(key, key => { var prefixBytes = key.IsSystemTargetKey ? GrainTypePrefix.SystemTargetPrefixBytes : key.IdCategory == UniqueKey.Category.Client ? ClientPrefixBytes : GrainTypePrefix.LegacyGrainPrefixBytes; return CreateGrainType(prefixBytes, key.TypeCodeData); })); } private static byte[] CreateGrainType(ReadOnlyMemory<byte> prefixBytes, ulong typeCode) { var prefix = prefixBytes.Span; var buf = new byte[prefix.Length + 16]; prefix.CopyTo(buf); Utf8Formatter.TryFormat(typeCode, buf.AsSpan(prefix.Length), out var len, new StandardFormat('X', 16)); Debug.Assert(len == 16); return buf; } public static GrainType CreateGrainTypeForGrain(int typeCode) { return new GrainType(CreateGrainType(GrainTypePrefix.LegacyGrainPrefixBytes, (ulong)typeCode)); } public static GrainType CreateGrainTypeForSystemTarget(int typeCode) { return new GrainType(CreateGrainType(GrainTypePrefix.SystemTargetPrefixBytes, (ulong)typeCode)); } private IdSpan GetGrainKey() { return new IdSpan(grainKeyInternCache.FindOrCreate(Key, k => Encoding.UTF8.GetBytes($"{k.N0:X16}{k.N1:X16}{(k.HasKeyExt ? "+" : null)}{k.KeyExt}"))); } public GrainId ToGrainId() { return new GrainId(GetGrainType(Key), this.GetGrainKey()); } public static bool TryConvertFromGrainId(GrainId id, out LegacyGrainId legacyId) { legacyId = FromGrainIdInternal(id); return legacyId is object; } public static LegacyGrainId FromGrainId(GrainId id) { return FromGrainIdInternal(id) ?? ThrowNotLegacyGrainId(id); } private static LegacyGrainId FromGrainIdInternal(GrainId id) { var typeSpan = id.Type.AsSpan(); if (typeSpan.Length != GrainTypePrefix.LegacyGrainPrefix.Length + 16) return null; if (!typeSpan.StartsWith(GrainTypePrefix.LegacyGrainPrefixBytes.Span)) return null; typeSpan = typeSpan.Slice(GrainTypePrefix.LegacyGrainPrefix.Length, 16); if (!Utf8Parser.TryParse(typeSpan, out ulong typeCodeData, out var len, 'X') || len < 16) return null; string keyExt = null; var keySpan = id.Key.Value.Span; if (keySpan.Length < 32) return null; if (!Utf8Parser.TryParse(keySpan.Slice(0, 16), out ulong n0, out len, 'X') || len < 16) return null; if (!Utf8Parser.TryParse(keySpan.Slice(16, 16), out ulong n1, out len, 'X') || len < 16) return null; if (keySpan.Length > 32) { if (keySpan[32] != '+') return null; keyExt = keySpan.Slice(33).GetUtf8String(); } return FindOrCreateGrainId(UniqueKey.NewKey(n0, n1, typeCodeData, keyExt)); } [MethodImpl(MethodImplOptions.NoInlining)] private static LegacyGrainId ThrowNotLegacyGrainId(GrainId id) { throw new InvalidOperationException($"Cannot convert non-legacy id {id} into legacy id"); } private static LegacyGrainId FindOrCreateGrainId(UniqueKey key) { return grainIdInternCache.FindOrCreate(key, k => new LegacyGrainId(k)); } public bool Equals(LegacyGrainId other) { return other != null && Key.Equals(other.Key); } public override bool Equals(object obj) { var o = obj as LegacyGrainId; return o != null && Key.Equals(o.Key); } // Keep compiler happy -- it does not like classes to have Equals(...) without GetHashCode() methods public override int GetHashCode() { return Key.GetHashCode(); } /// <summary> /// Get a uniformly distributed hash code value for this grain, based on Jenkins Hash function. /// NOTE: Hash code value may be positive or NEGATIVE. /// </summary> /// <returns>Hash code for this LegacyGrainId</returns> public uint GetUniformHashCode() { return Key.GetUniformHashCode(); } public override string ToString() { return ToStringImpl(false); } // same as ToString, just full primary key and type code internal string ToDetailedString() { return ToStringImpl(true); } // same as ToString, just full primary key and type code private string ToStringImpl(bool detailed) { // TODO Get name of system/target grain + name of the grain type var keyString = Key.ToString(); // this should grab the least-significant half of n1, suffixing it with the key extension. string idString = keyString; if (!detailed) { if (keyString.Length >= 48) idString = keyString.Substring(24, 8) + keyString.Substring(48); else idString = keyString.Substring(24, 8); } string fullString; switch (Category) { case UniqueKey.Category.Grain: case UniqueKey.Category.KeyExtGrain: var typeString = TypeCode.ToString("X"); if (!detailed) typeString = typeString.Substring(Math.Max(0, typeString.Length - 8)); fullString = $"*grn/{typeString}/{idString}"; break; case UniqueKey.Category.Client: fullString = $"*cli/{idString}"; break; case UniqueKey.Category.SystemTarget: case UniqueKey.Category.KeyExtSystemTarget: fullString = $"*stg/{Key.N1}/{idString}"; break; case UniqueKey.Category.SystemGrain: fullString = $"*sgn/{Key.PrimaryKeyToGuid()}/{idString}"; break; default: fullString = "???/" + idString; break; } return detailed ? String.Format("{0}-0x{1, 8:X8}", fullString, GetUniformHashCode()) : fullString; } public static bool IsLegacyGrainType(Type type) { return typeof(IGrainWithGuidKey).IsAssignableFrom(type) || typeof(IGrainWithIntegerKey).IsAssignableFrom(type) || typeof(IGrainWithStringKey).IsAssignableFrom(type) || typeof(IGrainWithGuidCompoundKey).IsAssignableFrom(type) || typeof(IGrainWithIntegerCompoundKey).IsAssignableFrom(type); } public static bool IsLegacyKeyExtGrainType(Type type) { return typeof(IGrainWithGuidCompoundKey).IsAssignableFrom(type) || typeof(IGrainWithIntegerCompoundKey).IsAssignableFrom(type); } /// <summary> /// Return this LegacyGrainId in a standard string form, suitable for later use with the <c>FromParsableString</c> method. /// </summary> /// <returns>LegacyGrainId in a standard string format.</returns> internal string ToParsableString() { // NOTE: This function must be the "inverse" of FromParsableString, and data must round-trip reliably. return Key.ToHexString(); } /// <summary> /// Create a new LegacyGrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method. /// </summary> /// <param name="grainId">String containing the LegacyGrainId info to be parsed.</param> /// <returns>New LegacyGrainId object created from the input data.</returns> internal static LegacyGrainId FromParsableString(string grainId) { return FromParsableString(grainId.AsSpan()); } /// <summary> /// Create a new LegacyGrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method. /// </summary> /// <param name="grainId">String containing the LegacyGrainId info to be parsed.</param> /// <returns>New LegacyGrainId object created from the input data.</returns> internal static LegacyGrainId FromParsableString(ReadOnlySpan<char> grainId) { // NOTE: This function must be the "inverse" of ToParsableString, and data must round-trip reliably. var key = UniqueKey.Parse(grainId); return FindOrCreateGrainId(key); } public uint GetHashCode_Modulo(uint umod) { int key = Key.GetHashCode(); int mod = (int)umod; key = ((key % mod) + mod) % mod; // key should be positive now. So assert with checked. return checked((uint)key); } public int CompareTo(LegacyGrainId other) { return Key.CompareTo(other.Key); } } }
#region --- License --- /* Copyright (c) 2006, 2007 Stefanos Apostolopoulos * See license.txt for license info */ #endregion using System; using System.Collections.Generic; #if !MINIMAL using System.Drawing; #endif using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using OpenTK.Input; namespace OpenTK.Platform.X11 { /// \internal /// <summary> /// Drives the InputDriver on X11. /// This class supports OpenTK, and is not intended for users of OpenTK. /// </summary> internal sealed class X11Input : IInputDriver { X11Joystick joystick_driver = new X11Joystick(); //X11WindowInfo window; KeyboardDevice keyboard = new KeyboardDevice(); MouseDevice mouse = new MouseDevice(); List<KeyboardDevice> dummy_keyboard_list = new List<KeyboardDevice>(1); List<MouseDevice> dummy_mice_list = new List<MouseDevice>(1); X11KeyMap keymap = new X11KeyMap(); int firstKeyCode, lastKeyCode; // The smallest and largest KeyCode supported by the X server. int keysyms_per_keycode; // The number of KeySyms for each KeyCode. IntPtr[] keysyms; //bool disposed; #region --- Constructors --- /// <summary> /// Constructs a new X11Input driver. Creates a hidden InputOnly window, child to /// the main application window, which selects input events and routes them to /// the device specific drivers (Keyboard, Mouse, Hid). /// </summary> /// <param name="attach">The window which the InputDriver will attach itself on.</param> public X11Input(IWindowInfo attach) { Debug.WriteLine("Initalizing X11 input driver."); Debug.Indent(); if (attach == null) throw new ArgumentException("A valid parent window must be defined, in order to create an X11Input driver."); //window = new X11WindowInfo(attach); X11WindowInfo window = (X11WindowInfo)attach; // Init mouse mouse.Description = "Default X11 mouse"; mouse.DeviceID = IntPtr.Zero; mouse.NumberOfButtons = 5; mouse.NumberOfWheels = 1; dummy_mice_list.Add(mouse); using (new XLock(window.Display)) { // Init keyboard API.DisplayKeycodes(window.Display, ref firstKeyCode, ref lastKeyCode); Debug.Print("First keycode: {0}, last {1}", firstKeyCode, lastKeyCode); IntPtr keysym_ptr = API.GetKeyboardMapping(window.Display, (byte)firstKeyCode, lastKeyCode - firstKeyCode + 1, ref keysyms_per_keycode); Debug.Print("{0} keysyms per keycode.", keysyms_per_keycode); keysyms = new IntPtr[(lastKeyCode - firstKeyCode + 1) * keysyms_per_keycode]; Marshal.PtrToStructure(keysym_ptr, keysyms); API.Free(keysym_ptr); KeyboardDevice kb = new KeyboardDevice(); keyboard.Description = "Default X11 keyboard"; keyboard.NumberOfKeys = lastKeyCode - firstKeyCode + 1; keyboard.DeviceID = IntPtr.Zero; dummy_keyboard_list.Add(keyboard); // Request that auto-repeat is only set on devices that support it physically. // This typically means that it's turned off for keyboards (which is what we want). // We prefer this method over XAutoRepeatOff/On, because the latter needs to // be reset before the program exits. bool supported; Functions.XkbSetDetectableAutoRepeat(window.Display, true, out supported); } Debug.Unindent(); } #endregion #region private void InternalPoll() #if false private void InternalPoll() { X11.XEvent e = new XEvent(); try { while (!disposed) { Functions.XMaskEvent(window.Display, EventMask.PointerMotionMask | EventMask.PointerMotionHintMask | EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.KeyPressMask | EventMask.KeyReleaseMask | EventMask.StructureNotifyMask, ref e); if (disposed) return; switch (e.type) { case XEventName.KeyPress: case XEventName.KeyRelease: keyboardDriver.ProcessKeyboardEvent(ref e.KeyEvent); break; case XEventName.ButtonPress: case XEventName.ButtonRelease: mouseDriver.ProcessButton(ref e.ButtonEvent); break; case XEventName.MotionNotify: mouseDriver.ProcessMotion(ref e.MotionEvent); break; case XEventName.DestroyNotify: Functions.XPutBackEvent(window.Display, ref e); Functions.XAutoRepeatOn(window.Display); return; } } } catch (ThreadAbortException expt) { Functions.XUnmapWindow(window.Display, window.Handle); Functions.XDestroyWindow(window.Display, window.Handle); return; } } #endif #endregion #region internal void ProcessEvent(ref XEvent e) internal void ProcessEvent(ref XEvent e) { switch (e.type) { case XEventName.KeyPress: case XEventName.KeyRelease: bool pressed = e.type == XEventName.KeyPress; IntPtr keysym = API.LookupKeysym(ref e.KeyEvent, 0); IntPtr keysym2 = API.LookupKeysym(ref e.KeyEvent, 1); if (keymap.ContainsKey((XKey)keysym)) keyboard[keymap[(XKey)keysym]] = pressed; else if (keymap.ContainsKey((XKey)keysym2)) keyboard[keymap[(XKey)keysym2]] = pressed; else Debug.Print("KeyCode {0} (Keysym: {1}, {2}) not mapped.", e.KeyEvent.keycode, (XKey)keysym, (XKey)keysym2); break; case XEventName.ButtonPress: if (e.ButtonEvent.button == 1) mouse[OpenTK.Input.MouseButton.Left] = true; else if (e.ButtonEvent.button == 2) mouse[OpenTK.Input.MouseButton.Middle] = true; else if (e.ButtonEvent.button == 3) mouse[OpenTK.Input.MouseButton.Right] = true; else if (e.ButtonEvent.button == 4) mouse.Wheel++; else if (e.ButtonEvent.button == 5) mouse.Wheel--; else if (e.ButtonEvent.button == 6) mouse[OpenTK.Input.MouseButton.Button1] = true; else if (e.ButtonEvent.button == 7) mouse[OpenTK.Input.MouseButton.Button2] = true; else if (e.ButtonEvent.button == 8) mouse[OpenTK.Input.MouseButton.Button3] = true; else if (e.ButtonEvent.button == 9) mouse[OpenTK.Input.MouseButton.Button4] = true; else if (e.ButtonEvent.button == 10) mouse[OpenTK.Input.MouseButton.Button5] = true; else if (e.ButtonEvent.button == 11) mouse[OpenTK.Input.MouseButton.Button6] = true; else if (e.ButtonEvent.button == 12) mouse[OpenTK.Input.MouseButton.Button7] = true; else if (e.ButtonEvent.button == 13) mouse[OpenTK.Input.MouseButton.Button8] = true; else if (e.ButtonEvent.button == 14) mouse[OpenTK.Input.MouseButton.Button9] = true; //if ((e.state & (int)X11.MouseMask.Button4Mask) != 0) m.Wheel++; //if ((e.state & (int)X11.MouseMask.Button5Mask) != 0) m.Wheel--; //Debug.Print("Button pressed: {0}", e.ButtonEvent.button); break; case XEventName.ButtonRelease: if (e.ButtonEvent.button == 1) mouse[OpenTK.Input.MouseButton.Left] = false; else if (e.ButtonEvent.button == 2) mouse[OpenTK.Input.MouseButton.Middle] = false; else if (e.ButtonEvent.button == 3) mouse[OpenTK.Input.MouseButton.Right] = false; else if (e.ButtonEvent.button == 6) mouse[OpenTK.Input.MouseButton.Button1] = false; else if (e.ButtonEvent.button == 7) mouse[OpenTK.Input.MouseButton.Button2] = false; else if (e.ButtonEvent.button == 8) mouse[OpenTK.Input.MouseButton.Button3] = false; else if (e.ButtonEvent.button == 9) mouse[OpenTK.Input.MouseButton.Button4] = false; else if (e.ButtonEvent.button == 10) mouse[OpenTK.Input.MouseButton.Button5] = false; else if (e.ButtonEvent.button == 11) mouse[OpenTK.Input.MouseButton.Button6] = false; else if (e.ButtonEvent.button == 12) mouse[OpenTK.Input.MouseButton.Button7] = false; else if (e.ButtonEvent.button == 13) mouse[OpenTK.Input.MouseButton.Button8] = false; else if (e.ButtonEvent.button == 14) mouse[OpenTK.Input.MouseButton.Button9] = false; break; case XEventName.MotionNotify: mouse.Position = new Point(e.MotionEvent.x, e.MotionEvent.y); break; } } #endregion #region --- IInputDriver Members --- #region public IList<Keyboard> Keyboard public IList<KeyboardDevice> Keyboard { get { return dummy_keyboard_list; }//return keyboardDriver.Keyboard; } #endregion #region public IList<Mouse> Mouse public IList<MouseDevice> Mouse { get { return (IList<MouseDevice>)dummy_mice_list; } //return mouseDriver.Mouse; } #endregion #region public IList<JoystickDevice> Joysticks public IList<JoystickDevice> Joysticks { get { return joystick_driver.Joysticks; } } #endregion #region public void Poll() /// <summary> /// Polls and updates state of all keyboard, mouse and joystick devices. /// </summary> public void Poll() { joystick_driver.Poll(); } #endregion #endregion #region --- IDisposable Members --- public void Dispose() { //this.Dispose(true); //GC.SuppressFinalize(this); } //private void Dispose(bool manual) //{ // if (!disposed) // { // //disposing = true; // if (pollingThread != null && pollingThread.IsAlive) // pollingThread.Abort(); // if (manual) // { // } // disposed = true; // } //} //~X11Input() //{ // this.Dispose(false); //} #endregion } }
/*- * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * See the file LICENSE for license information. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Xml; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class TransactionTest : CSharpTestFixture { private DatabaseEnvironment deadLockEnv; [TestFixtureSetUp] public void SetUpTestFixture() { testFixtureName = "TransactionTest"; base.SetUpTestfixture(); DatabaseEnvironment.Remove(testFixtureHome); } [Test, ExpectedException(typeof(ExpectedTestException))] public void TestAbort() { testName = "TestAbort"; SetUpTest(true); DatabaseEnvironment env; Transaction txn; BTreeDatabase db; /* * Open an environment and begin a transaction. Open * a db and write a record the db within this transaction. */ PutRecordWithTxn(out env, testHome, testName, out txn); // Abort the transaction. txn.Abort(); /* * Undo all operations in the transaction so the * database couldn't be reopened. */ try { OpenBtreeDBInEnv(testName + ".db", env, out db, false, null); } catch (DatabaseException) { throw new ExpectedTestException(); } finally { env.Close(); } } [Test] public void TestCommit() { testName = "TestCommit"; SetUpTest(true); DatabaseEnvironment env; Transaction txn; BTreeDatabase db; /* * Open an environment and begin a transaction. Open * a db and write a record the db within this transaction. */ PutRecordWithTxn(out env, testHome, testName, out txn); // Commit the transaction. txn.Commit(); // Reopen the database. OpenBtreeDBInEnv(testName + ".db", env, out db, false, null); /* * Confirm that the record("key", "data") exists in the * database. */ try { db.GetBoth(new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")), new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data"))); } catch (DatabaseException) { throw new TestException(); } finally { db.Close(); env.Close(); } } [Test, ExpectedException(typeof(AccessViolationException))] public void TestDiscard() { DatabaseEnvironment env; byte[] gid; testName = "TestDiscard"; SetUpTest(true); /* * Open an environment and begin a transaction * called "transaction". Within the transacion, open a * database, write a record and close it. Then prepare * the transaction and panic the environment. */ PanicPreparedTxn(testHome, testName, out env, out gid); /* * Recover the environment. Log and db files are not * destoyed so run normal recovery. Recovery should * use DB_CREATE and DB_INIT_TXN flags when * opening the environment. */ DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.RunRecovery = true; envConfig.Create = true; envConfig.UseTxns = true; envConfig.UseMPool = true; env = DatabaseEnvironment.Open(testHome, envConfig); PreparedTransaction[] preparedTxns = new PreparedTransaction[10]; preparedTxns = env.Recover(10, true); Assert.AreEqual(gid, preparedTxns[0].GlobalID); preparedTxns[0].Txn.Discard(); try { preparedTxns[0].Txn.Commit(); } catch (AccessViolationException) { } finally { env.Close(); } } [Test] public void TestPrepare() { testName = "TestPrepare"; SetUpTest(true); DatabaseEnvironment env; byte[] gid; /* * Open an environment and begin a transaction * called "transaction". Within the transacion, open a * database, write a record and close it. Then prepare * the transaction and panic the environment. */ PanicPreparedTxn(testHome, testName, out env, out gid); /* * Recover the environment. Log and db files are not * destoyed so run normal recovery. Recovery should * use DB_CREATE and DB_INIT_TXN flags when * opening the environment. */ DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.RunRecovery = true; envConfig.Create = true; envConfig.UseTxns = true; envConfig.UseMPool = true; env = DatabaseEnvironment.Open(testHome, envConfig); // Reopen the database. BTreeDatabase db; OpenBtreeDBInEnv(testName + ".db", env, out db, false, null); /* * Confirm that record("key", "data") exists in the * database. */ DatabaseEntry key, data; key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data")); try { db.GetBoth(key, data); } catch (DatabaseException) { throw new TestException(); } finally { db.Close(); env.Close(); } } public void PanicPreparedTxn(string home, string dbName, out DatabaseEnvironment env, out byte[] globalID) { Transaction txn; // Put record into database within transaction. PutRecordWithTxn(out env, home, dbName, out txn); /* * Generate global ID for the transaction. Copy * transaction ID to the first 4 tyes in global ID. */ globalID = new byte[Transaction.GlobalIdLength]; byte[] txnID = new byte[4]; txnID = BitConverter.GetBytes(txn.Id); for (int i = 0; i < txnID.Length; i++) globalID[i] = txnID[i]; // Prepare the transaction. txn.Prepare(globalID); // Panic the environment. env.Panic(); } [Test] public void TestTxnName() { DatabaseEnvironment env; Transaction txn; testName = "TestTxnName"; SetUpTest(true); SetUpTransactionalEnv(testHome, out env); txn = env.BeginTransaction(); txn.Name = testName; Assert.AreEqual(testName, txn.Name); txn.Commit(); env.Close(); } [Test] public void TestTxnPriority() { DatabaseEnvironment env; Transaction txn; testName = "TestTxnPriority"; SetUpTest(true); SetUpTransactionalEnv(testHome, out env); txn = env.BeginTransaction(); txn.Priority = 555; Assert.AreEqual(555, txn.Priority); txn.Commit(); env.Close(); } [Test] public void TestSetLockTimeout() { testName = "TestSetLockTimeout"; SetUpTest(true); // Set lock timeout. TestTimeOut(true); } [Test] public void TestSetTxnTimeout() { testName = "TestSetTxnTimeout"; SetUpTest(true); // Set transaction time out. TestTimeOut(false); } /* * ifSetLock is used to indicate which timeout function * is used, SetLockTimeout or SetTxnTimeout. */ public void TestTimeOut(bool ifSetLock) { // Open environment and begin transaction. Transaction txn; deadLockEnv = null; SetUpEnvWithTxnAndLocking(testHome, out deadLockEnv, out txn, 0, 0, 0, 0); // Define deadlock detection and resolve policy. deadLockEnv.DeadlockResolution = DeadlockPolicy.YOUNGEST; if (ifSetLock == true) txn.SetLockTimeout(10); else txn.SetTxnTimeout(10); txn.Commit(); deadLockEnv.Close(); } public static void SetUpEnvWithTxnAndLocking(string envHome, out DatabaseEnvironment env, out Transaction txn, uint maxLock, uint maxLocker, uint maxObject, uint partition) { // Configure env and locking subsystem. LockingConfig lkConfig = new LockingConfig(); /* * If the maximum number of locks/lockers/objects * is given, then the LockingConfig is set. Unless, * it is not set to any value. */ if (maxLock != 0) lkConfig.MaxLocks = maxLock; if (maxLocker != 0) lkConfig.MaxLockers = maxLocker; if (maxObject != 0) lkConfig.MaxObjects = maxObject; if (partition != 0) lkConfig.Partitions = partition; DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseTxns = true; envConfig.UseMPool = true; envConfig.LockSystemCfg = lkConfig; envConfig.UseLocking = true; envConfig.NoLocking = false; env = DatabaseEnvironment.Open(envHome, envConfig); txn = env.BeginTransaction(); } public void PutRecordWithTxn(out DatabaseEnvironment env, string home, string dbName, out Transaction txn) { BTreeDatabase db; // Open a new environment and begin a transaction. SetUpTransactionalEnv(home, out env); TransactionConfig txnConfig = new TransactionConfig(); txnConfig.Name = "Transaction"; txn = env.BeginTransaction(txnConfig); Assert.AreEqual("Transaction", txn.Name); // Open a new database within the transaction. OpenBtreeDBInEnv(dbName + ".db", env, out db, true, txn); // Write to the database within the transaction. WriteOneIntoBtreeDBWithTxn(db, txn); // Close the database. db.Close(); } public void SetUpTransactionalEnv(string home, out DatabaseEnvironment env) { DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseLogging = true; envConfig.UseLocking = true; envConfig.UseMPool = true; envConfig.UseTxns = true; env = DatabaseEnvironment.Open( home, envConfig); } public void OpenBtreeDBInEnv(string dbName, DatabaseEnvironment env, out BTreeDatabase db, bool create, Transaction txn) { BTreeDatabaseConfig btreeDBConfig = new BTreeDatabaseConfig(); btreeDBConfig.Env = env; if (create == true) btreeDBConfig.Creation = CreatePolicy.IF_NEEDED; else btreeDBConfig.Creation = CreatePolicy.NEVER; if (txn == null) db = BTreeDatabase.Open(dbName, btreeDBConfig); else db = BTreeDatabase.Open(dbName, btreeDBConfig, txn); } public void WriteOneIntoBtreeDBWithTxn(BTreeDatabase db, Transaction txn) { DatabaseEntry key, data; key = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("key")); data = new DatabaseEntry( ASCIIEncoding.ASCII.GetBytes("data")); db.Put(key, data, txn); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/group_service.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Monitoring.V3 { /// <summary>Holder for reflection information generated from google/monitoring/v3/group_service.proto</summary> public static partial class GroupServiceReflection { #region Descriptor /// <summary>File descriptor for google/monitoring/v3/group_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GroupServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cihnb29nbGUvbW9uaXRvcmluZy92My9ncm91cF9zZXJ2aWNlLnByb3RvEhRn", "b29nbGUubW9uaXRvcmluZy52MxocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5w", "cm90bxojZ29vZ2xlL2FwaS9tb25pdG9yZWRfcmVzb3VyY2UucHJvdG8aIWdv", "b2dsZS9tb25pdG9yaW5nL3YzL2NvbW1vbi5wcm90bxogZ29vZ2xlL21vbml0", "b3JpbmcvdjMvZ3JvdXAucHJvdG8aG2dvb2dsZS9wcm90b2J1Zi9lbXB0eS5w", "cm90byKtAQoRTGlzdEdyb3Vwc1JlcXVlc3QSDAoEbmFtZRgHIAEoCRIbChFj", "aGlsZHJlbl9vZl9ncm91cBgCIAEoCUgAEhwKEmFuY2VzdG9yc19vZl9ncm91", "cBgDIAEoCUgAEh4KFGRlc2NlbmRhbnRzX29mX2dyb3VwGAQgASgJSAASEQoJ", "cGFnZV9zaXplGAUgASgFEhIKCnBhZ2VfdG9rZW4YBiABKAlCCAoGZmlsdGVy", "IlkKEkxpc3RHcm91cHNSZXNwb25zZRIqCgVncm91cBgBIAMoCzIbLmdvb2ds", "ZS5tb25pdG9yaW5nLnYzLkdyb3VwEhcKD25leHRfcGFnZV90b2tlbhgCIAEo", "CSIfCg9HZXRHcm91cFJlcXVlc3QSDAoEbmFtZRgDIAEoCSJlChJDcmVhdGVH", "cm91cFJlcXVlc3QSDAoEbmFtZRgEIAEoCRIqCgVncm91cBgCIAEoCzIbLmdv", "b2dsZS5tb25pdG9yaW5nLnYzLkdyb3VwEhUKDXZhbGlkYXRlX29ubHkYAyAB", "KAgiVwoSVXBkYXRlR3JvdXBSZXF1ZXN0EioKBWdyb3VwGAIgASgLMhsuZ29v", "Z2xlLm1vbml0b3JpbmcudjMuR3JvdXASFQoNdmFsaWRhdGVfb25seRgDIAEo", "CCIiChJEZWxldGVHcm91cFJlcXVlc3QSDAoEbmFtZRgDIAEoCSKUAQoXTGlz", "dEdyb3VwTWVtYmVyc1JlcXVlc3QSDAoEbmFtZRgHIAEoCRIRCglwYWdlX3Np", "emUYAyABKAUSEgoKcGFnZV90b2tlbhgEIAEoCRIOCgZmaWx0ZXIYBSABKAkS", "NAoIaW50ZXJ2YWwYBiABKAsyIi5nb29nbGUubW9uaXRvcmluZy52My5UaW1l", "SW50ZXJ2YWwidwoYTGlzdEdyb3VwTWVtYmVyc1Jlc3BvbnNlEi4KB21lbWJl", "cnMYASADKAsyHS5nb29nbGUuYXBpLk1vbml0b3JlZFJlc291cmNlEhcKD25l", "eHRfcGFnZV90b2tlbhgCIAEoCRISCgp0b3RhbF9zaXplGAMgASgFMrsGCgxH", "cm91cFNlcnZpY2UShQEKCkxpc3RHcm91cHMSJy5nb29nbGUubW9uaXRvcmlu", "Zy52My5MaXN0R3JvdXBzUmVxdWVzdBooLmdvb2dsZS5tb25pdG9yaW5nLnYz", "Lkxpc3RHcm91cHNSZXNwb25zZSIkgtPkkwIeEhwvdjMve25hbWU9cHJvamVj", "dHMvKn0vZ3JvdXBzEnYKCEdldEdyb3VwEiUuZ29vZ2xlLm1vbml0b3Jpbmcu", "djMuR2V0R3JvdXBSZXF1ZXN0GhsuZ29vZ2xlLm1vbml0b3JpbmcudjMuR3Jv", "dXAiJoLT5JMCIBIeL3YzL3tuYW1lPXByb2plY3RzLyovZ3JvdXBzLyp9EoEB", "CgtDcmVhdGVHcm91cBIoLmdvb2dsZS5tb25pdG9yaW5nLnYzLkNyZWF0ZUdy", "b3VwUmVxdWVzdBobLmdvb2dsZS5tb25pdG9yaW5nLnYzLkdyb3VwIiuC0+ST", "AiUiHC92My97bmFtZT1wcm9qZWN0cy8qfS9ncm91cHM6BWdyb3VwEokBCgtV", "cGRhdGVHcm91cBIoLmdvb2dsZS5tb25pdG9yaW5nLnYzLlVwZGF0ZUdyb3Vw", "UmVxdWVzdBobLmdvb2dsZS5tb25pdG9yaW5nLnYzLkdyb3VwIjOC0+STAi0a", "JC92My97Z3JvdXAubmFtZT1wcm9qZWN0cy8qL2dyb3Vwcy8qfToFZ3JvdXAS", "dwoLRGVsZXRlR3JvdXASKC5nb29nbGUubW9uaXRvcmluZy52My5EZWxldGVH", "cm91cFJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiJoLT5JMCICoe", "L3YzL3tuYW1lPXByb2plY3RzLyovZ3JvdXBzLyp9EqEBChBMaXN0R3JvdXBN", "ZW1iZXJzEi0uZ29vZ2xlLm1vbml0b3JpbmcudjMuTGlzdEdyb3VwTWVtYmVy", "c1JlcXVlc3QaLi5nb29nbGUubW9uaXRvcmluZy52My5MaXN0R3JvdXBNZW1i", "ZXJzUmVzcG9uc2UiLoLT5JMCKBImL3YzL3tuYW1lPXByb2plY3RzLyovZ3Jv", "dXBzLyp9L21lbWJlcnNCqQEKGGNvbS5nb29nbGUubW9uaXRvcmluZy52M0IR", "R3JvdXBTZXJ2aWNlUHJvdG9QAVo+Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJv", "dG8vZ29vZ2xlYXBpcy9tb25pdG9yaW5nL3YzO21vbml0b3JpbmeqAhpHb29n", "bGUuQ2xvdWQuTW9uaXRvcmluZy5WM8oCGkdvb2dsZVxDbG91ZFxNb25pdG9y", "aW5nXFYzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.MonitoredResourceReflection.Descriptor, global::Google.Cloud.Monitoring.V3.CommonReflection.Descriptor, global::Google.Cloud.Monitoring.V3.GroupReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.ListGroupsRequest), global::Google.Cloud.Monitoring.V3.ListGroupsRequest.Parser, new[]{ "Name", "ChildrenOfGroup", "AncestorsOfGroup", "DescendantsOfGroup", "PageSize", "PageToken" }, new[]{ "Filter" }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.ListGroupsResponse), global::Google.Cloud.Monitoring.V3.ListGroupsResponse.Parser, new[]{ "Group", "NextPageToken" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.GetGroupRequest), global::Google.Cloud.Monitoring.V3.GetGroupRequest.Parser, new[]{ "Name" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.CreateGroupRequest), global::Google.Cloud.Monitoring.V3.CreateGroupRequest.Parser, new[]{ "Name", "Group", "ValidateOnly" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UpdateGroupRequest), global::Google.Cloud.Monitoring.V3.UpdateGroupRequest.Parser, new[]{ "Group", "ValidateOnly" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.DeleteGroupRequest), global::Google.Cloud.Monitoring.V3.DeleteGroupRequest.Parser, new[]{ "Name" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest), global::Google.Cloud.Monitoring.V3.ListGroupMembersRequest.Parser, new[]{ "Name", "PageSize", "PageToken", "Filter", "Interval" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse), global::Google.Cloud.Monitoring.V3.ListGroupMembersResponse.Parser, new[]{ "Members", "NextPageToken", "TotalSize" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// The `ListGroup` request. /// </summary> public sealed partial class ListGroupsRequest : pb::IMessage<ListGroupsRequest> { private static readonly pb::MessageParser<ListGroupsRequest> _parser = new pb::MessageParser<ListGroupsRequest>(() => new ListGroupsRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListGroupsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupsRequest(ListGroupsRequest other) : this() { name_ = other.name_; pageSize_ = other.pageSize_; pageToken_ = other.pageToken_; switch (other.FilterCase) { case FilterOneofCase.ChildrenOfGroup: ChildrenOfGroup = other.ChildrenOfGroup; break; case FilterOneofCase.AncestorsOfGroup: AncestorsOfGroup = other.AncestorsOfGroup; break; case FilterOneofCase.DescendantsOfGroup: DescendantsOfGroup = other.DescendantsOfGroup; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupsRequest Clone() { return new ListGroupsRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 7; private string name_ = ""; /// <summary> /// The project whose groups are to be listed. The format is /// `"projects/{project_id_or_number}"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "children_of_group" field.</summary> public const int ChildrenOfGroupFieldNumber = 2; /// <summary> /// A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. /// Returns groups whose `parentName` field contains the group /// name. If no groups have this parent, the results are empty. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ChildrenOfGroup { get { return filterCase_ == FilterOneofCase.ChildrenOfGroup ? (string) filter_ : ""; } set { filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); filterCase_ = FilterOneofCase.ChildrenOfGroup; } } /// <summary>Field number for the "ancestors_of_group" field.</summary> public const int AncestorsOfGroupFieldNumber = 3; /// <summary> /// A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. /// Returns groups that are ancestors of the specified group. /// The groups are returned in order, starting with the immediate parent and /// ending with the most distant ancestor. If the specified group has no /// immediate parent, the results are empty. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string AncestorsOfGroup { get { return filterCase_ == FilterOneofCase.AncestorsOfGroup ? (string) filter_ : ""; } set { filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); filterCase_ = FilterOneofCase.AncestorsOfGroup; } } /// <summary>Field number for the "descendants_of_group" field.</summary> public const int DescendantsOfGroupFieldNumber = 4; /// <summary> /// A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. /// Returns the descendants of the specified group. This is a superset of /// the results returned by the `childrenOfGroup` filter, and includes /// children-of-children, and so forth. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string DescendantsOfGroup { get { return filterCase_ == FilterOneofCase.DescendantsOfGroup ? (string) filter_ : ""; } set { filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); filterCase_ = FilterOneofCase.DescendantsOfGroup; } } /// <summary>Field number for the "page_size" field.</summary> public const int PageSizeFieldNumber = 5; private int pageSize_; /// <summary> /// A positive number that is the maximum number of results to return. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int PageSize { get { return pageSize_; } set { pageSize_ = value; } } /// <summary>Field number for the "page_token" field.</summary> public const int PageTokenFieldNumber = 6; private string pageToken_ = ""; /// <summary> /// If this field is not empty then it must contain the `nextPageToken` value /// returned by a previous call to this method. Using this field causes the /// method to return additional results from the previous method call. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PageToken { get { return pageToken_; } set { pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } private object filter_; /// <summary>Enum of possible cases for the "filter" oneof.</summary> public enum FilterOneofCase { None = 0, ChildrenOfGroup = 2, AncestorsOfGroup = 3, DescendantsOfGroup = 4, } private FilterOneofCase filterCase_ = FilterOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FilterOneofCase FilterCase { get { return filterCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearFilter() { filterCase_ = FilterOneofCase.None; filter_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListGroupsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListGroupsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (ChildrenOfGroup != other.ChildrenOfGroup) return false; if (AncestorsOfGroup != other.AncestorsOfGroup) return false; if (DescendantsOfGroup != other.DescendantsOfGroup) return false; if (PageSize != other.PageSize) return false; if (PageToken != other.PageToken) return false; if (FilterCase != other.FilterCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (filterCase_ == FilterOneofCase.ChildrenOfGroup) hash ^= ChildrenOfGroup.GetHashCode(); if (filterCase_ == FilterOneofCase.AncestorsOfGroup) hash ^= AncestorsOfGroup.GetHashCode(); if (filterCase_ == FilterOneofCase.DescendantsOfGroup) hash ^= DescendantsOfGroup.GetHashCode(); if (PageSize != 0) hash ^= PageSize.GetHashCode(); if (PageToken.Length != 0) hash ^= PageToken.GetHashCode(); hash ^= (int) filterCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (filterCase_ == FilterOneofCase.ChildrenOfGroup) { output.WriteRawTag(18); output.WriteString(ChildrenOfGroup); } if (filterCase_ == FilterOneofCase.AncestorsOfGroup) { output.WriteRawTag(26); output.WriteString(AncestorsOfGroup); } if (filterCase_ == FilterOneofCase.DescendantsOfGroup) { output.WriteRawTag(34); output.WriteString(DescendantsOfGroup); } if (PageSize != 0) { output.WriteRawTag(40); output.WriteInt32(PageSize); } if (PageToken.Length != 0) { output.WriteRawTag(50); output.WriteString(PageToken); } if (Name.Length != 0) { output.WriteRawTag(58); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (filterCase_ == FilterOneofCase.ChildrenOfGroup) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ChildrenOfGroup); } if (filterCase_ == FilterOneofCase.AncestorsOfGroup) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AncestorsOfGroup); } if (filterCase_ == FilterOneofCase.DescendantsOfGroup) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DescendantsOfGroup); } if (PageSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize); } if (PageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListGroupsRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.PageSize != 0) { PageSize = other.PageSize; } if (other.PageToken.Length != 0) { PageToken = other.PageToken; } switch (other.FilterCase) { case FilterOneofCase.ChildrenOfGroup: ChildrenOfGroup = other.ChildrenOfGroup; break; case FilterOneofCase.AncestorsOfGroup: AncestorsOfGroup = other.AncestorsOfGroup; break; case FilterOneofCase.DescendantsOfGroup: DescendantsOfGroup = other.DescendantsOfGroup; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 18: { ChildrenOfGroup = input.ReadString(); break; } case 26: { AncestorsOfGroup = input.ReadString(); break; } case 34: { DescendantsOfGroup = input.ReadString(); break; } case 40: { PageSize = input.ReadInt32(); break; } case 50: { PageToken = input.ReadString(); break; } case 58: { Name = input.ReadString(); break; } } } } } /// <summary> /// The `ListGroups` response. /// </summary> public sealed partial class ListGroupsResponse : pb::IMessage<ListGroupsResponse> { private static readonly pb::MessageParser<ListGroupsResponse> _parser = new pb::MessageParser<ListGroupsResponse>(() => new ListGroupsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListGroupsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupsResponse(ListGroupsResponse other) : this() { group_ = other.group_.Clone(); nextPageToken_ = other.nextPageToken_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupsResponse Clone() { return new ListGroupsResponse(this); } /// <summary>Field number for the "group" field.</summary> public const int GroupFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.Monitoring.V3.Group> _repeated_group_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.Monitoring.V3.Group.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.Group> group_ = new pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.Group>(); /// <summary> /// The groups that match the specified filters. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.Group> Group { get { return group_; } } /// <summary>Field number for the "next_page_token" field.</summary> public const int NextPageTokenFieldNumber = 2; private string nextPageToken_ = ""; /// <summary> /// If there are more results than have been returned, then this field is set /// to a non-empty value. To see the additional results, /// use that value as `pageToken` in the next call to this method. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string NextPageToken { get { return nextPageToken_; } set { nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListGroupsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListGroupsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!group_.Equals(other.group_)) return false; if (NextPageToken != other.NextPageToken) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= group_.GetHashCode(); if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { group_.WriteTo(output, _repeated_group_codec); if (NextPageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(NextPageToken); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += group_.CalculateSize(_repeated_group_codec); if (NextPageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListGroupsResponse other) { if (other == null) { return; } group_.Add(other.group_); if (other.NextPageToken.Length != 0) { NextPageToken = other.NextPageToken; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { group_.AddEntriesFrom(input, _repeated_group_codec); break; } case 18: { NextPageToken = input.ReadString(); break; } } } } } /// <summary> /// The `GetGroup` request. /// </summary> public sealed partial class GetGroupRequest : pb::IMessage<GetGroupRequest> { private static readonly pb::MessageParser<GetGroupRequest> _parser = new pb::MessageParser<GetGroupRequest>(() => new GetGroupRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetGroupRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGroupRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGroupRequest(GetGroupRequest other) : this() { name_ = other.name_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGroupRequest Clone() { return new GetGroupRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 3; private string name_ = ""; /// <summary> /// The group to retrieve. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetGroupRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetGroupRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(26); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetGroupRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 26: { Name = input.ReadString(); break; } } } } } /// <summary> /// The `CreateGroup` request. /// </summary> public sealed partial class CreateGroupRequest : pb::IMessage<CreateGroupRequest> { private static readonly pb::MessageParser<CreateGroupRequest> _parser = new pb::MessageParser<CreateGroupRequest>(() => new CreateGroupRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CreateGroupRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateGroupRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateGroupRequest(CreateGroupRequest other) : this() { name_ = other.name_; Group = other.group_ != null ? other.Group.Clone() : null; validateOnly_ = other.validateOnly_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateGroupRequest Clone() { return new CreateGroupRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 4; private string name_ = ""; /// <summary> /// The project in which to create the group. The format is /// `"projects/{project_id_or_number}"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "group" field.</summary> public const int GroupFieldNumber = 2; private global::Google.Cloud.Monitoring.V3.Group group_; /// <summary> /// A group definition. It is an error to define the `name` field because /// the system assigns the name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Monitoring.V3.Group Group { get { return group_; } set { group_ = value; } } /// <summary>Field number for the "validate_only" field.</summary> public const int ValidateOnlyFieldNumber = 3; private bool validateOnly_; /// <summary> /// If true, validate this request but do not create the group. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool ValidateOnly { get { return validateOnly_; } set { validateOnly_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CreateGroupRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CreateGroupRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(Group, other.Group)) return false; if (ValidateOnly != other.ValidateOnly) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (group_ != null) hash ^= Group.GetHashCode(); if (ValidateOnly != false) hash ^= ValidateOnly.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (group_ != null) { output.WriteRawTag(18); output.WriteMessage(Group); } if (ValidateOnly != false) { output.WriteRawTag(24); output.WriteBool(ValidateOnly); } if (Name.Length != 0) { output.WriteRawTag(34); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (group_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Group); } if (ValidateOnly != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CreateGroupRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.group_ != null) { if (group_ == null) { group_ = new global::Google.Cloud.Monitoring.V3.Group(); } Group.MergeFrom(other.Group); } if (other.ValidateOnly != false) { ValidateOnly = other.ValidateOnly; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 18: { if (group_ == null) { group_ = new global::Google.Cloud.Monitoring.V3.Group(); } input.ReadMessage(group_); break; } case 24: { ValidateOnly = input.ReadBool(); break; } case 34: { Name = input.ReadString(); break; } } } } } /// <summary> /// The `UpdateGroup` request. /// </summary> public sealed partial class UpdateGroupRequest : pb::IMessage<UpdateGroupRequest> { private static readonly pb::MessageParser<UpdateGroupRequest> _parser = new pb::MessageParser<UpdateGroupRequest>(() => new UpdateGroupRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UpdateGroupRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateGroupRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateGroupRequest(UpdateGroupRequest other) : this() { Group = other.group_ != null ? other.Group.Clone() : null; validateOnly_ = other.validateOnly_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateGroupRequest Clone() { return new UpdateGroupRequest(this); } /// <summary>Field number for the "group" field.</summary> public const int GroupFieldNumber = 2; private global::Google.Cloud.Monitoring.V3.Group group_; /// <summary> /// The new definition of the group. All fields of the existing group, /// excepting `name`, are replaced with the corresponding fields of this group. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Monitoring.V3.Group Group { get { return group_; } set { group_ = value; } } /// <summary>Field number for the "validate_only" field.</summary> public const int ValidateOnlyFieldNumber = 3; private bool validateOnly_; /// <summary> /// If true, validate this request but do not update the existing group. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool ValidateOnly { get { return validateOnly_; } set { validateOnly_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UpdateGroupRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UpdateGroupRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Group, other.Group)) return false; if (ValidateOnly != other.ValidateOnly) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (group_ != null) hash ^= Group.GetHashCode(); if (ValidateOnly != false) hash ^= ValidateOnly.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (group_ != null) { output.WriteRawTag(18); output.WriteMessage(Group); } if (ValidateOnly != false) { output.WriteRawTag(24); output.WriteBool(ValidateOnly); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (group_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Group); } if (ValidateOnly != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UpdateGroupRequest other) { if (other == null) { return; } if (other.group_ != null) { if (group_ == null) { group_ = new global::Google.Cloud.Monitoring.V3.Group(); } Group.MergeFrom(other.Group); } if (other.ValidateOnly != false) { ValidateOnly = other.ValidateOnly; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 18: { if (group_ == null) { group_ = new global::Google.Cloud.Monitoring.V3.Group(); } input.ReadMessage(group_); break; } case 24: { ValidateOnly = input.ReadBool(); break; } } } } } /// <summary> /// The `DeleteGroup` request. You can only delete a group if it has no children. /// </summary> public sealed partial class DeleteGroupRequest : pb::IMessage<DeleteGroupRequest> { private static readonly pb::MessageParser<DeleteGroupRequest> _parser = new pb::MessageParser<DeleteGroupRequest>(() => new DeleteGroupRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<DeleteGroupRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteGroupRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteGroupRequest(DeleteGroupRequest other) : this() { name_ = other.name_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteGroupRequest Clone() { return new DeleteGroupRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 3; private string name_ = ""; /// <summary> /// The group to delete. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as DeleteGroupRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(DeleteGroupRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(26); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(DeleteGroupRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 26: { Name = input.ReadString(); break; } } } } } /// <summary> /// The `ListGroupMembers` request. /// </summary> public sealed partial class ListGroupMembersRequest : pb::IMessage<ListGroupMembersRequest> { private static readonly pb::MessageParser<ListGroupMembersRequest> _parser = new pb::MessageParser<ListGroupMembersRequest>(() => new ListGroupMembersRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListGroupMembersRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupMembersRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupMembersRequest(ListGroupMembersRequest other) : this() { name_ = other.name_; pageSize_ = other.pageSize_; pageToken_ = other.pageToken_; filter_ = other.filter_; Interval = other.interval_ != null ? other.Interval.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupMembersRequest Clone() { return new ListGroupMembersRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 7; private string name_ = ""; /// <summary> /// The group whose members are listed. The format is /// `"projects/{project_id_or_number}/groups/{group_id}"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "page_size" field.</summary> public const int PageSizeFieldNumber = 3; private int pageSize_; /// <summary> /// A positive number that is the maximum number of results to return. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int PageSize { get { return pageSize_; } set { pageSize_ = value; } } /// <summary>Field number for the "page_token" field.</summary> public const int PageTokenFieldNumber = 4; private string pageToken_ = ""; /// <summary> /// If this field is not empty then it must contain the `nextPageToken` value /// returned by a previous call to this method. Using this field causes the /// method to return additional results from the previous method call. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PageToken { get { return pageToken_; } set { pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "filter" field.</summary> public const int FilterFieldNumber = 5; private string filter_ = ""; /// <summary> /// An optional [list filter](/monitoring/api/learn_more#filtering) describing /// the members to be returned. The filter may reference the type, labels, and /// metadata of monitored resources that comprise the group. /// For example, to return only resources representing Compute Engine VM /// instances, use this filter: /// /// resource.type = "gce_instance" /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Filter { get { return filter_; } set { filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "interval" field.</summary> public const int IntervalFieldNumber = 6; private global::Google.Cloud.Monitoring.V3.TimeInterval interval_; /// <summary> /// An optional time interval for which results should be returned. Only /// members that were part of the group during the specified interval are /// included in the response. If no interval is provided then the group /// membership over the last minute is returned. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Monitoring.V3.TimeInterval Interval { get { return interval_; } set { interval_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListGroupMembersRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListGroupMembersRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (PageSize != other.PageSize) return false; if (PageToken != other.PageToken) return false; if (Filter != other.Filter) return false; if (!object.Equals(Interval, other.Interval)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (PageSize != 0) hash ^= PageSize.GetHashCode(); if (PageToken.Length != 0) hash ^= PageToken.GetHashCode(); if (Filter.Length != 0) hash ^= Filter.GetHashCode(); if (interval_ != null) hash ^= Interval.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (PageSize != 0) { output.WriteRawTag(24); output.WriteInt32(PageSize); } if (PageToken.Length != 0) { output.WriteRawTag(34); output.WriteString(PageToken); } if (Filter.Length != 0) { output.WriteRawTag(42); output.WriteString(Filter); } if (interval_ != null) { output.WriteRawTag(50); output.WriteMessage(Interval); } if (Name.Length != 0) { output.WriteRawTag(58); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (PageSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize); } if (PageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken); } if (Filter.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter); } if (interval_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Interval); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListGroupMembersRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.PageSize != 0) { PageSize = other.PageSize; } if (other.PageToken.Length != 0) { PageToken = other.PageToken; } if (other.Filter.Length != 0) { Filter = other.Filter; } if (other.interval_ != null) { if (interval_ == null) { interval_ = new global::Google.Cloud.Monitoring.V3.TimeInterval(); } Interval.MergeFrom(other.Interval); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 24: { PageSize = input.ReadInt32(); break; } case 34: { PageToken = input.ReadString(); break; } case 42: { Filter = input.ReadString(); break; } case 50: { if (interval_ == null) { interval_ = new global::Google.Cloud.Monitoring.V3.TimeInterval(); } input.ReadMessage(interval_); break; } case 58: { Name = input.ReadString(); break; } } } } } /// <summary> /// The `ListGroupMembers` response. /// </summary> public sealed partial class ListGroupMembersResponse : pb::IMessage<ListGroupMembersResponse> { private static readonly pb::MessageParser<ListGroupMembersResponse> _parser = new pb::MessageParser<ListGroupMembersResponse>(() => new ListGroupMembersResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListGroupMembersResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupMembersResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupMembersResponse(ListGroupMembersResponse other) : this() { members_ = other.members_.Clone(); nextPageToken_ = other.nextPageToken_; totalSize_ = other.totalSize_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListGroupMembersResponse Clone() { return new ListGroupMembersResponse(this); } /// <summary>Field number for the "members" field.</summary> public const int MembersFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Api.MonitoredResource> _repeated_members_codec = pb::FieldCodec.ForMessage(10, global::Google.Api.MonitoredResource.Parser); private readonly pbc::RepeatedField<global::Google.Api.MonitoredResource> members_ = new pbc::RepeatedField<global::Google.Api.MonitoredResource>(); /// <summary> /// A set of monitored resources in the group. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.MonitoredResource> Members { get { return members_; } } /// <summary>Field number for the "next_page_token" field.</summary> public const int NextPageTokenFieldNumber = 2; private string nextPageToken_ = ""; /// <summary> /// If there are more results than have been returned, then this field is /// set to a non-empty value. To see the additional results, use that value as /// `pageToken` in the next call to this method. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string NextPageToken { get { return nextPageToken_; } set { nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "total_size" field.</summary> public const int TotalSizeFieldNumber = 3; private int totalSize_; /// <summary> /// The total number of elements matching this request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int TotalSize { get { return totalSize_; } set { totalSize_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListGroupMembersResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListGroupMembersResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!members_.Equals(other.members_)) return false; if (NextPageToken != other.NextPageToken) return false; if (TotalSize != other.TotalSize) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= members_.GetHashCode(); if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode(); if (TotalSize != 0) hash ^= TotalSize.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { members_.WriteTo(output, _repeated_members_codec); if (NextPageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(NextPageToken); } if (TotalSize != 0) { output.WriteRawTag(24); output.WriteInt32(TotalSize); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += members_.CalculateSize(_repeated_members_codec); if (NextPageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken); } if (TotalSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(TotalSize); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListGroupMembersResponse other) { if (other == null) { return; } members_.Add(other.members_); if (other.NextPageToken.Length != 0) { NextPageToken = other.NextPageToken; } if (other.TotalSize != 0) { TotalSize = other.TotalSize; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { members_.AddEntriesFrom(input, _repeated_members_codec); break; } case 18: { NextPageToken = input.ReadString(); break; } case 24: { TotalSize = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
/** * FreeRDP: A Remote Desktop Protocol Implementation * Time Zone Redirection Table Generator * * Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Globalization; using System.Collections.ObjectModel; namespace TimeZones { struct SYSTEM_TIME_ENTRY { public UInt16 wYear; public UInt16 wMonth; public UInt16 wDayOfWeek; public UInt16 wDay; public UInt16 wHour; public UInt16 wMinute; public UInt16 wSecond; public UInt16 wMilliseconds; }; struct TIME_ZONE_RULE_ENTRY { public long TicksStart; public long TicksEnd; public Int32 DaylightDelta; public SYSTEM_TIME_ENTRY StandardDate; public SYSTEM_TIME_ENTRY DaylightDate; }; struct TIME_ZONE_ENTRY { public string Id; public Int32 Bias; public bool SupportsDST; public string DisplayName; public string StandardName; public string DaylightName; public string RuleTable; public UInt32 RuleTableCount; }; class TimeZones { static void Main(string[] args) { int i; UInt32 index; const string file = @"TimeZones.txt"; TimeZoneInfo.AdjustmentRule[] rules; StreamWriter stream = new StreamWriter(file, false); ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones(); stream.WriteLine(); stream.WriteLine("struct _TIME_ZONE_RULE_ENTRY"); stream.WriteLine("{"); stream.WriteLine("\tUINT64 TicksStart;"); stream.WriteLine("\tUINT64 TicksEnd;"); stream.WriteLine("\tINT32 DaylightDelta;"); stream.WriteLine("\tSYSTEMTIME StandardDate;"); stream.WriteLine("\tSYSTEMTIME DaylightDate;"); stream.WriteLine("};"); stream.WriteLine("typedef struct _TIME_ZONE_RULE_ENTRY TIME_ZONE_RULE_ENTRY;"); stream.WriteLine(); stream.WriteLine("struct _TIME_ZONE_ENTRY"); stream.WriteLine("{"); stream.WriteLine("\tconst char* Id;"); stream.WriteLine("\tINT32 Bias;"); stream.WriteLine("\tBOOL SupportsDST;"); stream.WriteLine("\tconst char* DisplayName;"); stream.WriteLine("\tconst char* StandardName;"); stream.WriteLine("\tconst char* DaylightName;"); stream.WriteLine("\tTIME_ZONE_RULE_ENTRY* RuleTable;"); stream.WriteLine("\tUINT32 RuleTableCount;"); stream.WriteLine("};"); stream.WriteLine("typedef struct _TIME_ZONE_ENTRY TIME_ZONE_ENTRY;"); stream.WriteLine(); index = 0; foreach (TimeZoneInfo timeZone in timeZones) { rules = timeZone.GetAdjustmentRules(); if ((!timeZone.SupportsDaylightSavingTime) || (rules.Length < 1)) { index++; continue; } stream.WriteLine("static const TIME_ZONE_RULE_ENTRY TimeZoneRuleTable_{0}[] =", index); stream.WriteLine("{"); i = 0; foreach (TimeZoneInfo.AdjustmentRule rule in rules) { DateTime time; TIME_ZONE_RULE_ENTRY tzr; TimeZoneInfo.TransitionTime transition; tzr.TicksStart = rule.DateEnd.ToUniversalTime().Ticks; tzr.TicksEnd = rule.DateStart.ToUniversalTime().Ticks; tzr.DaylightDelta = (Int32)rule.DaylightDelta.TotalMinutes; transition = rule.DaylightTransitionEnd; time = transition.TimeOfDay; tzr.StandardDate.wYear = (UInt16)0; tzr.StandardDate.wMonth = (UInt16)transition.Month; tzr.StandardDate.wDayOfWeek = (UInt16)transition.DayOfWeek; tzr.StandardDate.wDay = (UInt16)transition.Week; tzr.StandardDate.wHour = (UInt16)time.Hour; tzr.StandardDate.wMinute = (UInt16)time.Minute; tzr.StandardDate.wSecond = (UInt16)time.Second; tzr.StandardDate.wMilliseconds = (UInt16)time.Millisecond; transition = rule.DaylightTransitionStart; time = transition.TimeOfDay; tzr.DaylightDate.wYear = (UInt16)0; tzr.DaylightDate.wMonth = (UInt16)transition.Month; tzr.DaylightDate.wDayOfWeek = (UInt16)transition.DayOfWeek; tzr.DaylightDate.wDay = (UInt16)transition.Week; tzr.DaylightDate.wHour = (UInt16)time.Hour; tzr.DaylightDate.wMinute = (UInt16)time.Minute; tzr.DaylightDate.wSecond = (UInt16)time.Second; tzr.DaylightDate.wMilliseconds = (UInt16)time.Millisecond; stream.Write("\t{"); stream.Write(" {0}ULL, {1}ULL, {2},", tzr.TicksStart, tzr.TicksEnd, tzr.DaylightDelta); stream.Write(" { "); stream.Write("{0}, {1}, {2}, {3}, {4}, {5}", tzr.StandardDate.wYear, tzr.StandardDate.wMonth, tzr.StandardDate.wDayOfWeek, tzr.StandardDate.wDay, tzr.StandardDate.wHour, tzr.StandardDate.wMinute, tzr.StandardDate.wSecond, tzr.StandardDate.wMilliseconds); stream.Write(" }, "); stream.Write("{ "); stream.Write("{0}, {1}, {2}, {3}, {4}, {5}", tzr.DaylightDate.wYear, tzr.DaylightDate.wMonth, tzr.DaylightDate.wDayOfWeek, tzr.DaylightDate.wDay, tzr.DaylightDate.wHour, tzr.DaylightDate.wMinute, tzr.DaylightDate.wSecond, tzr.DaylightDate.wMilliseconds); stream.Write(" },"); if (++i < rules.Length) stream.WriteLine(" },"); else stream.WriteLine(" }"); } stream.WriteLine("};"); stream.WriteLine(); index++; } index = 0; stream.WriteLine("static const TIME_ZONE_ENTRY TimeZoneTable[] ="); stream.WriteLine("{"); foreach (TimeZoneInfo timeZone in timeZones) { TIME_ZONE_ENTRY tz; TimeSpan offset = timeZone.BaseUtcOffset; rules = timeZone.GetAdjustmentRules(); tz.Id = timeZone.Id; tz.Bias = -(Int32)offset.TotalMinutes; tz.SupportsDST = timeZone.SupportsDaylightSavingTime; tz.DisplayName = timeZone.DisplayName; tz.StandardName = timeZone.StandardName; tz.DaylightName = timeZone.DaylightName; if ((!tz.SupportsDST) || (rules.Length < 1)) { tz.RuleTableCount = 0; tz.RuleTable = "NULL"; } else { tz.RuleTableCount = (UInt32)rules.Length; tz.RuleTable = "&TimeZoneRuleTable_" + index; tz.RuleTable = "(TIME_ZONE_RULE_ENTRY*) &TimeZoneRuleTable_" + index; } stream.WriteLine("\t{"); stream.WriteLine("\t\t\"{0}\", {1}, {2}, \"{3}\",", tz.Id, tz.Bias, tz.SupportsDST ? "TRUE" : "FALSE", tz.DisplayName); stream.WriteLine("\t\t\"{0}\", \"{1}\",", tz.StandardName, tz.DaylightName); stream.WriteLine("\t\t{0}, {1}", tz.RuleTable, tz.RuleTableCount); index++; if ((int)index < timeZones.Count) stream.WriteLine("\t},"); else stream.WriteLine("\t}"); } stream.WriteLine("};"); stream.WriteLine(); stream.Close(); } } }
// Date.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System.Runtime.CompilerServices; namespace System { /// <summary> /// Equivalent to the Date type in Javascript. /// </summary> [ScriptIgnoreNamespace] [ScriptImport] public sealed class Date { /// <summary> /// Creates a new instance of Date initialized from the current time. /// </summary> public Date() { } /// <summary> /// Creates a new instance of Date initialized from the specified number of milliseconds. /// </summary> /// <param name="milliseconds">Milliseconds since January 1st, 1970.</param> public Date(int milliseconds) { } /// <summary> /// Creates a new instance of Date initialized from parsing the specified date. /// </summary> /// <param name="date"></param> public Date(string date) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (0 through 11)</param> /// <param name="date">The day of the month (1 through # of days in the specified month)</param> public Date(int year, int month, int date) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (0 through 11)</param> /// <param name="date">The day of the month (1 through # of days in the specified month)</param> /// <param name="hours">The hours (0 through 23)</param> public Date(int year, int month, int date, int hours) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (0 through 11)</param> /// <param name="date">The day of the month (1 through # of days in the specified month)</param> /// <param name="hours">The hours (0 through 23)</param> /// <param name="minutes">The minutes (0 through 59)</param> public Date(int year, int month, int date, int hours, int minutes) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (0 through 11)</param> /// <param name="date">The day of the month (1 through # of days in the specified month)</param> /// <param name="hours">The hours (0 through 23)</param> /// <param name="minutes">The minutes (0 through 59)</param> /// <param name="seconds">The seconds (0 through 59)</param> public Date(int year, int month, int date, int hours, int minutes, int seconds) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (0 through 11)</param> /// <param name="date">The day of the month (1 through # of days in the specified month)</param> /// <param name="hours">The hours (0 through 23)</param> /// <param name="minutes">The minutes (0 through 59)</param> /// <param name="seconds">The seconds (0 through 59)</param> /// <param name="milliseconds">The milliseconds (0 through 999)</param> public Date(int year, int month, int date, int hours, int minutes, int seconds, int milliseconds) { } /// <summary> /// Returns the current date and time. /// </summary> [ScriptField] [ScriptAlias("ss.now()")] public static Date Now { get { return null; } } /// <summary> /// Returns the current date with the time part set to 00:00:00. /// </summary> [ScriptField] [ScriptAlias("ss.today()")] public static Date Today { get { return null; } } public int GetDate() { return 0; } public int GetDay() { return 0; } public int GetFullYear() { return 0; } public int GetHours() { return 0; } public int GetMilliseconds() { return 0; } public int GetMinutes() { return 0; } public int GetMonth() { return 0; } public int GetSeconds() { return 0; } public int GetTime() { return 0; } public int GetTimezoneOffset() { return 0; } public int GetUTCDate() { return 0; } public int GetUTCDay() { return 0; } public int GetUTCFullYear() { return 0; } public int GetUTCHours() { return 0; } public int GetUTCMilliseconds() { return 0; } public int GetUTCMinutes() { return 0; } public int GetUTCMonth() { return 0; } public int GetUTCSeconds() { return 0; } [ScriptAlias("ss.date")] public static Date Parse(string value) { return null; } public void SetDate(int date) { } public void SetFullYear(int year) { } public void SetFullYear(int year, int month) { } public void SetFullYear(int year, int month, int day) { } public void SetHours(int hours) { } public void SetMilliseconds(int milliseconds) { } public void SetMinutes(int minutes) { } public void SetMonth(int month) { } public void SetSeconds(int seconds) { } public void SetTime(int milliseconds) { } public void SetUTCDate(int date) { } public void SetUTCFullYear(int year) { } public void SetUTCHours(int hours) { } public void SetUTCMilliseconds(int milliseconds) { } public void SetUTCMinutes(int minutes) { } public void SetUTCMonth(int month) { } public void SetUTCSeconds(int seconds) { } public void SetYear(int year) { } public string ToDateString() { return null; } public string ToISOString() { return null; } public string ToLocaleDateString() { return null; } public string ToLocaleTimeString() { return null; } public string ToTimeString() { return null; } public string ToUTCString() { return null; } [ScriptName(PreserveCase = true)] public static int UTC(int year, int month, int day) { return 0; } [ScriptName(PreserveCase = true)] public static int UTC(int year, int month, int day, int hours) { return 0; } [ScriptName(PreserveCase = true)] public static int UTC(int year, int month, int day, int hours, int minutes) { return 0; } [ScriptName(PreserveCase = true)] public static int UTC(int year, int month, int day, int hours, int minutes, int seconds) { return 0; } [ScriptName(PreserveCase = true)] public static int UTC(int year, int month, int day, int hours, int minutes, int seconds, int milliseconds) { return 0; } // NOTE: There is no + operator since in JavaScript that returns the // concatenation of the date strings, which is pretty much useless. /// <summary> /// Returns the difference in milliseconds between two dates. /// </summary> public static int operator -(Date a, Date b) { return 0; } /// <summary> /// Compares two dates /// </summary> public static bool operator ==(Date a, Date b) { return false; } /// <summary> /// Compares two dates /// </summary> public static bool operator !=(Date a, Date b) { return false; } /// <summary> /// Compares two dates /// </summary> public static bool operator <(Date a, Date b) { return false; } /// <summary> /// Compares two dates /// </summary> public static bool operator >(Date a, Date b) { return false; } /// <summary> /// Compares two dates /// </summary> public static bool operator <=(Date a, Date b) { return false; } /// <summary> /// Compares two dates /// </summary> public static bool operator >=(Date a, Date b) { return false; } } }
using Signum.Engine.Authorization; using Signum.Engine.Processes; using Signum.Engine.Scheduler; using Signum.Entities.Basics; using Signum.Entities.Processes; using Signum.Entities.Reflection; using Signum.Entities.Scheduler; using Signum.Entities.Workflow; namespace Signum.Engine.Workflow; public static class WorkflowEventTaskLogic { [AutoExpressionField] public static IQueryable<WorkflowEventTaskConditionResultEntity> ConditionResults(this WorkflowEventTaskEntity e) => As.Expression(() => Database.Query<WorkflowEventTaskConditionResultEntity>().Where(a => a.WorkflowEventTask.Is(e))); [AutoExpressionField] public static ScheduledTaskEntity? ScheduledTask(this WorkflowEventEntity e) => As.Expression(() => Database.Query<ScheduledTaskEntity>().SingleOrDefault(s => ((WorkflowEventTaskEntity)s.Task).Event.Is(e))); [AutoExpressionField] public static WorkflowEventTaskEntity? WorkflowEventTask(this WorkflowEventEntity e) => As.Expression(() => Database.Query<WorkflowEventTaskEntity>().SingleOrDefault(et => et.Event.Is(e))); public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { var ib = sb.Schema.Settings.FieldAttribute<ImplementedByAttribute>(PropertyRoute.Construct((ScheduledTaskEntity e) => e.Rule))!; sb.Schema.Settings.FieldAttributes((WorkflowEventTaskModel a) => a.Rule).Replace(new ImplementedByAttribute(ib.ImplementedTypes)); sb.Include<WorkflowEventTaskEntity>() .WithDelete(WorkflowEventTaskOperation.Delete) .WithQuery(() => e => new { Entity = e, e.Id, e.Workflow, e.TriggeredOn, e.Event, }); new Graph<WorkflowEventTaskEntity>.Execute(WorkflowEventTaskOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (e.TriggeredOn == TriggeredOn.Always) e.Condition = null; e.Save(); }, }.Register(); sb.Schema.EntityEvents<WorkflowEventTaskEntity>().PreUnsafeDelete += tasks => { tasks.SelectMany(a => a.ConditionResults()).UnsafeDelete(); return null; }; ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs; sb.Include<WorkflowEventTaskConditionResultEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.CreationDate, e.WorkflowEventTask, e.Result, }); SchedulerLogic.ExecuteTask.Register((WorkflowEventTaskEntity wet, ScheduledTaskContext ctx) => ExecuteTask(wet)); sb.AddIndex((WorkflowEventTaskConditionResultEntity e) => e.CreationDate); WorkflowEventTaskModel.GetModel = (@event) => { if (!@event.Type.IsScheduledStart()) return null; var schedule = @event.ScheduledTask(); var task = (schedule?.Task as WorkflowEventTaskEntity); var triggeredOn = task?.TriggeredOn ?? TriggeredOn.Always; return new WorkflowEventTaskModel { Suspended = schedule?.Suspended ?? true, Rule = schedule?.Rule, TriggeredOn = triggeredOn, Condition = triggeredOn == TriggeredOn.Always ? null : new WorkflowEventTaskConditionEval() { Script = task!.Condition!.Script }, Action = new WorkflowEventTaskActionEval() { Script = task?.Action!.Script ?? "" } }; }; WorkflowEventTaskModel.ApplyModel = (@event, model) => { var schedule = @event.IsNew ? null : @event.ScheduledTask(); if (!@event.Type.IsScheduledStart()) { if (schedule != null) DeleteWorkflowEventScheduledTask(schedule); return; } if (model == null) throw new ArgumentNullException(nameof(model)); if (schedule != null) { var task = (WorkflowEventTaskEntity)schedule.Task; schedule.Suspended = model.Suspended; if (!object.ReferenceEquals(schedule.Rule, model.Rule)) { schedule.Rule = null!; schedule.Rule = model.Rule!; } task.TriggeredOn = model.TriggeredOn; if (model.TriggeredOn == TriggeredOn.Always) task.Condition = null; else { if (task.Condition == null) task.Condition = new WorkflowEventTaskConditionEval(); task.Condition.Script = model.Condition!.Script; }; task.Action!.Script = model.Action!.Script; if (GraphExplorer.IsGraphModified(schedule)) { task.Execute(WorkflowEventTaskOperation.Save); schedule.Execute(ScheduledTaskOperation.Save); } } else { var newTask = new WorkflowEventTaskEntity() { Workflow = @event.Lane.Pool.Workflow.ToLite(), Event = @event.ToLite(), TriggeredOn = model.TriggeredOn, Condition = model.TriggeredOn == TriggeredOn.Always ? null : new WorkflowEventTaskConditionEval() { Script = model.Condition!.Script }, Action = new WorkflowEventTaskActionEval() { Script = model.Action!.Script }, }.Execute(WorkflowEventTaskOperation.Save); schedule = new ScheduledTaskEntity { Suspended = model.Suspended, Rule = model.Rule!, Task = newTask, User = AuthLogic.SystemUser!.ToLite(), }.Execute(ScheduledTaskOperation.Save); } }; } } internal static void CloneScheduledTasks(WorkflowEventEntity oldEvent, WorkflowEventEntity newEvent) { var task = Database.Query<WorkflowEventTaskEntity>().SingleOrDefault(a => a.Event.Is(oldEvent)); if (task == null) return; var st = Database.Query<ScheduledTaskEntity>().SingleOrDefaultEx(a => a.Task == task); if (st == null) return; var newTask = new WorkflowEventTaskEntity() { Workflow = newEvent.Lane.Pool.Workflow.ToLite(), fullWorkflow = newEvent.Lane.Pool.Workflow, Event = newEvent.ToLite(), TriggeredOn = task.TriggeredOn, Condition = task.Condition != null ? new WorkflowEventTaskConditionEval() { Script = task.Condition.Script } : null, Action = new WorkflowEventTaskActionEval() { Script = task.Action!.Script }, }.Execute(WorkflowEventTaskOperation.Save); new ScheduledTaskEntity() { Suspended = st.Suspended, Rule = st.Rule.Clone(), Task = newTask, User = AuthLogic.SystemUser!.ToLite(), }.Execute(ScheduledTaskOperation.Save); } public static void DeleteWorkflowEventScheduledTask(ScheduledTaskEntity schedule) { var workflowEventTask = ((WorkflowEventTaskEntity)schedule.Task); schedule.Delete(ScheduledTaskOperation.Delete); workflowEventTask.Delete(WorkflowEventTaskOperation.Delete); } public static void ExceptionLogic_DeleteLogs(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token) { var dateLimit = parameters.GetDateLimitDelete(typeof(WorkflowEventTaskConditionResultEntity).ToTypeEntity()); if (dateLimit != null) Database.Query<WorkflowEventTaskConditionResultEntity>() .Where(a => a.CreationDate < dateLimit.Value) .UnsafeDeleteChunksLog(parameters, sb, token); } public static Lite<IEntity>? ExecuteTask(WorkflowEventTaskEntity wet) { var workflow = wet.GetWorkflow(); if (workflow.HasExpired()) throw new InvalidOperationException(WorkflowMessage.Workflow0HasExpiredOn1.NiceToString(workflow, workflow.ExpirationDate!.Value.ToString())); using (var tr = new Transaction()) { if (!EvaluateCondition(wet)) return tr.Commit<Lite<IEntity>?>(null); var mainEntities = wet.Action!.Algorithm.EvaluateUntyped(); var caseActivities = new List<Lite<CaseActivityEntity>>(); foreach (var me in mainEntities) { var @case = wet.ConstructFrom(CaseActivityOperation.CreateCaseFromWorkflowEventTask, me); caseActivities.AddRange(@case.CaseActivities().Select(a => a.ToLite()).ToList()); caseActivities.AddRange(@case.SubCases().SelectMany(sc => sc.CaseActivities()).Select(a => a.ToLite()).ToList()); } var result = caseActivities.Count == 0 ? null : caseActivities.Count == 1 ? (Lite<IEntity>)caseActivities.SingleEx() : new PackageEntity { Name = wet.Event.ToString() + " " + Clock.Now.ToString()} .CreateLines(caseActivities).ToLite(); return tr.Commit(result); } } private static bool EvaluateCondition(WorkflowEventTaskEntity task) { if (task.TriggeredOn == TriggeredOn.Always) return true; var result = task.Condition!.Algorithm.Evaluate(); if (task.TriggeredOn == TriggeredOn.ConditionIsTrue) return result; var last = task.ConditionResults().OrderByDescending(a => a.CreationDate).FirstOrDefault(); new WorkflowEventTaskConditionResultEntity { WorkflowEventTask = task.ToLite(), Result = result }.Save(); return result && (last == null || !last.Result); } }
// Inftree.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-October-28 12:43:54> // // ------------------------------------------------------------------ // // This module defines classes used in decompression. This code is derived // from the jzlib implementation of zlib. In keeping with the license for jzlib, // the copyright to that code is below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- #nullable disable using System; namespace SharpCompress.Compressors.Deflate { internal sealed class InfTree { private const int MANY = 1440; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_NEED_DICT = 2; private const int Z_ERRNO = -1; private const int Z_STREAM_ERROR = -2; private const int Z_DATA_ERROR = -3; private const int Z_MEM_ERROR = -4; private const int Z_BUF_ERROR = -5; private const int Z_VERSION_ERROR = -6; internal const int fixed_bl = 9; internal const int fixed_bd = 5; internal const int BMAX = 15; // maximum bit length of any code //UPGRADE_NOTE: Final was removed from the declaration of 'fixed_tl'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] fixed_tl = { 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0 , 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50 , 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2 , 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26 , 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8 , 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0 , 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0 , 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0 , 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0 , 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15 , 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8 , 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0 , 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116 , 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8 , 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0 , 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42 , 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8 , 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8 , 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8 , 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0 , 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8 , 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0 , 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143 , 0, 8, 79, 0, 9, 255 }; //UPGRADE_NOTE: Final was removed from the declaration of 'fixed_td'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] fixed_td = { 80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33 , 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80 , 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537 , 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92 , 5 , 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 }; // Tables for deflate from PKZIP's appnote.txt. //UPGRADE_NOTE: Final was removed from the declaration of 'cplens'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] cplens = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51 , 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; // see note #13 above about 258 //UPGRADE_NOTE: Final was removed from the declaration of 'cplext'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] cplext = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4 , 4 , 4, 5, 5, 5, 5, 0, 112, 112 }; //UPGRADE_NOTE: Final was removed from the declaration of 'cpdist'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] cpdist = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385 , 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; //UPGRADE_NOTE: Final was removed from the declaration of 'cpdext'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" internal static readonly int[] cpdext = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9 , 10, 10, 11, 11, 12, 12, 13, 13 }; // If BMAX needs to be larger than 16, then h and x[] should be uLong. internal int[] c; // bit length count table internal int[] hn; // hufts used in space internal int[] r; // table entry for structure assignment internal int[] u; // table stack internal int[] v; // work area for huft_build internal int[] x; // bit offsets, then code stack private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[] t, int[] m, int[] hp, int[] hn, int[] v) { // Given a list of code lengths and a maximum table size, make a set of // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR // if the given code set is incomplete (the tables are still built in this // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of // lengths), or Z_MEM_ERROR if not enough memory. int a; // counter for codes of length k int f; // i repeats in table every f entries int g; // maximum code length int h; // table level int i; // counter, current code int j; // counter int k; // number of bits in current code int l; // bits per table (returned in m) int mask; // (1 << w) - 1, to avoid cc -O bug on HP int p; // pointer into c[], b[], or v[] int q; // points to current table int w; // bits before this table == (l * h) int xp; // pointer into x int y; // number of dummy codes added int z; // number of entries in current table // Generate counts for each bit length p = 0; i = n; do { c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX } while (i != 0); if (c[0] == n) { // null input--all zero length codes t[0] = -1; m[0] = 0; return Z_OK; } // Find minimum and maximum length, bound *m by those l = m[0]; for (j = 1; j <= BMAX; j++) { if (c[j] != 0) { break; } } k = j; // minimum code length if (l < j) { l = j; } for (i = BMAX; i != 0; i--) { if (c[i] != 0) { break; } } g = i; // maximum code length if (l > i) { l = i; } m[0] = l; // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; j++, y <<= 1) { if ((y -= c[j]) < 0) { return Z_DATA_ERROR; } } if ((y -= c[i]) < 0) { return Z_DATA_ERROR; } c[i] += y; // Generate starting offsets into the value table for each length x[1] = j = 0; p = 1; xp = 2; while (--i != 0) { // note that i == g from above x[xp] = (j += c[p]); xp++; p++; } // Make a table of values in order of bit lengths i = 0; p = 0; do { if ((j = b[bindex + p]) != 0) { v[x[j]++] = i; } p++; } while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries x[0] = i = 0; // first Huffman code is zero p = 0; // grab values in bit order h = -1; // no tables yet--level -1 w = -l; // bits decoded == (l * h) u[0] = 0; // just to keep compilers happy q = 0; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; k++) { a = c[k]; while (a-- != 0) { // here i is the Huffman code of length k bits for value *p // make tables up to required level while (k > w + l) { h++; w += l; // previous table always l bits // compute minimum size table less than or equal to l bits z = g - w; z = (z > l) ? l : z; // table size upper limit if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table // too few codes for k-w bit table f -= (a + 1); // deduct codes from patterns left xp = k; if (j < z) { while (++j < z) { // try smaller tables up to z bits if ((f <<= 1) <= c[++xp]) { break; // enough codes to use up j bits } f -= c[xp]; // else deduct codes from patterns } } } z = 1 << j; // table entries for j-bit table // allocate new table if (hn[0] + z > MANY) { // (note: doesn't matter for fixed) return Z_DATA_ERROR; // overflow of MANY } u[h] = q = hn[0]; // DEBUG hn[0] += z; // connect to last table, if there is one if (h != 0) { x[h] = i; // save pattern for backing up r[0] = (sbyte)j; // bits in this table r[1] = (sbyte)l; // bits to dump before this table j = SharedUtils.URShift(i, (w - l)); r[2] = (q - u[h - 1] - j); // offset to this table Array.Copy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect to last table } else { t[0] = q; // first table is returned result } } // set up table entry in r r[1] = (sbyte)(k - w); if (p >= n) { r[0] = 128 + 64; // out of values--invalid code } else if (v[p] < s) { r[0] = (sbyte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block r[2] = v[p++]; // simple code is just the value } else { r[0] = (sbyte)(e[v[p] - s] + 16 + 64); // non-simple--look up in lists r[2] = d[v[p++] - s]; } // fill code-like entries with r f = 1 << (k - w); for (j = SharedUtils.URShift(i, w); j < z; j += f) { Array.Copy(r, 0, hp, (q + j) * 3, 3); } // backwards increment the k-bit code i for (j = 1 << (k - 1); (i & j) != 0; j = SharedUtils.URShift(j, 1)) { i ^= j; } i ^= j; // backup over finished tables mask = (1 << w) - 1; // needed on HP, cc -O bug while ((i & mask) != x[h]) { h--; // don't need to update q w -= l; mask = (1 << w) - 1; } } } // Return Z_BUF_ERROR if we were given an incomplete table return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; } internal int inflate_trees_bits(int[] c, int[] bb, int[] tb, int[] hp, ZlibCodec z) { int result; initWorkArea(19); hn[0] = 0; result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v); if (result == Z_DATA_ERROR) { z.Message = "oversubscribed dynamic bit lengths tree"; } else if (result == Z_BUF_ERROR || bb[0] == 0) { z.Message = "incomplete dynamic bit lengths tree"; result = Z_DATA_ERROR; } return result; } internal int inflate_trees_dynamic(int nl, int nd, int[] c, int[] bl, int[] bd, int[] tl, int[] td, int[] hp, ZlibCodec z) { int result; // build literal/length tree initWorkArea(288); hn[0] = 0; result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v); if (result != Z_OK || bl[0] == 0) { if (result == Z_DATA_ERROR) { z.Message = "oversubscribed literal/length tree"; } else if (result != Z_MEM_ERROR) { z.Message = "incomplete literal/length tree"; result = Z_DATA_ERROR; } return result; } // build distance tree initWorkArea(288); result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v); if (result != Z_OK || (bd[0] == 0 && nl > 257)) { if (result == Z_DATA_ERROR) { z.Message = "oversubscribed distance tree"; } else if (result == Z_BUF_ERROR) { z.Message = "incomplete distance tree"; result = Z_DATA_ERROR; } else if (result != Z_MEM_ERROR) { z.Message = "empty distance tree with lengths"; result = Z_DATA_ERROR; } return result; } return Z_OK; } internal static int inflate_trees_fixed(int[] bl, int[] bd, int[][] tl, int[][] td, ZlibCodec z) { bl[0] = fixed_bl; bd[0] = fixed_bd; tl[0] = fixed_tl; td[0] = fixed_td; return Z_OK; } private void initWorkArea(int vsize) { if (hn is null) { hn = new int[1]; v = new int[vsize]; c = new int[BMAX + 1]; r = new int[3]; u = new int[BMAX]; x = new int[BMAX + 1]; } else { if (v.Length < vsize) { v = new int[vsize]; } Array.Clear(v, 0, vsize); Array.Clear(c, 0, BMAX + 1); r[0] = 0; r[1] = 0; r[2] = 0; // for(int i=0; i<BMAX; i++){u[i]=0;} //Array.Copy(c, 0, u, 0, BMAX); Array.Clear(u, 0, BMAX); // for(int i=0; i<BMAX+1; i++){x[i]=0;} //Array.Copy(c, 0, x, 0, BMAX + 1); Array.Clear(x, 0, BMAX + 1); } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using QuantConnect.Data.Market; using QuantConnect.Securities; namespace QuantConnect.Orders.Fills { /// <summary> /// Represents the default fill model used to simulate order fills /// </summary> public class ImmediateFillModel : IFillModel { /// <summary> /// Default market fill model for the base security class. Fills at the last traded price. /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="SecurityTransactionModel.StopMarketFill"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> public virtual OrderEvent MarketFill(Security asset, MarketOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; //Order [fill]price for a market order model is the current security price fill.FillPrice = asset.Price; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default stop fill model implementation in base class security. (Stop Market Order Type) /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="MarketFill(Security, MarketOrder)"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> public virtual OrderEvent StopMarketFill(Security asset, StopMarketOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: decimal minimumPrice; decimal maximumPrice; DataMinMaxPrices(asset, out minimumPrice, out maximumPrice); //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Check if the Stop Order was filled: opposite to a limit order switch (order.Direction) { case OrderDirection.Sell: //-> 1.1 Sell Stop: If Price below setpoint, Sell: if (minimumPrice < order.StopPrice) { fill.Status = OrderStatus.Filled; // Assuming worse case scenario fill - fill at lowest of the stop & asset price. fill.FillPrice = Math.Min(order.StopPrice, asset.Price - slip); } break; case OrderDirection.Buy: //-> 1.2 Buy Stop: If Price Above Setpoint, Buy: if (maximumPrice > order.StopPrice) { fill.Status = OrderStatus.Filled; // Assuming worse case scenario fill - fill at highest of the stop & asset price. fill.FillPrice = Math.Max(order.StopPrice, asset.Price + slip); } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default stop limit fill model implementation in base class security. (Stop Limit Order Type) /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> /// <remarks> /// There is no good way to model limit orders with OHLC because we never know whether the market has /// gapped past our fill price. We have to make the assumption of a fluid, high volume market. /// /// Stop limit orders we also can't be sure of the order of the H - L values for the limit fill. The assumption /// was made the limit fill will be done with closing price of the bar after the stop has been triggered.. /// </remarks> public virtual OrderEvent StopLimitFill(Security asset, StopLimitOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: decimal minimumPrice; decimal maximumPrice; DataMinMaxPrices(asset, out minimumPrice, out maximumPrice); //Check if the Stop Order was filled: opposite to a limit order switch (order.Direction) { case OrderDirection.Buy: //-> 1.2 Buy Stop: If Price Above Setpoint, Buy: if (maximumPrice > order.StopPrice || order.StopTriggered) { order.StopTriggered = true; // Fill the limit order, using closing price of bar: // Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered. if (asset.Price < order.LimitPrice) { fill.Status = OrderStatus.Filled; fill.FillPrice = order.LimitPrice; } } break; case OrderDirection.Sell: //-> 1.1 Sell Stop: If Price below setpoint, Sell: if (minimumPrice < order.StopPrice || order.StopTriggered) { order.StopTriggered = true; // Fill the limit order, using minimum price of the bar // Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered. if (asset.Price > order.LimitPrice) { fill.Status = OrderStatus.Filled; fill.FillPrice = order.LimitPrice; // Fill at limit price not asset price. } } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default limit order fill model in the base security class. /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/> /// <seealso cref="MarketFill(Security, MarketOrder)"/> public virtual OrderEvent LimitFill(Security asset, LimitOrder order) { //Initialise; var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: decimal minimumPrice; decimal maximumPrice; DataMinMaxPrices(asset, out minimumPrice, out maximumPrice); //-> Valid Live/Model Order: switch (order.Direction) { case OrderDirection.Buy: //Buy limit seeks lowest price if (minimumPrice < order.LimitPrice) { //Set order fill: fill.Status = OrderStatus.Filled; // fill at the worse price this bar or the limit price, this allows far out of the money limits // to be executed properly fill.FillPrice = Math.Min(maximumPrice, order.LimitPrice); } break; case OrderDirection.Sell: //Sell limit seeks highest price possible if (maximumPrice > order.LimitPrice) { fill.Status = OrderStatus.Filled; // fill at the worse price this bar or the limit price, this allows far out of the money limits // to be executed properly fill.FillPrice = Math.Max(minimumPrice, order.LimitPrice); } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Market on Open Fill Model. Return an order event with the fill details /// </summary> /// <param name="asset">Asset we're trading with this order</param> /// <param name="order">Order to be filled</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> public OrderEvent MarketOnOpenFill(Security asset, MarketOnOpenOrder order) { var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; // MOO should never fill on the same bar or on stale data // Imagine the case where we have a thinly traded equity, ASUR, and another liquid // equity, say SPY, SPY gets data every minute but ASUR, if not on fill forward, maybe // have large gaps, in which case the currentBar.EndTime will be in the past // ASUR | | | [order] | | | | | | | // SPY | | | | | | | | | | | | | | | | | | | | var currentBar = asset.GetLastData(); var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone); if (currentBar == null || localOrderTime >= currentBar.EndTime) return fill; // if the MOO was submitted during market the previous day, wait for a day to turn over if (asset.Exchange.DateTimeIsOpen(localOrderTime) && localOrderTime.Date == asset.LocalTime.Date) { return fill; } // wait until market open // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; fill.FillPrice = asset.Open; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Market on Close Fill Model. Return an order event with the fill details /// </summary> /// <param name="asset">Asset we're trading with this order</param> /// <param name="order">Order to be filled</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order) { var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone); var nextMarketClose = asset.Exchange.Hours.GetNextMarketClose(localOrderTime, false); // wait until market closes after the order time if (asset.LocalTime < nextMarketClose) { return fill; } fill.FillPrice = asset.Close; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Get the minimum and maximum price for this security in the last bar: /// </summary> /// <param name="asset">Security asset we're checking</param> /// <param name="minimumPrice">Minimum price in the last data bar</param> /// <param name="maximumPrice">Minimum price in the last data bar</param> public virtual void DataMinMaxPrices(Security asset, out decimal minimumPrice, out decimal maximumPrice) { var marketData = asset.GetLastData(); var tradeBar = marketData as TradeBar; if (tradeBar != null) { minimumPrice = tradeBar.Low; maximumPrice = tradeBar.High; } else { minimumPrice = marketData.Value; maximumPrice = marketData.Value; } } /// <summary> /// Determines if the exchange is open using the current time of the asset /// </summary> private static bool IsExchangeOpen(Security asset) { if (!asset.Exchange.DateTimeIsOpen(asset.LocalTime)) { // if we're not open at the current time exactly, check the bar size, this handle large sized bars (hours/days) var currentBar = asset.GetLastData(); if (asset.LocalTime.Date != currentBar.EndTime.Date || !asset.Exchange.IsOpenDuringBar(currentBar.Time, currentBar.EndTime, false)) { return false; } } return true; } } }
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Text; using Excel.Core.BinaryFormat; namespace Excel { /// <summary> /// ExcelDataReader Class /// </summary> public class ExcelDataReader : IDisposable { #region Members private Stream m_file; private XlsHeader m_hdr; private List<XlsWorksheet> m_sheets; private XlsBiffStream m_stream; private DataSet m_workbookData; private XlsWorkbookGlobals m_globals; private ushort m_version; private bool m_PromoteToColumns; private bool m_ConvertOADate; private bool m_IsProtected; private Encoding m_encoding; private readonly Encoding m_Default_Encoding = Encoding.UTF8; private const string WORKBOOK = "Workbook"; private const string BOOK = "Book"; private const string COLUMN_DEFAULT_NAME = "Column"; private bool disposed; #endregion #region Properties /// <summary> /// DataSet with workbook data, Tables represent Sheets /// </summary> public DataSet WorkbookData { get { return m_workbookData; } } /// <summary> /// Gets a value indicating whether the Xls file is protected. /// </summary> /// <value> /// <c>true</c> if this Xls file is proteted; otherwise, <c>false</c>. /// </value> public bool IsProtected { get { return m_IsProtected; } } #endregion #region Constructor and IDisposable Members /// <summary> /// Initializes a new instance of the <see cref="ExcelDataReader"/> class. /// </summary> /// <param name="fileStream">Xls Stream</param> public ExcelDataReader(Stream fileStream) : this(fileStream, false, true) { } /// <summary> /// Initializes a new instance of the <see cref="ExcelDataReader"/> class. /// </summary> /// <param name="fileStream">Xls Stream</param> /// <param name="promoteToColumns">if is set to <c>true</c> the first row will be moved in to column names.</param> /// <param name="convertOADate">if is set to <c>true</c> the Date and Time values from the Xls Stream will be mapped as strings in the output DataSet.</param> public ExcelDataReader(Stream fileStream, bool promoteToColumns, bool convertOADate) { m_PromoteToColumns = promoteToColumns; m_encoding = m_Default_Encoding; m_version = 0x0600; m_ConvertOADate = convertOADate; m_sheets = new List<XlsWorksheet>(); ParseXlsStream(fileStream); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { m_workbookData.Dispose(); m_sheets.Clear(); } m_workbookData = null; m_sheets = null; m_stream = null; m_globals = null; m_encoding = null; m_hdr = null; disposed = true; } } ~ExcelDataReader() { Dispose(false); } #endregion #region Private methods private void ParseXlsStream(Stream fileStream) { using (m_file = fileStream) { m_hdr = XlsHeader.ReadHeader(m_file); XlsRootDirectory dir = new XlsRootDirectory(m_hdr); XlsDirectoryEntry workbookEntry = dir.FindEntry(WORKBOOK) ?? dir.FindEntry(BOOK); if (workbookEntry == null) throw new FileNotFoundException(Errors.ErrorStreamWorkbookNotFound); if (workbookEntry.EntryType != STGTY.STGTY_STREAM) throw new FormatException(Errors.ErrorWorkbookIsNotStream); m_stream = new XlsBiffStream(m_hdr, workbookEntry.StreamFirstSector); ReadWorkbookGlobals(); m_workbookData = new DataSet(); for (int i = 0; i < m_sheets.Count; i++) { if (ReadWorksheet(m_sheets[i])) m_workbookData.Tables.Add(m_sheets[i].Data); } m_globals.SST = null; m_globals = null; m_sheets = null; m_stream = null; m_hdr = null; GC.Collect(); GC.SuppressFinalize(this); } } private void ReadWorkbookGlobals() { m_globals = new XlsWorkbookGlobals(); m_stream.Seek(0, SeekOrigin.Begin); XlsBiffRecord rec = m_stream.Read(); XlsBiffBOF bof = rec as XlsBiffBOF; if (bof == null || bof.Type != BIFFTYPE.WorkbookGlobals) throw new ArgumentException(Errors.ErrorWorkbookGlobalsInvalidData); m_version = bof.Version; bool sst = false; while (null != (rec = m_stream.Read())) { switch (rec.ID) { case BIFFRECORDTYPE.INTERFACEHDR: m_globals.InterfaceHdr = (XlsBiffInterfaceHdr)rec; break; case BIFFRECORDTYPE.BOUNDSHEET: XlsBiffBoundSheet sheet = (XlsBiffBoundSheet)rec; if (sheet.Type != XlsBiffBoundSheet.SheetType.Worksheet) break; sheet.IsV8 = IsV8(); sheet.UseEncoding = m_encoding; m_sheets.Add(new XlsWorksheet(m_globals.Sheets.Count, sheet)); m_globals.Sheets.Add(sheet); break; case BIFFRECORDTYPE.MMS: m_globals.MMS = rec; break; case BIFFRECORDTYPE.COUNTRY: m_globals.Country = rec; break; case BIFFRECORDTYPE.CODEPAGE: m_globals.CodePage = (XlsBiffSimpleValueRecord)rec; try { m_encoding = Encoding.GetEncoding(m_globals.CodePage.Value); } catch { // Warning - Password protection // TODO: Attach to ILog } break; case BIFFRECORDTYPE.FONT: case BIFFRECORDTYPE.FONT_V34: m_globals.Fonts.Add(rec); break; case BIFFRECORDTYPE.FORMAT: case BIFFRECORDTYPE.FORMAT_V23: m_globals.Formats.Add(rec); break; case BIFFRECORDTYPE.XF: case BIFFRECORDTYPE.XF_V4: case BIFFRECORDTYPE.XF_V3: case BIFFRECORDTYPE.XF_V2: m_globals.ExtendedFormats.Add(rec); break; case BIFFRECORDTYPE.SST: m_globals.SST = (XlsBiffSST)rec; sst = true; break; case BIFFRECORDTYPE.CONTINUE: if (!sst) break; XlsBiffContinue contSST = (XlsBiffContinue)rec; m_globals.SST.Append(contSST); break; case BIFFRECORDTYPE.EXTSST: m_globals.ExtSST = rec; sst = false; break; case BIFFRECORDTYPE.PROTECT: case BIFFRECORDTYPE.PASSWORD: case BIFFRECORDTYPE.PROT4REVPASSWORD: m_IsProtected = true; break; case BIFFRECORDTYPE.EOF: if (m_globals.SST != null) m_globals.SST.ReadStrings(); return; default: continue; } } } private bool ReadWorksheet(XlsWorksheet sheet) { m_stream.Seek((int)sheet.DataOffset, SeekOrigin.Begin); XlsBiffBOF bof = m_stream.Read() as XlsBiffBOF; if (bof == null || bof.Type != BIFFTYPE.Worksheet) return false; XlsBiffIndex idx = m_stream.Read() as XlsBiffIndex; if (null == idx) return false; idx.IsV8 = IsV8(); DataTable dt = new DataTable(sheet.Name); XlsBiffRecord trec; XlsBiffDimensions dims = null; do { trec = m_stream.Read(); if (trec.ID == BIFFRECORDTYPE.DIMENSIONS) { dims = (XlsBiffDimensions)trec; break; } } while (trec != null && trec.ID != BIFFRECORDTYPE.ROW); int maxCol = 256; if (dims != null) { dims.IsV8 = IsV8(); maxCol = dims.LastColumn - 1; sheet.Dimensions = dims; } InitializeColumns(ref dt, maxCol); sheet.Data = dt; uint maxRow = idx.LastExistingRow; if (idx.LastExistingRow <= idx.FirstExistingRow) { return true; } dt.BeginLoadData(); for (int i = 0; i < maxRow; i++) { dt.Rows.Add(dt.NewRow()); } uint[] dbCellAddrs = idx.DbCellAddresses; for (int i = 0; i < dbCellAddrs.Length; i++) { XlsBiffDbCell dbCell = (XlsBiffDbCell)m_stream.ReadAt((int)dbCellAddrs[i]); XlsBiffRow row = null; int offs = dbCell.RowAddress; do { row = m_stream.ReadAt(offs) as XlsBiffRow; if (row == null) break; offs += row.Size; } while (null != row); while (true) { XlsBiffRecord rec = m_stream.ReadAt(offs); offs += rec.Size; if (rec is XlsBiffDbCell) break; if (rec is XlsBiffEOF) break; XlsBiffBlankCell cell = rec as XlsBiffBlankCell; if (cell == null) continue; if (cell.ColumnIndex >= maxCol) continue; if (cell.RowIndex > maxRow) continue; string _sValue; double _dValue; switch (cell.ID) { case BIFFRECORDTYPE.INTEGER: case BIFFRECORDTYPE.INTEGER_OLD: dt.Rows[cell.RowIndex][cell.ColumnIndex] = ((XlsBiffIntegerCell)cell).Value.ToString(); break; case BIFFRECORDTYPE.NUMBER: case BIFFRECORDTYPE.NUMBER_OLD: _dValue = ((XlsBiffNumberCell)cell).Value; if ((_sValue = TryConvertOADate(_dValue, cell.XFormat)) != null) { dt.Rows[cell.RowIndex][cell.ColumnIndex] = _sValue; } else { dt.Rows[cell.RowIndex][cell.ColumnIndex] = _dValue; } break; case BIFFRECORDTYPE.LABEL: case BIFFRECORDTYPE.LABEL_OLD: case BIFFRECORDTYPE.RSTRING: dt.Rows[cell.RowIndex][cell.ColumnIndex] = ((XlsBiffLabelCell)cell).Value; break; case BIFFRECORDTYPE.LABELSST: string tmp = m_globals.SST.GetString(((XlsBiffLabelSSTCell)cell).SSTIndex); dt.Rows[cell.RowIndex][cell.ColumnIndex] = tmp; break; case BIFFRECORDTYPE.RK: _dValue = ((XlsBiffRKCell)cell).Value; if ((_sValue = TryConvertOADate(_dValue, cell.XFormat)) != null) { dt.Rows[cell.RowIndex][cell.ColumnIndex] = _sValue; } else { dt.Rows[cell.RowIndex][cell.ColumnIndex] = _dValue; } break; case BIFFRECORDTYPE.MULRK: XlsBiffMulRKCell _rkCell = (XlsBiffMulRKCell)cell; for (ushort j = cell.ColumnIndex; j <= _rkCell.LastColumnIndex; j++) { dt.Rows[cell.RowIndex][j] = _rkCell.GetValue(j); } break; case BIFFRECORDTYPE.BLANK: case BIFFRECORDTYPE.BLANK_OLD: case BIFFRECORDTYPE.MULBLANK: // Skip blank cells break; case BIFFRECORDTYPE.FORMULA: case BIFFRECORDTYPE.FORMULA_OLD: object _oValue = ((XlsBiffFormulaCell)cell).Value; if (null != _oValue && _oValue is FORMULAERROR) _oValue = null; if (null != _oValue && (_sValue = TryConvertOADate(_oValue, cell.XFormat)) != null) { dt.Rows[cell.RowIndex][cell.ColumnIndex] = _sValue; } else { dt.Rows[cell.RowIndex][cell.ColumnIndex] = _oValue; } break; default: break; } } } dt.EndLoadData(); if (m_PromoteToColumns) { RemapColumnsNames(ref dt, dt.Rows[0].ItemArray); dt.Rows.RemoveAt(0); dt.AcceptChanges(); } return true; } private string TryConvertOADate(double value, ushort XFormat) { if (!m_ConvertOADate) return null; switch (XFormat) { //Time format case 63: case 68: DateTime time = DateTime.FromOADate(value); return (time.Second == 0) ? time.ToShortTimeString() : time.ToLongTimeString(); //Date Format case 62: case 64: case 67: case 69: case 70: return DateTime.FromOADate(value).ToShortDateString(); default: return null; } } private string TryConvertOADate(object value, ushort XFormat) { if (!m_ConvertOADate || null == value) return null; double _dValue; string _re; try { _dValue = double.Parse(value.ToString()); _re = TryConvertOADate(_dValue, XFormat); } catch { _re = null; } return _re; } private static void InitializeColumns(ref DataTable dataTable, int columnsCount) { for (int i = 0; i < columnsCount; i++) { dataTable.Columns.Add(COLUMN_DEFAULT_NAME + (i + 1), typeof(string)); } } private static void RemapColumnsNames(ref DataTable dataTable, object[] columnNames) { for (int index = 0; index < columnNames.Length; index++) { if (!string.IsNullOrEmpty(columnNames[index].ToString().Trim())) { dataTable.Columns[index].ColumnName = columnNames[index].ToString().Trim(); } } } private bool IsV8() { return m_version >= 0x600; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Cake.Core; using Cake.Core.IO; using Cake.Core.Tooling; namespace Cake.Common.Tools.WiX.Heat { /// <summary> /// The WiX Heat runner. /// </summary> public sealed class HeatRunner : Tool<HeatSettings> { private readonly ICakeEnvironment _environment; /// <summary> /// Initializes a new instance of the <see cref="HeatRunner" /> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> /// <param name="processRunner">The process runner.</param> /// <param name="toolService">The tool service.</param> public HeatRunner(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator toolService) : base(fileSystem, environment, processRunner, toolService) { if (environment == null) { throw new ArgumentNullException(nameof(environment)); } _environment = environment; } /// <summary> /// Runs the Wix Heat runner for the specified directory path. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <param name="outputFile">The output file.</param> /// <param name="harvestType">The WiX harvest type.</param> /// <param name="settings">The settings.</param> public void Run(DirectoryPath directoryPath, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { if (directoryPath == null) { throw new ArgumentNullException(nameof(directoryPath)); } if (outputFile == null) { throw new ArgumentNullException(nameof(outputFile)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } Run(settings, GetArguments(directoryPath, outputFile, harvestType, settings)); } /// <summary> /// Runs the Wix Heat runner for the specified directory path. /// </summary> /// <param name="objectFile">The object file.</param> /// <param name="outputFile">The output file.</param> /// <param name="harvestType">The WiX harvest type.</param> /// <param name="settings">The settings.</param> public void Run(FilePath objectFile, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { if (objectFile == null) { throw new ArgumentNullException(nameof(objectFile)); } if (outputFile == null) { throw new ArgumentNullException(nameof(outputFile)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } Run(settings, GetArguments(objectFile, outputFile, harvestType, settings)); } /// <summary> /// Runs the Wix Heat runner for the specified directory path. /// </summary> /// <param name="harvestTarget">The harvest target.</param> /// <param name="outputFile">The output file.</param> /// <param name="harvestType">The WiX harvest type.</param> /// <param name="settings">The settings.</param> public void Run(string harvestTarget, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { if (harvestTarget == null) { throw new ArgumentNullException(nameof(harvestTarget)); } if (outputFile == null) { throw new ArgumentNullException(nameof(outputFile)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } Run(settings, GetArguments(harvestTarget, outputFile, harvestType, settings)); } private ProcessArgumentBuilder GetArguments(FilePath objectFile, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append(GetHarvestType(harvestType)); builder.AppendQuoted(objectFile.MakeAbsolute(_environment).FullPath); var args = GetArguments(outputFile, settings); args.CopyTo(builder); return builder; } private ProcessArgumentBuilder GetArguments(DirectoryPath directoryPath, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append(GetHarvestType(harvestType)); builder.AppendQuoted(directoryPath.MakeAbsolute(_environment).FullPath); var args = GetArguments(outputFile, settings); args.CopyTo(builder); return builder; } private ProcessArgumentBuilder GetArguments(string harvestTarget, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append(GetHarvestType(harvestType)); builder.AppendQuoted(harvestTarget); var args = GetArguments(outputFile, settings); args.CopyTo(builder); return builder; } private ProcessArgumentBuilder GetArguments(FilePath outputFile, HeatSettings settings) { var builder = new ProcessArgumentBuilder(); // Add extensions if (settings.Extensions != null && settings.Extensions.Any()) { var extensions = settings.Extensions.Select(extension => string.Format(CultureInfo.InvariantCulture, "-ext {0}", extension)); foreach (var extension in extensions) { builder.Append(extension); } } // No logo if (settings.NoLogo) { builder.Append("-nologo"); } // Suppress specific warnings if (settings.SuppressSpecificWarnings != null && settings.SuppressSpecificWarnings.Any()) { var warnings = settings.SuppressSpecificWarnings.Select(warning => string.Format(CultureInfo.InvariantCulture, "-sw{0}", warning)); foreach (var warning in warnings) { builder.Append(warning); } } // Treat specific warnings as errors if (settings.TreatSpecificWarningsAsErrors != null && settings.TreatSpecificWarningsAsErrors.Any()) { var errors = settings.TreatSpecificWarningsAsErrors.Select(error => string.Format(CultureInfo.InvariantCulture, "-wx{0}", error)); foreach (var error in errors) { builder.Append(error); } } // Auto generate guids if (settings.AutogeneratedGuid) { builder.Append("-ag"); } // Component group name if (settings.ComponentGroupName != null) { builder.Append("-cg"); builder.Append(settings.ComponentGroupName); } if (!string.IsNullOrEmpty(settings.Configuration)) { builder.Append("-configuration"); builder.Append(settings.Configuration); } // Directory reference id if (!string.IsNullOrEmpty(settings.DirectoryId)) { builder.Append("-directoryid"); builder.Append(settings.DirectoryId); } if (!string.IsNullOrWhiteSpace(settings.DirectoryReferenceId)) { builder.Append("-dr"); builder.Append(settings.DirectoryReferenceId); } // Default is components if (settings.Generate != WiXGenerateType.Components) { builder.Append("-generate"); builder.Append(settings.Generate.ToString().ToLower()); } if (settings.GenerateGuid) { builder.Append("-gg"); } if (settings.GenerateGuidWithoutBraces) { builder.Append("-g1"); } if (settings.KeepEmptyDirectories) { builder.Append("-ke"); } if (!string.IsNullOrEmpty(settings.Platform)) { builder.Append("-platform"); builder.Append(settings.Platform); } if (settings.OutputGroup != null) { builder.Append("-pog"); switch (settings.OutputGroup) { case WiXOutputGroupType.Binaries: builder.Append("Binaries"); break; case WiXOutputGroupType.Symbols: builder.Append("Symbols"); break; case WiXOutputGroupType.Documents: builder.Append("Documents"); break; case WiXOutputGroupType.Satellites: builder.Append("Satellites"); break; case WiXOutputGroupType.Sources: builder.Append("Sources"); break; case WiXOutputGroupType.Content: builder.Append("Content"); break; } } if (!string.IsNullOrEmpty(settings.ProjectName)) { builder.Append("-projectname"); builder.Append(settings.ProjectName); } // Suppress Com if (settings.SuppressCom) { builder.Append("-scom"); } // Suppress fragments if (settings.SuppressFragments) { builder.Append("-sfrag"); } // Suppress unique identifiers if (settings.SuppressUniqueIds) { builder.Append("-suid"); } // Suppress root directory if (settings.SuppressRootDirectory) { builder.Append("-srd"); } // Suppress root directory if (settings.SuppressRegistry) { builder.Append("-sreg"); } if (settings.SuppressVb6Com) { builder.Append("-svb6"); } if (settings.Template != null) { builder.Append("-template"); switch (settings.Template) { case WiXTemplateType.Fragment: builder.Append("fragment"); break; case WiXTemplateType.Module: builder.Append("module"); break; case WiXTemplateType.Product: builder.Append("product"); break; } } if (settings.Transform != null) { builder.Append("-t"); builder.AppendQuoted(settings.Transform); } if (settings.Indent != null) { builder.Append("-indent"); builder.Append(settings.Indent.ToString()); } // Verbose if (settings.Verbose) { builder.Append("-v"); } // Preprocessor variable if (!string.IsNullOrEmpty(settings.PreprocessorVariable)) { builder.Append("-var"); builder.Append(settings.PreprocessorVariable); } // Generate binder variables if (settings.GenerateBinderVariables) { builder.Append("-wixvar"); } // Output file builder.Append("-out"); builder.AppendQuoted(outputFile.MakeAbsolute(_environment).FullPath); return builder; } private string GetHarvestType(WiXHarvestType harvestType) { switch (harvestType) { case WiXHarvestType.Dir: return "dir"; case WiXHarvestType.File: return "file"; case WiXHarvestType.Project: return "project"; case WiXHarvestType.Reg: return "reg"; case WiXHarvestType.Perf: return "perf"; case WiXHarvestType.Website: return "website"; default: return "dir"; } } /// <summary> /// Gets the name of the tool. /// </summary> /// <returns> The name of the tool. </returns> protected override string GetToolName() { return "Heat"; } /// <summary> /// Gets the possible names of the tool executable. /// </summary> /// <returns> The tool executable name. </returns> protected override IEnumerable<string> GetToolExecutableNames() { return new[] { "heat.exe" }; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataFactory { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LinkedServicesOperations operations. /// </summary> internal partial class LinkedServicesOperations : IServiceOperations<DataFactoryManagementClient>, ILinkedServicesOperations { /// <summary> /// Initializes a new instance of the LinkedServicesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LinkedServicesOperations(DataFactoryManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataFactoryManagementClient /// </summary> public DataFactoryManagementClient Client { get; private set; } /// <summary> /// Lists linked services. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='factoryName'> /// The factory name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LinkedServiceResource>>> ListByFactoryWithHttpMessagesAsync(string resourceGroupName, string factoryName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (factoryName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "factoryName"); } if (factoryName != null) { if (factoryName.Length > 63) { throw new ValidationException(ValidationRules.MaxLength, "factoryName", 63); } if (factoryName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "factoryName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(factoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$")) { throw new ValidationException(ValidationRules.Pattern, "factoryName", "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("factoryName", factoryName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByFactory", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/linkedservices").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{factoryName}", System.Uri.EscapeDataString(factoryName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LinkedServiceResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LinkedServiceResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a linked service. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='factoryName'> /// The factory name. /// </param> /// <param name='linkedServiceName'> /// The linked service name. /// </param> /// <param name='linkedService'> /// Linked service resource definition. /// </param> /// <param name='ifMatch'> /// ETag of the linkedService entity. Should only be specified for update, for /// which it should match existing entity or can be * for unconditional update. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LinkedServiceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string factoryName, string linkedServiceName, LinkedServiceResource linkedService, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (factoryName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "factoryName"); } if (factoryName != null) { if (factoryName.Length > 63) { throw new ValidationException(ValidationRules.MaxLength, "factoryName", 63); } if (factoryName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "factoryName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(factoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$")) { throw new ValidationException(ValidationRules.Pattern, "factoryName", "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); } } if (linkedServiceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "linkedServiceName"); } if (linkedServiceName != null) { if (linkedServiceName.Length > 260) { throw new ValidationException(ValidationRules.MaxLength, "linkedServiceName", 260); } if (linkedServiceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "linkedServiceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(linkedServiceName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$")) { throw new ValidationException(ValidationRules.Pattern, "linkedServiceName", "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (linkedService == null) { throw new ValidationException(ValidationRules.CannotBeNull, "linkedService"); } if (linkedService != null) { linkedService.Validate(); } if (linkedService == null) { linkedService = new LinkedServiceResource(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("factoryName", factoryName); tracingParameters.Add("linkedServiceName", linkedServiceName); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("linkedService", linkedService); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/linkedservices/{linkedServiceName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{factoryName}", System.Uri.EscapeDataString(factoryName)); _url = _url.Replace("{linkedServiceName}", System.Uri.EscapeDataString(linkedServiceName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(linkedService != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(linkedService, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LinkedServiceResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LinkedServiceResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a linked service. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='factoryName'> /// The factory name. /// </param> /// <param name='linkedServiceName'> /// The linked service name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LinkedServiceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string factoryName, string linkedServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (factoryName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "factoryName"); } if (factoryName != null) { if (factoryName.Length > 63) { throw new ValidationException(ValidationRules.MaxLength, "factoryName", 63); } if (factoryName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "factoryName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(factoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$")) { throw new ValidationException(ValidationRules.Pattern, "factoryName", "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); } } if (linkedServiceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "linkedServiceName"); } if (linkedServiceName != null) { if (linkedServiceName.Length > 260) { throw new ValidationException(ValidationRules.MaxLength, "linkedServiceName", 260); } if (linkedServiceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "linkedServiceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(linkedServiceName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$")) { throw new ValidationException(ValidationRules.Pattern, "linkedServiceName", "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("factoryName", factoryName); tracingParameters.Add("linkedServiceName", linkedServiceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/linkedservices/{linkedServiceName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{factoryName}", System.Uri.EscapeDataString(factoryName)); _url = _url.Replace("{linkedServiceName}", System.Uri.EscapeDataString(linkedServiceName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LinkedServiceResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LinkedServiceResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a linked service. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='factoryName'> /// The factory name. /// </param> /// <param name='linkedServiceName'> /// The linked service name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string factoryName, string linkedServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (factoryName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "factoryName"); } if (factoryName != null) { if (factoryName.Length > 63) { throw new ValidationException(ValidationRules.MaxLength, "factoryName", 63); } if (factoryName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "factoryName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(factoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$")) { throw new ValidationException(ValidationRules.Pattern, "factoryName", "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); } } if (linkedServiceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "linkedServiceName"); } if (linkedServiceName != null) { if (linkedServiceName.Length > 260) { throw new ValidationException(ValidationRules.MaxLength, "linkedServiceName", 260); } if (linkedServiceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "linkedServiceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(linkedServiceName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$")) { throw new ValidationException(ValidationRules.Pattern, "linkedServiceName", "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("factoryName", factoryName); tracingParameters.Add("linkedServiceName", linkedServiceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/linkedservices/{linkedServiceName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{factoryName}", System.Uri.EscapeDataString(factoryName)); _url = _url.Replace("{linkedServiceName}", System.Uri.EscapeDataString(linkedServiceName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists linked services. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LinkedServiceResource>>> ListByFactoryNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByFactoryNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LinkedServiceResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LinkedServiceResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_CTYPES using System; using System.Collections.Generic; using System.Numerics; using System.Reflection.Emit; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { /// <summary> /// The meta class for ctypes pointers. /// </summary> [PythonType, PythonHidden] public class PointerType : PythonType, INativeType { internal INativeType _type; private readonly string _typeFormat; public PointerType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members) : base(context, name, bases, members) { object type; if (members.TryGetValue("_type_", out type) && !(type is INativeType)) { throw PythonOps.TypeError("_type_ must be a type"); } _type = (INativeType)type; if (_type != null) { _typeFormat = _type.TypeFormat; } } private PointerType(Type underlyingSystemType) : base(underlyingSystemType) { } public object from_param([NotNull]CData obj) { return new NativeArgument((CData)PythonCalls.Call(this, obj), "P"); } /// <summary> /// Converts an object into a function call parameter. /// </summary> public object from_param(Pointer obj) { if (obj == null) { return ScriptingRuntimeHelpers.Int32ToObject(0); } if (obj.NativeType != this) { throw PythonOps.TypeError("assign to pointer of type {0} from {1} is not valid", Name, ((PythonType)obj.NativeType).Name); } Pointer res = (Pointer)PythonCalls.Call(this); res._memHolder.WriteIntPtr(0, obj._memHolder.ReadMemoryHolder(0)); return res; } public object from_param([NotNull]NativeArgument obj) { return (CData)PythonCalls.Call(this, obj._obj); } /// <summary> /// Access an instance at the specified address /// </summary> public object from_address(object obj) { throw new NotImplementedException("pointer from address"); } public void set_type(PythonType type) { _type = (INativeType)type; } internal static PythonType MakeSystemType(Type underlyingSystemType) { return PythonType.SetPythonType(underlyingSystemType, new PointerType(underlyingSystemType)); } public static ArrayType/*!*/ operator *(PointerType type, int count) { return MakeArrayType(type, count); } public static ArrayType/*!*/ operator *(int count, PointerType type) { return MakeArrayType(type, count); } #region INativeType Members int INativeType.Size { get { return IntPtr.Size; } } int INativeType.Alignment { get { return IntPtr.Size; } } object INativeType.GetValue(MemoryHolder owner, object readingFrom, int offset, bool raw) { if (!raw) { Pointer res = (Pointer)PythonCalls.Call(Context.SharedContext, this); res._memHolder.WriteIntPtr(0, owner.ReadIntPtr(offset)); res._memHolder.AddObject(offset, readingFrom); return res; } return owner.ReadIntPtr(offset).ToPython(); } object INativeType.SetValue(MemoryHolder address, int offset, object value) { Pointer ptr; _Array array; if (value == null) { address.WriteIntPtr(offset, IntPtr.Zero); } else if (value is int) { address.WriteIntPtr(offset, new IntPtr((int)value)); } else if (value is BigInteger) { address.WriteIntPtr(offset, new IntPtr((long)(BigInteger)value)); } else if ((ptr = value as Pointer) != null) { address.WriteIntPtr(offset, ptr._memHolder.ReadMemoryHolder(0)); return PythonOps.MakeDictFromItems(ptr, "0", ptr._objects, "1"); } else if ((array = value as _Array) != null) { address.WriteIntPtr(offset, array._memHolder); return array; } else { throw PythonOps.TypeErrorForTypeMismatch(Name, value); } return null; } Type INativeType.GetNativeType() { return typeof(IntPtr); } MarshalCleanup INativeType.EmitMarshalling(ILGenerator/*!*/ method, LocalOrArg argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { Type argumentType = argIndex.Type; Label nextTry = method.DefineLabel(); Label done = method.DefineLabel(); if (!argumentType.IsValueType) { argIndex.Emit(method); method.Emit(OpCodes.Ldnull); method.Emit(OpCodes.Bne_Un, nextTry); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_I); method.Emit(OpCodes.Br, done); } method.MarkLabel(nextTry); nextTry = method.DefineLabel(); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } constantPool.Add(this); SimpleType st = _type as SimpleType; MarshalCleanup res = null; if (st != null && !argIndex.Type.IsValueType) { if (st._type == SimpleTypeKind.Char || st._type == SimpleTypeKind.WChar) { if (st._type == SimpleTypeKind.Char) { SimpleType.TryToCharPtrConversion(method, argIndex, argumentType, done); } else { SimpleType.TryArrayToWCharPtrConversion(method, argIndex, argumentType, done); } Label notStr = method.DefineLabel(); LocalOrArg str = argIndex; if (argumentType != typeof(string)) { LocalBuilder lb = method.DeclareLocal(typeof(string)); method.Emit(OpCodes.Isinst, typeof(string)); method.Emit(OpCodes.Brfalse, notStr); argIndex.Emit(method); method.Emit(OpCodes.Castclass, typeof(string)); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); str = new Local(lb); } if (st._type == SimpleTypeKind.Char) { res = SimpleType.MarshalCharPointer(method, str); } else { SimpleType.MarshalWCharPointer(method, str); } method.Emit(OpCodes.Br, done); method.MarkLabel(notStr); argIndex.Emit(method); } } // native argument being pased (byref) method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CheckNativeArgument")); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Br, done); // lone cdata being passed method.MarkLabel(nextTry); nextTry = method.DefineLabel(); method.Emit(OpCodes.Pop); // extra null native arg argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("TryCheckCDataPointerType")); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Br, done); // pointer object being passed method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); // extra null cdata argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CheckCDataType")); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Ldind_I); method.MarkLabel(done); return res; } Type/*!*/ INativeType.GetPythonType() { return typeof(object); } void INativeType.EmitReverseMarshalling(ILGenerator method, LocalOrArg value, List<object> constantPool, int constantPoolArgument) { value.Emit(method); EmitCDataCreation(this, method, constantPool, constantPoolArgument); } string INativeType.TypeFormat { get { return "&" + (_typeFormat ?? _type.TypeFormat); } } #endregion } } } #endif
using System; using System.Collections.Generic; using ModestTree; namespace Zenject { [NoReflectionBaking] public abstract class StaticMemoryPoolBaseBase<TValue> : IDespawnableMemoryPool<TValue>, IDisposable where TValue : class { // I also tried using ConcurrentBag instead of Stack + lock here but that performed much much worse readonly Stack<TValue> _stack = new Stack<TValue>(); Action<TValue> _onDespawnedMethod; int _activeCount; #if ZEN_MULTITHREADING protected readonly object _locker = new object(); #endif public StaticMemoryPoolBaseBase(Action<TValue> onDespawnedMethod) { _onDespawnedMethod = onDespawnedMethod; #if UNITY_EDITOR StaticMemoryPoolRegistry.Add(this); #endif } public Action<TValue> OnDespawnedMethod { set { _onDespawnedMethod = value; } } public int NumTotal { get { return NumInactive + NumActive; } } public int NumActive { get { #if ZEN_MULTITHREADING lock (_locker) #endif { return _activeCount; } } } public int NumInactive { get { #if ZEN_MULTITHREADING lock (_locker) #endif { return _stack.Count; } } } public Type ItemType { get { return typeof(TValue); } } public void Resize(int desiredPoolSize) { #if ZEN_MULTITHREADING lock (_locker) #endif { ResizeInternal(desiredPoolSize); } } // We assume here that we're in a lock void ResizeInternal(int desiredPoolSize) { Assert.That(desiredPoolSize >= 0, "Attempted to resize the pool to a negative amount"); while (_stack.Count > desiredPoolSize) { _stack.Pop(); } while (desiredPoolSize > _stack.Count) { _stack.Push(Alloc()); } Assert.IsEqual(_stack.Count, desiredPoolSize); } public void Dispose() { #if UNITY_EDITOR StaticMemoryPoolRegistry.Remove(this); #endif } public void ClearActiveCount() { #if ZEN_MULTITHREADING lock (_locker) #endif { _activeCount = 0; } } public void Clear() { Resize(0); } public void ShrinkBy(int numToRemove) { #if ZEN_MULTITHREADING lock (_locker) #endif { ResizeInternal(_stack.Count - numToRemove); } } public void ExpandBy(int numToAdd) { #if ZEN_MULTITHREADING lock (_locker) #endif { ResizeInternal(_stack.Count + numToAdd); } } // We assume here that we're in a lock protected TValue SpawnInternal() { TValue element; if (_stack.Count == 0) { element = Alloc(); } else { element = _stack.Pop(); } _activeCount++; return element; } void IMemoryPool.Despawn(object item) { Despawn((TValue)item); } public void Despawn(TValue element) { if (_onDespawnedMethod != null) { _onDespawnedMethod(element); } #if ZEN_MULTITHREADING lock (_locker) #endif { Assert.That(!_stack.Contains(element), "Attempted to despawn element twice!"); _activeCount--; _stack.Push(element); } } protected abstract TValue Alloc(); } [NoReflectionBaking] public abstract class StaticMemoryPoolBase<TValue> : StaticMemoryPoolBaseBase<TValue> where TValue : class, new() { public StaticMemoryPoolBase(Action<TValue> onDespawnedMethod) : base(onDespawnedMethod) { } protected override TValue Alloc() { return new TValue(); } } // Zero parameters [NoReflectionBaking] public class StaticMemoryPool<TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TValue> where TValue : class, new() { Action<TValue> _onSpawnMethod; public StaticMemoryPool( Action<TValue> onSpawnMethod = null, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { _onSpawnMethod = onSpawnMethod; } public Action<TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn() { #if ZEN_MULTITHREADING lock (_locker) #endif { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(item); } return item; } } } // One parameter [NoReflectionBaking] public class StaticMemoryPool<TParam1, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TValue> where TValue : class, new() { Action<TParam1, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 param) { #if ZEN_MULTITHREADING lock (_locker) #endif { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(param, item); } return item; } } } // Two parameter [NoReflectionBaking] public class StaticMemoryPool<TParam1, TParam2, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TValue> where TValue : class, new() { Action<TParam1, TParam2, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TParam2, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TParam2, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2) { #if ZEN_MULTITHREADING lock (_locker) #endif { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, item); } return item; } } } // Three parameters [NoReflectionBaking] public class StaticMemoryPool<TParam1, TParam2, TParam3, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TValue> where TValue : class, new() { Action<TParam1, TParam2, TParam3, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TParam2, TParam3, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TParam2, TParam3, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3) { #if ZEN_MULTITHREADING lock (_locker) #endif { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, item); } return item; } } } // Four parameters [NoReflectionBaking] public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> where TValue : class, new() { #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4) { #if ZEN_MULTITHREADING lock (_locker) #endif { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, item); } return item; } } } // Five parameters [NoReflectionBaking] public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> where TValue : class, new() { #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5) { #if ZEN_MULTITHREADING lock (_locker) #endif { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, item); } return item; } } } // Six parameters [NoReflectionBaking] public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> where TValue : class, new() { #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6) { #if ZEN_MULTITHREADING lock (_locker) #endif { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, p6, item); } return item; } } } // Seven parameters [NoReflectionBaking] public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> where TValue : class, new() { #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 && !NET_STANDARD_2_0 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7) { #if ZEN_MULTITHREADING lock (_locker) #endif { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, p6, p7, item); } return item; } } } }
using GameLibrary.Dependencies.Entities; using GameLibrary.Dependencies.Physics; using GameLibrary.Dependencies.Physics.Collision; using GameLibrary.Dependencies.Physics.Collision.Shapes; using GameLibrary.Dependencies.Physics.Common; using GameLibrary.Dependencies.Physics.Controllers; using GameLibrary.Dependencies.Physics.Dynamics; using GameLibrary.Dependencies.Physics.Dynamics.Contacts; using GameLibrary.Dependencies.Physics.Dynamics.Joints; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; namespace GameLibrary.Helpers.Debug { /// <summary> /// A debug view that works in XNA. /// A debug view shows you what happens inside the physics engine. You can view /// bodies, joints, fixtures and more. /// </summary> public class DebugView : PhysicsDebugView, IDisposable { //Drawing private PrimitiveBatch _primitiveBatch; private SpriteBatch _batch; private SpriteFont _font; private GraphicsDevice _device; private Vector2[] _tempVertices = new Vector2[Settings.MaxPolygonVertices]; private List<StringData> _stringData; private List<StringData> _worldStringData; private Camera _camera; private Matrix _localProjection; private Matrix _localView; //Shapes public Color DefaultShapeColor = new Color(0.9f, 0.7f, 0.7f); public Color InactiveShapeColor = new Color(0.5f, 0.5f, 0.3f); public Color KinematicShapeColor = new Color(0.5f, 0.5f, 0.9f); public Color SleepingShapeColor = new Color(0.6f, 0.6f, 0.6f); public Color StaticShapeColor = new Color(0.5f, 0.9f, 0.5f); public Color TextColor = Color.LightGreen; //Contacts private int _pointCount; private const int MaxContactPoints = 2048; private ContactPoint[] _points = new ContactPoint[MaxContactPoints]; //Debug panel #if XBOX public Vector2 DebugPanelPosition = new Vector2(55, 100); #else public Vector2 DebugPanelPosition = new Vector2(40, 100); #endif private int _max; private int _avg; private int _min; /// <summary> /// UserData to be displayed on the debug panel. /// </summary> public Dictionary<string, object> DebugPanelUserData; //Performance graph public bool AdaptiveLimits = true; public float ValuesToGraph = 500; public float MinimumValue = -1000; public float MaximumValue = 1000; private List<float> _graphTotalValues = new List<float>(); private List<float> _graphPhysicsValues = new List<float>(); private List<float> _graphEntitiesValues = new List<float>(); #if XBOX public Rectangle PerformancePanelBounds = new Rectangle(305, 100, 200, 100); #else public Rectangle PerformancePanelBounds = new Rectangle(300, 100, 200, 100); #endif private Vector2[] _background = new Vector2[4]; public bool Enabled = true; #if XBOX || WINDOWS_PHONE public const int CircleSegments = 16; #else public const int CircleSegments = 32; #endif public DebugView(EntityWorld world, Camera camera) : base(world) { world.ContactManager.PreSolve += PreSolve; //Default flags AppendFlags(DebugViewFlags.Shape); AppendFlags(DebugViewFlags.Controllers); AppendFlags(DebugViewFlags.Joint); DebugPanelUserData = new Dictionary<string, object>(); this._camera = camera; } public void BeginCustomDraw() { Matrix proj = _camera.SimProjection, view = _camera.SimView; BeginCustomDraw(ref proj, ref view); } public void BeginCustomDraw(ref Matrix projection, ref Matrix view) { _primitiveBatch.Begin(ref projection, ref view); } public void EndCustomDraw() { _primitiveBatch.End(); } #region IDisposable Members public void Dispose() { World.ContactManager.PreSolve -= PreSolve; } #endregion IDisposable Members private void PreSolve(Contact contact, ref Manifold oldManifold) { if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints) { Manifold manifold = contact.Manifold; if (manifold.PointCount == 0) { return; } Fixture fixtureA = contact.FixtureA; FixedArray2<PointState> state1, state2; Collision.GetPointStates(out state1, out state2, ref oldManifold, ref manifold); FixedArray2<Vector2> points; Vector2 normal; contact.GetWorldManifold(out normal, out points); for (int i = 0; i < manifold.PointCount && _pointCount < MaxContactPoints; ++i) { if (fixtureA == null) { _points[i] = new ContactPoint(); } ContactPoint cp = _points[_pointCount]; cp.Position = points[i]; cp.Normal = normal; cp.State = state2[i]; _points[_pointCount] = cp; ++_pointCount; } } } /// <summary> /// Call this to draw shapes and other debug draw data. /// </summary> private void DrawDebugData() { if ((Flags & DebugViewFlags.Shape) == DebugViewFlags.Shape) { foreach (PhysicsBody b in World.BodyList) { if (b.UserData != null && b.UserData is Entity) //Draw the name of the entity DrawString(true, (int)ConvertUnits.ToDisplayUnits(b.WorldCenter.X), (int)ConvertUnits.ToDisplayUnits(b.WorldCenter.Y), "[" + (b.UserData as Entity).Id + "] " + (b.UserData as Entity).Tag.ToString(), Color.LightSalmon, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); Transform xf; b.GetTransform(out xf); foreach (Fixture f in b.FixtureList) { if (b.Enabled == false) { DrawShape(f, xf, InactiveShapeColor); } else if (b.BodyType == BodyType.Static) { DrawShape(f, xf, StaticShapeColor); } else if (b.BodyType == BodyType.Kinematic) { DrawShape(f, xf, KinematicShapeColor); } else if (b.Awake == false) { DrawShape(f, xf, SleepingShapeColor); } else { DrawShape(f, xf, DefaultShapeColor); } } } } if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints) { const float axisScale = 0.3f; for (int i = 0; i < _pointCount; ++i) { ContactPoint point = _points[i]; if (point.State == PointState.Add) { // Add DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.95f, 0.3f)); } else if (point.State == PointState.Persist) { // Persist DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.3f, 0.95f)); } if ((Flags & DebugViewFlags.ContactNormals) == DebugViewFlags.ContactNormals) { Vector2 p1 = point.Position; Vector2 p2 = p1 + axisScale * point.Normal; DrawSegment(p1, p2, new Color(0.4f, 0.9f, 0.4f)); } } _pointCount = 0; } if ((Flags & DebugViewFlags.PolygonPoints) == DebugViewFlags.PolygonPoints) { foreach (PhysicsBody body in World.BodyList) { foreach (Fixture f in body.FixtureList) { PolygonShape polygon = f.Shape as PolygonShape; if (polygon != null) { Transform xf; body.GetTransform(out xf); for (int i = 0; i < polygon.Vertices.Count; i++) { Vector2 tmp = MathUtils.Multiply(ref xf, polygon.Vertices[i]); DrawPoint(tmp, 0.1f, Color.LightSalmon); } } } } } if ((Flags & DebugViewFlags.Joint) == DebugViewFlags.Joint) { foreach (PhysicsJoint j in World.JointList) { DrawJoint(j); } } if ((Flags & DebugViewFlags.Pair) == DebugViewFlags.Pair) { Color color = new Color(0.3f, 0.9f, 0.9f); for (int i = 0; i < World.ContactManager.ContactList.Count; i++) { Contact c = World.ContactManager.ContactList[i]; Fixture fixtureA = c.FixtureA; Fixture fixtureB = c.FixtureB; AABB aabbA; fixtureA.GetAABB(out aabbA, 0); AABB aabbB; fixtureB.GetAABB(out aabbB, 0); Vector2 cA = aabbA.Center; Vector2 cB = aabbB.Center; DrawSegment(cA, cB, color); } } if ((Flags & DebugViewFlags.AABB) == DebugViewFlags.AABB) { Color color = new Color(0.9f, 0.3f, 0.9f); IBroadPhase bp = World.ContactManager.BroadPhase; foreach (PhysicsBody b in World.BodyList) { if (b.Enabled == false) { continue; } foreach (Fixture f in b.FixtureList) { for (int t = 0; t < f.ProxyCount; ++t) { FixtureProxy proxy = f.Proxies[t]; AABB aabb; bp.GetFatAABB(proxy.ProxyId, out aabb); DrawAABB(ref aabb, color); } } } } if ((Flags & DebugViewFlags.CenterOfMass) == DebugViewFlags.CenterOfMass) { foreach (PhysicsBody b in World.BodyList) { Transform xf; b.GetTransform(out xf); xf.Position = b.WorldCenter; DrawTransform(ref xf); } } if ((Flags & DebugViewFlags.Controllers) == DebugViewFlags.Controllers) { for (int i = 0; i < World.ControllerList.Count; i++) { Controller controller = World.ControllerList[i]; BuoyancyController buoyancy = controller as BuoyancyController; if (buoyancy != null) { AABB container = buoyancy.Container; DrawAABB(ref container, Color.LightBlue); } } } if ((Flags & DebugViewFlags.DebugPanel) == DebugViewFlags.DebugPanel) { DrawDebugPanel(); } } private List<float> _graphAvgTotalValues = new List<float>(); private void DrawPerformanceGraph() { _graphTotalValues.Add(World.PhysicsUpdateTime + World.EntitySystemUpdateTime); _graphEntitiesValues.Add(World.EntitySystemUpdateTime); _graphPhysicsValues.Add(World.PhysicsUpdateTime); if (_graphTotalValues.Count > ValuesToGraph + 1) _graphTotalValues.RemoveAt(0); if (_graphEntitiesValues.Count > ValuesToGraph + 1) _graphEntitiesValues.RemoveAt(0); if (_graphPhysicsValues.Count > ValuesToGraph + 1) _graphPhysicsValues.RemoveAt(0); if (_graphAvgTotalValues.Count > ValuesToGraph + 1) _graphAvgTotalValues.RemoveAt(0); float x = PerformancePanelBounds.X; float deltaX = PerformancePanelBounds.Width / (float)ValuesToGraph; float yScale = PerformancePanelBounds.Bottom - (float)PerformancePanelBounds.Top; float yAxis = (PerformancePanelBounds.Bottom + (MinimumValue / (MaximumValue - MinimumValue)) * yScale); // we must have at least 2 values to start rendering if (_graphTotalValues.Count > 2) { _max = (int)_graphTotalValues.Max(); _avg = (int)_graphTotalValues.Average(); _graphAvgTotalValues.Add(_avg); _min = (int)_graphEntitiesValues.Min(); if (AdaptiveLimits) { MaximumValue = _graphAvgTotalValues[0] * 2; MinimumValue = -500; } #region Draw Total x = PerformancePanelBounds.X; // start at last value (newest value added) // continue until no values are left for (int i = _graphTotalValues.Count - 1; i > 0; i--) { float y1 = yAxis - ((_graphTotalValues[i] / (MaximumValue - MinimumValue)) * yScale); float y2 = yAxis - ((_graphTotalValues[i - 1] / (MaximumValue - MinimumValue)) * yScale); Vector2 x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); Vector2 x2 = new Vector2( MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); DrawSegment(x1, x2, Color.LightGreen); x += deltaX; } #endregion Draw Total #region Draw Physics x = PerformancePanelBounds.X; // start at last value (newest value added) // continue until no values are left for (int i = _graphPhysicsValues.Count - 1; i > 0; i--) { float y1 = yAxis - ((_graphPhysicsValues[i] / (MaximumValue - MinimumValue)) * yScale); float y2 = yAxis - ((_graphPhysicsValues[i - 1] / (MaximumValue - MinimumValue)) * yScale); Vector2 x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); Vector2 x2 = new Vector2( MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); DrawSegment(x1, x2, Color.LightBlue); x += deltaX; } #endregion Draw Physics #region Draw Entities x = PerformancePanelBounds.X; // start at last value (newest value added) // continue until no values are left for (int i = _graphEntitiesValues.Count - 1; i > 0; i--) { float y1 = yAxis - ((_graphEntitiesValues[i] / (MaximumValue - MinimumValue)) * yScale); float y2 = yAxis - ((_graphEntitiesValues[i - 1] / (MaximumValue - MinimumValue)) * yScale); Vector2 x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); Vector2 x2 = new Vector2( MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); DrawSegment(x1, x2, Color.LightSalmon); x += deltaX; } #endregion Draw Entities #region Draw Average x = PerformancePanelBounds.X; // start at last value (newest value added) // continue until no values are left for (int i = _graphAvgTotalValues.Count - 1; i > 0; i--) { float y1 = yAxis - ((_graphAvgTotalValues[i] / (MaximumValue - MinimumValue)) * yScale); float y2 = yAxis - ((_graphAvgTotalValues[i - 1] / (MaximumValue - MinimumValue)) * yScale); Vector2 x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); Vector2 x2 = new Vector2( MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); DrawSegment(x1, x2, Color.White); x += deltaX; } #endregion Draw Average } float avgAxis; if (_graphAvgTotalValues.Count > 0) avgAxis = yAxis - ((_graphAvgTotalValues.Last() / (MaximumValue - MinimumValue)) * yScale) - 4; else avgAxis = PerformancePanelBounds.Center.Y - 4; DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Top, "Max: " + _max, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); DrawString(PerformancePanelBounds.Right + 10, (int)MathHelper.Clamp(avgAxis, PerformancePanelBounds.Top, yAxis), "Avg: " + _avg, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Bottom - 15, "Min: " + _min, Color.LightSalmon, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); //Draw background. _background[0] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y); _background[1] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y + PerformancePanelBounds.Height); _background[2] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y + PerformancePanelBounds.Height); _background[3] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y); DrawSolidPolygon(_background, 4, Color.DarkGray, true); #region Draw Zero DrawSegment(new Vector2(PerformancePanelBounds.X, yAxis), new Vector2(PerformancePanelBounds.X - 8, yAxis), Color.White); DrawString(PerformancePanelBounds.X - 8, (int)yAxis - 12, "0", Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); #endregion Draw Zero } private void DrawDebugPanel() { int fixtures = 0; for (int i = 0; i < World.BodyList.Count; i++) { fixtures += World.BodyList[i].FixtureList.Count; } int x = (int)DebugPanelPosition.X; int y = (int)DebugPanelPosition.Y; DrawString(x, y, "Objects:"); DrawString(x, y, "\n- Bodies: " + World.BodyList.Count + "\n- Fixtures: " + fixtures + "\n- Contacts: " + World.ContactList.Count + "\n- Joints: " + World.JointList.Count + "\n- Controllers: " + World.ControllerList.Count + "\n- Proxies: " + World.ProxyCount, Color.LightBlue); DrawString(x, y, "\n\n\n\n\n\n\n- Entities: " + World.EntityManager.ActiveEntitiesCount, Color.LightSalmon); DrawString(x + 110, y, "Update Time: " + (_graphEntitiesValues.Average() + _graphPhysicsValues.Average()).ToString()); DrawString(x + 110, y, "\n --Physics: " + _graphPhysicsValues.Average() + "\n - Body: " + World.SolveUpdateTime + "\n - Contact: " + World.ContactsUpdateTime + "\n - CCD: " + World.ContinuousPhysicsTime + "\n - Joint: " + World.Island.JointUpdateTime + "\n - Controller: " + World.ControllersUpdateTime, Color.LightBlue); DrawString(x + 110, y, "\n\n\n\n\n\n\n --Entity: " + _graphEntitiesValues.Average(), Color.LightSalmon); if (DebugPanelUserData.Count > 0) { DrawString(x, y + 130, "UserData:" + _GetUserDataString(), Color.Green); } } internal string _GetUserDataString() { string outputString = ""; foreach (string Key in DebugPanelUserData.Keys) outputString += "\n- " + Key + ": " + DebugPanelUserData[Key].ToString(); return outputString; } public void DrawAABB(ref AABB aabb, Color color) { Vector2[] verts = new Vector2[4]; verts[0] = new Vector2(aabb.LowerBound.X, aabb.LowerBound.Y); verts[1] = new Vector2(aabb.UpperBound.X, aabb.LowerBound.Y); verts[2] = new Vector2(aabb.UpperBound.X, aabb.UpperBound.Y); verts[3] = new Vector2(aabb.LowerBound.X, aabb.UpperBound.Y); DrawPolygon(verts, 4, color); } private void DrawJoint(PhysicsJoint joint) { if (!joint.Enabled) return; PhysicsBody b1 = joint.BodyA; PhysicsBody b2 = joint.BodyB; Transform xf1, xf2; b1.GetTransform(out xf1); Vector2 x2 = Vector2.Zero; // WIP David if (!joint.IsFixedType()) { b2.GetTransform(out xf2); x2 = xf2.Position; } Vector2 p1 = joint.WorldAnchorA; Vector2 p2 = joint.WorldAnchorB; Vector2 x1 = xf1.Position; Color color = new Color(0.5f, 0.8f, 0.8f); switch (joint.JointType) { case JointType.Distance: DrawSegment(p1, p2, color); break; case JointType.Pulley: PulleyJoint pulley = (PulleyJoint)joint; Vector2 s1 = pulley.GroundAnchorA; Vector2 s2 = pulley.GroundAnchorB; DrawSegment(s1, p1, color); DrawSegment(s2, p2, color); DrawSegment(s1, s2, color); break; case JointType.FixedMouse: DrawPoint(p1, 0.5f, new Color(0.0f, 1.0f, 0.0f)); DrawSegment(p1, p2, new Color(0.8f, 0.8f, 0.8f)); break; case JointType.Revolute: //DrawSegment(x2, p1, color); DrawSegment(p2, p1, color); DrawSolidCircle(p2, 0.1f, Vector2.Zero, Color.LightSalmon); DrawSolidCircle(p1, 0.1f, Vector2.Zero, Color.LightBlue); break; case JointType.FixedAngle: //Should not draw anything. break; case JointType.FixedRevolute: DrawSegment(x1, p1, color); DrawSolidCircle(p1, 0.1f, Vector2.Zero, Color.Pink); break; case JointType.FixedLine: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); break; case JointType.FixedDistance: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); break; case JointType.FixedPrismatic: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); break; case JointType.Gear: DrawSegment(x1, x2, color); break; //case JointType.Weld: // break; default: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); DrawSegment(x2, p2, color); break; } } public void DrawShape(Fixture fixture, Transform xf, Color color) { switch (fixture.ShapeType) { case ShapeType.Circle: { CircleShape circle = (CircleShape)fixture.Shape; Vector2 center = MathUtils.Multiply(ref xf, circle.Position); float radius = circle.Radius; Vector2 axis = xf.R.Col1; DrawSolidCircle(center, radius, axis, color); } break; case ShapeType.Polygon: { PolygonShape poly = (PolygonShape)fixture.Shape; int vertexCount = poly.Vertices.Count; System.Diagnostics.Debug.Assert(vertexCount <= Settings.MaxPolygonVertices); for (int i = 0; i < vertexCount; ++i) { _tempVertices[i] = MathUtils.Multiply(ref xf, poly.Vertices[i]); } DrawSolidPolygon(_tempVertices, vertexCount, color); } break; case ShapeType.Edge: { EdgeShape edge = (EdgeShape)fixture.Shape; Vector2 v1 = MathUtils.Multiply(ref xf, edge.Vertex1); Vector2 v2 = MathUtils.Multiply(ref xf, edge.Vertex2); DrawSegment(v1, v2, color); } break; case ShapeType.Loop: { LoopShape loop = (LoopShape)fixture.Shape; int count = loop.Vertices.Count; Vector2 v1 = MathUtils.Multiply(ref xf, loop.Vertices[count - 1]); DrawCircle(v1, 0.05f, color); for (int i = 0; i < count; ++i) { Vector2 v2 = MathUtils.Multiply(ref xf, loop.Vertices[i]); DrawSegment(v1, v2, color); v1 = v2; } } break; } } public override void DrawPolygon(Vector2[] vertices, int count, float red, float green, float blue) { DrawPolygon(vertices, count, new Color(red, green, blue)); } public void DrawPolygon(Vector2[] vertices, int count, Color color) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } for (int i = 0; i < count - 1; i++) { _primitiveBatch.AddVertex(vertices[i], color, PrimitiveType.LineList); _primitiveBatch.AddVertex(vertices[i + 1], color, PrimitiveType.LineList); } _primitiveBatch.AddVertex(vertices[count - 1], color, PrimitiveType.LineList); _primitiveBatch.AddVertex(vertices[0], color, PrimitiveType.LineList); } public override void DrawSolidPolygon(Vector2[] vertices, int count, float red, float green, float blue) { DrawSolidPolygon(vertices, count, new Color(red, green, blue), true); } public void DrawSolidPolygon(Vector2[] vertices, int count, Color color) { DrawSolidPolygon(vertices, count, color, true); } public void DrawSolidPolygon(Vector2[] vertices, int count, Color color, bool outline) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } if (count == 2) { DrawPolygon(vertices, count, color); return; } Color colorFill = color * (outline ? 0.5f : 1.0f); for (int i = 1; i < count - 1; i++) { _primitiveBatch.AddVertex(vertices[0], colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(vertices[i], colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(vertices[i + 1], colorFill, PrimitiveType.TriangleList); } if (outline) { DrawPolygon(vertices, count, color); } } public override void DrawCircle(Vector2 center, float radius, float red, float green, float blue) { DrawCircle(center, radius, new Color(red, green, blue)); } public void DrawCircle(Vector2 center, float radius, Color color) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } const double increment = Math.PI * 2.0 / CircleSegments; double theta = 0.0; for (int i = 0; i < CircleSegments; i++) { Vector2 v1 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)); Vector2 v2 = center + radius * new Vector2((float)Math.Cos(theta + increment), (float)Math.Sin(theta + increment)); _primitiveBatch.AddVertex(v1, color, PrimitiveType.LineList); _primitiveBatch.AddVertex(v2, color, PrimitiveType.LineList); theta += increment; } } public override void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, float red, float green, float blue) { DrawSolidCircle(center, radius, axis, new Color(red, green, blue)); } public void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, Color color) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } const double increment = Math.PI * 2.0 / CircleSegments; double theta = 0.0; Color colorFill = color * 0.5f; Vector2 v0 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)); theta += increment; for (int i = 1; i < CircleSegments - 1; i++) { Vector2 v1 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)); Vector2 v2 = center + radius * new Vector2((float)Math.Cos(theta + increment), (float)Math.Sin(theta + increment)); _primitiveBatch.AddVertex(v0, colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(v1, colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(v2, colorFill, PrimitiveType.TriangleList); theta += increment; } DrawCircle(center, radius, color); DrawSegment(center, center + axis * radius, color); } public override void DrawSegment(Vector2 start, Vector2 end, float red, float green, float blue) { DrawSegment(start, end, new Color(red, green, blue)); } public void DrawSegment(Vector2 start, Vector2 end, Color color) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } _primitiveBatch.AddVertex(start, color, PrimitiveType.LineList); _primitiveBatch.AddVertex(end, color, PrimitiveType.LineList); } public override void DrawTransform(ref Transform transform) { const float axisScale = 0.4f; Vector2 p1 = transform.Position; Vector2 p2 = p1 + axisScale * transform.R.Col1; DrawSegment(p1, p2, Color.LightSalmon); p2 = p1 + axisScale * transform.R.Col2; DrawSegment(p1, p2, Color.LightGreen); } public void DrawPoint(Vector2 p, float size, Color color) { Vector2[] verts = new Vector2[4]; float hs = size / 2.0f; verts[0] = p + new Vector2(-hs, -hs); verts[1] = p + new Vector2(hs, -hs); verts[2] = p + new Vector2(hs, hs); verts[3] = p + new Vector2(-hs, hs); DrawSolidPolygon(verts, 4, color, true); } public void DrawString(int x, int y, string s, params object[] args) { this.DrawString(x, y, s, TextColor, args); } public void DrawString(int x, int y, string s, Color color, params object[] args) { _stringData.Add(new StringData(x, y, s, args, color)); } public void DrawString(bool drawInWorld, int x, int y, string s, Color color, params object[] args) { if (drawInWorld) _worldStringData.Add(new StringData(x, y, s, args, color)); else _stringData.Add(new StringData(x, y, s, args, color)); } public void DrawArrow(Vector2 start, Vector2 end, float length, float width, bool drawStartIndicator, Color color) { // Draw connection segment between start- and end-point DrawSegment(start, end, color); // Precalculate halfwidth float halfWidth = width / 2; // Create directional reference Vector2 rotation = (start - end); rotation.Normalize(); // Calculate angle of directional vector float angle = (float)Math.Atan2(rotation.X, -rotation.Y); // Create matrix for rotation Matrix rotMatrix = Matrix.CreateRotationZ(angle); // Create translation matrix for end-point Matrix endMatrix = Matrix.CreateTranslation(end.X, end.Y, 0); // Setup arrow end shape Vector2[] verts = new Vector2[3]; verts[0] = new Vector2(0, 0); verts[1] = new Vector2(-halfWidth, -length); verts[2] = new Vector2(halfWidth, -length); // Rotate end shape Vector2.Transform(verts, ref rotMatrix, verts); // Translate end shape Vector2.Transform(verts, ref endMatrix, verts); // Draw arrow end shape DrawSolidPolygon(verts, 3, color, false); if (drawStartIndicator) { // Create translation matrix for start Matrix startMatrix = Matrix.CreateTranslation(start.X, start.Y, 0); // Setup arrow start shape Vector2[] baseVerts = new Vector2[4]; baseVerts[0] = new Vector2(-halfWidth, length / 4); baseVerts[1] = new Vector2(halfWidth, length / 4); baseVerts[2] = new Vector2(halfWidth, 0); baseVerts[3] = new Vector2(-halfWidth, 0); // Rotate start shape Vector2.Transform(baseVerts, ref rotMatrix, baseVerts); // Translate start shape Vector2.Transform(baseVerts, ref startMatrix, baseVerts); // Draw start shape DrawSolidPolygon(baseVerts, 4, color, false); } } public void RenderDebugData(ref Matrix projection, ref Matrix view) { if (!Enabled) { return; } //Nothing is enabled - don't draw the debug view. if (Flags == 0) return; _device.RasterizerState = RasterizerState.CullNone; _device.DepthStencilState = DepthStencilState.Default; _primitiveBatch.Begin(ref projection, ref view); DrawDebugData(); _primitiveBatch.End(); if ((Flags & DebugViewFlags.PerformanceGraph) == DebugViewFlags.PerformanceGraph) { _primitiveBatch.Begin(ref _localProjection, ref _localView); DrawPerformanceGraph(); _primitiveBatch.End(); } // begin the sprite batch effect _batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); // draw any strings we have (NORMAL) for (int i = 0; i < _stringData.Count; i++) { if (_stringData[i].Args.Length > 0) //If they have variable arguments { _batch.DrawString(_font, string.Format(_stringData[i].S, _stringData[i].Args), new Vector2(_stringData[i].X + 1f, _stringData[i].Y + 1f), Color.Black); _batch.DrawString(_font, string.Format(_stringData[i].S, _stringData[i].Args), new Vector2(_stringData[i].X, _stringData[i].Y), _stringData[i].Color); } else { _batch.DrawString(_font, _stringData[i].S, new Vector2(_stringData[i].X + 1f, _stringData[i].Y + 1f), Color.Black); _batch.DrawString(_font, _stringData[i].S, new Vector2(_stringData[i].X, _stringData[i].Y), _stringData[i].Color); } } // end the sprite batch effect _batch.End(); _stringData.Clear(); //draw any strings that are in the (WORLD) _batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, _camera.View); for (int i = 0; i < _worldStringData.Count; i++) { if (_worldStringData[i].Args.Length > 0) //If they have variable arguments { _batch.DrawString(_font, string.Format(_worldStringData[i].S, _worldStringData[i].Args), new Vector2(_worldStringData[i].X + 1f, _worldStringData[i].Y + 1f), Color.Black, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); _batch.DrawString(_font, string.Format(_worldStringData[i].S, _worldStringData[i].Args, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f), new Vector2(_worldStringData[i].X, _worldStringData[i].Y), _worldStringData[i].Color, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); } else { _batch.DrawString(_font, _worldStringData[i].S, new Vector2(_worldStringData[i].X + 1f, _worldStringData[i].Y + 1f), Color.Black, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); _batch.DrawString(_font, _worldStringData[i].S, new Vector2(_worldStringData[i].X, _worldStringData[i].Y), _worldStringData[i].Color, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f); } #if WINDOWS _worldStringData.RemoveAll(new Predicate<StringData>(x => x.S == _worldStringData[i].S)); #endif i--; } _batch.End(); _worldStringData.Clear(); } public void RenderDebugData(ref Matrix projection) { if (!Enabled) { return; } Matrix view = Matrix.Identity; RenderDebugData(ref projection, ref view); } public void LoadContent(GraphicsDevice device, ContentManager content, params KeyValuePair<string, object>[] userData) { // Create a new SpriteBatch, which can be used to draw textures. _device = device; _batch = new SpriteBatch(_device); _primitiveBatch = new PrimitiveBatch(_device, 1000); _font = content.Load<SpriteFont>("Fonts/debugfont"); _stringData = new List<StringData>(); _worldStringData = new List<StringData>(); _localProjection = Matrix.CreateOrthographicOffCenter(0f, _device.Viewport.Width, _device.Viewport.Height, 0f, 0f, 1f); _localView = Matrix.Identity; if (userData != null && userData.Length > 0) { foreach (KeyValuePair<string, object> data in userData) DebugPanelUserData.Add(data.Key, data.Value); this.EnableOrDisableFlag(DebugViewFlags.PerformanceGraph); this.EnableOrDisableFlag(DebugViewFlags.DebugPanel); } _graphTotalValues.Add(World.PhysicsUpdateTime + World.EntitySystemUpdateTime); _graphEntitiesValues.Add(World.EntitySystemUpdateTime); _graphPhysicsValues.Add(World.PhysicsUpdateTime); } #region Nested type: ContactPoint private struct ContactPoint { public Vector2 Normal; public Vector2 Position; public PointState State; } #endregion Nested type: ContactPoint #region Nested type: StringData private struct StringData { public object[] Args; public Color Color; public string S; public int X, Y; public StringData(int x, int y, string s, object[] args, Color color) { X = x; Y = y; S = s; Args = args; Color = color; } } #endregion Nested type: StringData } }
//----------------------------------------------------------------------- // <copyright file="TangoApplication.cs" company="Google"> // // Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace Tango { using System; using System.Collections; using System.IO; using System.Linq; using System.Runtime.InteropServices; using UnityEngine; /// <summary> /// Delegate for permission callbacks. /// </summary> /// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param> public delegate void PermissionsEvent(bool permissionsGranted); /// <summary> /// Delegate for service connection. /// </summary> public delegate void OnTangoConnectEventHandler(); /// <summary> /// Delegate for service disconnection. /// </summary> public delegate void OnTangoDisconnectEventHandler(); /// <summary> /// Main entry point for the Tango Service. /// /// This component handles nearly all communication with the underlying TangoService. You must have one of these /// in your scene for Tango to work. Customization of the Tango connection can be done in the Unity editor or by /// programatically setting the member flags. /// /// This sends out events to Components that derive from the ITangoPose, ITangoDepth, etc. interfaces and /// register themselves via Register. This also sends out events to callbacks passed in through /// RegisterOnTangoConnect, RegisterOnTangoDisconnect, and RegisterPermissionsCallback. /// /// Note: To connect to the Tango Service, you should call InitApplication after properly registering everything. /// </summary> public class TangoApplication : MonoBehaviour { public bool m_allowOutOfDateTangoAPI = false; public bool m_enableMotionTracking = true; public bool m_enableDepth = true; public bool m_enableVideoOverlay = false; public bool m_motionTrackingAutoReset = true; public bool m_enableAreaLearning = false; public bool m_enableADFLoading = false; public bool m_useExperimentalVideoOverlay = true; public bool m_autoConnectToService = false; internal bool m_enableCloudADF = false; private const string CLASS_NAME = "TangoApplication"; private const int MINIMUM_API_VERSION = 6804; private static string m_tangoServiceVersion = string.Empty; /// <summary> /// If RequestPermissions() has been called automatically. /// /// This only matters if m_autoConnectToService is set. /// </summary> private bool m_autoConnectRequestedPermissions = false; private PermissionsTypes m_requiredPermissions = 0; private IntPtr m_callbackContext = IntPtr.Zero; private bool m_isServiceInitialized = false; private bool m_isServiceConnected = false; private bool m_shouldReconnectService = false; private bool m_sendPermissions = false; private bool m_permissionsSuccessful = false; private PoseListener m_poseListener; private DepthListener m_depthListener; private VideoOverlayListener m_videoOverlayListener; private TangoEventListener m_tangoEventListener; private TangoCloudEventListener m_tangoCloudEventListener; private AreaDescriptionEventListener m_areaDescriptionEventListener; private YUVTexture m_yuvTexture; private TangoConfig m_tangoConfig; private TangoConfig m_tangoRuntimeConfig; /// <summary> /// Occurs when permission event. /// </summary> private event PermissionsEvent PermissionEvent; /// <summary> /// Occurs when on tango connect. /// </summary> private event OnTangoConnectEventHandler OnTangoConnect; /// <summary> /// Occurs when on tango disconnect. /// </summary> private event OnTangoDisconnectEventHandler OnTangoDisconnect; /// <summary> /// Permission types used by Tango applications. /// </summary> [Flags] private enum PermissionsTypes { // All entries must be a power of two for // use in a bit field as flags. NONE = 0, MOTION_TRACKING = 0x1, AREA_LEARNING = 0x2, } /// <summary> /// Gets the Tango config. Useful for debugging. /// </summary> /// <value>The config.</value> internal TangoConfig Config { get { return m_tangoConfig; } } /// <summary> /// Gets the current Tango runtime config. Useful for debugging. /// </summary> /// <value>The current runtime config.</value> internal TangoConfig RuntimeConfig { get { return m_tangoRuntimeConfig; } } /// <summary> /// Get the Tango service version name. /// </summary> /// <returns>String for the version name.</returns> public static string GetTangoServiceVersion() { if (m_tangoServiceVersion == string.Empty) { m_tangoServiceVersion = AndroidHelper.GetVersionName("com.projecttango.tango"); } return m_tangoServiceVersion; } /// <summary> /// Get the video overlay texture. /// </summary> /// <returns>The video overlay texture.</returns> public YUVTexture GetVideoOverlayTextureYUV() { return m_yuvTexture; } /// <summary> /// Register to get Tango callbacks. /// /// The object should derive from one of ITangoDepth, ITangoEvent, ITangoPos, ITangoVideoOverlay, or /// ITangoExperimentalTangoVideoOverlay. You will get callback during Update until you unregister. /// </summary> /// <param name="tangoObject">Object to get Tango callbacks from.</param> public void Register(System.Object tangoObject) { ITangoAreaDescriptionEvent areaDescriptionEvent = tangoObject as ITangoAreaDescriptionEvent; if (areaDescriptionEvent != null) { _RegisterOnAreaDescriptionEvent(areaDescriptionEvent.OnAreaDescriptionImported, areaDescriptionEvent.OnAreaDescriptionExported); } ITangoEvent tangoEvent = tangoObject as ITangoEvent; if (tangoEvent != null) { _RegisterOnTangoEvent(tangoEvent.OnTangoEventAvailableEventHandler); } ITangoEventMultithreaded tangoEventMultithreaded = tangoObject as ITangoEventMultithreaded; if (tangoEventMultithreaded != null) { _RegisterOnTangoEventMultithreaded(tangoEventMultithreaded.OnTangoEventMultithreadedAvailableEventHandler); } ITangoLifecycle tangoLifecycle = tangoObject as ITangoLifecycle; if (tangoLifecycle != null) { _RegisterPermissionsCallback(tangoLifecycle.OnTangoPermissions); _RegisterOnTangoConnect(tangoLifecycle.OnTangoServiceConnected); _RegisterOnTangoDisconnect(tangoLifecycle.OnTangoServiceDisconnected); } ITangoCloudEvent tangoCloudEvent = tangoObject as ITangoCloudEvent; if (tangoCloudEvent != null) { _RegisterOnTangoCloudEvent(tangoCloudEvent.OnTangoCloudEventAvailableEventHandler); } if (m_enableMotionTracking) { ITangoPose poseHandler = tangoObject as ITangoPose; if (poseHandler != null) { _RegisterOnTangoPoseEvent(poseHandler.OnTangoPoseAvailable); } } if (m_enableDepth) { ITangoDepth depthHandler = tangoObject as ITangoDepth; if (depthHandler != null) { _RegisterOnTangoDepthEvent(depthHandler.OnTangoDepthAvailable); } } if (m_enableVideoOverlay) { if (m_useExperimentalVideoOverlay) { IExperimentalTangoVideoOverlay videoOverlayHandler = tangoObject as IExperimentalTangoVideoOverlay; if (videoOverlayHandler != null) { _RegisterOnExperimentalTangoVideoOverlay(videoOverlayHandler.OnExperimentalTangoImageAvailable); } } else { ITangoVideoOverlay videoOverlayHandler = tangoObject as ITangoVideoOverlay; if (videoOverlayHandler != null) { _RegisterOnTangoVideoOverlay(videoOverlayHandler.OnTangoImageAvailableEventHandler); } } } } /// <summary> /// Unregister from Tango callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="tangoObject">Object to stop getting Tango callbacks from.</param> public void Unregister(System.Object tangoObject) { ITangoAreaDescriptionEvent areaDescriptionEvent = tangoObject as ITangoAreaDescriptionEvent; if (areaDescriptionEvent != null) { _UnregisterOnAreaDescriptionEvent(areaDescriptionEvent.OnAreaDescriptionImported, areaDescriptionEvent.OnAreaDescriptionExported); } ITangoEvent tangoEvent = tangoObject as ITangoEvent; if (tangoEvent != null) { _UnregisterOnTangoEvent(tangoEvent.OnTangoEventAvailableEventHandler); } ITangoEventMultithreaded tangoEventMultithreaded = tangoObject as ITangoEventMultithreaded; if (tangoEventMultithreaded != null) { _UnregisterOnTangoEventMultithreaded(tangoEventMultithreaded.OnTangoEventMultithreadedAvailableEventHandler); } ITangoLifecycle tangoLifecycle = tangoObject as ITangoLifecycle; if (tangoLifecycle != null) { _UnregisterPermissionsCallback(tangoLifecycle.OnTangoPermissions); _UnregisterOnTangoConnect(tangoLifecycle.OnTangoServiceConnected); _UnregisterOnTangoDisconnect(tangoLifecycle.OnTangoServiceDisconnected); } ITangoCloudEvent tangoCloudEvent = tangoObject as ITangoCloudEvent; if (tangoCloudEvent != null) { _UnregisterOnTangoCloudEvent(tangoCloudEvent.OnTangoCloudEventAvailableEventHandler); } if (m_enableMotionTracking) { ITangoPose poseHandler = tangoObject as ITangoPose; if (poseHandler != null) { _UnregisterOnTangoPoseEvent(poseHandler.OnTangoPoseAvailable); } } if (m_enableDepth) { ITangoDepth depthHandler = tangoObject as ITangoDepth; if (depthHandler != null) { _UnregisterOnTangoDepthEvent(depthHandler.OnTangoDepthAvailable); } } if (m_enableVideoOverlay) { if (m_useExperimentalVideoOverlay) { IExperimentalTangoVideoOverlay videoOverlayHandler = tangoObject as IExperimentalTangoVideoOverlay; if (videoOverlayHandler != null) { _UnregisterOnExperimentalTangoVideoOverlay(videoOverlayHandler.OnExperimentalTangoImageAvailable); } } else { ITangoVideoOverlay videoOverlayHandler = tangoObject as ITangoVideoOverlay; if (videoOverlayHandler != null) { _UnregisterOnTangoVideoOverlay(videoOverlayHandler.OnTangoImageAvailableEventHandler); } } } } /// <summary> /// Check if all requested permissions have been granted. /// </summary> /// <returns><c>true</c> if all requested permissions were granted; otherwise, <c>false</c>.</returns> public bool HasRequestedPermissions() { return m_requiredPermissions == PermissionsTypes.NONE; } /// <summary> /// Manual initialization step 1: Call this to request Tango permissions. /// /// To know the result of the permissions request, implement the interface ITangoLifecycle and register /// yourself before calling this. /// /// Once all permissions have been granted, you can call TangoApplication.Startup, optionally passing in the /// AreaDescription to load. You can get the list of AreaDescriptions once the appropriate permission is /// granted. /// </summary> public void RequestPermissions() { _ResetPermissionsFlags(); _RequestNextPermission(); } /// <summary> /// Manual initalization step 2: Call this to connect to the Tango service. /// /// After connecting to the Tango service, you will get updates for Motion Tracking, Depth Sensing, and Area /// Learning. If you have a specific Area Description you want to localize too, pass that Area Description in /// here. /// </summary> /// <param name="areaDescription">If not null, the Area Description to localize to.</param> public void Startup(AreaDescription areaDescription) { // Make sure all required permissions have been granted. if (m_requiredPermissions != PermissionsTypes.NONE) { Debug.Log("TangoApplication.Startup() -- ERROR: Not all required permissions were accepted yet."); return; } _CheckTangoVersion(); if (m_enableVideoOverlay && m_useExperimentalVideoOverlay) { int yTextureWidth = 0; int yTextureHeight = 0; int uvTextureWidth = 0; int uvTextureHeight = 0; m_tangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_Y_TEXTURE_WIDTH, ref yTextureWidth); m_tangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_Y_TEXTURE_HEIGHT, ref yTextureHeight); m_tangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_UV_TEXTURE_WIDTH, ref uvTextureWidth); m_tangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_UV_TEXTURE_HEIGHT, ref uvTextureHeight); if (yTextureWidth == 0 || yTextureHeight == 0 || uvTextureWidth == 0 || uvTextureHeight == 0) { Debug.Log("Video overlay texture sizes were not set properly"); } m_yuvTexture.ResizeAll(yTextureWidth, yTextureHeight, uvTextureWidth, uvTextureHeight); } if (areaDescription != null) { _InitializeMotionTracking(areaDescription.m_uuid); } else { _InitializeMotionTracking(null); } if (m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_DEPTH_PERCEPTION_BOOL, m_enableDepth) && m_enableDepth) { _SetDepthCallbacks(); } if (m_enableVideoOverlay) { _SetVideoOverlayCallbacks(); } _SetEventCallbacks(); _TangoConnect(); } /// <summary> /// Disconnect from the Tango service. /// /// This is called automatically when the TangoApplication goes away. You only need /// to call this to disconnect from the Tango service before the TangoApplication goes /// away. /// </summary> public void Shutdown() { Debug.Log("Tango Shutdown"); _TangoDisconnect(); } /// <summary> /// Set the framerate of the depth camera. /// /// Disabling or reducing the framerate of the depth camera when it is running can save a significant amount /// of battery. /// </summary> /// <param name="rate">The rate in frames per second, for the depth camera to run at.</param> public void SetDepthCameraRate(int rate) { if (rate < 0) { Debug.Log("Invalid rate passed to SetDepthCameraRate"); return; } m_tangoRuntimeConfig.SetInt32(TangoConfig.Keys.RUNTIME_DEPTH_FRAMERATE, rate); m_tangoRuntimeConfig.SetRuntimeConfig(); } /// <summary> /// Set the framerate of the depth camera. /// /// Disabling or reducing the framerate of the depth camera when it is running can save a significant amount /// of battery. /// </summary> /// <param name="rate">A special rate to set the depth camera to.</param> public void SetDepthCameraRate(TangoEnums.TangoDepthCameraRate rate) { switch (rate) { case TangoEnums.TangoDepthCameraRate.DISABLED: SetDepthCameraRate(0); break; case TangoEnums.TangoDepthCameraRate.MAXIMUM: // Set the depth frame rate to a sufficiently high number, it will get rounded down. There is no // way to actually get the maximum value to pass in. SetDepthCameraRate(9000); break; } } /// <summary> /// Propagates an event from the java plugin connected to the Cloud Service through UnitySendMessage(). /// </summary> /// <param name="message">A string representation of the cloud event key and value.</param> internal void SendCloudEvent(string message) { Debug.Log("New message from Cloud Service: " + message); string[] keyValue = message.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries); int key; int value; if (m_tangoCloudEventListener != null && keyValue.Length == 2 && Int32.TryParse(keyValue[0], out key) && Int32.TryParse(keyValue[1], out value)) { m_tangoCloudEventListener.OnCloudEventAvailable(key, value); } } /// <summary> /// Gets the get tango API version code. /// </summary> /// <returns>The get tango API version code.</returns> private static int _GetTangoAPIVersion() { return AndroidHelper.GetVersionCode("com.projecttango.tango"); } /// <summary> /// Register to get Tango pose callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Callback handler.</param> private void _RegisterOnTangoPoseEvent(OnTangoPoseAvailableEventHandler handler) { if (m_poseListener != null) { m_poseListener.RegisterTangoPoseAvailable(handler); } } /// <summary> /// Unregister from the Tango pose callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event handler to remove.</param> private void _UnregisterOnTangoPoseEvent(OnTangoPoseAvailableEventHandler handler) { if (m_poseListener != null) { m_poseListener.UnregisterTangoPoseAvailable(handler); } } /// <summary> /// Register to get Tango depth callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event handler.</param> private void _RegisterOnTangoDepthEvent(OnTangoDepthAvailableEventHandler handler) { if (m_depthListener != null) { m_depthListener.RegisterOnTangoDepthAvailable(handler); } } /// <summary> /// Unregister from the Tango depth callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event handler to remove.</param> private void _UnregisterOnTangoDepthEvent(OnTangoDepthAvailableEventHandler handler) { if (m_depthListener != null) { m_depthListener.UnregisterOnTangoDepthAvailable(handler); } } /// <summary> /// Register to get Tango cloud event callbacks. /// /// See TangoApplication.Register for details. /// </summary> /// <param name="handler">Event handler.</param> private void _RegisterOnTangoCloudEvent(OnTangoCloudEventAvailableEventHandler handler) { if (m_tangoCloudEventListener != null) { m_tangoCloudEventListener.RegisterOnTangoCloudEventAvailable(handler); } } /// <summary> /// Unregister from the Tango cloud event callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event handler to remove.</param> private void _UnregisterOnTangoCloudEvent(OnTangoCloudEventAvailableEventHandler handler) { if (m_tangoCloudEventListener != null) { m_tangoCloudEventListener.UnregisterOnTangoCloudEventAvailable(handler); } } /// <summary> /// Register to get Tango event callbacks. /// /// See TangoApplication.Register for details. /// </summary> /// <param name="handler">Event handler.</param> private void _RegisterOnTangoEvent(OnTangoEventAvailableEventHandler handler) { if (m_tangoEventListener != null) { m_tangoEventListener.RegisterOnTangoEventAvailable(handler); } } /// <summary> /// Unregister from the Tango event callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event handler to remove.</param> private void _UnregisterOnTangoEvent(OnTangoEventAvailableEventHandler handler) { if (m_tangoEventListener != null) { m_tangoEventListener.UnregisterOnTangoEventAvailable(handler); } } /// <summary> /// Register to get Tango event callbacks. /// /// See TangoApplication.Register for details. /// </summary> /// <param name="handler">Event handler.</param> private void _RegisterOnTangoEventMultithreaded(OnTangoEventAvailableEventHandler handler) { if (m_tangoEventListener != null) { m_tangoEventListener.RegisterOnTangoEventMultithreadedAvailable(handler); } } /// <summary> /// Unregister from the Tango event callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event to remove.</param> private void _UnregisterOnTangoEventMultithreaded(OnTangoEventAvailableEventHandler handler) { if (m_tangoEventListener != null) { m_tangoEventListener.UnregisterOnTangoEventMultithreadedAvailable(handler); } } /// <summary> /// Register to get Tango video overlay callbacks. /// /// See TangoApplication.Register for details. /// </summary> /// <param name="handler">Event handler.</param> private void _RegisterOnTangoVideoOverlay(OnTangoImageAvailableEventHandler handler) { if (m_videoOverlayListener != null) { m_videoOverlayListener.RegisterOnTangoImageAvailable(handler); } } /// <summary> /// Unregister from the Tango video overlay callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event handler to remove.</param> private void _UnregisterOnTangoVideoOverlay(OnTangoImageAvailableEventHandler handler) { if (m_videoOverlayListener != null) { m_videoOverlayListener.UnregisterOnTangoImageAvailable(handler); } } /// <summary> /// Experimental API only, subject to change. Register to get Tango video overlay callbacks. /// </summary> /// <param name="handler">Event handler.</param> private void _RegisterOnExperimentalTangoVideoOverlay(OnExperimentalTangoImageAvailableEventHandler handler) { if (m_videoOverlayListener != null) { m_videoOverlayListener.RegisterOnExperimentalTangoImageAvailable(handler); } } /// <summary> /// Experimental API only, subject to change. Unregister from the Tango video overlay callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event handler to remove.</param> private void _UnregisterOnExperimentalTangoVideoOverlay(OnExperimentalTangoImageAvailableEventHandler handler) { if (m_videoOverlayListener != null) { m_videoOverlayListener.UnregisterOnExperimentalTangoImageAvailable(handler); } } /// <summary> /// Register to get Tango event callbacks. /// /// See TangoApplication.Register for details. /// </summary> /// <param name="import">The handler to the import callback function.</param> /// <param name="export">The handler to the export callback function.</param> private void _RegisterOnAreaDescriptionEvent(OnAreaDescriptionImportEventHandler import, OnAreaDescriptionExportEventHandler export) { if (m_areaDescriptionEventListener != null) { m_areaDescriptionEventListener.Register(import, export); } } /// <summary> /// Unregister from the Tango event callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="import">The handler to the import callback function.</param> /// <param name="export">The handler to the export callback function.</param> private void _UnregisterOnAreaDescriptionEvent(OnAreaDescriptionImportEventHandler import, OnAreaDescriptionExportEventHandler export) { if (m_areaDescriptionEventListener != null) { m_areaDescriptionEventListener.Unregister(import, export); } } /// <summary> /// Register to get an event callback when all permissions are granted. /// /// The passed event will get called once all Tango permissions have been granted. Registering /// after all permissions have already been granted will cause the event to never fire. /// </summary> /// <param name="permissionsEventHandler">Event to call.</param> private void _RegisterPermissionsCallback(PermissionsEvent permissionsEventHandler) { if (permissionsEventHandler != null) { PermissionEvent += permissionsEventHandler; } } /// <summary> /// Unregister from the permission callbacks. /// /// See TangoApplication.RegisterPermissionsCallback for more details. /// </summary> /// <param name="permissionsEventHandler">Event to remove.</param> private void _UnregisterPermissionsCallback(PermissionsEvent permissionsEventHandler) { if (permissionsEventHandler != null) { PermissionEvent -= permissionsEventHandler; } } /// <summary> /// Register to get an event callback when connected to the Tango service. /// /// The passed event will get called once connected to the Tango service. Registering /// after already connected will cause the event to not fire until disconnected and then /// connecting again. /// </summary> /// <param name="handler">Event to call.</param> private void _RegisterOnTangoConnect(OnTangoConnectEventHandler handler) { if (handler != null) { OnTangoConnect += handler; } } /// <summary> /// Unregister from the callback when connected to the Tango service. /// /// See TangoApplication.RegisterOnTangoConnect for more details. /// </summary> /// <param name="handler">Event to remove.</param> private void _UnregisterOnTangoConnect(OnTangoConnectEventHandler handler) { if (handler != null) { OnTangoConnect -= handler; } } /// <summary> /// Register to get an event callback when disconnected from the Tango service. /// /// The passed event will get called when disconnected from the Tango service. /// </summary> /// <param name="handler">Event to remove.</param> private void _RegisterOnTangoDisconnect(OnTangoDisconnectEventHandler handler) { if (handler != null) { OnTangoDisconnect += handler; } } /// <summary> /// Unregister from the callback when disconnected from the Tango service. /// /// See TangoApplication.RegisterOnTangoDisconnect for more details. /// </summary> /// <param name="handler">Event to remove.</param> private void _UnregisterOnTangoDisconnect(OnTangoDisconnectEventHandler handler) { if (handler != null) { OnTangoDisconnect -= handler; } } /// <summary> /// Helper method that will resume the tango services on App Resume. /// Locks the config again and connects the service. /// </summary> private void _ResumeTangoServices() { RequestPermissions(); } /// <summary> /// Helper method that will suspend the tango services on App Suspend. /// Unlocks the tango config and disconnects the service. /// </summary> private void _SuspendTangoServices() { Debug.Log("Suspending Tango Service"); _TangoDisconnect(); } /// <summary> /// Set callbacks on all PoseListener objects. /// </summary> /// <param name="framePairs">Frame pairs.</param> private void _SetMotionTrackingCallbacks(TangoCoordinateFramePair[] framePairs) { Debug.Log("TangoApplication._SetMotionTrackingCallbacks()"); if (m_poseListener != null) { m_poseListener.AutoReset = m_motionTrackingAutoReset; m_poseListener.SetCallback(framePairs); } } /// <summary> /// Set callbacks for all DepthListener objects. /// </summary> private void _SetDepthCallbacks() { Debug.Log("TangoApplication._SetDepthCallbacks()"); if (m_depthListener != null) { m_depthListener.SetCallback(); } } /// <summary> /// Set callbacks for all TangoEventListener objects. /// </summary> private void _SetEventCallbacks() { Debug.Log("TangoApplication._SetEventCallbacks()"); if (m_tangoEventListener != null) { m_tangoEventListener.SetCallback(); } } /// <summary> /// Set callbacks for all VideoOverlayListener objects. /// </summary> private void _SetVideoOverlayCallbacks() { Debug.Log("TangoApplication._SetVideoOverlayCallbacks()"); if (m_videoOverlayListener != null) { m_videoOverlayListener.SetCallback(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, m_useExperimentalVideoOverlay, m_yuvTexture); } } /// <summary> /// Initialize motion tracking. /// </summary> /// <param name="uuid">ADF UUID to load.</param> private void _InitializeMotionTracking(string uuid) { Debug.Log("TangoApplication._InitializeMotionTracking(" + uuid + ")"); System.Collections.Generic.List<TangoCoordinateFramePair> framePairs = new System.Collections.Generic.List<TangoCoordinateFramePair>(); if (m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_MOTION_TRACKING_BOOL, m_enableMotionTracking) && m_enableMotionTracking) { TangoCoordinateFramePair motionTracking; motionTracking.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE; motionTracking.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; framePairs.Add(motionTracking); bool areaLearningEnabled = false; if (m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_AREA_LEARNING_BOOL, m_enableAreaLearning) && m_enableAreaLearning) { areaLearningEnabled = true; Debug.Log("Area Learning is enabled."); } // For backward compatibility, don't require the m_enableADFLoading to be set. if (areaLearningEnabled || m_enableADFLoading) { if (!string.IsNullOrEmpty(uuid)) { m_tangoConfig.SetString(TangoConfig.Keys.LOAD_AREA_DESCRIPTION_UUID_STRING, uuid); } } if (areaLearningEnabled || m_enableADFLoading) { TangoCoordinateFramePair areaDescription; areaDescription.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION; areaDescription.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; TangoCoordinateFramePair startToADF; startToADF.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION; startToADF.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE; framePairs.Add(areaDescription); framePairs.Add(startToADF); } } if (framePairs.Count > 0) { _SetMotionTrackingCallbacks(framePairs.ToArray()); } // The C API does not default this to on, but it is locked down. m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_LOW_LATENCY_IMU_INTEGRATION, true); m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_MOTION_TRACKING_AUTO_RECOVERY_BOOL, m_motionTrackingAutoReset); if (m_enableCloudADF) { Debug.Log("Connect to Cloud Service."); AndroidHelper.ConnectCloud(); } } /// <summary> /// Validate the TangoService version is supported. /// </summary> private void _CheckTangoVersion() { int tangoVersion = _GetTangoAPIVersion(); if (tangoVersion < MINIMUM_API_VERSION) { Debug.Log(string.Format(CLASS_NAME + ".Initialize() Invalid API version {0}. Please update Project Tango Core to at least {1}.", tangoVersion, MINIMUM_API_VERSION)); if (!m_allowOutOfDateTangoAPI) { AndroidHelper.ShowAndroidToastMessage("Please update Tango Core"); return; } } m_isServiceInitialized = true; Debug.Log(CLASS_NAME + ".Initialize() Tango was initialized!"); } /// <summary> /// Connect to the Tango Service. /// </summary> private void _TangoConnect() { Debug.Log("TangoApplication._TangoConnect()"); if (!m_isServiceInitialized) { return; } if (!m_isServiceConnected) { m_isServiceConnected = true; AndroidHelper.PerformanceLog("Unity _TangoConnect start"); if (TangoServiceAPI.TangoService_connect(m_callbackContext, m_tangoConfig.GetHandle()) != Common.ErrorType.TANGO_SUCCESS) { AndroidHelper.ShowAndroidToastMessage("Failed to connect to Tango Service."); Debug.Log(CLASS_NAME + ".Connect() Could not connect to the Tango Service!"); } else { AndroidHelper.PerformanceLog("Unity _TangoConnect end"); Debug.Log(CLASS_NAME + ".Connect() Tango client connected to service!"); if (OnTangoConnect != null) { OnTangoConnect(); } } } } /// <summary> /// Disconnect from the Tango Service. /// </summary> private void _TangoDisconnect() { Debug.Log(CLASS_NAME + ".Disconnect() Disconnecting from the Tango Service"); m_isServiceConnected = false; if (TangoServiceAPI.TangoService_disconnect() != Common.ErrorType.TANGO_SUCCESS) { Debug.Log(CLASS_NAME + ".Disconnect() Could not disconnect from the Tango Service!"); } else { Debug.Log(CLASS_NAME + ".Disconnect() Tango client disconnected from service!"); if (OnTangoDisconnect != null) { OnTangoDisconnect(); } } if (m_enableCloudADF) { Debug.Log("Disconnect from Cloud Service."); AndroidHelper.DisconnectCloud(); } } /// <summary> /// Android on pause. /// </summary> private void _androidOnPause() { if (m_isServiceConnected && m_requiredPermissions == PermissionsTypes.NONE) { Debug.Log("Pausing services"); m_shouldReconnectService = true; _SuspendTangoServices(); } Debug.Log("androidOnPause done"); } /// <summary> /// Android on resume. /// </summary> private void _androidOnResume() { if (m_shouldReconnectService) { Debug.Log("Resuming services"); m_shouldReconnectService = false; _ResumeTangoServices(); } Debug.Log("androidOnResume done"); } /// <summary> /// EventHandler for Android's on activity result. /// </summary> /// <param name="requestCode">Request code.</param> /// <param name="resultCode">Result code.</param> /// <param name="data">Intent data.</param> private void _androidOnActivityResult(int requestCode, int resultCode, AndroidJavaObject data) { Debug.Log("Activity returned result code : " + resultCode); switch (requestCode) { case Common.TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE: { if (resultCode == (int)Common.AndroidResult.SUCCESS) { _FlipBitAndCheckPermissions(PermissionsTypes.MOTION_TRACKING); } else { _PermissionWasDenied(); } break; } case Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE: { if (resultCode == (int)Common.AndroidResult.SUCCESS) { _FlipBitAndCheckPermissions(PermissionsTypes.AREA_LEARNING); } else { _PermissionWasDenied(); } break; } default: { break; } } Debug.Log("Activity returned result end"); } /// <summary> /// Awake this instance. /// </summary> private void Awake() { AndroidHelper.RegisterPauseEvent(_androidOnPause); AndroidHelper.RegisterResumeEvent(_androidOnResume); AndroidHelper.RegisterOnActivityResultEvent(_androidOnActivityResult); // Setup listeners. m_tangoEventListener = new TangoEventListener(); m_areaDescriptionEventListener = new AreaDescriptionEventListener(); if (m_enableCloudADF) { m_tangoCloudEventListener = new TangoCloudEventListener(); } if (m_enableMotionTracking) { m_poseListener = new PoseListener(); } if (m_enableDepth) { m_depthListener = new DepthListener(); } if (m_enableVideoOverlay) { int yTextureWidth = 0; int yTextureHeight = 0; int uvTextureWidth = 0; int uvTextureHeight = 0; m_yuvTexture = new YUVTexture(yTextureWidth, yTextureHeight, uvTextureWidth, uvTextureHeight, TextureFormat.RGBA32, false); m_videoOverlayListener = new VideoOverlayListener(); } // Setup configs. m_tangoConfig = new TangoConfig(TangoEnums.TangoConfigType.TANGO_CONFIG_DEFAULT); m_tangoRuntimeConfig = new TangoConfig(TangoEnums.TangoConfigType.TANGO_CONFIG_RUNTIME); } /// <summary> /// Reset permissions flags. /// </summary> private void _ResetPermissionsFlags() { if (m_requiredPermissions == PermissionsTypes.NONE) { m_requiredPermissions |= m_enableAreaLearning ? PermissionsTypes.AREA_LEARNING : PermissionsTypes.NONE; m_requiredPermissions |= m_enableADFLoading ? PermissionsTypes.AREA_LEARNING : PermissionsTypes.NONE; } } /// <summary> /// Flip a permission bit and check to see if all permissions were accepted. /// </summary> /// <param name="permission">Permission bit to flip.</param> private void _FlipBitAndCheckPermissions(PermissionsTypes permission) { m_requiredPermissions ^= permission; if (m_requiredPermissions == 0) { // all permissions are good! Debug.Log("All permissions have been accepted!"); _SendPermissionEvent(true); } else { _RequestNextPermission(); } } /// <summary> /// A Tango permission was denied. /// </summary> private void _PermissionWasDenied() { m_requiredPermissions = PermissionsTypes.NONE; if (PermissionEvent != null) { _SendPermissionEvent(false); } } /// <summary> /// Request next permission. /// </summary> private void _RequestNextPermission() { Debug.Log("TangoApplication._RequestNextPermission()"); // if no permissions are needed let's kick-off the Tango connect if (m_requiredPermissions == PermissionsTypes.NONE) { _SendPermissionEvent(true); } if ((m_requiredPermissions & PermissionsTypes.MOTION_TRACKING) == PermissionsTypes.MOTION_TRACKING) { if (AndroidHelper.ApplicationHasTangoPermissions(Common.TANGO_MOTION_TRACKING_PERMISSIONS)) { _androidOnActivityResult(Common.TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE, -1, null); } else { AndroidHelper.StartTangoPermissionsActivity(Common.TANGO_MOTION_TRACKING_PERMISSIONS); } } else if ((m_requiredPermissions & PermissionsTypes.AREA_LEARNING) == PermissionsTypes.AREA_LEARNING) { if (AndroidHelper.ApplicationHasTangoPermissions(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS)) { _androidOnActivityResult(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE, -1, null); } else { AndroidHelper.StartTangoPermissionsActivity(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS); } } } /// <summary> /// Sends the permission event. /// </summary> /// <param name="permissions">If set to <c>true</c> permissions.</param> private void _SendPermissionEvent(bool permissions) { m_sendPermissions = true; m_permissionsSuccessful = permissions; } /// <summary> /// Disperse any events related to Tango functionality. /// </summary> private void Update() { // Autoconnect requesting permissions can not be moved earlier into Awake() or Start(). All other scripts // must be able to register for the permissions callback before RequestPermissions() is called. The // earliest another script can register is in Start(). Therefore, this logic must be run after Start() has // run on all scripts. That means it must be in FixedUpdate(), Update(), LateUpdate(), or a coroutine. if (m_autoConnectToService) { if (!m_autoConnectRequestedPermissions) { RequestPermissions(); m_autoConnectRequestedPermissions = true; } } if (m_sendPermissions) { if (PermissionEvent != null) { PermissionEvent(m_permissionsSuccessful); } if (m_permissionsSuccessful && m_autoConnectToService) { Startup(null); } m_sendPermissions = false; } if (m_poseListener != null) { m_poseListener.SendPoseIfAvailable(); } if (m_tangoEventListener != null) { m_tangoEventListener.SendIfTangoEventAvailable(); } if (m_tangoCloudEventListener != null) { m_tangoCloudEventListener.SendIfTangoCloudEventAvailable(); } if (m_depthListener != null) { m_depthListener.SendDepthIfAvailable(); } if (m_videoOverlayListener != null) { m_videoOverlayListener.SendIfVideoOverlayAvailable(); } if (m_areaDescriptionEventListener != null) { m_areaDescriptionEventListener.SendEventIfAvailable(); } } /// <summary> /// Unity callback when this object is destroyed. /// </summary> private void OnDestroy() { Shutdown(); // Clean up configs. if (m_tangoConfig != null) { m_tangoConfig.Dispose(); m_tangoConfig = null; } if (m_tangoRuntimeConfig != null) { m_tangoRuntimeConfig.Dispose(); m_tangoRuntimeConfig = null; } } #region NATIVE_FUNCTIONS /// <summary> /// Interface for native function calls to Tango Service. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "C API Wrapper.")] private struct TangoServiceAPI { #if UNITY_ANDROID && !UNITY_EDITOR [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_initialize(IntPtr jniEnv, IntPtr appContext); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_connect(IntPtr callbackContext, IntPtr config); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_disconnect(); #else public static int TangoService_initialize(IntPtr jniEnv, IntPtr appContext) { return Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_connect(IntPtr callbackContext, IntPtr config) { return Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_disconnect() { return Common.ErrorType.TANGO_SUCCESS; } #endif } #endregion // NATIVE_FUNCTIONS } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.Runtime { public struct TimeoutHelper { public static readonly TimeSpan MaxWait = TimeSpan.FromMilliseconds(Int32.MaxValue); private static readonly CancellationToken s_precancelledToken = new CancellationToken(true); private bool _cancellationTokenInitialized; private bool _deadlineSet; private CancellationToken _cancellationToken; private DateTime _deadline; private TimeSpan _originalTimeout; public TimeoutHelper(TimeSpan timeout) { Contract.Assert(timeout >= TimeSpan.Zero, "timeout must be non-negative"); _cancellationTokenInitialized = false; _originalTimeout = timeout; _deadline = DateTime.MaxValue; _deadlineSet = (timeout == TimeSpan.MaxValue); } public CancellationToken GetCancellationToken() { return GetCancellationTokenAsync().Result; } public async Task<CancellationToken> GetCancellationTokenAsync() { if (!_cancellationTokenInitialized) { var timeout = RemainingTime(); if (timeout >= MaxWait || timeout == Timeout.InfiniteTimeSpan) { _cancellationToken = CancellationToken.None; } else if (timeout > TimeSpan.Zero) { _cancellationToken = await TimeoutTokenSource.FromTimeoutAsync((int)timeout.TotalMilliseconds); } else { _cancellationToken = s_precancelledToken; } _cancellationTokenInitialized = true; } return _cancellationToken; } public TimeSpan OriginalTimeout { get { return _originalTimeout; } } public static bool IsTooLarge(TimeSpan timeout) { return (timeout > TimeoutHelper.MaxWait) && (timeout != TimeSpan.MaxValue); } public static TimeSpan FromMilliseconds(int milliseconds) { if (milliseconds == Timeout.Infinite) { return TimeSpan.MaxValue; } else { return TimeSpan.FromMilliseconds(milliseconds); } } public static int ToMilliseconds(TimeSpan timeout) { if (timeout == TimeSpan.MaxValue) { return Timeout.Infinite; } else { long ticks = Ticks.FromTimeSpan(timeout); if (ticks / TimeSpan.TicksPerMillisecond > int.MaxValue) { return int.MaxValue; } return Ticks.ToMilliseconds(ticks); } } public static TimeSpan Min(TimeSpan val1, TimeSpan val2) { if (val1 > val2) { return val2; } else { return val1; } } public static TimeSpan Add(TimeSpan timeout1, TimeSpan timeout2) { return Ticks.ToTimeSpan(Ticks.Add(Ticks.FromTimeSpan(timeout1), Ticks.FromTimeSpan(timeout2))); } public static DateTime Add(DateTime time, TimeSpan timeout) { if (timeout >= TimeSpan.Zero && DateTime.MaxValue - time <= timeout) { return DateTime.MaxValue; } if (timeout <= TimeSpan.Zero && DateTime.MinValue - time >= timeout) { return DateTime.MinValue; } return time + timeout; } public static DateTime Subtract(DateTime time, TimeSpan timeout) { return Add(time, TimeSpan.Zero - timeout); } public static TimeSpan Divide(TimeSpan timeout, int factor) { if (timeout == TimeSpan.MaxValue) { return TimeSpan.MaxValue; } return Ticks.ToTimeSpan((Ticks.FromTimeSpan(timeout) / factor) + 1); } public TimeSpan RemainingTime() { if (!_deadlineSet) { this.SetDeadline(); return _originalTimeout; } else if (_deadline == DateTime.MaxValue) { return TimeSpan.MaxValue; } else { TimeSpan remaining = _deadline - DateTime.UtcNow; if (remaining <= TimeSpan.Zero) { return TimeSpan.Zero; } else { return remaining; } } } public TimeSpan ElapsedTime() { return _originalTimeout - this.RemainingTime(); } private void SetDeadline() { Contract.Assert(!_deadlineSet, "TimeoutHelper deadline set twice."); _deadline = DateTime.UtcNow + _originalTimeout; _deadlineSet = true; } public static void ThrowIfNegativeArgument(TimeSpan timeout) { ThrowIfNegativeArgument(timeout, "timeout"); } public static void ThrowIfNegativeArgument(TimeSpan timeout, string argumentName) { if (timeout < TimeSpan.Zero) { throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, InternalSR.TimeoutMustBeNonNegative(argumentName, timeout)); } } public static void ThrowIfNonPositiveArgument(TimeSpan timeout) { ThrowIfNonPositiveArgument(timeout, "timeout"); } public static void ThrowIfNonPositiveArgument(TimeSpan timeout, string argumentName) { if (timeout <= TimeSpan.Zero) { throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, InternalSR.TimeoutMustBePositive(argumentName, timeout)); } } public static bool WaitOne(WaitHandle waitHandle, TimeSpan timeout) { ThrowIfNegativeArgument(timeout); if (timeout == TimeSpan.MaxValue) { waitHandle.WaitOne(); return true; } else { // http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx // with exitContext was used in Desktop which is not supported in Net Native or CoreClr return waitHandle.WaitOne(timeout); } } internal static TimeoutException CreateEnterTimedOutException(TimeSpan timeout) { return new TimeoutException(SR.Format(SR.LockTimeoutExceptionMessage, timeout)); } } /// <summary> /// This class coalesces timeout tokens because cancelation tokens with timeouts are more expensive to expose. /// Disposing too many such tokens will cause thread contentions in high throughput scenario. /// /// Tokens with target cancelation time 15ms apart would resolve to the same instance. /// </summary> internal static class TimeoutTokenSource { /// <summary> /// These are constants use to calculate timeout coalescing, for more description see method FromTimeoutAsync /// </summary> private const int CoalescingFactor = 15; private const int GranularityFactor = 2000; private const int SegmentationFactor = CoalescingFactor * GranularityFactor; private static readonly ConcurrentDictionary<long, Task<CancellationToken>> s_tokenCache = new ConcurrentDictionary<long, Task<CancellationToken>>(); private static readonly Action<object> s_deregisterToken = (object state) => { var args = (Tuple<long, CancellationTokenSource>)state; Task<CancellationToken> ignored; try { s_tokenCache.TryRemove(args.Item1, out ignored); } finally { args.Item2.Dispose(); } }; public static CancellationToken FromTimeout(int millisecondsTimeout) { return FromTimeoutAsync(millisecondsTimeout).Result; } public static Task<CancellationToken> FromTimeoutAsync(int millisecondsTimeout) { // Note that CancellationTokenSource constructor requires input to be >= -1, // restricting millisecondsTimeout to be >= -1 would enforce that if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("Invalid millisecondsTimeout value " + millisecondsTimeout); } // To prevent s_tokenCache growing too large, we have to adjust the granularity of the our coalesce depending // on the value of millisecondsTimeout. The coalescing span scales proportionally with millisecondsTimeout which // would garentee constant s_tokenCache size in the case where similar millisecondsTimeout values are accepted. // If the method is given a wildly different millisecondsTimeout values all the time, the dictionary would still // only grow logarithmically with respect to the range of the input values uint currentTime = (uint)Environment.TickCount; long targetTime = millisecondsTimeout + currentTime; // Formula for our coalescing span: // Divide millisecondsTimeout by SegmentationFactor and take the highest bit and then multiply CoalescingFactor back var segmentValue = millisecondsTimeout / SegmentationFactor; var coalescingSpanMs = CoalescingFactor; while (segmentValue > 0) { segmentValue >>= 1; coalescingSpanMs <<= 1; } targetTime = ((targetTime + (coalescingSpanMs - 1)) / coalescingSpanMs) * coalescingSpanMs; Task<CancellationToken> tokenTask; if (!s_tokenCache.TryGetValue(targetTime, out tokenTask)) { var tcs = new TaskCompletionSource<CancellationToken>(TaskCreationOptions.RunContinuationsAsynchronously); // only a single thread may succeed adding its task into the cache if (s_tokenCache.TryAdd(targetTime, tcs.Task)) { // Since this thread was successful reserving a spot in the cache, it would be the only thread // that construct the CancellationTokenSource var tokenSource = new CancellationTokenSource((int)(targetTime - currentTime)); var token = tokenSource.Token; // Clean up cache when Token is canceled token.Register(s_deregisterToken, Tuple.Create(targetTime, tokenSource)); // set the result so other thread may observe the token, and return tcs.TrySetResult(token); tokenTask = tcs.Task; } else { // for threads that failed when calling TryAdd, there should be one already in the cache if (!s_tokenCache.TryGetValue(targetTime, out tokenTask)) { // In unlikely scenario the token was already cancelled and timed out, we would not find it in cache. // In this case we would simply create a non-coalesced token tokenTask = Task.FromResult(new CancellationTokenSource(millisecondsTimeout).Token); } } } return tokenTask; } } }
using System; namespace Versioning { public class CurrencyData : Sage_Container, IData { /* Autogenerated by sage_wrapper_generator.pl */ SageDataObject110.CurrencyData cd11; SageDataObject120.CurrencyData cd12; SageDataObject130.CurrencyData cd13; SageDataObject140.CurrencyData cd14; SageDataObject150.CurrencyData cd15; SageDataObject160.CurrencyData cd16; SageDataObject170.CurrencyData cd17; public CurrencyData(object inner, int version) : base(version) { switch (m_version) { case 11: { cd11 = (SageDataObject110.CurrencyData)inner; m_fields = new Fields(cd11.Fields,m_version); return; } case 12: { cd12 = (SageDataObject120.CurrencyData)inner; m_fields = new Fields(cd12.Fields,m_version); return; } case 13: { cd13 = (SageDataObject130.CurrencyData)inner; m_fields = new Fields(cd13.Fields,m_version); return; } case 14: { cd14 = (SageDataObject140.CurrencyData)inner; m_fields = new Fields(cd14.Fields,m_version); return; } case 15: { cd15 = (SageDataObject150.CurrencyData)inner; m_fields = new Fields(cd15.Fields,m_version); return; } case 16: { cd16 = (SageDataObject160.CurrencyData)inner; m_fields = new Fields(cd16.Fields,m_version); return; } case 17: { cd17 = (SageDataObject170.CurrencyData)inner; m_fields = new Fields(cd17.Fields,m_version); return; } default: throw new InvalidOperationException("ver"); } } /* Autogenerated with data_generator.pl */ const string ACCOUNT_REF = "ACCOUNT_REF"; const string CURRENCYDATA = "CurrencyData"; public bool Open(OpenMode mode) { bool ret; switch (m_version) { case 11: { ret = cd11.Open((SageDataObject110.OpenMode)mode); break; } case 12: { ret = cd12.Open((SageDataObject120.OpenMode)mode); break; } case 13: { ret = cd13.Open((SageDataObject130.OpenMode)mode); break; } case 14: { ret = cd14.Open((SageDataObject140.OpenMode)mode); break; } case 15: { ret = cd15.Open((SageDataObject150.OpenMode)mode); break; } case 16: { ret = cd16.Open((SageDataObject160.OpenMode)mode); break; } case 17: { ret = cd17.Open((SageDataObject170.OpenMode)mode); break; } default: throw new InvalidOperationException("ver"); } return ret; } public void Close() { switch (m_version) { case 11: { cd11.Close(); break; } case 12: { cd12.Close(); break; } case 13: { cd13.Close(); break; } case 14: { cd14.Close(); break; } case 15: { cd15.Close(); break; } case 16: { cd16.Close(); break; } case 17: { cd17.Close(); break; } default: throw new InvalidOperationException("ver"); } } public bool Read(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = cd11.Read(IRecNo); break; } case 12: { ret = cd12.Read(IRecNo); break; } case 13: { ret = cd13.Read(IRecNo); break; } case 14: { ret = cd14.Read(IRecNo); break; } case 15: { ret = cd15.Read(IRecNo); break; } case 16: { ret = cd16.Read(IRecNo); break; } case 17: { ret = cd17.Read(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Write(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = cd11.Write(IRecNo); break; } case 12: { ret = cd12.Write(IRecNo); break; } case 13: { ret = cd13.Write(IRecNo); break; } case 14: { ret = cd14.Write(IRecNo); break; } case 15: { ret = cd15.Write(IRecNo); break; } case 16: { ret = cd16.Write(IRecNo); break; } case 17: { ret = cd17.Write(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Seek(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = cd11.Seek(IRecNo); break; } case 12: { ret = cd12.Seek(IRecNo); break; } case 13: { ret = cd13.Seek(IRecNo); break; } case 14: { ret = cd14.Seek(IRecNo); break; } case 15: { ret = cd15.Seek(IRecNo); break; } case 16: { ret = cd16.Seek(IRecNo); break; } case 17: { ret = cd17.Seek(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Lock(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = cd11.Lock(IRecNo); break; } case 12: { ret = cd12.Lock(IRecNo); break; } case 13: { ret = cd13.Lock(IRecNo); break; } case 14: { ret = cd14.Lock(IRecNo); break; } case 15: { ret = cd15.Lock(IRecNo); break; } case 16: { ret = cd16.Lock(IRecNo); break; } case 17: { ret = cd17.Lock(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Unlock(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = cd11.Unlock(IRecNo); break; } case 12: { ret = cd12.Unlock(IRecNo); break; } case 13: { ret = cd13.Unlock(IRecNo); break; } case 14: { ret = cd14.Unlock(IRecNo); break; } case 15: { ret = cd15.Unlock(IRecNo); break; } case 16: { ret = cd16.Unlock(IRecNo); break; } case 17: { ret = cd17.Unlock(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool FindFirst(object varField, object varSearch) { bool ret; switch (m_version) { case 11: { ret = cd11.FindFirst(varField, varSearch); break; } case 12: { ret = cd12.FindFirst(varField, varSearch); break; } case 13: { ret = cd13.FindFirst(varField, varSearch); break; } case 14: { ret = cd14.FindFirst(varField, varSearch); break; } case 15: { ret = cd15.FindFirst(varField, varSearch); break; } case 16: { ret = cd16.FindFirst(varField, varSearch); break; } case 17: { ret = cd17.FindFirst(varField, varSearch); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool FindNext(object varField, object varSearch) { bool ret; switch (m_version) { case 11: { ret = cd11.FindNext(varField, varSearch); break; } case 12: { ret = cd12.FindNext(varField, varSearch); break; } case 13: { ret = cd13.FindNext(varField, varSearch); break; } case 14: { ret = cd14.FindNext(varField, varSearch); break; } case 15: { ret = cd15.FindNext(varField, varSearch); break; } case 16: { ret = cd16.FindNext(varField, varSearch); break; } case 17: { ret = cd17.FindNext(varField, varSearch); break; } default: throw new InvalidOperationException("ver"); } return ret; } public int Count { get { int ret; switch (m_version) { case 11: { ret = cd11.Count(); break; } case 12: { ret = cd12.Count(); break; } case 13: { ret = cd13.Count(); break; } case 14: { ret = cd14.Count(); break; } case 15: { ret = cd15.Count(); break; } case 16: { ret = cd16.Count(); break; } case 17: { ret = cd17.Count(); break; } default: throw new InvalidOperationException("ver"); } return ret; } } } }
using System; using System.Collections; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.X509 { /// <remarks> /// The Holder object. /// <pre> /// Holder ::= SEQUENCE { /// baseCertificateID [0] IssuerSerial OPTIONAL, /// -- the issuer and serial number of /// -- the holder's Public Key Certificate /// entityName [1] GeneralNames OPTIONAL, /// -- the name of the claimant or role /// objectDigestInfo [2] ObjectDigestInfo OPTIONAL /// -- used to directly authenticate the holder, /// -- for example, an executable /// } /// </pre> /// </remarks> public class AttributeCertificateHolder //: CertSelector, Selector : IX509Selector { internal readonly Holder holder; internal AttributeCertificateHolder( Asn1Sequence seq) { holder = Holder.GetInstance(seq); } public AttributeCertificateHolder( X509Name issuerName, BigInteger serialNumber) { holder = new Holder( new IssuerSerial( GenerateGeneralNames(issuerName), new DerInteger(serialNumber))); } public AttributeCertificateHolder( X509Certificate cert) { X509Name name; try { name = PrincipalUtilities.GetIssuerX509Principal(cert); } catch (Exception e) { throw new CertificateParsingException(e.Message); } holder = new Holder(new IssuerSerial(GenerateGeneralNames(name), new DerInteger(cert.SerialNumber))); } public AttributeCertificateHolder( X509Name principal) { holder = new Holder(GenerateGeneralNames(principal)); } /** * Constructs a holder for v2 attribute certificates with a hash value for * some type of object. * <p> * <code>digestedObjectType</code> can be one of the following: * <ul> * <li>0 - publicKey - A hash of the public key of the holder must be * passed.</li> * <li>1 - publicKeyCert - A hash of the public key certificate of the * holder must be passed.</li> * <li>2 - otherObjectDigest - A hash of some other object type must be * passed. <code>otherObjectTypeID</code> must not be empty.</li> * </ul> * </p> * <p>This cannot be used if a v1 attribute certificate is used.</p> * * @param digestedObjectType The digest object type. * @param digestAlgorithm The algorithm identifier for the hash. * @param otherObjectTypeID The object type ID if * <code>digestedObjectType</code> is * <code>otherObjectDigest</code>. * @param objectDigest The hash value. */ public AttributeCertificateHolder( int digestedObjectType, string digestAlgorithm, string otherObjectTypeID, byte[] objectDigest) { // TODO Allow 'objectDigest' to be null? holder = new Holder(new ObjectDigestInfo(digestedObjectType, otherObjectTypeID, new AlgorithmIdentifier(digestAlgorithm), Arrays.Clone(objectDigest))); } /** * Returns the digest object type if an object digest info is used. * <p> * <ul> * <li>0 - publicKey - A hash of the public key of the holder must be * passed.</li> * <li>1 - publicKeyCert - A hash of the public key certificate of the * holder must be passed.</li> * <li>2 - otherObjectDigest - A hash of some other object type must be * passed. <code>otherObjectTypeID</code> must not be empty.</li> * </ul> * </p> * * @return The digest object type or -1 if no object digest info is set. */ public int DigestedObjectType { get { ObjectDigestInfo odi = holder.ObjectDigestInfo; return odi == null ? -1 : odi.DigestedObjectType.Value.IntValue; } } /** * Returns the other object type ID if an object digest info is used. * * @return The other object type ID or <code>null</code> if no object * digest info is set. */ public string DigestAlgorithm { get { ObjectDigestInfo odi = holder.ObjectDigestInfo; return odi == null ? null : odi.DigestAlgorithm.ObjectID.Id; } } /** * Returns the hash if an object digest info is used. * * @return The hash or <code>null</code> if no object digest info is set. */ public byte[] GetObjectDigest() { ObjectDigestInfo odi = holder.ObjectDigestInfo; return odi == null ? null : odi.ObjectDigest.GetBytes(); } /** * Returns the digest algorithm ID if an object digest info is used. * * @return The digest algorithm ID or <code>null</code> if no object * digest info is set. */ public string OtherObjectTypeID { get { ObjectDigestInfo odi = holder.ObjectDigestInfo; return odi == null ? null : odi.OtherObjectTypeID.Id; } } private GeneralNames GenerateGeneralNames( X509Name principal) { // return GeneralNames.GetInstance(new DerSequence(new GeneralName(principal))); return new GeneralNames(new GeneralName(principal)); } private bool MatchesDN( X509Name subject, GeneralNames targets) { GeneralName[] names = targets.GetNames(); for (int i = 0; i != names.Length; i++) { GeneralName gn = names[i]; if (gn.TagNo == GeneralName.DirectoryName) { try { if (X509Name.GetInstance(gn.Name).Equivalent(subject)) { return true; } } catch (Exception) { } } } return false; } private object[] GetNames( GeneralName[] names) { ArrayList l = new ArrayList(names.Length); for (int i = 0; i != names.Length; i++) { if (names[i].TagNo == GeneralName.DirectoryName) { l.Add(X509Name.GetInstance(names[i].Name)); } } return l.ToArray(); } private X509Name[] GetPrincipals( GeneralNames names) { object[] p = this.GetNames(names.GetNames()); ArrayList l = new ArrayList(p.Length); for (int i = 0; i != p.Length; i++) { if (p[i] is X509Name) { l.Add(p[i]); } } return (X509Name[]) l.ToArray(typeof(X509Name)); } /** * Return any principal objects inside the attribute certificate holder entity names field. * * @return an array of IPrincipal objects (usually X509Name), null if no entity names field is set. */ public X509Name[] GetEntityNames() { if (holder.EntityName != null) { return GetPrincipals(holder.EntityName); } return null; } /** * Return the principals associated with the issuer attached to this holder * * @return an array of principals, null if no BaseCertificateID is set. */ public X509Name[] GetIssuer() { if (holder.BaseCertificateID != null) { return GetPrincipals(holder.BaseCertificateID.Issuer); } return null; } /** * Return the serial number associated with the issuer attached to this holder. * * @return the certificate serial number, null if no BaseCertificateID is set. */ public BigInteger SerialNumber { get { if (holder.BaseCertificateID != null) { return holder.BaseCertificateID.Serial.Value; } return null; } } public object Clone() { return new AttributeCertificateHolder((Asn1Sequence)holder.ToAsn1Object()); } public bool Match( // Certificate cert) X509Certificate x509Cert) { // if (!(cert is X509Certificate)) // { // return false; // } // // X509Certificate x509Cert = (X509Certificate)cert; try { if (holder.BaseCertificateID != null) { return holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer); } if (holder.EntityName != null) { if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName)) { return true; } } if (holder.ObjectDigestInfo != null) { IDigest md = null; try { md = DigestUtilities.GetDigest(DigestAlgorithm); } catch (Exception) { return false; } switch (DigestedObjectType) { case ObjectDigestInfo.PublicKey: { // TODO: DSA Dss-parms //byte[] b = x509Cert.GetPublicKey().getEncoded(); // TODO Is this the right way to encode? byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( x509Cert.GetPublicKey()).GetEncoded(); md.BlockUpdate(b, 0, b.Length); break; } case ObjectDigestInfo.PublicKeyCert: { byte[] b = x509Cert.GetEncoded(); md.BlockUpdate(b, 0, b.Length); break; } // TODO Default handler? } // TODO Shouldn't this be the other way around? if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest())) { return false; } } } catch (CertificateEncodingException) { return false; } return false; } public override bool Equals( object obj) { if (obj == this) { return true; } if (!(obj is AttributeCertificateHolder)) { return false; } AttributeCertificateHolder other = (AttributeCertificateHolder)obj; return this.holder.Equals(other.holder); } public override int GetHashCode() { return this.holder.GetHashCode(); } public bool Match( object obj) { if (!(obj is X509Certificate)) { return false; } // return Match((Certificate)obj); return Match((X509Certificate)obj); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; namespace System.Globalization { public partial class CompareInfo { internal unsafe CompareInfo(CultureInfo culture) { // TODO: Implement This Fully. } internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Contract.Assert(source != null); Contract.Assert(value != null); // TODO: Implement This Fully. if (value.Length == 0) { return startIndex; } if (ignoreCase) { source = source.ToUpper(CultureInfo.InvariantCulture); value = value.ToUpper(CultureInfo.InvariantCulture); } source = source.Substring(startIndex, count); for (int i = 0; i + value.Length <= source.Length; i++) { for (int j = 0; j < value.Length; j++) { if (source[i + j] != value[j]) { break; } if (j == value.Length - 1) { return i + startIndex; } } } return -1; } internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Contract.Assert(source != null); Contract.Assert(value != null); // TODO: Implement This Fully. if (value.Length == 0) { return startIndex; } if (ignoreCase) { source = source.ToUpper(CultureInfo.InvariantCulture); value = value.ToUpper(CultureInfo.InvariantCulture); } source = source.Substring(startIndex - count + 1, count); int last = -1; int cur = 0; while ((cur = IndexOfOrdinal(source, value, last + 1, source.Length - last - 1, false)) != -1) { last = cur; } return last >= 0 ? last + startIndex - count + 1 : -1; } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Contract.Assert(source != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); // TODO: Implement This Fully. int hash = 5381; unchecked { for (int i = 0; i < source.Length; i++) { hash = ((hash << 5) + hash) + ChangeCaseAscii(source[i]); } } return hash; } [System.Security.SecuritySafeCritical] private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { // TODO: Implement This Fully. return CompareStringOrdinalAscii(string1, count1, string2, count2, ignoreCase: true); } [System.Security.SecuritySafeCritical] private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { Contract.Assert(string1 != null); Contract.Assert(string2 != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); // TODO: Implement This Fully. string s1 = string1.Substring(offset1, length1); string s2 = string2.Substring(offset2, length2); fixed (char* c1 = s1) { fixed (char* c2 = s2) { return CompareStringOrdinalAscii(c1, s1.Length, c2, s2.Length, IgnoreCase(options)); } } } private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(target != null); Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Implement This Fully. return IndexOfOrdinal(source, target, startIndex, count, IgnoreCase(options)); } private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(target != null); Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Implement This Fully. return LastIndexOfOrdinal(source, target, startIndex, count, IgnoreCase(options)); } private bool StartsWith(string source, string prefix, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(!string.IsNullOrEmpty(prefix)); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); // TODO: Implement This Fully. if(prefix.Length > source.Length) return false; return StringEqualsAscii(source.Substring(0, prefix.Length), prefix, IgnoreCase(options)); } private bool EndsWith(string source, string suffix, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(!string.IsNullOrEmpty(suffix)); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); // TODO: Implement This Fully. if(suffix.Length > source.Length) return false; return StringEqualsAscii(source.Substring(source.Length - suffix.Length), suffix, IgnoreCase(options)); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private static char ChangeCaseAscii(char c, bool toUpper = true) { if (toUpper && c >= 'a' && c <= 'z') { return (char)('A' + (c - 'a')); } else if (!toUpper && c >= 'A' && c <= 'Z') { return (char)('a' + (c - 'A')); } return c; } private static bool StringEqualsAscii(string s1, string s2, bool ignoreCase = true) { if (s1.Length != s2.Length) return false; for (int i = 0; i < s1.Length; i++) { char c1 = ignoreCase ? ChangeCaseAscii(s1[i]) : s1[i]; char c2 = ignoreCase ? ChangeCaseAscii(s2[i]) : s2[i]; if (c1 != c2) return false; } return true; } [System.Security.SecuritySafeCritical] private static unsafe int CompareStringOrdinalAscii(char* s1, int count1, char* s2, int count2, bool ignoreCase) { int countMin = Math.Min(count1, count2); { for (int i = 0; i < countMin; i++) { char c1 = ignoreCase ? ChangeCaseAscii(s1[i]) : s1[i]; char c2 = ignoreCase ? ChangeCaseAscii(s2[i]) : s2[i]; if (c1 < c2) { return -1; } else if (c1 > c2) { return 1; } } } if (count1 == count2) return 0; if (count1 > count2) return 1; return -1; } private static bool IgnoreCase(CompareOptions options) { return ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase); } } }
// Copyright (C) 2014 - 2015 Stephan Bouchard - All Rights Reserved // This code can only be used under the standard Unity Asset Store End User License Agreement // A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms using UnityEngine; using UnityEditor; using System.Collections; namespace TMPro.EditorUtilities { [CustomEditor(typeof(TextMeshProFont))] public class TMPro_FontEditor : Editor { private struct UI_PanelState { public static bool fontInfoPanel = true; public static bool glyphInfoPanel = false; public static bool kerningInfoPanel = true; } private int m_page = 0; private const string k_UndoRedo = "UndoRedoPerformed"; private SerializedProperty font_atlas_prop; private SerializedProperty font_material_prop; private SerializedProperty font_normalStyle_prop; private SerializedProperty font_boldStyle_prop; private SerializedProperty font_boldSpacing_prop; private SerializedProperty font_italicStyle_prop; private SerializedProperty font_tabSize_prop; private SerializedProperty m_fontInfo_prop; private SerializedProperty m_glyphInfoList_prop; private SerializedProperty m_kerningInfo_prop; private KerningTable m_kerningTable; private SerializedProperty m_kerningPair_prop; private TextMeshProFont m_fontAsset; private bool isAssetDirty = false; private int errorCode; private System.DateTime timeStamp; private string[] uiStateLabel = new string[] { "<i>(Click to expand)</i>", "<i>(Click to collapse)</i>" }; public void OnEnable() { font_atlas_prop = serializedObject.FindProperty("atlas"); font_material_prop = serializedObject.FindProperty("material"); font_normalStyle_prop = serializedObject.FindProperty("NormalStyle"); font_boldStyle_prop = serializedObject.FindProperty("BoldStyle"); font_boldSpacing_prop = serializedObject.FindProperty("boldSpacing"); font_italicStyle_prop = serializedObject.FindProperty("ItalicStyle"); font_tabSize_prop = serializedObject.FindProperty("TabSize"); m_fontInfo_prop = serializedObject.FindProperty("m_fontInfo"); m_glyphInfoList_prop = serializedObject.FindProperty("m_glyphInfoList"); m_kerningInfo_prop = serializedObject.FindProperty("m_kerningInfo"); m_kerningPair_prop = serializedObject.FindProperty("m_kerningPair"); //m_isGlyphInfoListExpanded_prop = serializedObject.FindProperty("isGlyphInfoListExpanded"); //m_isKerningTableExpanded_prop = serializedObject.FindProperty("isKerningTableExpanded"); m_fontAsset = target as TextMeshProFont; m_kerningTable = m_fontAsset.kerningInfo; // Get the UI Skin and Styles for the various Editors TMP_UIStyleManager.GetUIStyles(); } public override void OnInspectorGUI() { //Debug.Log("OnInspectorGUI Called."); Event evt = Event.current; serializedObject.Update(); GUILayout.Label("<b>TextMesh Pro! Font Asset</b>", TMP_UIStyleManager.Section_Label); // TextMeshPro Font Info Panel GUILayout.Label("Face Info", TMP_UIStyleManager.Section_Label); EditorGUI.indentLevel = 1; GUI.enabled = false; // Lock UI float labelWidth = EditorGUIUtility.labelWidth = 135f; float fieldWidth = EditorGUIUtility.fieldWidth; EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Name"), new GUIContent("Font Source")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("PointSize")); GUI.enabled = true; EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("LineHeight")); //GUI.enabled = false; EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Baseline")); GUI.enabled = true; EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Ascender")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Descender")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Underline")); //EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("UnderlineThickness")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SuperscriptOffset")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("SubscriptOffset")); SerializedProperty subSize_prop = m_fontInfo_prop.FindPropertyRelative("SubSize"); EditorGUILayout.PropertyField(subSize_prop); subSize_prop.floatValue = Mathf.Clamp(subSize_prop.floatValue, 0.25f, 1f); GUI.enabled = false; //EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding")); //GUILayout.Label("Atlas Size"); EditorGUI.indentLevel = 1; GUILayout.Space(18); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasWidth"), new GUIContent("Width")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasHeight"), new GUIContent("Height")); GUI.enabled = true; EditorGUI.indentLevel = 0; GUILayout.Space(20); GUILayout.Label("Font Sub-Assets", TMP_UIStyleManager.Section_Label); GUI.enabled = false; EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas:")); EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material:")); GUI.enabled = true; // Font SETTINGS GUILayout.Space(10); GUILayout.Label("Face Style", TMP_UIStyleManager.Section_Label); string evt_cmd = Event.current.commandName; // Get Current Event CommandName to check for Undo Events EditorGUILayout.BeginHorizontal(); EditorGUIUtility.labelWidth = 110f; EditorGUIUtility.fieldWidth = 30f; EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Normal Weight")); font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3.0f, 3.0f); if (GUI.changed || evt_cmd == k_UndoRedo) { GUI.changed = false; Material mat = font_material_prop.objectReferenceValue as Material; mat.SetFloat("_WeightNormal", font_normalStyle_prop.floatValue); } EditorGUIUtility.labelWidth = 90f; EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold Weight")); font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3.0f, 3.0f); if (GUI.changed || evt_cmd == k_UndoRedo) { GUI.changed = false; Material mat = font_material_prop.objectReferenceValue as Material; mat.SetFloat("_WeightBold", font_boldStyle_prop.floatValue); } EditorGUIUtility.labelWidth = 100f; EditorGUILayout.PropertyField(font_boldSpacing_prop, new GUIContent("Bold Spacing")); font_boldSpacing_prop.floatValue = Mathf.Clamp(font_boldSpacing_prop.floatValue, 0, 100); if (GUI.changed || evt_cmd == k_UndoRedo) { GUI.changed = false; } EditorGUIUtility.labelWidth = labelWidth; EditorGUIUtility.fieldWidth = fieldWidth; EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Style: ")); font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60); EditorGUILayout.PropertyField(font_tabSize_prop, new GUIContent("Tab Multiple: ")); EditorGUILayout.EndHorizontal(); GUILayout.Space(10); EditorGUI.indentLevel = 0; if (GUILayout.Button("Glyph Info \t\t\t" + (UI_PanelState.glyphInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label)) UI_PanelState.glyphInfoPanel = !UI_PanelState.glyphInfoPanel; if (UI_PanelState.glyphInfoPanel) { //Rect lastRect = GUILayoutUtility.GetLastRect(); int arraySize = m_glyphInfoList_prop.arraySize; int itemsPerPage = 15; if (arraySize > 0) { // Display each GlyphInfo entry using the GlyphInfo property drawer. for (int i = itemsPerPage * m_page; i < arraySize && i < itemsPerPage * (m_page + 1); i++) { SerializedProperty glyphInfo = m_glyphInfoList_prop.GetArrayElementAtIndex(i); EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label); EditorGUILayout.PropertyField(glyphInfo); EditorGUILayout.EndVertical(); } } Rect pagePos = EditorGUILayout.GetControlRect(false, 20); pagePos.width /= 2; int shiftMultiplier = evt.shift ? 10 : 1; if (m_page > 0) GUI.enabled = true; else GUI.enabled = false; if (GUI.Button(pagePos, "Previous Page")) m_page -= 1 * shiftMultiplier; pagePos.x += pagePos.width; if (itemsPerPage * (m_page + 1) < arraySize) GUI.enabled = true; else GUI.enabled = false; if (GUI.Button(pagePos, "Next Page")) m_page += 1 * shiftMultiplier; m_page = Mathf.Clamp(m_page, 0, arraySize / itemsPerPage); } // KERNING TABLE PANEL if (GUILayout.Button("Kerning Table Info\t\t\t" + (UI_PanelState.kerningInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label)) UI_PanelState.kerningInfoPanel = !UI_PanelState.kerningInfoPanel; if (UI_PanelState.kerningInfoPanel) { Rect pos; SerializedProperty kerningPairs_prop = m_kerningInfo_prop.FindPropertyRelative("kerningPairs"); int pairCount = kerningPairs_prop.arraySize; EditorGUILayout.BeginHorizontal(); GUILayout.Label("Left Char", TMP_UIStyleManager.TMP_GUISkin.label); GUILayout.Label("Right Char", TMP_UIStyleManager.TMP_GUISkin.label); GUILayout.Label("Offset Value", TMP_UIStyleManager.TMP_GUISkin.label); GUILayout.Label(GUIContent.none, GUILayout.Width(20)); EditorGUILayout.EndHorizontal(); GUILayout.BeginVertical(TMP_UIStyleManager.TMP_GUISkin.label); for (int i = 0; i < pairCount; i++) { SerializedProperty kerningPair_prop = kerningPairs_prop.GetArrayElementAtIndex(i); pos = EditorGUILayout.BeginHorizontal(); EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), kerningPair_prop, GUIContent.none); // Button to Delete Kerning Pair if (GUILayout.Button("-", GUILayout.ExpandWidth(false))) { m_kerningTable.RemoveKerningPair(i); m_fontAsset.ReadFontDefinition(); // Reload Font Definition. serializedObject.Update(); // Get an updated version of the SerializedObject. isAssetDirty = true; break; } EditorGUILayout.EndHorizontal(); } GUILayout.EndVertical(); GUILayout.Space(10); // Add New Kerning Pair Section GUILayout.BeginVertical(TMP_UIStyleManager.SquareAreaBox85G); pos = EditorGUILayout.BeginHorizontal(); // Draw Empty Kerning Pair EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), m_kerningPair_prop); GUILayout.Label(GUIContent.none, GUILayout.Height(19)); EditorGUILayout.EndHorizontal(); GUILayout.Space(5); if (GUILayout.Button("Add New Kerning Pair")) { int asci_left = m_kerningPair_prop.FindPropertyRelative("AscII_Left").intValue; int asci_right = m_kerningPair_prop.FindPropertyRelative("AscII_Right").intValue; float xOffset = m_kerningPair_prop.FindPropertyRelative("XadvanceOffset").floatValue; errorCode = m_kerningTable.AddKerningPair(asci_left, asci_right, xOffset); // Sort Kerning Pairs & Reload Font Asset if new kerning pair was added. if (errorCode != -1) { m_kerningTable.SortKerningPairs(); m_fontAsset.ReadFontDefinition(); // Reload Font Definition. serializedObject.Update(); // Get an updated version of the SerializedObject. isAssetDirty = true; } else { timeStamp = System.DateTime.Now.AddSeconds(5); } } if (errorCode == -1) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label("Kerning Pair already <color=#ffff00>exists!</color>", TMP_UIStyleManager.Label); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); if (System.DateTime.Now > timeStamp) errorCode = 0; } GUILayout.EndVertical(); } if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty) { //Debug.Log("Serialized properties have changed."); TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset); isAssetDirty = false; EditorUtility.SetDirty(target); //TMPro_EditorUtility.RepaintAll(); // Consider SetDirty } } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.CoreModules.Scripting.HttpRequest { public class HttpRequestObject : IServiceRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool _finished = false; public bool Finished { get { return _finished; } } private int _HttpBodyMaxLength = 2048; public int HttpBodyMaxLength { get { return _HttpBodyMaxLength; } set { if ((value > 0) && (value <= 16384)) _HttpBodyMaxLength = value; } } // Parameter members and default values public string HttpMethod = "GET"; public string HttpMIMEType = "text/plain;charset=utf-8"; public int HttpTimeout; public bool HttpVerifyCert = true; public bool HttpVerboseThrottle = true; // Request info private UUID _itemID; public UUID ItemID { get { return _itemID; } set { _itemID = value; } } private uint _localID; public uint LocalID { get { return _localID; } set { _localID = value; } } public UUID SogID { get; set; } public DateTime Next; public string proxyurl; public string proxyexcepts; public string OutboundBody; private UUID _reqID; public UUID ReqID { get { return _reqID; } set { _reqID = value; } } public HttpWebRequest Request; public string ResponseBody; public List<string> ResponseMetadata; public Dictionary<string, string> ResponseHeaders; public int Status; public string Url; public ulong RequestDuration {get; set;} public bool IsLowPriority { get; set; } public void Process() { _finished = false; SendRequest(); } // Supports http://httpwg.org/specs/rfc7233.html#byte.ranges // e.g. "range: bytes=200-299", or "range: bytes=300-" or "range: bytes=-99,100-199,200-" private void AddRequestRanges(string headerValue) { string temp = headerValue.Trim(); if (temp.IndexOf("bytes") != 0) return; temp = temp.Remove(0, 5).Trim(); if (temp.IndexOf("=") != 0) return; string remaining = temp.Remove(0, 1).Trim(); int start, end; while (remaining.Length > 0) { string chunk; int pos = remaining.IndexOf(","); if (pos > 0) { // more than one range chunk = remaining.Substring(0, pos).Trim(); remaining = remaining.Remove(0, pos + 1).Trim(); } else { // just this one range chunk = remaining; remaining = String.Empty; } // chunk has one range in it pos = chunk.IndexOf("-"); if (pos == 0) { // no starting value start = 0; } else { start = Convert.ToInt32(chunk.Substring(0,pos)); } temp = chunk.Substring(pos+1); if (temp.Length > 0) end = Convert.ToInt32(temp); else // no end value end = int.MaxValue; Request.AddRange(start,end); } } /* * TODO: More work on the response codes. Right now * returning 200 for success or 499 for exception */ public void SendRequest() { HttpWebResponse response = null; ulong requestStart = Util.GetLongTickCount(); try { Request = (HttpWebRequest)WebRequest.Create(Url); Request.Method = HttpMethod; Request.ContentType = HttpMIMEType; Request.Timeout = HttpTimeout; Request.ReadWriteTimeout = HttpTimeout; if (!HttpVerifyCert) { Request.Headers.Add("NoVerifyCert", "true"); } if (!string.IsNullOrEmpty(proxyurl)) { if (!string.IsNullOrEmpty(proxyexcepts)) { string[] elist = proxyexcepts.Split(';'); Request.Proxy = new WebProxy(proxyurl, true, elist); } else { Request.Proxy = new WebProxy(proxyurl, true); } } foreach (KeyValuePair<string, string> entry in ResponseHeaders) { // There are some headers (like "user-agent") that cannot be set via the Headers member. // See https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers%28v=vs.110%29.aspx if (entry.Key.ToLower().Equals("accept")) Request.Accept = entry.Value; else if (entry.Key.ToLower().Equals("content-length")) Request.ContentLength = Convert.ToInt64(entry.Value); else if (entry.Key.ToLower().Equals("content-type")) Request.ContentType = entry.Value; else if (entry.Key.ToLower().Equals("expect")) Request.Expect = entry.Value; else if (entry.Key.ToLower().Equals("host")) Request.Host = entry.Value; else if (entry.Key.ToLower().Equals("date")) Request.Date = Convert.ToDateTime(entry.Value); else if (entry.Key.ToLower().Equals("if-modified-since")) Request.IfModifiedSince = Convert.ToDateTime(entry.Value); else if (entry.Key.ToLower().Equals("range")) AddRequestRanges(entry.Value); else if (entry.Key.ToLower().Equals("user-agent")) Request.UserAgent = entry.Value; else if (entry.Key.ToLower().Equals("transfer-encoding")) { Request.SendChunked = true; Request.TransferEncoding = entry.Value; } else if (entry.Key.ToLower().Equals("connection")) { string tempValue = entry.Value.ToLower(); int pos = tempValue.IndexOf("keep-alive"); if (pos >= 0) { tempValue = tempValue.Remove(pos, 10).Trim(); Request.KeepAlive = true; } else { Request.KeepAlive = false; } Request.Connection = tempValue; } else Request.Headers[entry.Key] = entry.Value; } // Encode outbound data if (!String.IsNullOrEmpty(OutboundBody)) { byte[] data = Encoding.UTF8.GetBytes(OutboundBody); Request.ContentLength = data.Length; using (Stream requestStream = Request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); requestStream.Close(); } } response = (HttpWebResponse)Request.GetResponse(); Status = (int)response.StatusCode; using (Stream responseStream = response.GetResponseStream()) { int readSoFar = 0; int count = 0; byte[] buf = new byte[HttpBodyMaxLength]; do { count = responseStream.Read(buf, readSoFar, HttpBodyMaxLength - readSoFar); if (count > 0) readSoFar += count; } while (count > 0 && readSoFar < HttpBodyMaxLength); // translate from bytes to ASCII text ResponseBody = Encoding.UTF8.GetString(buf, 0, readSoFar); } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse webRsp = (HttpWebResponse)e.Response; Status = (int)webRsp.StatusCode; ResponseBody = webRsp.StatusDescription; } else { Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = e.Message; } } catch (Exception e) { Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = e.Message; m_log.ErrorFormat("[HTTPREQUEST]: 499 - Exception on httprequest: {0}", e.ToString()); } finally { if (response != null) response.Close(); RequestDuration = Util.GetLongTickCount() - requestStart; } _finished = true; } public void Stop() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryAddTests { #region Test methods [Fact] public static void CheckByteAddTest() { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteAdd(array[i], array[j]); } } } [Fact] public static void CheckSByteAddTest() { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteAdd(array[i], array[j]); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUShortAddTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortAdd(array[i], array[j], useInterpreter); VerifyUShortAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckShortAddTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortAdd(array[i], array[j], useInterpreter); VerifyShortAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUIntAddTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntAdd(array[i], array[j], useInterpreter); VerifyUIntAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIntAddTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntAdd(array[i], array[j], useInterpreter); VerifyIntAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckULongAddTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongAdd(array[i], array[j], useInterpreter); VerifyULongAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLongAddTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongAdd(array[i], array[j], useInterpreter); VerifyLongAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckFloatAddTest(bool useInterpreter) { float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyFloatAdd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDoubleAddTest(bool useInterpreter) { double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDoubleAdd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecimalAddTest(bool useInterpreter) { decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDecimalAdd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckCharAddTest(bool useInterpreter) { char[] array = new char[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyCharAdd(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyByteAdd(byte a, byte b) { Expression aExp = Expression.Constant(a, typeof(byte)); Expression bExp = Expression.Constant(b, typeof(byte)); Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp)); } private static void VerifySByteAdd(sbyte a, sbyte b) { Expression aExp = Expression.Constant(a, typeof(sbyte)); Expression bExp = Expression.Constant(b, typeof(sbyte)); Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp)); } private static void VerifyUShortAdd(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Add( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal(unchecked((ushort)(a + b)), f()); } private static void VerifyUShortAddOvf(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.AddChecked( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); int expected = a + b; if (expected < 0 || expected > ushort.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifyShortAdd(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Add( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal(unchecked((short)(a + b)), f()); } private static void VerifyShortAddOvf(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.AddChecked( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); int expected = a + b; if (expected < short.MinValue || expected > short.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifyUIntAdd(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Add( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a + b), f()); } private static void VerifyUIntAddOvf(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.AddChecked( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); long expected = a + (long)b; if (expected < 0 || expected > uint.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifyIntAdd(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Add( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a + b), f()); } private static void VerifyIntAddOvf(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.AddChecked( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); long expected = a + (long)b; if (expected < int.MinValue || expected > int.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifyULongAdd(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Add( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a + b), f()); } private static void VerifyULongAddOvf(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.AddChecked( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); ulong expected = 0; try { expected = checked(a + b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyLongAdd(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Add( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a + b), f()); } private static void VerifyLongAddOvf(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.AddChecked( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); long expected = 0; try { expected = checked(a + b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyFloatAdd(float a, float b, bool useInterpreter) { Expression<Func<float>> e = Expression.Lambda<Func<float>>( Expression.Add( Expression.Constant(a, typeof(float)), Expression.Constant(b, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<float> f = e.Compile(useInterpreter); float expected = 0; try { expected = checked(a + b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyDoubleAdd(double a, double b, bool useInterpreter) { Expression<Func<double>> e = Expression.Lambda<Func<double>>( Expression.Add( Expression.Constant(a, typeof(double)), Expression.Constant(b, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<double> f = e.Compile(useInterpreter); double expected = 0; try { expected = checked(a + b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyDecimalAdd(decimal a, decimal b, bool useInterpreter) { Expression<Func<decimal>> e = Expression.Lambda<Func<decimal>>( Expression.Add( Expression.Constant(a, typeof(decimal)), Expression.Constant(b, typeof(decimal))), Enumerable.Empty<ParameterExpression>()); Func<decimal> f = e.Compile(useInterpreter); decimal expected = 0; try { expected = a + b; } catch(OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyCharAdd(char a, char b) { Expression aExp = Expression.Constant(a, typeof(char)); Expression bExp = Expression.Constant(b, typeof(char)); Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp)); } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.Add(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void CannotReduceChecked() { Expression exp = Expression.AddChecked(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Add(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Add(Expression.Constant(""), null)); } [Fact] public static void CheckedThrowsOnLeftNull() { AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.AddChecked(null, Expression.Constant(""))); } [Fact] public static void CheckedThrowsOnRightNull() { AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.AddChecked(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("left", () => Expression.Add(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value)); } [Fact] public static void CheckedThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("left", () => Expression.AddChecked(value, Expression.Constant(1))); } [Fact] public static void CheckedThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e1 = Expression.Add(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a + b)", e1.ToString()); BinaryExpression e2 = Expression.AddChecked(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a + b)", e2.ToString()); } } }
// This code is part of the Fungus library (https://github.com/snozbot/fungus) // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.Serialization; using System.Collections.Generic; using System.Globalization; namespace Fungus { /// <summary> /// A Character that can be used in dialogue via the Say, Conversation and Portrait commands. /// </summary> [ExecuteInEditMode] public class Character : MonoBehaviour, ILocalizable, IComparer<Character> { [Tooltip("Character name as displayed in Say Dialog.")] [SerializeField] protected string nameText; // We need a separate name as the object name is used for character variations (e.g. "Smurf Happy", "Smurf Sad") [Tooltip("Color to display the character name in Say Dialog.")] [SerializeField] protected Color nameColor = Color.white; [Tooltip("Sound effect to play when this character is speaking.")] [SerializeField] protected AudioClip soundEffect; [Tooltip("List of portrait images that can be displayed for this character.")] [SerializeField] protected List<Sprite> portraits; [Tooltip("Direction that portrait sprites face.")] [SerializeField] protected FacingDirection portraitsFace; [Tooltip("Sets the active Say dialog with a reference to a Say Dialog object in the scene. This Say Dialog will be used whenever the character speaks.")] [SerializeField] protected SayDialog setSayDialog; [FormerlySerializedAs("notes")] [TextArea(5,10)] [SerializeField] protected string description; protected PortraitState portaitState = new PortraitState(); protected static List<Character> activeCharacters = new List<Character>(); protected virtual void OnEnable() { if (!activeCharacters.Contains(this)) { activeCharacters.Add(this); activeCharacters.Sort(this); } } protected virtual void OnDisable() { activeCharacters.Remove(this); } #region Public members /// <summary> /// Gets the list of active characters. /// </summary> public static List<Character> ActiveCharacters { get { return activeCharacters; } } /// <summary> /// Character name as displayed in Say Dialog. /// </summary> public virtual string NameText { get { return nameText; } } /// <summary> /// Color to display the character name in Say Dialog. /// </summary> public virtual Color NameColor { get { return nameColor; } } /// <summary> /// Sound effect to play when this character is speaking. /// </summary> /// <value>The sound effect.</value> public virtual AudioClip SoundEffect { get { return soundEffect; } } /// <summary> /// List of portrait images that can be displayed for this character. /// </summary> public virtual List<Sprite> Portraits { get { return portraits; } } /// <summary> /// Direction that portrait sprites face. /// </summary> public virtual FacingDirection PortraitsFace { get { return portraitsFace; } } /// <summary> /// Currently display profile sprite for this character. /// </summary> /// <value>The profile sprite.</value> public virtual Sprite ProfileSprite { get; set; } /// <summary> /// Current display state of this character's portrait. /// </summary> /// <value>The state.</value> public virtual PortraitState State { get { return portaitState; } } /// <summary> /// Sets the active Say dialog with a reference to a Say Dialog object in the scene. This Say Dialog will be used whenever the character speaks. /// </summary> public virtual SayDialog SetSayDialog { get { return setSayDialog; } } /// <summary> /// Returns the name of the game object. /// </summary> public string GetObjectName() { return gameObject.name; } /// <summary> /// Returns true if the character name starts with the specified string. Case insensitive. /// </summary> public virtual bool NameStartsWith(string matchString) { #if NETFX_CORE return name.StartsWith(matchString, StringComparison.CurrentCultureIgnoreCase) || nameText.StartsWith(matchString, StringComparison.CurrentCultureIgnoreCase); #else return name.StartsWith(matchString, true, System.Globalization.CultureInfo.CurrentCulture) || nameText.StartsWith(matchString, true, System.Globalization.CultureInfo.CurrentCulture); #endif } /// <summary> /// Returns true if the character name is a complete match to the specified string. Case insensitive. /// </summary> public virtual bool NameMatch(string matchString) { return string.Compare(name, matchString, true, CultureInfo.CurrentCulture) == 0 || string.Compare(nameText, matchString, true, CultureInfo.CurrentCulture) == 0; } public int Compare(Character x, Character y) { if (x == y) return 0; if (y == null) return 1; if (x == null) return -1; return x.name.CompareTo(y.name); } /// <summary> /// Looks for a portrait by name on a character /// If none is found, give a warning and return a blank sprite /// </summary> public virtual Sprite GetPortrait(string portraitString) { if (string.IsNullOrEmpty(portraitString)) { return null; } for (int i = 0; i < portraits.Count; i++) { if (portraits[i] != null && string.Compare(portraits[i].name, portraitString, true) == 0) { return portraits[i]; } } return null; } #endregion #region ILocalizable implementation public virtual string GetStandardText() { return nameText; } public virtual void SetStandardText(string standardText) { nameText = standardText; } public virtual string GetDescription() { return description; } public virtual string GetStringId() { // String id for character names is CHARACTER.<Character Name> return "CHARACTER." + nameText; } #endregion protected virtual void OnValidate() { if (portraits != null && portraits.Count > 1) { portraits.Sort(PortraitUtil.PortraitCompareTo); } } } }
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System.Threading; using System.Threading.Tasks; using Amqp; using Amqp.Framing; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Transactions; namespace Test.Amqp { [TestClass] public class TransactionTests { TestTarget testTarget = new TestTarget(); [ClassInitialize] public static void Initialize(TestContext context) { } // if the project is targeted 4.5.1, TransactionScope can be created with // TransactionScopeAsyncFlowOption.Enabled option, and message can be sent // using SendAsync method. [TestMethod] public void TransactedPosting() { string testName = "TransactedPosting"; int nMsgs = 5; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); // commit using (var ts = new TransactionScope()) { for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName }; sender.Send(message); } ts.Complete(); } // rollback using (var ts = new TransactionScope()) { for (int i = nMsgs; i < nMsgs * 2; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "rollback" + i, GroupId = testName }; sender.Send(message); } } // commit using (var ts = new TransactionScope()) { for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName }; sender.Send(message); } ts.Complete(); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs * 2; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.IsTrue(message.Properties.MessageId.StartsWith("commit")); } connection.Close(); } [TestMethod] public void TransactedRetiring() { string testName = "TransactedRetiring"; int nMsgs = 10; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); // send one extra for validation for (int i = 0; i < nMsgs + 1; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; sender.Send(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); Message[] messages = new Message[nMsgs]; for (int i = 0; i < nMsgs; i++) { messages[i] = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", messages[i].Properties.MessageId); } // commit harf using (var ts = new TransactionScope()) { for (int i = 0; i < nMsgs / 2; i++) { receiver.Accept(messages[i]); } ts.Complete(); } // rollback using (var ts = new TransactionScope()) { for (int i = nMsgs / 2; i < nMsgs; i++) { receiver.Accept(messages[i]); } } // after rollback, messages should be still acquired { Message message = receiver.Receive(); Assert.AreEqual("msg" + nMsgs, message.Properties.MessageId); receiver.Release(message); } // commit using (var ts = new TransactionScope()) { for (int i = nMsgs / 2; i < nMsgs; i++) { receiver.Accept(messages[i]); } ts.Complete(); } // only the last message is left { Message message = receiver.Receive(); Assert.AreEqual("msg" + nMsgs, message.Properties.MessageId); receiver.Accept(message); } // at this point, the queue should have zero messages. // If there are messages, it is a bug in the broker. connection.Close(); } [TestMethod] public void TransactedRetiringAndPosting() { string testName = "TransactedRetiringAndPosting"; int nMsgs = 10; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; sender.Send(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); receiver.SetCredit(2, false); Message message1 = receiver.Receive(); Message message2 = receiver.Receive(); // ack message1 and send a new message in a txn using (var ts = new TransactionScope()) { receiver.Accept(message1); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + nMsgs, GroupId = testName }; sender.Send(message); ts.Complete(); } // ack message2 and send a new message in a txn but abort the txn using (var ts = new TransactionScope()) { receiver.Accept(message2); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + (nMsgs + 1), GroupId = testName }; sender.Send(message1); } receiver.Release(message2); // receive all messages. should see the effect of the first txn receiver.SetCredit(nMsgs, false); for (int i = 1; i <= nMsgs; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.AreEqual("msg" + i, message.Properties.MessageId); } connection.Close(); } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * 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. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Text; using NUnit.Framework; using MindTouch.Tasking; using MindTouch.Dream; using MindTouch.Xml; using MindTouch.Dream.Test; namespace MindTouch.Deki.Tests.PageTests { [TestFixture] public class TemplateTests { /// <summary> /// Create a template with several subpages and import it to page /// </summary> /// <feature> /// <name>GET:pages/{pageid}/subpages</name> /// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3apages%2f%2f%7Bpageid%7D%2f%2fsubpages</uri> /// </feature> /// <expected>Number of subpages for page refelects number of template subpages</expected> [Test] public void TemplateWithManyChildren() { StringBuilder pageContent = new StringBuilder("<p>TEMPLATE_</p><ul>"); int countOfTemplates = Utils.Settings.CountOfRepeats; // Log in as ADMIN Plug p = Utils.BuildPlugForAdmin(); // Create template page string templateid = null; string templatepath = null; DreamMessage msg = PageUtils.CreateRandomPage(p, "TEMPLATE:" + Utils.GenerateUniqueName(), out templateid, out templatepath); // Create countOfTemplates subpages for template. for (int i = 0; i < countOfTemplates; i++) { PageUtils.SavePage(p, templatepath + "/TEMPLATE_" + i, "Page content for " + i); pageContent.Append(string.Format("<li><a class=\"site\" href=\"/#\" template=\"{0}/TEMPLATE_{1}\">TEMPLATE_{1}</a></li>\n", templatepath, i)); } pageContent.Append("</ul>"); // Create a page and invoke template to page string pageid = null; string pagepath = null; msg = PageUtils.CreateRandomPage(p, out pageid, out pagepath); msg = PageUtils.SavePage(p, pagepath, pageContent.ToString()); // Make sure template invoked correctly msg = p.At("pages", pageid, "subpages").Get(); XDoc page = msg.ToDocument(); Assert.IsTrue(page["page.subpage"].ListLength == countOfTemplates, "Number of subpages does not match generated number of templates!"); for (int i = 0; i < countOfTemplates; i++) Assert.IsFalse(page["page.subpage[path='" + pagepath + "/TEMPLATE_" + i + "']"].IsEmpty, "Page doesn't contain one of the subpages defined in template!"); // Clean up PageUtils.DeletePageByID(p, pageid, true); PageUtils.DeletePageByID(p, templateid, true); } /// <summary> /// Create a template with a child tree and save the links to page using [] notation /// </summary> /// <feature> /// <name>GET:pages/{pageid}/subpages</name> /// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3apages%2f%2f%7Bpageid%7D%2f%2fsubpages</uri> /// </feature> /// <assumption>child tree: /Temp_1/Temp_2/Temp_3/.../Temp_N</assumption> /// <expected>Links point to template child tree</expected> [Test] public void TemplateWithChildTree() { int countOfTemplates = Utils.Settings.CountOfRepeats; StringBuilder pageContent = new StringBuilder("<p>TEMPLATE_</p><ul>"); StringBuilder currentTemplateName = new StringBuilder(); // Log in as ADMIN Plug p = Utils.BuildPlugForAdmin(); // Create template page string templateid = null; string templatepath = null; DreamMessage msg = PageUtils.CreateRandomPage(p, "TEMPLATE:" + Utils.GenerateUniqueName(), out templateid, out templatepath); // Create a template page countOfTemplates deep for (int i = 0; i < countOfTemplates; i++) { currentTemplateName.AppendFormat("/TEMPLATE_{0}", i); PageUtils.SavePage(p, templatepath + currentTemplateName.ToString(), "Page content for " + i); // when i use this then count of subpages is 0 pageContent.AppendFormat("<li>[[{0}{1}|{1}]]</li>", templatepath, currentTemplateName); // when i use this then count of outbound links is 0 //pageContent.Append(String.Format("<li><a class=\"site\" href=\"/#\" template=\"{0}{1}\">{1}</a></li>\n", templatepath, currentTemplateName)); } pageContent.Append("</ul>"); // Create a page and invoke template to page string pageid = null; string pagepath = null; msg = PageUtils.CreateRandomPage(p, out pageid, out pagepath); msg = PageUtils.SavePage(p, pagepath, pageContent.ToString()); msg = PageUtils.GetPage(p, pagepath); Assert.IsTrue(msg.ToDocument()["outbound/page"].ListLength == countOfTemplates, "Number of outbound links does not match generated number of templates!"); msg = p.At("pages", pageid, "subpages").Get(); Assert.IsTrue(msg.ToDocument()["page.subpage"].ListLength == 0, "Page has subpages!"); PageUtils.DeletePageByID(p, pageid, true); PageUtils.DeletePageByID(p, templateid, true); } /// <summary> /// Create a template with a child tree and save the links to page using HTML tagging /// </summary> /// <feature> /// <name>GET:pages/{pageid}/subpages</name> /// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3apages%2f%2f%7Bpageid%7D%2f%2fsubpages</uri> /// </feature> /// <assumption>child tree: /Temp_1/Temp_2/Temp_3/.../Temp_N</assumption> /// <expected>Child tree to descend from page that imported template</expected> [Test] public void TemplateWithChildTreeThroughATag() { int countOfTemplates = Utils.Settings.CountOfRepeats; StringBuilder pageContent = new StringBuilder("<p>TEMPLATE_</p><ul>"); StringBuilder currentTemplateName = new StringBuilder(); // Log in as ADMIN Plug p = Utils.BuildPlugForAdmin(); // Create template page string templateid = null; string templatepath = null; DreamMessage msg = PageUtils.CreateRandomPage(p, "TEMPLATE:" + Utils.GenerateUniqueName(), out templateid, out templatepath); // Create template with countOfTemplates pages deep for (int i = 0; i < countOfTemplates; i++) { currentTemplateName.AppendFormat("/TEMPLATE_{0}", i); PageUtils.SavePage(p, templatepath + currentTemplateName.ToString(), "Page content for " + i); // when i use this then count of subpages is 0 //pageContent.AppendFormat("<li>[[{0}{1}|{1}]]</li>", templatepath, currentTemplateName); // when i use this then count of outbound links is 0 pageContent.Append(String.Format("<li><a class=\"site\" href=\"/#\" template=\"{0}{1}\">{1}</a></li>\n", templatepath, currentTemplateName)); } pageContent.Append("</ul>"); // Create page and invoke template string pageid = null; string pagepath = null; msg = PageUtils.CreateRandomPage(p, out pageid, out pagepath); msg = PageUtils.SavePage(p, pagepath, pageContent.ToString()); // Check template invoked correctly msg = PageUtils.GetPage(p, pagepath); Assert.IsTrue(msg.ToDocument()["outbound/page"].ListLength == countOfTemplates, "Number of outbound links does not match generated number of templates!"); msg = p.At("pages", pageid, "subpages").Get(); Assert.IsTrue(msg.ToDocument()["page.subpage"].ListLength == 1, "Page does not have exactly 1 subpage!"); // Clean up PageUtils.DeletePageByID(p, pageid, true); PageUtils.DeletePageByID(p, templateid, true); } [Test] public void InvokeADMINTemplateWithUnsafeContent() { // This test contains two parts: // 1. Invoke template (created by admin) by ADMIN // 2. Invoke template by user without UNSAFECONTENT permissions // // Expected: All content (unsafe included) is present // Log in as ADMIN Plug p = Utils.BuildPlugForAdmin(); // Create a template with unsafe content string safe_content = "<p>This is a template</p>"; string unsafe_content = "<p><script type=\"text/javascript\">document.write(\"With unsafe content\");</script></p>"; string template_content = safe_content + unsafe_content; string template_name = "test" + DateTime.Now.Ticks.ToString(); string template_path = "Template:" + template_name; DreamMessage msg = p.At("pages", "=" + XUri.DoubleEncode(template_path), "contents") .Post(DreamMessage.Ok(MimeType.TEXT_UTF8, template_content), new Result<DreamMessage>()).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Template page creation failed!"); // script contents are injected with CDATA sections, so retrieve contents with injection msg = p.At("pages", "=" + XUri.DoubleEncode(template_path), "contents").Get(new Result<DreamMessage>()).Wait(); template_content = msg.ToDocument()["body"].AsText ?? String.Empty; // There are 3 different dekiscript methods to invoke templates string[] template_call = new string[] { "<pre class=\"script\">Template('" + template_name + "');</pre>", "<pre class=\"script\">Template." + template_name + "();</pre>", "<pre class=\"script\">wiki.Template('" + template_name + "');</pre>" }; // Create page that calls template string page_id; string page_path; PageUtils.CreateRandomPage(p, out page_id, out page_path); for (int i = 0; i < template_call.Length; i++) { // Use template_call[i] as page contents msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents") .With("edittime", String.Format("{0:yyyyMMddHHmmss}", DateTime.Now)) .Post(DreamMessage.Ok(MimeType.TEXT_UTF8, template_call[i]), new Result<DreamMessage>()).Wait(); // Retrieve page contents and verify it matches _all_ template content msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents").Get(new Result<DreamMessage>()).Wait(); Assert.AreEqual(template_content, msg.ToDocument()["body"].AsText ?? String.Empty, "Unexpected contents"); } // Part 2: Invoke template as user without USC permissions string userid; string username; msg = UserUtils.CreateRandomContributor(p, out userid, out username); p = Utils.BuildPlugForUser(username, "password"); // Check that user does not have USC permissions Assert.IsFalse((msg.ToDocument()["permissions.effective/operations"].AsText ?? "UNSAFECONTENT").Contains("UNSAFECONTENT"), "Created user has UNSAFECONTENT permissions"); for (int i = 0; i < template_call.Length; i++) { // Use template_call[i] as page contents msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents") .With("edittime", String.Format("{0:yyyyMMddHHmmss}", DateTime.Now)) .Post(DreamMessage.Ok(MimeType.TEXT_UTF8, template_call[i]), new Result<DreamMessage>()).Wait(); // Retrieve page contents and verify it matches _all_ template content msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents").Get(new Result<DreamMessage>()).Wait(); Assert.AreEqual(template_content, msg.ToDocument()["body"].AsText ?? String.Empty, "Unexpected contents"); } // Clean up PageUtils.DeletePageByName(p, template_path, true); } [Test] public void InvokeNoUSCTemplateWithUnsafeContent() { // Create a contributor string userid; string username; DreamMessage msg = UserUtils.CreateRandomContributor(Utils.BuildPlugForAdmin(), out userid, out username); Plug p = Utils.BuildPlugForUser(username, "password"); // Check that user does not have USC permissions Assert.IsFalse((msg.ToDocument()["permissions.effective/operations"].AsText ?? "UNSAFECONTENT").Contains("UNSAFECONTENT"), "Created user has UNSAFECONTENT permissions"); // Create a template with unsafe content string safe_content = "This is a template"; string unsafe_content = "<p><script type=\"text/javascript\">document.write(\"With unsafe content\");</script></p>"; string template_content = safe_content + unsafe_content; string template_name = "test" + DateTime.Now.Ticks.ToString(); string template_path = "Template:" + template_name; msg = p.At("pages", "=" + XUri.DoubleEncode(template_path), "contents") .Post(DreamMessage.Ok(MimeType.TEXT_UTF8, template_content), new Result<DreamMessage>()).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Template page creation failed!"); // Log in as ADMIN p = Utils.BuildPlugForAdmin(); // There are 3 different dekiscript methods to invoke templates string[] template_call = new string[] { "<pre class=\"script\">Template('" + template_name + "');</pre>", "<pre class=\"script\">Template." + template_name + "();</pre>", "<pre class=\"script\">wiki.Template('" + template_name + "');</pre>" }; // Create page that calls template string page_id; string page_path; PageUtils.CreateRandomPage(p, out page_id, out page_path); for (int i = 0; i < template_call.Length; i++) { // Use template_call[i] as page contents msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents") .With("edittime", String.Format("{0:yyyyMMddHHmmss}", DateTime.Now)) .Post(DreamMessage.Ok(MimeType.TEXT_UTF8, template_call[i]), new Result<DreamMessage>()).Wait(); // Retrieve page contents. Expected only safe content present msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents").Get(new Result<DreamMessage>()).Wait(); Assert.AreEqual(safe_content, msg.ToDocument()["body"].AsText ?? String.Empty, "Unexpected contents"); } // Clean up PageUtils.DeletePageByName(p, template_path, true); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Text; namespace fastJSON { /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to doubles. /// </summary> internal class JsonParser { private const int TOKEN_NONE = 0; private const int TOKEN_CURLY_OPEN = 1; private const int TOKEN_CURLY_CLOSE = 2; private const int TOKEN_SQUARED_OPEN = 3; private const int TOKEN_SQUARED_CLOSE = 4; private const int TOKEN_COLON = 5; private const int TOKEN_COMMA = 6; private const int TOKEN_STRING = 7; private const int TOKEN_NUMBER = 8; private const int TOKEN_TRUE = 9; private const int TOKEN_FALSE = 10; private const int TOKEN_NULL = 11; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a dictionary, a double, a string, null, true, or false</returns> internal static object JsonDecode(string json) { bool success = true; return JsonDecode(json, ref success); } /// <summary> /// Parses the string json into a value; and fills 'success' with the successfullness of the parse. /// </summary> /// <param name="json">A JSON string.</param> /// <param name="success">Successful parse?</param> /// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns> private static object JsonDecode(string json, ref bool success) { success = true; if (json != null) { char[] charArray = json.ToCharArray(); int index = 0; object value = ParseValue(charArray, ref index, ref success); return value; } else { return null; } } protected static Dictionary<string,object> ParseObject(char[] json, ref int index, ref bool success) { Dictionary<string,object> table = new Dictionary<string, object>(); int token; // { NextToken(json, ref index); bool done = false; while (!done) { token = LookAhead(json, index); if (token == TOKEN_NONE) { success = false; return null; } else if (token == TOKEN_COMMA) { NextToken(json, ref index); } else if (token == TOKEN_CURLY_CLOSE) { NextToken(json, ref index); return table; } else { // name string name = ParseString(json, ref index, ref success); if (!success) { success = false; return null; } // : token = NextToken(json, ref index); if (token != TOKEN_COLON) { success = false; return null; } // value object value = ParseValue(json, ref index, ref success); if (!success) { success = false; return null; } table[name] = value; } } return table; } protected static ArrayList ParseArray(char[] json, ref int index, ref bool success) { ArrayList array = new ArrayList(); NextToken(json, ref index); bool done = false; while (!done) { int token = LookAhead(json, index); if (token == TOKEN_NONE) { success = false; return null; } else if (token == TOKEN_COMMA) { NextToken(json, ref index); } else if (token == TOKEN_SQUARED_CLOSE) { NextToken(json, ref index); break; } else { object value = ParseValue(json, ref index, ref success); if (!success) { return null; } array.Add(value); } } return array; } protected static object ParseValue(char[] json, ref int index, ref bool success) { switch (LookAhead(json, index)) { case TOKEN_NUMBER: return ParseNumber(json, ref index, ref success); case TOKEN_STRING: return ParseString(json, ref index, ref success); case TOKEN_CURLY_OPEN: return ParseObject(json, ref index, ref success); case TOKEN_SQUARED_OPEN: return ParseArray(json, ref index, ref success); case TOKEN_TRUE: NextToken(json, ref index); return true; case TOKEN_FALSE: NextToken(json, ref index); return false; case TOKEN_NULL: NextToken(json, ref index); return null; case TOKEN_NONE: break; } success = false; return null; } protected static string ParseString(char[] json, ref int index, ref bool success) { StringBuilder s = new StringBuilder(); char c; EatWhitespace(json, ref index); // " c = json[index++]; bool complete = false; while (!complete) { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { complete = true; break; } else if (c == '\\') { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { s.Append('"'); } else if (c == '\\') { s.Append('\\'); } else if (c == '/') { s.Append('/'); } else if (c == 'b') { s.Append('\b'); } else if (c == 'f') { s.Append('\f'); } else if (c == 'n') { s.Append('\n'); } else if (c == 'r') { s.Append('\r'); } else if (c == 't') { s.Append('\t'); } else if (c == 'u') { int remainingLength = json.Length - index; if (remainingLength >= 4) { // parse the 32 bit hex into an integer codepoint uint codePoint; if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) { return ""; } // convert the integer codepoint to a unicode char and add to string s.Append(Char.ConvertFromUtf32((int)codePoint)); // skip 4 chars index += 4; } else { break; } } } else { s.Append(c); } } if (!complete) { success = false; return null; } return s.ToString(); } protected static string ParseNumber(char[] json, ref int index, ref bool success) { EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); int charLength = (lastIndex - index) + 1; string number = new string(json,index,charLength); success = true; index = lastIndex + 1; return number; } protected static int GetLastIndexOfNumber(char[] json, int index) { int lastIndex; for (lastIndex = index; lastIndex < json.Length; lastIndex++) { if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) { break; } } return lastIndex - 1; } protected static void EatWhitespace(char[] json, ref int index) { for (; index < json.Length; index++) { if (" \t\n\r".IndexOf(json[index]) == -1) { break; } } } protected static int LookAhead(char[] json, int index) { int saveIndex = index; return NextToken(json, ref saveIndex); } protected static int NextToken(char[] json, ref int index) { EatWhitespace(json, ref index); if (index == json.Length) { return TOKEN_NONE; } char c = json[index]; index++; switch (c) { case '{': return TOKEN_CURLY_OPEN; case '}': return TOKEN_CURLY_CLOSE; case '[': return TOKEN_SQUARED_OPEN; case ']': return TOKEN_SQUARED_CLOSE; case ',': return TOKEN_COMMA; case '"': return TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN_NUMBER; case ':': return TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if (remainingLength >= 5) { if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return TOKEN_FALSE; } } // true if (remainingLength >= 4) { if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return TOKEN_TRUE; } } // null if (remainingLength >= 4) { if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return TOKEN_NULL; } } return TOKEN_NONE; } protected static bool SerializeValue(object value, StringBuilder builder) { bool success = true; if (value is string) { success = SerializeString((string)value, builder); } else if (value is Hashtable) { success = SerializeObject((Hashtable)value, builder); } else if (value is ArrayList) { success = SerializeArray((ArrayList)value, builder); } else if (IsNumeric(value)) { success = SerializeNumber(Convert.ToDouble(value), builder); } else if ((value is Boolean) && ((Boolean)value == true)) { builder.Append("true"); } else if ((value is Boolean) && ((Boolean)value == false)) { builder.Append("false"); } else if (value == null) { builder.Append("null"); } else { success = false; } return success; } protected static bool SerializeObject(Hashtable anObject, StringBuilder builder) { builder.Append("{"); IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while (e.MoveNext()) { string key = e.Key.ToString(); object value = e.Value; if (!first) { builder.Append(", "); } SerializeString(key, builder); builder.Append(":"); if (!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("}"); return true; } protected static bool SerializeArray(ArrayList anArray, StringBuilder builder) { builder.Append("["); bool first = true; for (int i = 0; i < anArray.Count; i++) { object value = anArray[i]; if (!first) { builder.Append(", "); } if (!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("]"); return true; } protected static bool SerializeString(string aString, StringBuilder builder) { builder.Append("\""); char[] charArray = aString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { char c = charArray[i]; if (c == '"') { builder.Append("\\\""); } else if (c == '\\') { builder.Append("\\\\"); } else if (c == '\b') { builder.Append("\\b"); } else if (c == '\f') { builder.Append("\\f"); } else if (c == '\n') { builder.Append("\\n"); } else if (c == '\r') { builder.Append("\\r"); } else if (c == '\t') { builder.Append("\\t"); } else { int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } } } builder.Append("\""); return true; } protected static bool SerializeNumber(double number, StringBuilder builder) { builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture)); return true; } protected static bool IsNumeric(object o) { double result; return (o == null) ? false : Double.TryParse(o.ToString(), out result); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.CoreModules.Avatar.Chat; namespace OpenSim.Region.OptionalModules.Avatar.Concierge { public class ConciergeModule : ChatModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int DEBUG_CHANNEL = 2147483647; private List<IScene> m_scenes = new List<IScene>(); private List<IScene> m_conciergedScenes = new List<IScene>(); private bool m_replacingChatModule = false; private IConfig m_config; private string m_whoami = "conferencier"; private Regex m_regions = null; private string m_welcomes = null; private int m_conciergeChannel = 42; private string m_announceEntering = "{0} enters {1} (now {2} visitors in this region)"; private string m_announceLeaving = "{0} leaves {1} (back to {2} visitors in this region)"; private string m_xmlRpcPassword = String.Empty; private string m_brokerURI = String.Empty; private int m_brokerUpdateTimeout = 300; internal object m_syncy = new object(); internal bool m_enabled = false; #region ISharedRegionModule Members public override void Initialise(IConfigSource config) { m_config = config.Configs["Concierge"]; if (null == m_config) { m_log.Info("[Concierge]: no config found, plugin disabled"); return; } if (!m_config.GetBoolean("enabled", false)) { m_log.Info("[Concierge]: plugin disabled by configuration"); return; } m_enabled = true; // check whether ChatModule has been disabled: if yes, // then we'll "stand in" try { if (config.Configs["Chat"] == null) { // if Chat module has not been configured it's // enabled by default, so we are not going to // replace it. m_replacingChatModule = false; } else { m_replacingChatModule = !config.Configs["Chat"].GetBoolean("enabled", true); } } catch (Exception) { m_replacingChatModule = false; } m_log.InfoFormat("[Concierge] {0} ChatModule", m_replacingChatModule ? "replacing" : "not replacing"); // take note of concierge channel and of identity m_conciergeChannel = config.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel); m_whoami = m_config.GetString("whoami", "conferencier"); m_welcomes = m_config.GetString("welcomes", m_welcomes); m_announceEntering = m_config.GetString("announce_entering", m_announceEntering); m_announceLeaving = m_config.GetString("announce_leaving", m_announceLeaving); m_xmlRpcPassword = m_config.GetString("password", m_xmlRpcPassword); m_brokerURI = m_config.GetString("broker", m_brokerURI); m_brokerUpdateTimeout = m_config.GetInt("broker_timeout", m_brokerUpdateTimeout); m_log.InfoFormat("[Concierge] reporting as \"{0}\" to our users", m_whoami); // calculate regions Regex if (m_regions == null) { string regions = m_config.GetString("regions", String.Empty); if (!String.IsNullOrEmpty(regions)) { m_regions = new Regex(@regions, RegexOptions.Compiled | RegexOptions.IgnoreCase); } } } public override void AddRegion(Scene scene) { if (!m_enabled) return; MainServer.Instance.AddXmlRPCHandler("concierge_update_welcome", XmlRpcUpdateWelcomeMethod, false); lock (m_syncy) { if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); if (m_regions == null || m_regions.IsMatch(scene.RegionInfo.RegionName)) m_conciergedScenes.Add(scene); // subscribe to NewClient events scene.EventManager.OnNewClient += OnNewClient; // subscribe to *Chat events scene.EventManager.OnChatFromWorld += OnChatFromWorld; if (!m_replacingChatModule) scene.EventManager.OnChatFromClient += OnChatFromClient; scene.EventManager.OnChatBroadcast += OnChatBroadcast; // subscribe to agent change events scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; } } m_log.InfoFormat("[Concierge]: initialized for {0}", scene.RegionInfo.RegionName); } public override void RemoveRegion(Scene scene) { if (!m_enabled) return; MainServer.Instance.RemoveXmlRPCHandler("concierge_update_welcome"); lock (m_syncy) { // unsubscribe from NewClient events scene.EventManager.OnNewClient -= OnNewClient; // unsubscribe from *Chat events scene.EventManager.OnChatFromWorld -= OnChatFromWorld; if (!m_replacingChatModule) scene.EventManager.OnChatFromClient -= OnChatFromClient; scene.EventManager.OnChatBroadcast -= OnChatBroadcast; // unsubscribe from agent change events scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent; scene.EventManager.OnMakeChildAgent -= OnMakeChildAgent; if (m_scenes.Contains(scene)) { m_scenes.Remove(scene); } if (m_conciergedScenes.Contains(scene)) { m_conciergedScenes.Remove(scene); } } m_log.InfoFormat("[Concierge]: removed {0}", scene.RegionInfo.RegionName); } public override void PostInitialise() { } public override void Close() { } new public Type ReplaceableInterface { get { return null; } } public override string Name { get { return "ConciergeModule"; } } #endregion #region ISimChat Members public override void OnChatBroadcast(Object sender, OSChatMessage c) { if (m_replacingChatModule) { // distribute chat message to each and every avatar in // the region base.OnChatBroadcast(sender, c); } // TODO: capture logic return; } public override void OnChatFromClient(Object sender, OSChatMessage c) { if (m_replacingChatModule) { // replacing ChatModule: need to redistribute // ChatFromClient to interested subscribers c = FixPositionOfChatMessage(c); Scene scene = (Scene)c.Scene; scene.EventManager.TriggerOnChatFromClient(sender, c); if (m_conciergedScenes.Contains(c.Scene)) { // when we are replacing ChatModule, we treat // OnChatFromClient like OnChatBroadcast for // concierged regions, effectively extending the // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; } } // redistribution will be done by base class base.OnChatFromClient(sender, c); } // TODO: capture chat return; } public override void OnChatFromWorld(Object sender, OSChatMessage c) { if (m_replacingChatModule) { if (m_conciergedScenes.Contains(c.Scene)) { // when we are replacing ChatModule, we treat // OnChatFromClient like OnChatBroadcast for // concierged regions, effectively extending the // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; } } base.OnChatFromWorld(sender, c); } return; } #endregion public override void OnNewClient(IClientAPI client) { client.OnLogout += OnClientLoggedOut; if (m_replacingChatModule) client.OnChatFromClient += OnChatFromClient; } public void OnClientLoggedOut(IClientAPI client) { client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; if (m_conciergedScenes.Contains(client.Scene)) { Scene scene = client.Scene as Scene; m_log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, scene.RegionInfo.RegionName); AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, client.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public void OnMakeRootAgent(ScenePresence agent) { if (m_conciergedScenes.Contains(agent.Scene)) { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, scene.RegionInfo.RegionName); WelcomeAvatar(agent, scene); AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } public void OnMakeChildAgent(ScenePresence agent) { if (m_conciergedScenes.Contains(agent.Scene)) { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, scene.RegionInfo.RegionName); AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } } internal class BrokerState { public string Uri; public string Payload; public HttpWebRequest Poster; public Timer Timer; public BrokerState(string uri, string payload, HttpWebRequest poster) { Uri = uri; Payload = payload; Poster = poster; } } protected void UpdateBroker(Scene scene) { if (String.IsNullOrEmpty(m_brokerURI)) return; string uri = String.Format(m_brokerURI, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID); // create XML sniplet StringBuilder list = new StringBuilder(); list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n", scene.GetRootAgentCount(), scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, DateTime.UtcNow.ToString("s"))); scene.ForEachScenePresence(delegate(ScenePresence sp) { if (!sp.IsChildAgent) { list.Append(String.Format(" <avatar name=\"{0}\" uuid=\"{1}\" />\n", sp.Name, sp.UUID)); list.Append("</avatars>"); } }); string payload = list.ToString(); // post via REST to broker HttpWebRequest updatePost = WebRequest.Create(uri) as HttpWebRequest; updatePost.Method = "POST"; updatePost.ContentType = "text/xml"; updatePost.ContentLength = payload.Length; updatePost.UserAgent = "OpenSim.Concierge"; BrokerState bs = new BrokerState(uri, payload, updatePost); bs.Timer = new Timer(delegate(object state) { BrokerState b = state as BrokerState; b.Poster.Abort(); b.Timer.Dispose(); m_log.Debug("[Concierge]: async broker POST abort due to timeout"); }, bs, m_brokerUpdateTimeout * 1000, Timeout.Infinite); try { updatePost.BeginGetRequestStream(UpdateBrokerSend, bs); m_log.DebugFormat("[Concierge] async broker POST to {0} started", uri); } catch (WebException we) { m_log.ErrorFormat("[Concierge] async broker POST to {0} failed: {1}", uri, we.Status); } } private void UpdateBrokerSend(IAsyncResult result) { BrokerState bs = null; try { bs = result.AsyncState as BrokerState; string payload = bs.Payload; HttpWebRequest updatePost = bs.Poster; using (StreamWriter payloadStream = new StreamWriter(updatePost.EndGetRequestStream(result))) { payloadStream.Write(payload); payloadStream.Close(); } updatePost.BeginGetResponse(UpdateBrokerDone, bs); } catch (WebException we) { m_log.DebugFormat("[Concierge]: async broker POST to {0} failed: {1}", bs.Uri, we.Status); } catch (Exception) { m_log.DebugFormat("[Concierge]: async broker POST to {0} failed", bs.Uri); } } private void UpdateBrokerDone(IAsyncResult result) { BrokerState bs = null; try { bs = result.AsyncState as BrokerState; HttpWebRequest updatePost = bs.Poster; using (HttpWebResponse response = updatePost.EndGetResponse(result) as HttpWebResponse) { m_log.DebugFormat("[Concierge] broker update: status {0}", response.StatusCode); } bs.Timer.Dispose(); } catch (WebException we) { m_log.ErrorFormat("[Concierge] broker update to {0} failed with status {1}", bs.Uri, we.Status); if (null != we.Response) { using (HttpWebResponse resp = we.Response as HttpWebResponse) { m_log.ErrorFormat("[Concierge] response from {0} status code: {1}", bs.Uri, resp.StatusCode); m_log.ErrorFormat("[Concierge] response from {0} status desc: {1}", bs.Uri, resp.StatusDescription); m_log.ErrorFormat("[Concierge] response from {0} server: {1}", bs.Uri, resp.Server); if (resp.ContentLength > 0) { StreamReader content = new StreamReader(resp.GetResponseStream()); m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd()); content.Close(); } } } } } protected void WelcomeAvatar(ScenePresence agent, Scene scene) { // welcome mechanics: check whether we have a welcomes // directory set and wether there is a region specific // welcome file there: if yes, send it to the agent if (!String.IsNullOrEmpty(m_welcomes)) { string[] welcomes = new string[] { Path.Combine(m_welcomes, agent.Scene.RegionInfo.RegionName), Path.Combine(m_welcomes, "DEFAULT")}; foreach (string welcome in welcomes) { if (File.Exists(welcome)) { try { string[] welcomeLines = File.ReadAllLines(welcome); foreach (string l in welcomeLines) { AnnounceToAgent(agent, String.Format(l, agent.Name, scene.RegionInfo.RegionName, m_whoami)); } } catch (IOException ioe) { m_log.ErrorFormat("[Concierge]: run into trouble reading welcome file {0} for region {1} for avatar {2}: {3}", welcome, scene.RegionInfo.RegionName, agent.Name, ioe); } catch (FormatException fe) { m_log.ErrorFormat("[Concierge]: welcome file {0} is malformed: {1}", welcome, fe); } } return; } m_log.DebugFormat("[Concierge]: no welcome message for region {0}", scene.RegionInfo.RegionName); } } static private Vector3 PosOfGod = new Vector3(128, 128, 9999); // protected void AnnounceToAgentsRegion(Scene scene, string msg) // { // ScenePresence agent = null; // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetScenePresence(client.AgentId, out agent)) // AnnounceToAgentsRegion(agent, msg); // else // m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name); // } protected void AnnounceToAgentsRegion(IScene scene, string msg) { OSChatMessage c = new OSChatMessage(); c.Message = msg; c.Type = ChatTypeEnum.Say; c.Channel = 0; c.Position = PosOfGod; c.From = m_whoami; c.Sender = null; c.SenderUUID = UUID.Zero; c.Scene = scene; if (scene is Scene) (scene as Scene).EventManager.TriggerOnChatBroadcast(this, c); } protected void AnnounceToAgent(ScenePresence agent, string msg) { OSChatMessage c = new OSChatMessage(); c.Message = msg; c.Type = ChatTypeEnum.Say; c.Channel = 0; c.Position = PosOfGod; c.From = m_whoami; c.Sender = null; c.SenderUUID = UUID.Zero; c.Scene = agent.Scene; agent.ControllingClient.SendChatMessage(msg, (byte) ChatTypeEnum.Say, PosOfGod, m_whoami, UUID.Zero, (byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully); } private static void checkStringParameters(XmlRpcRequest request, string[] param) { Hashtable requestData = (Hashtable) request.Params[0]; foreach (string p in param) { if (!requestData.Contains(p)) throw new Exception(String.Format("missing string parameter {0}", p)); if (String.IsNullOrEmpty((string)requestData[p])) throw new Exception(String.Format("parameter {0} is empty", p)); } } public XmlRpcResponse XmlRpcUpdateWelcomeMethod(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Info("[Concierge]: processing UpdateWelcome request"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); try { Hashtable requestData = (Hashtable)request.Params[0]; checkStringParameters(request, new string[] { "password", "region", "welcome" }); // check password if (!String.IsNullOrEmpty(m_xmlRpcPassword) && (string)requestData["password"] != m_xmlRpcPassword) throw new Exception("wrong password"); if (String.IsNullOrEmpty(m_welcomes)) throw new Exception("welcome templates are not enabled, ask your OpenSim operator to set the \"welcomes\" option in the [Concierge] section of OpenSim.ini"); string msg = (string)requestData["welcome"]; if (String.IsNullOrEmpty(msg)) throw new Exception("empty parameter \"welcome\""); string regionName = (string)requestData["region"]; IScene scene = m_scenes.Find(delegate(IScene s) { return s.RegionInfo.RegionName == regionName; }); if (scene == null) throw new Exception(String.Format("unknown region \"{0}\"", regionName)); if (!m_conciergedScenes.Contains(scene)) throw new Exception(String.Format("region \"{0}\" is not a concierged region.", regionName)); string welcome = Path.Combine(m_welcomes, regionName); if (File.Exists(welcome)) { m_log.InfoFormat("[Concierge]: UpdateWelcome: updating existing template \"{0}\"", welcome); string welcomeBackup = String.Format("{0}~", welcome); if (File.Exists(welcomeBackup)) File.Delete(welcomeBackup); File.Move(welcome, welcomeBackup); } File.WriteAllText(welcome, msg); responseData["success"] = "true"; response.Value = responseData; } catch (Exception e) { m_log.InfoFormat("[Concierge]: UpdateWelcome failed: {0}", e.Message); responseData["success"] = "false"; responseData["error"] = e.Message; response.Value = responseData; } m_log.Debug("[Concierge]: done processing UpdateWelcome request"); return response; } } }
/*****************************************************************************/ /* Project : AviationInstruments */ /* File : InstrumentControl.cs */ /* Version : 1 */ /* Language : C# */ /* Summary : Generic class for the instrument control design */ /* Creation : 15/06/2008 */ /* Autor : Guillaume CHOUTEAU */ /* History : */ /*****************************************************************************/ using System; using System.ComponentModel; using System.Windows.Forms; using System.Collections; using System.Drawing; using System.Text; using System.Data; namespace AviationInstruments { public class InstrumentControl : System.Windows.Forms.Control { #region Generic methodes /// <summary> /// Rotate an image on a point with a specified angle /// </summary> /// <param name="pe">The paint area event where the image will be displayed</param> /// <param name="img">The image to display</param> /// <param name="alpha">The angle of rotation in radian</param> /// <param name="ptImg">The location of the left upper corner of the image to display in the paint area in nominal situation</param> /// <param name="ptRot">The location of the rotation point in the paint area</param> /// <param name="scaleFactor">Multiplication factor on the display image</param> protected void RotateImage(PaintEventArgs pe, Image img, Double alpha, Point ptImg, Point ptRot, float scaleFactor) { double beta = 0; // Angle between the Horizontal line and the line (Left upper corner - Rotation point) double d = 0; // Distance between Left upper corner and Rotation point) float deltaX = 0; // X componant of the corrected translation float deltaY = 0; // Y componant of the corrected translation // Compute the correction translation coeff if (ptImg != ptRot) { // if (ptRot.X != 0) { beta = Math.Atan((double)ptRot.Y / (double)ptRot.X); } d = Math.Sqrt((ptRot.X * ptRot.X) + (ptRot.Y * ptRot.Y)); // Computed offset deltaX = (float)(d * (Math.Cos(alpha - beta) - Math.Cos(alpha) * Math.Cos(alpha + beta) - Math.Sin(alpha) * Math.Sin(alpha + beta))); deltaY = (float)(d * (Math.Sin(beta - alpha) + Math.Sin(alpha) * Math.Cos(alpha + beta) - Math.Cos(alpha) * Math.Sin(alpha + beta))); } // Rotate image support pe.Graphics.RotateTransform((float)(alpha * 180 / Math.PI)); // Dispay image pe.Graphics.DrawImage(img, (ptImg.X + deltaX) * scaleFactor, (ptImg.Y + deltaY) * scaleFactor, img.Width * scaleFactor, img.Height * scaleFactor); // Put image support as found pe.Graphics.RotateTransform((float)(-alpha * 180 / Math.PI)); } /// <summary> /// Translate an image on line with a specified distance and a spcified angle /// </summary> /// <param name="pe">The paint area event where the image will be displayed</param> /// <param name="img">The image to display</param> ///<param name="deltaPx">The translation distance in pixel</param> /// <param name="alpha">The angle of translation direction in radian</param> /// <param name="ptImg">The location of the left upper corner of the image to display in the paint area in nominal situation</param> /// <param name="scaleFactor">Multiplication factor on the display image</param> protected void TranslateImage(PaintEventArgs pe, Image img, int deltaPx, float alpha, Point ptImg, float scaleFactor) { // Computed offset float deltaX = (float)(deltaPx * (Math.Sin(alpha))); float deltaY = (float)(- deltaPx * (Math.Cos(alpha))); // Dispay image pe.Graphics.DrawImage(img, (ptImg.X + deltaX) * scaleFactor, (ptImg.Y + deltaY) * scaleFactor, img.Width * scaleFactor, img.Height * scaleFactor); } /// <summary> /// Rotate an image an apply a translation on the rotated image and the display it /// </summary> /// <param name="pe">The paint area event where the image will be displayed</param> /// <param name="img">The image to display</param> /// <param name="alphaRot">The angle of rotation in radian</param> /// <param name="alphaTrs">The angle of translation direction in radian, expressed in the rotated image coordonate system</param> /// <param name="ptImg">The location of the left upper corner of the image to display in the paint area in nominal situation</param> /// <param name="ptRot">The location of the rotation point in the paint area</param> /// <param name="deltaPx">The translation distance in pixel</param> /// <param name="ptRot">The location of the rotation point in the paint area</param> /// <param name="scaleFactor">Multiplication factor on the display image</param> protected void RotateAndTranslate(PaintEventArgs pe, Image img, Double alphaRot, Double alphaTrs, Point ptImg, int deltaPx, Point ptRot, float scaleFactor) { double beta = 0; double d = 0; float deltaXRot = 0; float deltaYRot = 0; float deltaXTrs = 0; float deltaYTrs = 0; // Rotation if (ptImg != ptRot) { // Internals coeffs if (ptRot.X != 0) { beta = Math.Atan((double)ptRot.Y / (double)ptRot.X); } d = Math.Sqrt((ptRot.X * ptRot.X) + (ptRot.Y * ptRot.Y)); // Computed offset deltaXRot = (float)(d * (Math.Cos(alphaRot - beta) - Math.Cos(alphaRot) * Math.Cos(alphaRot + beta) - Math.Sin(alphaRot) * Math.Sin(alphaRot + beta))); deltaYRot = (float)(d * (Math.Sin(beta - alphaRot) + Math.Sin(alphaRot) * Math.Cos(alphaRot + beta) - Math.Cos(alphaRot) * Math.Sin(alphaRot + beta))); } // Translation // Computed offset deltaXTrs = (float)(deltaPx * (Math.Sin(alphaTrs))); deltaYTrs = (float)(- deltaPx * (-Math.Cos(alphaTrs))); // Rotate image support pe.Graphics.RotateTransform((float)(alphaRot * 180 / Math.PI)); // Dispay image pe.Graphics.DrawImage(img, (ptImg.X + deltaXRot + deltaXTrs) * scaleFactor, (ptImg.Y + deltaYRot + deltaYTrs) * scaleFactor, img.Width * scaleFactor, img.Height * scaleFactor); // Put image support as found pe.Graphics.RotateTransform((float)(-alphaRot * 180 / Math.PI)); } /// <summary> /// Display a Scroll counter image like on gas pumps /// </summary> /// <param name="pe">The paint area event where the image will be displayed</param> /// <param name="imgBand">The band counter image to display with digts : 0|1|2|3|4|5|6|7|8|9|0</param> /// <param name="nbOfDigits">The number of digits displayed by the counter</param> /// <param name="counterValue">The value to dispay on the counter</param> /// <param name="ptImg">The location of the left upper corner of the image to display in the paint area in nominal situation</param> /// <param name="scaleFactor">Multiplication factor on the display image</param> protected void ScrollCounter(PaintEventArgs pe, Image imgBand, int nbOfDigits, int counterValue, Point ptImg, float scaleFactor) { int indexDigit =0; int digitBoxHeight = (int)(imgBand.Height/11); int digitBoxWidth = imgBand.Width; for(indexDigit = 0; indexDigit<nbOfDigits; indexDigit++) { int currentDigit; int prevDigit; int xOffset; int yOffset; double fader; currentDigit = (int)((counterValue / Math.Pow(10, indexDigit)) % 10); if (indexDigit == 0) { prevDigit = 0; } else { prevDigit = (int)((counterValue / Math.Pow(10, indexDigit-1)) % 10); } // xOffset Computing xOffset = (int)(digitBoxWidth * (nbOfDigits - indexDigit - 1)); // yOffset Computing if(prevDigit == 9) { fader = 0.33; yOffset = (int)(-((fader + currentDigit) * digitBoxHeight)); } else { yOffset = (int)(-(currentDigit * digitBoxHeight)); } // Display Image pe.Graphics.DrawImage(imgBand,(ptImg.X + xOffset)*scaleFactor,(ptImg.Y + yOffset)*scaleFactor,imgBand.Width*scaleFactor,imgBand.Height*scaleFactor); } } private void DisplayRoundMark(PaintEventArgs pe, Image imgMark, InstrumentControlMarksDefinition insControlMarksDefinition, Point ptImg, int radiusPx, Boolean displayText, float scaleFactor) { Double alphaRot; int textBoxLength; int textPointRadiusPx; int textBoxHeight = (int)(insControlMarksDefinition.fontSize*1.1/scaleFactor); Point textPoint = new Point(); Point rotatePoint = new Point(); Font markFont = new Font("Arial", insControlMarksDefinition.fontSize); SolidBrush markBrush = new SolidBrush(insControlMarksDefinition.fontColor); InstrumentControlMarkPoint[] markArray = new InstrumentControlMarkPoint[2 + insControlMarksDefinition.numberOfDivisions]; // Buid the markArray markArray[0].value = insControlMarksDefinition.minPhy; markArray[0].angle = insControlMarksDefinition.minAngle; markArray[markArray.Length - 1].value = insControlMarksDefinition.maxPhy; markArray[markArray.Length - 1].angle = insControlMarksDefinition.maxAngle; for (int index = 1; index < insControlMarksDefinition.numberOfDivisions+1; index++) { markArray[index].value = (insControlMarksDefinition.maxPhy - insControlMarksDefinition.minPhy) / (insControlMarksDefinition.numberOfDivisions + 1) * index + insControlMarksDefinition.minPhy; markArray[index].angle = (insControlMarksDefinition.maxAngle - insControlMarksDefinition.minAngle) / (insControlMarksDefinition.numberOfDivisions + 1) * index + insControlMarksDefinition.minAngle; } // Define the rotate point (center of the indicator) rotatePoint.X = (int)((this.Width/2)/scaleFactor); rotatePoint.Y = rotatePoint.X; // Display mark array foreach (InstrumentControlMarkPoint markPoint in markArray) { // pre computings alphaRot = (Math.PI / 2) - markPoint.angle; textBoxLength = (int)(Convert.ToString(markPoint.value).Length * insControlMarksDefinition.fontSize*0.8/scaleFactor); textPointRadiusPx = (int)(radiusPx - 1.2*imgMark.Height - 0.5 * textBoxLength); textPoint.X = (int)((textPointRadiusPx * Math.Cos(markPoint.angle) - 0.5 * textBoxLength + rotatePoint.X) * scaleFactor); textPoint.Y = (int)((-textPointRadiusPx * Math.Sin(markPoint.angle) - 0.5 * textBoxHeight + rotatePoint.Y) * scaleFactor); // Display mark RotateImage(pe, imgMark, alphaRot, ptImg, rotatePoint, scaleFactor); // Display text if (displayText == true) { pe.Graphics.DrawString(Convert.ToString(markPoint.value), markFont, markBrush, textPoint); } } } /// <summary> /// Convert a physical value in an rad angle used by the rotate function /// </summary> /// <param name="phyVal">Physical value to interpol/param> /// <param name="minPhy">Minimum physical value</param> /// <param name="maxPhy">Maximum physical value</param> /// <param name="minAngle">The angle related to the minumum value, in deg</param> /// <param name="maxAngle">The angle related to the maximum value, in deg</param> /// <returns>The angle in radian witch correspond to the physical value</returns> protected float InterpolPhyToAngle(float phyVal, float minPhy, float maxPhy, float minAngle, float maxAngle) { float a; float b; float y; float x; if (phyVal < minPhy) { return (float)(minAngle * Math.PI / 180); } else if (phyVal > maxPhy) { return (float)(maxAngle * Math.PI / 180); } else { x = phyVal; a = (maxAngle - minAngle) / (maxPhy - minPhy); b = (float)(0.5 * (maxAngle + minAngle - a * (maxPhy + minPhy))); y = a * x + b; return (float)(y * Math.PI / 180); } } protected Point FromCartRefToImgRef(Point cartPoint) { Point imgPoint = new Point(); imgPoint.X = cartPoint.X + (this.Width/2); imgPoint.Y = -cartPoint.Y + (this.Height/2); return (imgPoint); } protected double FromDegToRad(double degAngle) { double radAngle = degAngle * Math.PI / 180; return radAngle; } #endregion } struct InstrumentControlMarksDefinition { public InstrumentControlMarksDefinition(float myMinPhy, float myMinAngle, float myMaxPhy, float myMaxAngle, int myNumberOfDivisions, int myFontSize, Color myFontColor, InstumentMarkScaleStyle myScaleStyle) { this.minPhy = myMinPhy; this.minAngle = myMinAngle; this.maxPhy = myMaxPhy; this.maxAngle = myMaxAngle; this.numberOfDivisions = myNumberOfDivisions; this.fontSize = myFontSize; this.fontColor = myFontColor; this.scaleStyle = myScaleStyle; } internal float minPhy; internal float minAngle; internal float maxPhy; internal float maxAngle; internal int numberOfDivisions; internal int fontSize; internal Color fontColor; internal InstumentMarkScaleStyle scaleStyle; } struct InstrumentControlMarkPoint { public InstrumentControlMarkPoint(float myValue, float myAngle) { this.value = myValue; this.angle = myAngle; } internal float value; internal float angle; } enum InstumentMarkScaleStyle { Linear = 0, Log = 1, }; }
using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Abp; using Abp.Configuration.Startup; using Abp.Domain.Uow; using Abp.Runtime.Session; using Abp.TestBase; using PlugInDemo.EntityFramework; using PlugInDemo.Migrations.SeedData; using PlugInDemo.MultiTenancy; using PlugInDemo.Users; using Castle.MicroKernel.Registration; using Effort; using EntityFramework.DynamicFilters; namespace PlugInDemo.Tests { public abstract class PlugInDemoTestBase : AbpIntegratedTestBase<PlugInDemoTestModule> { private DbConnection _hostDb; private Dictionary<int, DbConnection> _tenantDbs; //only used for db per tenant architecture protected PlugInDemoTestBase() { //Seed initial data for host AbpSession.TenantId = null; UsingDbContext(context => { new InitialHostDbBuilder(context).Create(); new DefaultTenantCreator(context).Create(); }); //Seed initial data for default tenant AbpSession.TenantId = 1; UsingDbContext(context => { new TenantRoleAndUserBuilder(context, 1).Create(); }); LoginAsDefaultTenantAdmin(); } protected override void PreInitialize() { base.PreInitialize(); /* You can switch database architecture here: */ UseSingleDatabase(); //UseDatabasePerTenant(); } /* Uses single database for host and all tenants. */ private void UseSingleDatabase() { _hostDb = DbConnectionFactory.CreateTransient(); LocalIocManager.IocContainer.Register( Component.For<DbConnection>() .UsingFactoryMethod(() => _hostDb) .LifestyleSingleton() ); } /* Uses single database for host and Default tenant, * but dedicated databases for all other tenants. */ private void UseDatabasePerTenant() { _hostDb = DbConnectionFactory.CreateTransient(); _tenantDbs = new Dictionary<int, DbConnection>(); LocalIocManager.IocContainer.Register( Component.For<DbConnection>() .UsingFactoryMethod((kernel) => { lock (_tenantDbs) { var currentUow = kernel.Resolve<ICurrentUnitOfWorkProvider>().Current; var abpSession = kernel.Resolve<IAbpSession>(); var tenantId = currentUow != null ? currentUow.GetTenantId() : abpSession.TenantId; if (tenantId == null || tenantId == 1) //host and default tenant are stored in host db { return _hostDb; } if (!_tenantDbs.ContainsKey(tenantId.Value)) { _tenantDbs[tenantId.Value] = DbConnectionFactory.CreateTransient(); } return _tenantDbs[tenantId.Value]; } }, true) .LifestyleTransient() ); } #region UsingDbContext protected IDisposable UsingTenantId(int? tenantId) { var previousTenantId = AbpSession.TenantId; AbpSession.TenantId = tenantId; return new DisposeAction(() => AbpSession.TenantId = previousTenantId); } protected void UsingDbContext(Action<PlugInDemoDbContext> action) { UsingDbContext(AbpSession.TenantId, action); } protected Task UsingDbContextAsync(Func<PlugInDemoDbContext, Task> action) { return UsingDbContextAsync(AbpSession.TenantId, action); } protected T UsingDbContext<T>(Func<PlugInDemoDbContext, T> func) { return UsingDbContext(AbpSession.TenantId, func); } protected Task<T> UsingDbContextAsync<T>(Func<PlugInDemoDbContext, Task<T>> func) { return UsingDbContextAsync(AbpSession.TenantId, func); } protected void UsingDbContext(int? tenantId, Action<PlugInDemoDbContext> action) { using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<PlugInDemoDbContext>()) { context.DisableAllFilters(); action(context); context.SaveChanges(); } } } protected async Task UsingDbContextAsync(int? tenantId, Func<PlugInDemoDbContext, Task> action) { using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<PlugInDemoDbContext>()) { context.DisableAllFilters(); await action(context); await context.SaveChangesAsync(); } } } protected T UsingDbContext<T>(int? tenantId, Func<PlugInDemoDbContext, T> func) { T result; using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<PlugInDemoDbContext>()) { context.DisableAllFilters(); result = func(context); context.SaveChanges(); } } return result; } protected async Task<T> UsingDbContextAsync<T>(int? tenantId, Func<PlugInDemoDbContext, Task<T>> func) { T result; using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<PlugInDemoDbContext>()) { context.DisableAllFilters(); result = await func(context); await context.SaveChangesAsync(); } } return result; } #endregion #region Login protected void LoginAsHostAdmin() { LoginAsHost(User.AdminUserName); } protected void LoginAsDefaultTenantAdmin() { LoginAsTenant(Tenant.DefaultTenantName, User.AdminUserName); } protected void LoginAsHost(string userName) { Resolve<IMultiTenancyConfig>().IsEnabled = true; AbpSession.TenantId = null; var user = UsingDbContext( context => context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName)); if (user == null) { throw new Exception("There is no user: " + userName + " for host."); } AbpSession.UserId = user.Id; } protected void LoginAsTenant(string tenancyName, string userName) { var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName)); if (tenant == null) { throw new Exception("There is no tenant: " + tenancyName); } AbpSession.TenantId = tenant.Id; var user = UsingDbContext( context => context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName)); if (user == null) { throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName); } AbpSession.UserId = user.Id; } #endregion /// <summary> /// Gets current user if <see cref="IAbpSession.UserId"/> is not null. /// Throws exception if it's null. /// </summary> protected async Task<User> GetCurrentUserAsync() { var userId = AbpSession.GetUserId(); return await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId)); } /// <summary> /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null. /// Throws exception if there is no current tenant. /// </summary> protected async Task<Tenant> GetCurrentTenantAsync() { var tenantId = AbpSession.GetTenantId(); return await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId)); } } }
// <copyright file="ChromeOptions.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Chrome { /// <summary> /// Class to manage options specific to <see cref="ChromeDriver"/> /// </summary> /// <remarks> /// Used with ChromeDriver.exe v17.0.963.0 and higher. /// </remarks> /// <example> /// <code> /// ChromeOptions options = new ChromeOptions(); /// options.AddExtensions("\path\to\extension.crx"); /// options.BinaryLocation = "\path\to\chrome"; /// </code> /// <para></para> /// <para>For use with ChromeDriver:</para> /// <para></para> /// <code> /// ChromeDriver driver = new ChromeDriver(options); /// </code> /// <para></para> /// <para>For use with RemoteWebDriver:</para> /// <para></para> /// <code> /// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities()); /// </code> /// </example> public class ChromeOptions : DriverOptions { /// <summary> /// Gets the name of the capability used to store Chrome options in /// a <see cref="DesiredCapabilities"/> object. /// </summary> public static readonly string Capability = "goog:chromeOptions"; private const string BrowserNameValue = "chrome"; private const string ArgumentsChromeOption = "args"; private const string BinaryChromeOption = "binary"; private const string ExtensionsChromeOption = "extensions"; private const string LocalStateChromeOption = "localState"; private const string PreferencesChromeOption = "prefs"; private const string DetachChromeOption = "detach"; private const string DebuggerAddressChromeOption = "debuggerAddress"; private const string ExcludeSwitchesChromeOption = "excludeSwitches"; private const string MinidumpPathChromeOption = "minidumpPath"; private const string MobileEmulationChromeOption = "mobileEmulation"; private const string PerformanceLoggingPreferencesChromeOption = "perfLoggingPrefs"; private const string WindowTypesChromeOption = "windowTypes"; private const string UseSpecCompliantProtocolOption = "w3c"; private bool leaveBrowserRunning; private bool useSpecCompliantProtocol; private string binaryLocation; private string debuggerAddress; private string minidumpPath; private List<string> arguments = new List<string>(); private List<string> extensionFiles = new List<string>(); private List<string> encodedExtensions = new List<string>(); private List<string> excludedSwitches = new List<string>(); private List<string> windowTypes = new List<string>(); private Dictionary<string, object> additionalCapabilities = new Dictionary<string, object>(); private Dictionary<string, object> additionalChromeOptions = new Dictionary<string, object>(); private Dictionary<string, object> userProfilePreferences; private Dictionary<string, object> localStatePreferences; private string mobileEmulationDeviceName; private ChromeMobileEmulationDeviceSettings mobileEmulationDeviceSettings; private ChromePerformanceLoggingPreferences perfLoggingPreferences; public ChromeOptions() : base() { this.BrowserName = BrowserNameValue; this.AddKnownCapabilityName(ChromeOptions.Capability, "current ChromeOptions class instance"); this.AddKnownCapabilityName(CapabilityType.LoggingPreferences, "SetLoggingPreference method"); this.AddKnownCapabilityName(ChromeOptions.ArgumentsChromeOption, "AddArguments method"); this.AddKnownCapabilityName(ChromeOptions.BinaryChromeOption, "BinaryLocation property"); this.AddKnownCapabilityName(ChromeOptions.ExtensionsChromeOption, "AddExtensions method"); this.AddKnownCapabilityName(ChromeOptions.LocalStateChromeOption, "AddLocalStatePreference method"); this.AddKnownCapabilityName(ChromeOptions.PreferencesChromeOption, "AddUserProfilePreference method"); this.AddKnownCapabilityName(ChromeOptions.DetachChromeOption, "LeaveBrowserRunning property"); this.AddKnownCapabilityName(ChromeOptions.DebuggerAddressChromeOption, "DebuggerAddress property"); this.AddKnownCapabilityName(ChromeOptions.ExcludeSwitchesChromeOption, "AddExcludedArgument property"); this.AddKnownCapabilityName(ChromeOptions.MinidumpPathChromeOption, "MinidumpPath property"); this.AddKnownCapabilityName(ChromeOptions.MobileEmulationChromeOption, "EnableMobileEmulation method"); this.AddKnownCapabilityName(ChromeOptions.PerformanceLoggingPreferencesChromeOption, "PerformanceLoggingPreferences property"); this.AddKnownCapabilityName(ChromeOptions.WindowTypesChromeOption, "AddWindowTypes method"); this.AddKnownCapabilityName(ChromeOptions.UseSpecCompliantProtocolOption, "UseSpecCompliantProtocol property"); } /// <summary> /// Gets or sets the location of the Chrome browser's binary executable file. /// </summary> public string BinaryLocation { get { return this.binaryLocation; } set { this.binaryLocation = value; } } /// <summary> /// Gets or sets a value indicating whether Chrome should be left running after the /// ChromeDriver instance is exited. Defaults to <see langword="false"/>. /// </summary> public bool LeaveBrowserRunning { get { return this.leaveBrowserRunning; } set { this.leaveBrowserRunning = value; } } /// <summary> /// Gets the list of arguments appended to the Chrome command line as a string array. /// </summary> public ReadOnlyCollection<string> Arguments { get { return this.arguments.AsReadOnly(); } } /// <summary> /// Gets the list of extensions to be installed as an array of base64-encoded strings. /// </summary> public ReadOnlyCollection<string> Extensions { get { List<string> allExtensions = new List<string>(this.encodedExtensions); foreach (string extensionFile in this.extensionFiles) { byte[] extensionByteArray = File.ReadAllBytes(extensionFile); string encodedExtension = Convert.ToBase64String(extensionByteArray); allExtensions.Add(encodedExtension); } return allExtensions.AsReadOnly(); } } /// <summary> /// Gets or sets the address of a Chrome debugger server to connect to. /// Should be of the form "{hostname|IP address}:port". /// </summary> public string DebuggerAddress { get { return this.debuggerAddress; } set { this.debuggerAddress = value; } } /// <summary> /// Gets or sets the directory in which to store minidump files. /// </summary> public string MinidumpPath { get { return this.minidumpPath; } set { this.minidumpPath = value; } } /// <summary> /// Gets or sets the performance logging preferences for the driver. /// </summary> public ChromePerformanceLoggingPreferences PerformanceLoggingPreferences { get { return this.perfLoggingPreferences; } set { this.perfLoggingPreferences = value; } } /// <summary> /// Gets or sets a value indicating whether the <see cref="ChromeDriver"/> instance /// should use the legacy OSS protocol dialect or a dialect compliant with the W3C /// WebDriver Specification. /// </summary> public bool UseSpecCompliantProtocol { get { return this.useSpecCompliantProtocol; } set { this.useSpecCompliantProtocol = value; } } /// <summary> /// Adds a single argument to the list of arguments to be appended to the Chrome.exe command line. /// </summary> /// <param name="argument">The argument to add.</param> public void AddArgument(string argument) { if (string.IsNullOrEmpty(argument)) { throw new ArgumentException("argument must not be null or empty", "argument"); } this.AddArguments(argument); } /// <summary> /// Adds arguments to be appended to the Chrome.exe command line. /// </summary> /// <param name="argumentsToAdd">An array of arguments to add.</param> public void AddArguments(params string[] argumentsToAdd) { this.AddArguments(new List<string>(argumentsToAdd)); } /// <summary> /// Adds arguments to be appended to the Chrome.exe command line. /// </summary> /// <param name="argumentsToAdd">An <see cref="IEnumerable{T}"/> object of arguments to add.</param> public void AddArguments(IEnumerable<string> argumentsToAdd) { if (argumentsToAdd == null) { throw new ArgumentNullException("argumentsToAdd", "argumentsToAdd must not be null"); } this.arguments.AddRange(argumentsToAdd); } /// <summary> /// Adds a single argument to be excluded from the list of arguments passed by default /// to the Chrome.exe command line by chromedriver.exe. /// </summary> /// <param name="argument">The argument to exclude.</param> public void AddExcludedArgument(string argument) { if (string.IsNullOrEmpty(argument)) { throw new ArgumentException("argument must not be null or empty", "argument"); } this.AddExcludedArguments(argument); } /// <summary> /// Adds arguments to be excluded from the list of arguments passed by default /// to the Chrome.exe command line by chromedriver.exe. /// </summary> /// <param name="argumentsToExclude">An array of arguments to exclude.</param> public void AddExcludedArguments(params string[] argumentsToExclude) { this.AddExcludedArguments(new List<string>(argumentsToExclude)); } /// <summary> /// Adds arguments to be excluded from the list of arguments passed by default /// to the Chrome.exe command line by chromedriver.exe. /// </summary> /// <param name="argumentsToExclude">An <see cref="IEnumerable{T}"/> object of arguments to exclude.</param> public void AddExcludedArguments(IEnumerable<string> argumentsToExclude) { if (argumentsToExclude == null) { throw new ArgumentNullException("argumentsToExclude", "argumentsToExclude must not be null"); } this.excludedSwitches.AddRange(argumentsToExclude); } /// <summary> /// Adds a path to a packed Chrome extension (.crx file) to the list of extensions /// to be installed in the instance of Chrome. /// </summary> /// <param name="pathToExtension">The full path to the extension to add.</param> public void AddExtension(string pathToExtension) { if (string.IsNullOrEmpty(pathToExtension)) { throw new ArgumentException("pathToExtension must not be null or empty", "pathToExtension"); } this.AddExtensions(pathToExtension); } /// <summary> /// Adds a list of paths to packed Chrome extensions (.crx files) to be installed /// in the instance of Chrome. /// </summary> /// <param name="extensions">An array of full paths to the extensions to add.</param> public void AddExtensions(params string[] extensions) { this.AddExtensions(new List<string>(extensions)); } /// <summary> /// Adds a list of paths to packed Chrome extensions (.crx files) to be installed /// in the instance of Chrome. /// </summary> /// <param name="extensions">An <see cref="IEnumerable{T}"/> of full paths to the extensions to add.</param> public void AddExtensions(IEnumerable<string> extensions) { if (extensions == null) { throw new ArgumentNullException("extensions", "extensions must not be null"); } foreach (string extension in extensions) { if (!File.Exists(extension)) { throw new FileNotFoundException("No extension found at the specified path", extension); } this.extensionFiles.Add(extension); } } /// <summary> /// Adds a base64-encoded string representing a Chrome extension to the list of extensions /// to be installed in the instance of Chrome. /// </summary> /// <param name="extension">A base64-encoded string representing the extension to add.</param> public void AddEncodedExtension(string extension) { if (string.IsNullOrEmpty(extension)) { throw new ArgumentException("extension must not be null or empty", "extension"); } this.AddEncodedExtensions(extension); } /// <summary> /// Adds a list of base64-encoded strings representing Chrome extensions to the list of extensions /// to be installed in the instance of Chrome. /// </summary> /// <param name="extensions">An array of base64-encoded strings representing the extensions to add.</param> public void AddEncodedExtensions(params string[] extensions) { this.AddEncodedExtensions(new List<string>(extensions)); } /// <summary> /// Adds a list of base64-encoded strings representing Chrome extensions to be installed /// in the instance of Chrome. /// </summary> /// <param name="extensions">An <see cref="IEnumerable{T}"/> of base64-encoded strings /// representing the extensions to add.</param> public void AddEncodedExtensions(IEnumerable<string> extensions) { if (extensions == null) { throw new ArgumentNullException("extensions", "extensions must not be null"); } foreach (string extension in extensions) { // Run the extension through the base64 converter to test that the // string is not malformed. try { Convert.FromBase64String(extension); } catch (FormatException ex) { throw new WebDriverException("Could not properly decode the base64 string", ex); } this.encodedExtensions.Add(extension); } } /// <summary> /// Adds a preference for the user-specific profile or "user data directory." /// If the specified preference already exists, it will be overwritten. /// </summary> /// <param name="preferenceName">The name of the preference to set.</param> /// <param name="preferenceValue">The value of the preference to set.</param> public void AddUserProfilePreference(string preferenceName, object preferenceValue) { if (this.userProfilePreferences == null) { this.userProfilePreferences = new Dictionary<string, object>(); } this.userProfilePreferences[preferenceName] = preferenceValue; } /// <summary> /// Adds a preference for the local state file in the user's data directory for Chrome. /// If the specified preference already exists, it will be overwritten. /// </summary> /// <param name="preferenceName">The name of the preference to set.</param> /// <param name="preferenceValue">The value of the preference to set.</param> public void AddLocalStatePreference(string preferenceName, object preferenceValue) { if (this.localStatePreferences == null) { this.localStatePreferences = new Dictionary<string, object>(); } this.localStatePreferences[preferenceName] = preferenceValue; } /// <summary> /// Allows the Chrome browser to emulate a mobile device. /// </summary> /// <param name="deviceName">The name of the device to emulate. The device name must be a /// valid device name from the Chrome DevTools Emulation panel.</param> /// <remarks>Specifying an invalid device name will not throw an exeption, but /// will generate an error in Chrome when the driver starts. To unset mobile /// emulation, call this method with <see langword="null"/> as the argument.</remarks> public void EnableMobileEmulation(string deviceName) { this.mobileEmulationDeviceSettings = null; this.mobileEmulationDeviceName = deviceName; } /// <summary> /// Allows the Chrome browser to emulate a mobile device. /// </summary> /// <param name="deviceSettings">The <see cref="ChromeMobileEmulationDeviceSettings"/> /// object containing the settings of the device to emulate.</param> /// <exception cref="ArgumentException">Thrown if the device settings option does /// not have a user agent string set.</exception> /// <remarks>Specifying an invalid device name will not throw an exeption, but /// will generate an error in Chrome when the driver starts. To unset mobile /// emulation, call this method with <see langword="null"/> as the argument.</remarks> public void EnableMobileEmulation(ChromeMobileEmulationDeviceSettings deviceSettings) { this.mobileEmulationDeviceName = null; if (deviceSettings != null && string.IsNullOrEmpty(deviceSettings.UserAgent)) { throw new ArgumentException("Device settings must include a user agent string.", "deviceSettings"); } this.mobileEmulationDeviceSettings = deviceSettings; } /// <summary> /// Adds a type of window that will be listed in the list of window handles /// returned by the Chrome driver. /// </summary> /// <param name="windowType">The name of the window type to add.</param> /// <remarks>This method can be used to allow the driver to access {webview} /// elements by adding "webview" as a window type.</remarks> public void AddWindowType(string windowType) { if (string.IsNullOrEmpty(windowType)) { throw new ArgumentException("windowType must not be null or empty", "windowType"); } this.AddWindowTypes(windowType); } /// <summary> /// Adds a list of window types that will be listed in the list of window handles /// returned by the Chrome driver. /// </summary> /// <param name="windowTypesToAdd">An array of window types to add.</param> public void AddWindowTypes(params string[] windowTypesToAdd) { this.AddWindowTypes(new List<string>(windowTypesToAdd)); } /// <summary> /// Adds a list of window types that will be listed in the list of window handles /// returned by the Chrome driver. /// </summary> /// <param name="windowTypesToAdd">An <see cref="IEnumerable{T}"/> of window types to add.</param> public void AddWindowTypes(IEnumerable<string> windowTypesToAdd) { if (windowTypesToAdd == null) { throw new ArgumentNullException("windowTypesToAdd", "windowTypesToAdd must not be null"); } this.windowTypes.AddRange(windowTypesToAdd); } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Chrome driver. /// </summary> /// <param name="capabilityName">The name of the capability to add.</param> /// <param name="capabilityValue">The value of the capability to add.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalCapability(string, object)"/> /// where <paramref name="capabilityName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="capabilityValue"/>. /// Also, by default, calling this method adds capabilities to the options object passed to /// chromedriver.exe.</remarks> public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { // Add the capability to the chromeOptions object by default. This is to handle // the 80% case where the chromedriver team adds a new option in chromedriver.exe // and the bindings have not yet had a type safe option added. this.AddAdditionalCapability(capabilityName, capabilityValue, false); } /// <summary> /// Provides a means to add additional capabilities not yet added as type safe options /// for the Chrome driver. /// </summary> /// <param name="capabilityName">The name of the capability to add.</param> /// <param name="capabilityValue">The value of the capability to add.</param> /// <param name="isGlobalCapability">Indicates whether the capability is to be set as a global /// capability for the driver instead of a Chrome-specific option.</param> /// <exception cref="ArgumentException"> /// thrown when attempting to add a capability for which there is already a type safe option, or /// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string. /// </exception> /// <remarks>Calling <see cref="AddAdditionalCapability(string, object, bool)"/> /// where <paramref name="capabilityName"/> has already been added will overwrite the /// existing value with the new value in <paramref name="capabilityValue"/></remarks> public void AddAdditionalCapability(string capabilityName, object capabilityValue, bool isGlobalCapability) { if (this.IsKnownCapabilityName(capabilityName)) { string typeSafeOptionName = this.GetTypeSafeOptionName(capabilityName); string message = string.Format(CultureInfo.InvariantCulture, "There is already an option for the {0} capability. Please use the {1} instead.", capabilityName, typeSafeOptionName); throw new ArgumentException(message, "capabilityName"); } if (string.IsNullOrEmpty(capabilityName)) { throw new ArgumentException("Capability name may not be null an empty string.", "capabilityName"); } if (isGlobalCapability) { this.additionalCapabilities[capabilityName] = capabilityValue; } else { this.additionalChromeOptions[capabilityName] = capabilityValue; } } /// <summary> /// Returns DesiredCapabilities for Chrome with these options included as /// capabilities. This does not copy the options. Further changes will be /// reflected in the returned capabilities. /// </summary> /// <returns>The DesiredCapabilities for Chrome with these options.</returns> public override ICapabilities ToCapabilities() { Dictionary<string, object> chromeOptions = this.BuildChromeOptionsDictionary(); DesiredCapabilities capabilities = this.GenerateDesiredCapabilities(false); capabilities.SetCapability(ChromeOptions.Capability, chromeOptions); Dictionary<string, object> loggingPreferences = this.GenerateLoggingPreferencesDictionary(); if (loggingPreferences != null) { capabilities.SetCapability(CapabilityType.LoggingPreferences, loggingPreferences); } foreach (KeyValuePair<string, object> pair in this.additionalCapabilities) { capabilities.SetCapability(pair.Key, pair.Value); } // Should return capabilities.AsReadOnly(), and will in a future release. return capabilities; } private Dictionary<string, object> BuildChromeOptionsDictionary() { Dictionary<string, object> chromeOptions = new Dictionary<string, object>(); if (this.Arguments.Count > 0) { chromeOptions[ArgumentsChromeOption] = this.Arguments; } if (!string.IsNullOrEmpty(this.binaryLocation)) { chromeOptions[BinaryChromeOption] = this.binaryLocation; } ReadOnlyCollection<string> extensions = this.Extensions; if (extensions.Count > 0) { chromeOptions[ExtensionsChromeOption] = extensions; } if (this.localStatePreferences != null && this.localStatePreferences.Count > 0) { chromeOptions[LocalStateChromeOption] = this.localStatePreferences; } if (this.userProfilePreferences != null && this.userProfilePreferences.Count > 0) { chromeOptions[PreferencesChromeOption] = this.userProfilePreferences; } if (this.leaveBrowserRunning) { chromeOptions[DetachChromeOption] = this.leaveBrowserRunning; } if (this.useSpecCompliantProtocol) { chromeOptions[UseSpecCompliantProtocolOption] = this.useSpecCompliantProtocol; } if (!string.IsNullOrEmpty(this.debuggerAddress)) { chromeOptions[DebuggerAddressChromeOption] = this.debuggerAddress; } if (this.excludedSwitches.Count > 0) { chromeOptions[ExcludeSwitchesChromeOption] = this.excludedSwitches; } if (!string.IsNullOrEmpty(this.minidumpPath)) { chromeOptions[MinidumpPathChromeOption] = this.minidumpPath; } if (!string.IsNullOrEmpty(this.mobileEmulationDeviceName) || this.mobileEmulationDeviceSettings != null) { chromeOptions[MobileEmulationChromeOption] = this.GenerateMobileEmulationSettingsDictionary(); } if (this.perfLoggingPreferences != null) { chromeOptions[PerformanceLoggingPreferencesChromeOption] = this.GeneratePerformanceLoggingPreferencesDictionary(); } if (this.windowTypes.Count > 0) { chromeOptions[WindowTypesChromeOption] = this.windowTypes; } foreach (KeyValuePair<string, object> pair in this.additionalChromeOptions) { chromeOptions.Add(pair.Key, pair.Value); } return chromeOptions; } private Dictionary<string, object> GeneratePerformanceLoggingPreferencesDictionary() { Dictionary<string, object> perfLoggingPrefsDictionary = new Dictionary<string, object>(); perfLoggingPrefsDictionary["enableNetwork"] = this.perfLoggingPreferences.IsCollectingNetworkEvents; perfLoggingPrefsDictionary["enablePage"] = this.perfLoggingPreferences.IsCollectingPageEvents; string tracingCategories = this.perfLoggingPreferences.TracingCategories; if (!string.IsNullOrEmpty(tracingCategories)) { perfLoggingPrefsDictionary["traceCategories"] = tracingCategories; } perfLoggingPrefsDictionary["bufferUsageReportingInterval"] = Convert.ToInt64(this.perfLoggingPreferences.BufferUsageReportingInterval.TotalMilliseconds); return perfLoggingPrefsDictionary; } private Dictionary<string, object> GenerateMobileEmulationSettingsDictionary() { Dictionary<string, object> mobileEmulationSettings = new Dictionary<string, object>(); if (!string.IsNullOrEmpty(this.mobileEmulationDeviceName)) { mobileEmulationSettings["deviceName"] = this.mobileEmulationDeviceName; } else if (this.mobileEmulationDeviceSettings != null) { mobileEmulationSettings["userAgent"] = this.mobileEmulationDeviceSettings.UserAgent; Dictionary<string, object> deviceMetrics = new Dictionary<string, object>(); deviceMetrics["width"] = this.mobileEmulationDeviceSettings.Width; deviceMetrics["height"] = this.mobileEmulationDeviceSettings.Height; deviceMetrics["pixelRatio"] = this.mobileEmulationDeviceSettings.PixelRatio; if (!this.mobileEmulationDeviceSettings.EnableTouchEvents) { deviceMetrics["touch"] = this.mobileEmulationDeviceSettings.EnableTouchEvents; } mobileEmulationSettings["deviceMetrics"] = deviceMetrics; } return mobileEmulationSettings; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Messages.Messages File: CandleMessage.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Messages { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Ecng.Common; using Ecng.Serialization; using StockSharp.Localization; /// <summary> /// Candle states. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public enum CandleStates { /// <summary> /// Empty state (candle doesn't exist). /// </summary> [EnumMember] None, /// <summary> /// Candle active. /// </summary> [EnumMember] Active, /// <summary> /// Candle finished. /// </summary> [EnumMember] Finished, } /// <summary> /// The message contains information about the candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public abstract class CandleMessage : Message { /// <summary> /// Security ID. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.SecurityIdKey)] [DescriptionLoc(LocalizedStrings.SecurityIdKey, true)] [MainCategory] public SecurityId SecurityId { get; set; } /// <summary> /// Open time. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleOpenTimeKey)] [DescriptionLoc(LocalizedStrings.CandleOpenTimeKey, true)] [MainCategory] public DateTimeOffset OpenTime { get; set; } /// <summary> /// Time of candle high. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleHighTimeKey)] [DescriptionLoc(LocalizedStrings.CandleHighTimeKey, true)] [MainCategory] public DateTimeOffset HighTime { get; set; } /// <summary> /// Time of candle low. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleLowTimeKey)] [DescriptionLoc(LocalizedStrings.CandleLowTimeKey, true)] [MainCategory] public DateTimeOffset LowTime { get; set; } /// <summary> /// Close time. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleCloseTimeKey)] [DescriptionLoc(LocalizedStrings.CandleCloseTimeKey, true)] [MainCategory] public DateTimeOffset CloseTime { get; set; } /// <summary> /// Opening price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str79Key)] [DescriptionLoc(LocalizedStrings.Str80Key)] [MainCategory] public decimal OpenPrice { get; set; } /// <summary> /// Highest price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.HighestPriceKey)] [DescriptionLoc(LocalizedStrings.Str82Key)] [MainCategory] public decimal HighPrice { get; set; } /// <summary> /// Lowest price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.LowestPriceKey)] [DescriptionLoc(LocalizedStrings.Str84Key)] [MainCategory] public decimal LowPrice { get; set; } /// <summary> /// Closing price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.ClosingPriceKey)] [DescriptionLoc(LocalizedStrings.Str86Key)] [MainCategory] public decimal ClosePrice { get; set; } /// <summary> /// Volume at open. /// </summary> [DataMember] [Nullable] public decimal? OpenVolume { get; set; } /// <summary> /// Volume at close. /// </summary> [DataMember] [Nullable] public decimal? CloseVolume { get; set; } /// <summary> /// Volume at high. /// </summary> [DataMember] [Nullable] public decimal? HighVolume { get; set; } /// <summary> /// Volume at low. /// </summary> [DataMember] [Nullable] public decimal? LowVolume { get; set; } /// <summary> /// Relative colume. /// </summary> [DataMember] public decimal? RelativeVolume { get; set; } /// <summary> /// Total volume. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.VolumeKey)] [DescriptionLoc(LocalizedStrings.TotalCandleVolumeKey)] [MainCategory] public decimal TotalVolume { get; set; } /// <summary> /// Open interest. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.OIKey)] [DescriptionLoc(LocalizedStrings.OpenInterestKey)] [MainCategory] public decimal? OpenInterest { get; set; } /// <summary> /// Number of ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TicksKey)] [DescriptionLoc(LocalizedStrings.TickCountKey)] [MainCategory] public int? TotalTicks { get; set; } /// <summary> /// Number of uptrending ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TickUpKey)] [DescriptionLoc(LocalizedStrings.TickUpCountKey)] [MainCategory] public int? UpTicks { get; set; } /// <summary> /// Number of downtrending ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TickDownKey)] [DescriptionLoc(LocalizedStrings.TickDownCountKey)] [MainCategory] public int? DownTicks { get; set; } /// <summary> /// State. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.StateKey)] [DescriptionLoc(LocalizedStrings.CandleStateKey)] [MainCategory] public CandleStates State { get; set; } /// <summary> /// ID of the original message <see cref="MarketDataMessage.TransactionId"/> for which this message is a response. /// </summary> [DataMember] public long OriginalTransactionId { get; set; } /// <summary> /// It is the last message in the requested batch of candles. /// </summary> [DataMember] public bool IsFinished { get; set; } /// <summary> /// Price levels. /// </summary> [DataMember] public IEnumerable<CandlePriceLevel> PriceLevels { get; set; } /// <summary> /// Candle arg. /// </summary> public abstract object Arg { get; set; } /// <summary> /// Initialize <see cref="CandleMessage"/>. /// </summary> /// <param name="type">Message type.</param> protected CandleMessage(MessageTypes type) : base(type) { } /// <summary> /// Copy parameters. /// </summary> /// <param name="copy">Copy.</param> /// <returns>Copy.</returns> protected CandleMessage CopyTo(CandleMessage copy) { if (copy == null) throw new ArgumentNullException(nameof(copy)); copy.LocalTime = LocalTime; copy.ClosePrice = ClosePrice; copy.CloseTime = CloseTime; copy.CloseVolume = CloseVolume; copy.HighPrice = HighPrice; copy.HighVolume = HighVolume; copy.LowPrice = LowPrice; copy.LowVolume = LowVolume; copy.OpenInterest = OpenInterest; copy.OpenPrice = OpenPrice; copy.OpenTime = OpenTime; copy.OpenVolume = OpenVolume; copy.SecurityId = SecurityId; copy.TotalVolume = TotalVolume; copy.RelativeVolume = RelativeVolume; copy.OriginalTransactionId = OriginalTransactionId; copy.DownTicks = DownTicks; copy.UpTicks = UpTicks; copy.TotalTicks = TotalTicks; copy.IsFinished = IsFinished; copy.PriceLevels = PriceLevels?.Select(l => l.Clone()).ToArray(); return copy; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"{Type},T={OpenTime:yyyy/MM/dd HH:mm:ss.fff},O={OpenPrice},H={HighPrice},L={LowPrice},C={ClosePrice},V={TotalVolume}"; } } /// <summary> /// The message contains information about the time-frame candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class TimeFrameCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="TimeFrameCandleMessage"/>. /// </summary> public TimeFrameCandleMessage() : base(MessageTypes.CandleTimeFrame) { } /// <summary> /// Time-frame. /// </summary> [DataMember] public TimeSpan TimeFrame { get; set; } /// <summary> /// Create a copy of <see cref="TimeFrameCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new TimeFrameCandleMessage { TimeFrame = TimeFrame }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return TimeFrame; } set { TimeFrame = (TimeSpan)value; } } } /// <summary> /// The message contains information about the tick candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class TickCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="TickCandleMessage"/>. /// </summary> public TickCandleMessage() : base(MessageTypes.CandleTick) { } /// <summary> /// Maximum tick count. /// </summary> [DataMember] public int MaxTradeCount { get; set; } /// <summary> /// Create a copy of <see cref="TickCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new TickCandleMessage { MaxTradeCount = MaxTradeCount }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return MaxTradeCount; } set { MaxTradeCount = (int)value; } } } /// <summary> /// The message contains information about the volume candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class VolumeCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="VolumeCandleMessage"/>. /// </summary> public VolumeCandleMessage() : base(MessageTypes.CandleVolume) { } /// <summary> /// Maximum volume. /// </summary> [DataMember] public decimal Volume { get; set; } /// <summary> /// Create a copy of <see cref="VolumeCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new VolumeCandleMessage { Volume = Volume }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return Volume; } set { Volume = (decimal)value; } } } /// <summary> /// The message contains information about the range candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class RangeCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="RangeCandleMessage"/>. /// </summary> public RangeCandleMessage() : base(MessageTypes.CandleRange) { } /// <summary> /// Range of price. /// </summary> [DataMember] public Unit PriceRange { get; set; } /// <summary> /// Create a copy of <see cref="RangeCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new RangeCandleMessage { PriceRange = PriceRange }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return PriceRange; } set { PriceRange = (Unit)value; } } } /// <summary> /// Symbol types. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public enum PnFTypes { /// <summary> /// X (price up). /// </summary> [EnumMember] X, /// <summary> /// 0 (price down). /// </summary> [EnumMember] O, } /// <summary> /// Point in fugure (X0) candle arg. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class PnFArg : Equatable<PnFArg> { private Unit _boxSize = new Unit(); /// <summary> /// Range of price above which create a new <see cref="PnFTypes.X"/> or <see cref="PnFTypes.O"/>. /// </summary> [DataMember] public Unit BoxSize { get { return _boxSize; } set { if (value == null) throw new ArgumentNullException(nameof(value)); _boxSize = value; } } /// <summary> /// The number of boxes (an <see cref="PnFTypes.X"/> or an <see cref="PnFTypes.O"/>) required to cause a reversal. /// </summary> [DataMember] public int ReversalAmount { get; set; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"Box = {BoxSize} RA = {ReversalAmount}"; } /// <summary> /// Create a copy of <see cref="PnFArg"/>. /// </summary> /// <returns>Copy.</returns> public override PnFArg Clone() { return new PnFArg { BoxSize = BoxSize.Clone(), ReversalAmount = ReversalAmount, }; } /// <summary> /// Compare <see cref="PnFArg"/> on the equivalence. /// </summary> /// <param name="other">Another value with which to compare.</param> /// <returns><see langword="true" />, if the specified object is equal to the current object, otherwise, <see langword="false" />.</returns> protected override bool OnEquals(PnFArg other) { return other.BoxSize == BoxSize && other.ReversalAmount == ReversalAmount; } /// <summary> /// Get the hash code of the object <see cref="PnFArg"/>. /// </summary> /// <returns>A hash code.</returns> public override int GetHashCode() { return BoxSize.GetHashCode() ^ ReversalAmount.GetHashCode(); } } /// <summary> /// The message contains information about the XO candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class PnFCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="PnFCandleMessage"/>. /// </summary> public PnFCandleMessage() : base(MessageTypes.CandlePnF) { } /// <summary> /// Value of arguments. /// </summary> [DataMember] public PnFArg PnFArg { get; set; } /// <summary> /// Type of symbols. /// </summary> [DataMember] public PnFTypes PnFType { get; set; } /// <summary> /// Create a copy of <see cref="PnFCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new PnFCandleMessage { PnFArg = PnFArg, PnFType = PnFType }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return PnFArg; } set { PnFArg = (PnFArg)value; } } } /// <summary> /// The message contains information about the renko candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class RenkoCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="RenkoCandleMessage"/>. /// </summary> public RenkoCandleMessage() : base(MessageTypes.CandleRenko) { } /// <summary> /// Possible price change range. /// </summary> [DataMember] public Unit BoxSize { get; set; } /// <summary> /// Create a copy of <see cref="RenkoCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new RenkoCandleMessage { BoxSize = BoxSize }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return BoxSize; } set { BoxSize = (Unit)value; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.ObjectModel; using System.Runtime.Serialization; namespace System.Management.Automation { /// <summary> /// Base class for items in the PSInformationalBuffers. /// /// A PSInformationalRecord consists of a string Message and the InvocationInfo and pipeline state corresponding /// to the command that created the record. /// </summary> [DataContract()] public abstract class InformationalRecord { /// <remarks> /// This class can be instantiated only by its derived classes /// </remarks> internal InformationalRecord(string message) { _message = message; _invocationInfo = null; _pipelineIterationInfo = null; _serializeExtendedInfo = false; } /// <summary> /// Creates an InformationalRecord object from a record serialized as a PSObject by ToPSObjectForRemoting. /// </summary> internal InformationalRecord(PSObject serializedObject) { _message = (string)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_Message"); _serializeExtendedInfo = (bool)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_SerializeInvocationInfo"); if (_serializeExtendedInfo) { _invocationInfo = new InvocationInfo(serializedObject); ArrayList pipelineIterationInfo = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(serializedObject, "InformationalRecord_PipelineIterationInfo"); _pipelineIterationInfo = new ReadOnlyCollection<int>((int[])pipelineIterationInfo.ToArray(typeof(int))); } else { _invocationInfo = null; } } /// <summary> /// The message written by the command that created this record. /// </summary> public string Message { get { return _message; } set { _message = value; } } /// <summary> /// The InvocationInfo of the command that created this record. /// </summary> /// <remarks> /// The InvocationInfo can be null if the record was not created by a command. /// </remarks> public InvocationInfo InvocationInfo { get { return _invocationInfo; } } /// <summary> /// The status of the pipeline when this record was created. /// </summary> /// <remarks> /// The PipelineIterationInfo can be null if the record was not created by a command. /// </remarks> public ReadOnlyCollection<int> PipelineIterationInfo { get { return _pipelineIterationInfo; } } /// <summary> /// Sets the InvocationInfo (and PipelineIterationInfo) for this record. /// </summary> internal void SetInvocationInfo(InvocationInfo invocationInfo) { _invocationInfo = invocationInfo; // // Copy a snapshot of the PipelineIterationInfo from the InvocationInfo to this InformationalRecord // if (invocationInfo.PipelineIterationInfo != null) { int[] snapshot = (int[])invocationInfo.PipelineIterationInfo.Clone(); _pipelineIterationInfo = new ReadOnlyCollection<int>(snapshot); } } /// <summary> /// Whether to serialize the InvocationInfo and PipelineIterationInfo during remote calls. /// </summary> internal bool SerializeExtendedInfo { get { return _serializeExtendedInfo; } set { _serializeExtendedInfo = value; } } /// <summary> /// Returns the record's message. /// </summary> public override string ToString() { return this.Message; } /// <summary> /// Adds the information about this informational record to a PSObject as note properties. /// The PSObject is used to serialize the record during remote operations. /// </summary> internal virtual void ToPSObjectForRemoting(PSObject psObject) { RemotingEncoder.AddNoteProperty<string>(psObject, "InformationalRecord_Message", () => this.Message); // // The invocation info may be null if the record was created via WriteVerbose/Warning/DebugLine instead of WriteVerbose/Warning/Debug, in that case // we set InformationalRecord_SerializeInvocationInfo to false. // if (!this.SerializeExtendedInfo || _invocationInfo == null) { RemotingEncoder.AddNoteProperty(psObject, "InformationalRecord_SerializeInvocationInfo", () => false); } else { RemotingEncoder.AddNoteProperty(psObject, "InformationalRecord_SerializeInvocationInfo", () => true); _invocationInfo.ToPSObjectForRemoting(psObject); RemotingEncoder.AddNoteProperty<object>(psObject, "InformationalRecord_PipelineIterationInfo", () => this.PipelineIterationInfo); } } [DataMember()] private string _message; private InvocationInfo _invocationInfo; private ReadOnlyCollection<int> _pipelineIterationInfo; private bool _serializeExtendedInfo; } /// <summary> /// A warning record in the PSInformationalBuffers. /// </summary> [DataContract()] public class WarningRecord : InformationalRecord { /// <summary> /// </summary> /// <param name="message"></param> public WarningRecord(string message) : base(message) { } /// <summary> /// </summary> /// <param name="record"></param> public WarningRecord(PSObject record) : base(record) { } /// <summary> /// Constructor for Fully qualified warning Id. /// </summary> /// <param name="fullyQualifiedWarningId">Fully qualified warning Id.</param> /// <param name="message">Warning message.</param> public WarningRecord(string fullyQualifiedWarningId, string message) : base(message) { _fullyQualifiedWarningId = fullyQualifiedWarningId; } /// <summary> /// Constructor for Fully qualified warning Id. /// </summary> /// <param name="fullyQualifiedWarningId">Fully qualified warning Id.</param> /// <param name="record">Warning serialized object.</param> public WarningRecord(string fullyQualifiedWarningId, PSObject record) : base(record) { _fullyQualifiedWarningId = fullyQualifiedWarningId; } /// <summary> /// String which uniquely identifies this warning condition. /// </summary> public string FullyQualifiedWarningId { get { return _fullyQualifiedWarningId ?? string.Empty; } } private string _fullyQualifiedWarningId; } /// <summary> /// A debug record in the PSInformationalBuffers. /// </summary> [DataContract()] public class DebugRecord : InformationalRecord { /// <summary> /// </summary> /// <param name="message"></param> public DebugRecord(string message) : base(message) { } /// <summary> /// </summary> /// <param name="record"></param> public DebugRecord(PSObject record) : base(record) { } } /// <summary> /// A verbose record in the PSInformationalBuffers. /// </summary> [DataContract()] public class VerboseRecord : InformationalRecord { /// <summary> /// </summary> /// <param name="message"></param> public VerboseRecord(string message) : base(message) { } /// <summary> /// </summary> /// <param name="record"></param> public VerboseRecord(PSObject record) : base(record) { } } }
using System; using UnityEngine; using System.Linq; using System.Diagnostics; using System.Collections.Generic; using System.Text; using UnityEngine.UI; public class DosBox : MonoBehaviour { public BoxInfo RightText; public GameObject Actors; public Arrow Arrow; public Box BoxPrefab; public Box[] Boxes; public bool ShowAdditionalInfo; public bool ShowAITD1Vars; public bool SpeedRunMode; public int CurrentCamera = -1; public int CurrentCameraRoom = -1; public int CurrentCameraFloor = -1; public ProcessMemory ProcessMemory; public Box Player; private int entryPoint; private readonly Dictionary<int, int> bodyIdToMemoryAddress = new Dictionary<int, int>(); private readonly Dictionary<int, int> animIdToMemoryAddress = new Dictionary<int, int>(); public GameVersion GameVersion; private GameConfig gameConfig; private readonly Dictionary<GameVersion, GameConfig> gameConfigs = new Dictionary<GameVersion, GameConfig> { { GameVersion.AITD1 , new GameConfig(0x220CE, 160, 82) }, { GameVersion.AITD1_FLOPPY , new GameConfig(0x20542, 160, 82) }, { GameVersion.AITD1_DEMO , new GameConfig(0x2050A, 160, 82) }, { GameVersion.AITD2 , new GameConfig(0x300D0, 180, 90) }, { GameVersion.AITD2_FLOPPY , new GameConfig(0x2F850, 180, 90) }, { GameVersion.AITD2_DEMO , new GameConfig(0x38DC0, 176, 86) }, { GameVersion.AITD3 , new GameConfig(0x38180, 182, 90) }, { GameVersion.AITD3_DEMO , new GameConfig(0x377A0, 182, 90) }, { GameVersion.JACK , new GameConfig(0x39EC4, 180, 90) }, { GameVersion.TIMEGATE , new GameConfig(0x00000, 202, 90, 0x2ADD0) }, { GameVersion.TIMEGATE_DEMO, new GameConfig(0x00000, 202, 90, 0x45B98) }, }; private Vector3 lastPlayerPosition; private int lastValidPlayerIndex = -1; private int linkfloor; private int linkroom; private readonly byte[] memory = new byte[640 * 1024]; //fps private int oldFramesCount; private readonly Queue<KeyValuePair<int, float>> previousFrames = new Queue<KeyValuePair<int, float>>(); private int frameCounter; private float lastDelay; private readonly Timer delayCounter = new Timer(); private readonly Timer totalDelay = new Timer(); private int inHand; private bool allowInventory; private bool saveTimerFlag; private uint internalTimer1, internalTimer1Frozen; private int internalTimer2, internalTimer2Frozen; Box GetActor(int index) { Box box = Boxes[index]; if (box == null) { box = Instantiate(BoxPrefab); box.transform.parent = Actors.transform; box.name = "Actor"; box.Slot = index; box.DosBox = this; box.RoomLoader = GetComponent<RoomLoader>(); Boxes[index] = box; } return box; } void RemoveActor(int index) { Box box = Boxes[index]; if (box != null) { Destroy(box.gameObject); Boxes[index] = null; } } void OnDestroy() { if (ProcessMemory != null) { ProcessMemory.Close(); } } bool AreActorsInitialized() { for (int i = 0 ; i < Boxes.Length ; i++) { int k = GetActorMemoryAddress(i); int id = memory.ReadShort(k); if (id != 0) { return true; } } return false; } public void RefreshMemory() { if (ProcessMemory != null && ProcessMemory.Read(memory, 0, memory.Length) == 0) { ProcessMemory.Close(); ProcessMemory = null; } } public void UpdateAllActors() { if (gameConfig == null) { return; } Player = null; bool initialized = AreActorsInitialized(); //read actors info for (int i = 0 ; i < Boxes.Length ; i++) //up to 50 actors max { int k = GetActorMemoryAddress(i); int id = memory.ReadShort(k + 0); if (id != -1 && initialized) { Box box = GetActor(i); box.ID = id; box.Body = memory.ReadShort(k + 2); box.Flags = memory.ReadShort(k + 4); box.ColFlags = memory.ReadShort(k + 6); memory.ReadBoundingBox(k + 8, out box.BoundingLower, out box.BoundingUpper); FixBoundingWrap(ref box.BoundingLower.x, ref box.BoundingUpper.x); FixBoundingWrap(ref box.BoundingLower.z, ref box.BoundingUpper.z); memory.ReadBoundingBox(k + 20, out box.Box2DLower, out box.Box2DUpper); box.LocalPosition = memory.ReadVector(k + 28); box.WorldPosition = memory.ReadVector(k + 34); box.Angles = memory.ReadVector(k + 40); box.Floor = memory.ReadShort(k + 46); box.Room = memory.ReadShort(k + 48); box.LifeMode = memory.ReadShort(k + 50); box.Life = memory.ReadShort(k + 52); box.Chrono = memory.ReadUnsignedInt(k + 54); box.RoomChrono = memory.ReadUnsignedInt(k + 58); box.Anim = memory.ReadShort(k + 62); box.AnimType = memory.ReadShort(k + 64); box.NextAnim = memory.ReadShort(k + 66); box.Keyframe = memory.ReadShort(k + 74); box.TotalFrames = memory.ReadShort(k + 76); box.EndFrame = memory.ReadShort(k + 78); box.EndAnim = memory.ReadShort(k + 80); box.TrackMode = memory.ReadShort(k + gameConfig.TrackModeOffset); box.TrackNumber = memory.ReadShort(k + 84); box.PositionInTrack = memory.ReadShort(k + 88); int bodyAddress, animAddress; if (bodyIdToMemoryAddress.TryGetValue(box.Body, out bodyAddress) && animIdToMemoryAddress.TryGetValue(box.Anim, out animAddress) && animAddress < memory.Length && bodyAddress < memory.Length) { int bonesInAnim = memory.ReadShort(animAddress + 2); int keyframeAddress = animAddress + box.Keyframe * (bonesInAnim * 8 + 8); box.KeyFrameTime = memory.ReadUnsignedShort(bodyAddress + 20); box.KeyFrameLength = memory.ReadShort(keyframeAddress + 4); } if (GameVersion == GameVersion.AITD1) { box.Mod = memory.ReadVector(k + 90); } else { box.Mod = Vector3Int.Zero; } box.OldAngle = memory.ReadShort(k + 106); box.NewAngle = memory.ReadShort(k + 108); box.RotateTime = memory.ReadShort(k + 110); box.Speed = memory.ReadShort(k + 116); box.Col = memory.ReadVector(k + 126); box.ColBy = memory.ReadShort(k + 132); box.HardTrigger = memory.ReadShort(k + 134); box.HardCol = memory.ReadShort(k + 136); box.Hit = memory.ReadShort(k + 138); box.HitBy = memory.ReadShort(k + 140); box.ActionType = memory.ReadShort(k + 142); box.HotBoxSize = memory.ReadShort(k + 148); box.HitForce = memory.ReadShort(k + 150); box.HotPosition = memory.ReadVector(k + 154); } else { RemoveActor(i); } } //search current camera target (fallback if player not found) int cameraTargetID = -1; if (GameVersion == GameVersion.AITD1) { int currentCameraTarget = memory.ReadShort(entryPoint + 0x19B6C); foreach (Box box in Boxes) { if (box != null && box.Slot == currentCameraTarget) { cameraTargetID = box.ID; break; } } } //search player foreach (Box box in Boxes) { if (box != null && (box.TrackMode == 1 || box.ID == lastValidPlayerIndex)) { //update player index lastValidPlayerIndex = cameraTargetID = box.ID; break; } } //automatically switch room and floor (has to be done before setting other actors positions) foreach (Box box in Boxes) { if (box != null && box.ID == cameraTargetID) { SwitchRoom(box.Floor, box.Room); } } //update all boxes foreach (Box box in Boxes) { if (box != null) { Vector3Int roomPosition; if (GetComponent<RoomLoader>().TryGetRoomPosition(box.Floor, box.Room, out roomPosition)) { //local to global position Vector3 boxPosition = (Vector3)(box.BoundingUpper + box.BoundingLower) / 2000.0f + (Vector3)roomPosition / 1000.0f; boxPosition = new Vector3(boxPosition.x, -boxPosition.y, boxPosition.z); if (box.transform.position != boxPosition) { Vector3 offset = 1000.0f * (box.transform.position - boxPosition); float distance = new Vector3(Mathf.Round(offset.x), 0.0f, Mathf.Round(offset.z)).magnitude; box.LastOffset = Mathf.RoundToInt(distance); box.LastDistance += distance; box.transform.position = boxPosition; } //make actors appears slightly bigger than they are to be not covered by colliders Vector3 delta = Vector3.one; box.transform.localScale = (box.BoundingSize + delta) / 1000.0f; //make sure very small actors are visible box.transform.localScale = Vector3.Max(box.transform.localScale, Vector3.one * 0.1f); if (GameVersion == GameVersion.AITD1) { UpdateHotPointBox(box, roomPosition); } //camera target if(box.ID == cameraTargetID) { //check if player has moved if (box.transform.position.x != lastPlayerPosition.x || box.transform.position.z != lastPlayerPosition.z) { //center camera to player position GetComponent<RoomLoader>().CenterCamera(new Vector2(box.transform.position.x, box.transform.position.z)); lastPlayerPosition = box.transform.position; } } //player bool isPlayer = box.ID == lastValidPlayerIndex; if (isPlayer) { //arrow follow player Arrow.transform.position = box.transform.position + new Vector3(0.0f, box.transform.localScale.y / 2.0f + 0.001f, 0.0f); //face camera float angle = box.Angles.y * 360.0f / 1024.0f; Arrow.transform.rotation = Quaternion.AngleAxis(90.0f, -Vector3.left); Arrow.transform.rotation *= Quaternion.AngleAxis((angle + 180.0f) % 360.0f, Vector3.forward); float minBoxScale = Mathf.Min(box.transform.localScale.x, box.transform.localScale.z); Arrow.transform.localScale = new Vector3( minBoxScale * 0.9f, minBoxScale * 0.9f, 1.0f); //player is white box.Color = new Color32(255, 255, 255, 255); Arrow.AlwaysOnTop = Camera.main.orthographic; Player = box; } else { if (box.Slot == 0) { box.Color = new Color32(255, 255, 255, 255); } else { //other actors are green box.Color = new Color32(0, 128, 0, 255); } } if (GameVersion == GameVersion.AITD1) { UpdateWorldPosBox(box, roomPosition, isPlayer); } box.AlwaysOnTop = Camera.main.orthographic; } else { RemoveActor(box.Slot); } } } if (GameVersion == GameVersion.AITD1) { CurrentCamera = memory.ReadShort(entryPoint + 0x24056); CurrentCameraFloor = memory.ReadShort(entryPoint + 0x24058); CurrentCameraRoom = memory.ReadShort(entryPoint + 0x2405A); } if (ShowAITD1Vars) { allowInventory = memory.ReadShort(entryPoint + 0x19B6E) == 1; inHand = memory.ReadShort(entryPoint + 0x24054); //set by AITD when long running code is started (eg: loading ressource) saveTimerFlag = memory[entryPoint + 0x1B0FC] == 1; internalTimer1 = memory.ReadUnsignedInt(entryPoint + 0x19D12); internalTimer2 = memory.ReadUnsignedShort(entryPoint + 0x242E0); internalTimer1Frozen = memory.ReadUnsignedInt(entryPoint + 0x1B0F8); internalTimer2Frozen = memory.ReadUnsignedShort(entryPoint + 0x1B0F6); } } public uint Timer1 { get { return saveTimerFlag ? internalTimer1Frozen : internalTimer1; } } public int Timer2 { get { return saveTimerFlag ? internalTimer2Frozen : internalTimer2; } } public void UpdateArrowVisibility() { //arrow is only active if actors are active and player is active Arrow.gameObject.SetActive(Actors.activeSelf && Player != null && Player.gameObject.activeSelf && Player.transform.localScale.magnitude > 0.01f); } void SwitchRoom(int floor, int room) { if (linkfloor != floor || linkroom != room) { linkfloor = floor; linkroom = room; GetComponent<RoomLoader>().RefreshRooms(linkfloor, linkroom); } } void RefreshCacheEntries(Dictionary<int, int> entries, int address) { entries.Clear(); int cacheAddress = memory.ReadFarPointer(entryPoint + address); if (cacheAddress > 0 && cacheAddress < memory.Length) { int numEntries = Math.Min((int)memory.ReadUnsignedShort(cacheAddress + 16), 100); int baseAddress = memory.ReadFarPointer(cacheAddress + 18); for (int i = 0 ; i < numEntries ; i++) { int addr = cacheAddress + 22 + i * 10; int id = memory.ReadUnsignedShort(addr); int offset = memory.ReadUnsignedShort(addr + 2); entries[id] = baseAddress + offset; } } } void UpdateHotPointBox(Box box, Vector3Int roomPosition) { //hot point Box hotPoint = box.BoxHotPoint; if (box.ActionType == 2) { if (hotPoint == null) { hotPoint = Instantiate(BoxPrefab); hotPoint.name = "HotPoint"; hotPoint.Color = new Color32(255, 0, 0, 255); Destroy(hotPoint.gameObject.GetComponent<BoxCollider>()); box.BoxHotPoint = hotPoint; } Vector3 finalPos = (Vector3)(box.HotPosition + box.LocalPosition + box.Mod + roomPosition) / 1000.0f; finalPos = new Vector3(finalPos.x, -finalPos.y, finalPos.z); hotPoint.transform.position = finalPos; hotPoint.transform.localScale = Vector3.one * (box.HotBoxSize / 500.0f); hotPoint.AlwaysOnTop = Camera.main.orthographic; } else if (hotPoint != null) { Destroy(hotPoint.gameObject); box.BoxHotPoint = null; } } void UpdateWorldPosBox(Box box, Vector3Int roomPosition, bool isPlayer) { Vector3Int currentRoomPos; if (GetComponent<RoomLoader>().TryGetRoomPosition(CurrentCameraFloor, CurrentCameraRoom, out currentRoomPos)) { Box worldPos = box.BoxWorldPos; Vector3Int boundingPos = box.WorldPosition + box.Mod + currentRoomPos - roomPosition; //worldpos unsync if (isPlayer && (boundingPos.x != box.BoundingPos.x || boundingPos.z != box.BoundingPos.z)) { if (worldPos == null) { worldPos = Instantiate(BoxPrefab); worldPos.name = "WorldPos"; worldPos.Color = new Color32(255, 0, 0, 128); Destroy(worldPos.gameObject.GetComponent<BoxCollider>()); box.BoxWorldPos = worldPos; } Vector3 finalPos = (Vector3)(box.WorldPosition + box.Mod + currentRoomPos) / 1000.0f; float height = -(box.BoundingUpper.y + box.BoundingUpper.y) / 2000.0f; finalPos = new Vector3(finalPos.x, height + 0.001f, finalPos.z); worldPos.transform.position = finalPos; worldPos.transform.localScale = box.transform.localScale; worldPos.AlwaysOnTop = Camera.main.orthographic; } else if (worldPos != null) { Destroy(worldPos.gameObject); box.BoxWorldPos = null; } } } public void UpdateRightText() { RightText.Clear(); if (Player != null) { float angle = Player.Angles.y * 360.0f / 1024.0f; float sideAngle = (angle + 45.0f) % 90.0f - 45.0f; RightText.Append("Position", Player.LocalPosition + Player.Mod); RightText.Append("Angle", "{0:N1} {1:N1}", angle, sideAngle); } if (ShowAITD1Vars || ShowAdditionalInfo) { if(Player != null) RightText.AppendLine(); if (ShowAITD1Vars) { int calculatedFps = previousFrames.Sum(x => x.Key); TimeSpan totalDelayTS = TimeSpan.FromSeconds(totalDelay.Elapsed); uint timer1Delay = internalTimer1 - internalTimer1Frozen; int timer2Delay = internalTimer2 - internalTimer2Frozen; RightText.Append("Timer 1", !saveTimerFlag ? "{0}.{1:D2}" : "{0}.{1:D2} {2:D2}.{3:D2}", TimeSpan.FromSeconds(Timer1 / 60), Timer1 % 60, timer1Delay / 60 % 60, timer1Delay % 60); RightText.Append("Timer 2", !saveTimerFlag ? "{0}.{1:D2}" : "{0}.{1:D2} {2:D2}.{3:D2}", TimeSpan.FromSeconds(Timer2 / 60), Timer2 % 60, timer2Delay / 60 % 60, timer2Delay % 60); RightText.Append("FPS/Frame/Delay", "{0}; {1}; {2} ms", calculatedFps, frameCounter, Mathf.FloorToInt(lastDelay * 1000)); RightText.Append("Total delay", "{0:D2}:{1:D2}:{2:D2}.{3:D3} ", totalDelayTS.Hours, totalDelayTS.Minutes, totalDelayTS.Seconds, totalDelayTS.Milliseconds); } Vector3Int mousePosition = GetComponent<RoomLoader>().GetMousePosition(linkroom, linkfloor); RightText.Append("Cursor position", "{0} {1}", Mathf.Clamp(mousePosition.x, -32768, 32767), Mathf.Clamp(mousePosition.z, -32768, 32767)); if(Player != null) RightText.Append("Last offset/dist", "{0}; {1}", Player.LastOffset, Mathf.RoundToInt(Player.LastDistance)); if (ShowAITD1Vars) { RightText.Append("Allow inventory", allowInventory ? "Yes" : "No"); RightText.Append("In hand", inHand); } } RightText.UpdateText(); } void Update() { if (Input.GetKeyDown(KeyCode.Q)) { totalDelay.Reset(); } if (Input.GetKeyDown(KeyCode.W)) { foreach (Box box in Boxes) { if (box != null) { box.LastDistance = 0.0f; } } } if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && GameVersion == GameVersion.AITD1 && ProcessMemory != null) { if (Input.GetKeyDown(KeyCode.Alpha1)) { //internal timer 1 byte[] buffer = new byte[4]; buffer.Write(Timer1 - 60 * 5, 0); //back 5 frames ProcessMemory.Write(buffer, entryPoint + 0x19D12, buffer.Length); } if (Input.GetKeyDown(KeyCode.Alpha2)) { //internal timer 2 byte[] buffer = new byte[2]; buffer.Write((ushort)(Timer2 - 60 * 5), 0); //back 5 frames ProcessMemory.Write(buffer, entryPoint + 0x242E0, buffer.Length); } } } public void RefreshCacheEntries() { if (ShowAITD1Vars) { RefreshCacheEntries(animIdToMemoryAddress, 0x218D3); RefreshCacheEntries(bodyIdToMemoryAddress, 0x218D7); } } public void CalculateFPS() { if (ProcessMemory == null) { return; } if (ShowAITD1Vars) { //fps int fps = memory.ReadShort(entryPoint + 0x19D18); //frames counter (reset to zero every second by AITD) int frames = memory.ReadShort(entryPoint + 0x2117C); //check how much frames elapsed since last time int diff; if (frames >= oldFramesCount) { diff = frames - oldFramesCount; //eg: 20 - 15 } else { diff = fps - oldFramesCount + frames; //special case: eg: 60 - 58 + 3 } oldFramesCount = frames; frameCounter += diff; float time = Time.time; if (diff > 0) { previousFrames.Enqueue(new KeyValuePair<int, float>(diff, time)); } //remove any frame info older than one second while (previousFrames.Count > 0 && previousFrames.Peek().Value < (time - 1.0f)) { previousFrames.Dequeue(); } } } public void CheckDelay() { if(ProcessMemory == null) { totalDelay.Stop(); delayCounter.Stop(); return; } if(ShowAITD1Vars) { if(delayCounter.Elapsed >= 0.1f) //100ms { lastDelay = delayCounter.Elapsed; } //check for large delays if (!saveTimerFlag) { delayCounter.Reset(); totalDelay.Stop(); } else { delayCounter.Start(); totalDelay.Start(); } } } void FixBoundingWrap(ref int a, ref int b) { if(a > b) { if(a < -b) { b += 65536; } else { a -= 65536; } } } #region SearchDOSBox int SearchDOSBoxProcess() { int? processId = Process.GetProcesses() .Where(x => GetProcessName(x).StartsWith("DOSBOX", StringComparison.InvariantCultureIgnoreCase)) .Select(x => (int?)x.Id) .FirstOrDefault(); if(processId.HasValue) { return processId.Value; } return -1; } string GetProcessName(Process process) { try { //could fail because not enough permissions (eg : admin process) return process.ProcessName; } catch { return string.Empty; } } bool TryGetMemoryReader(out ProcessMemory reader) { int processId = SearchDOSBoxProcess(); if (processId != -1) { reader = new ProcessMemory(processId); reader.BaseAddress = reader.SearchFor16MRegion(); if (reader.BaseAddress != -1) { return true; } reader.Close(); } reader = null; return false; } bool TryGetExeEntryPoint(out int entryPoint) { int psp = memory.ReadUnsignedShort(0x0B30) * 16; if (psp > 0) { int exeSize = memory.ReadUnsignedShort(psp - 16 + 3) * 16; if (exeSize > 100 * 1024 && exeSize < 250 * 1024) //is AITD exe loaded yet? { entryPoint = psp + 0x100; return true; } } entryPoint = -1; return false; } bool FindActorsAddressAITD(GameVersion gameVersion) { ProcessMemory.Read(memory, 0, memory.Length); if (!TryGetExeEntryPoint(out entryPoint)) { return false; } switch (gameVersion) { case GameVersion.AITD1: if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("CD Not Found")) == -1) { if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("USA.PAK")) != -1) { gameVersion = GameVersion.AITD1_DEMO; } else { gameVersion = GameVersion.AITD1_FLOPPY; } } break; case GameVersion.AITD2: if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("Not a CD-ROM drive")) == -1) { if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("BATL.PAK")) == -1) { gameVersion = GameVersion.AITD2_DEMO; } else { gameVersion = GameVersion.AITD2_FLOPPY; } } break; case GameVersion.AITD3: if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("AN3.PAK")) == -1) { gameVersion = GameVersion.AITD3_DEMO; } break; } GameVersion = gameVersion; gameConfig = gameConfigs[gameVersion]; return true; } bool FindActorsAddressTimeGate(GameVersion gameVersion) { //scan range: 0x110000 (extended memory) - 0x300000 (3MB) byte[] pattern = Encoding.ASCII.GetBytes("HARD_DEC"); int dataSegment = ProcessMemory.SearchForBytePattern(0x110000, 0x1F0000, buffer => Utils.IndexOf(buffer, pattern, 28, 16)); if (dataSegment != -1) { ProcessMemory.Read(memory, dataSegment, memory.Length); if (Utils.IndexOf(memory, Encoding.ASCII.GetBytes("Time Gate not found")) == -1) { gameVersion = GameVersion.TIMEGATE_DEMO; } GameVersion = gameVersion; gameConfig = gameConfigs[gameVersion]; ProcessMemory.Read(memory, dataSegment + gameConfig.ActorsPointer, 4); var result = memory.ReadUnsignedInt(0); //read pointer value if (result != 0) { ProcessMemory.BaseAddress += result; entryPoint = 0; return true; } } return false; } #endregion #region Room loader public bool LinkToDosBOX(int floor, int room, GameVersion gameVersion) { if (!TryGetMemoryReader(out ProcessMemory)) { return false; } if (!FindActorsAddress(gameVersion)) { ProcessMemory.Close(); ProcessMemory = null; return false; } //force reload linkfloor = floor; linkroom = room; Player = null; lastValidPlayerIndex = -1; return true; } public bool FindActorsAddress(GameVersion gameVersion) { if (gameVersion == GameVersion.TIMEGATE) { return FindActorsAddressTimeGate(gameVersion); } return FindActorsAddressAITD(gameVersion); } public void ResetCamera(int floor, int room) { lastPlayerPosition = Vector3.zero; linkfloor = floor; linkroom = room; } public int GetActorMemoryAddress(int index) { return gameConfig.ActorsAddress + entryPoint + index * gameConfig.ActorStructSize; } public int GetActorSize() { return gameConfig.ActorStructSize; } public int GetObjectMemoryAddress(int index) { int objectAddress = memory.ReadFarPointer(entryPoint + 0x2400E); return objectAddress + index * 52; } public Box RefreshBoxUsingID(Box box, int boxId) { //make sure ID still match if(box != null && box.ID != boxId) { box = null; } if (box == null && boxId != -1) { //if actor is no more available (eg : after room switch) search for it foreach (Box b in Boxes) { if (b != null && b.ID == boxId) { box = b; break; } } } return box; } #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. // URLString // // // Implementation of membership condition for zones // namespace System.Security.Util { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Runtime.Serialization; using System.Globalization; using System.Text; using System.IO; using System.Diagnostics.Contracts; #if FEATURE_SERIALIZATION [Serializable] #endif internal sealed class URLString : SiteString { private String m_protocol; [OptionalField(VersionAdded = 2)] private String m_userpass; private SiteString m_siteString; private int m_port; #if !PLATFORM_UNIX private LocalSiteString m_localSite; #endif // !PLATFORM_UNIX private DirectoryString m_directory; private const String m_defaultProtocol = "file"; [OptionalField(VersionAdded = 2)] private bool m_parseDeferred; [OptionalField(VersionAdded = 2)] private String m_urlOriginal; [OptionalField(VersionAdded = 2)] private bool m_parsedOriginal; [OptionalField(VersionAdded = 3)] private bool m_isUncShare; // legacy field from v1.x, not used in v2 and beyond. Retained purely for serialization compatibility. private String m_fullurl; [OnDeserialized] public void OnDeserialized(StreamingContext ctx) { if (m_urlOriginal == null) { // pre-v2 deserialization. Need to fix-up fields here m_parseDeferred = false; m_parsedOriginal = false; // Dont care what this value is - never used m_userpass = ""; m_urlOriginal = m_fullurl; m_fullurl = null; } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { DoDeferredParse(); m_fullurl = m_urlOriginal; } } [OnSerialized] private void OnSerialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_fullurl = null; } } public URLString() { m_protocol = ""; m_userpass = ""; m_siteString = new SiteString(); m_port = -1; #if !PLATFORM_UNIX m_localSite = null; #endif // !PLATFORM_UNIX m_directory = new DirectoryString(); m_parseDeferred = false; } private void DoDeferredParse() { if (m_parseDeferred) { ParseString(m_urlOriginal, m_parsedOriginal); m_parseDeferred = false; } } public URLString(string url) : this(url, false, false) {} public URLString(string url, bool parsed) : this(url, parsed, false) {} internal URLString(string url, bool parsed, bool doDeferredParsing) { m_port = -1; m_userpass = ""; DoFastChecks(url); m_urlOriginal = url; m_parsedOriginal = parsed; m_parseDeferred = true; if (doDeferredParsing) DoDeferredParse(); } // Converts %XX and %uYYYY to the actual characters (I.e. Unesacpes any escape characters present in the URL) private String UnescapeURL(String url) { StringBuilder intermediate = StringBuilderCache.Acquire(url.Length); int Rindex = 0; // index into temp that gives the rest of the string to be processed int index; int braIndex = -1; int ketIndex = -1; braIndex = url.IndexOf('[',Rindex); if (braIndex != -1) ketIndex = url.IndexOf(']', braIndex); do { index = url.IndexOf( '%', Rindex); if (index == -1) { intermediate = intermediate.Append(url, Rindex, (url.Length - Rindex)); break; } // if we hit a '%' in the middle of an IPv6 address, dont process that if (index > braIndex && index < ketIndex) { intermediate = intermediate.Append(url, Rindex, (ketIndex - Rindex+1)); Rindex = ketIndex+1; continue; } if (url.Length - index < 2) // Check that there is at least 1 char after the '%' throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); if (url[index+1] == 'u' || url[index+1] == 'U') { if (url.Length - index < 6) // example: "%u004d" is 6 chars long throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); // We have a unicode character specified in hex try { char c = (char)(Hex.ConvertHexDigit( url[index+2] ) << 12 | Hex.ConvertHexDigit( url[index+3] ) << 8 | Hex.ConvertHexDigit( url[index+4] ) << 4 | Hex.ConvertHexDigit( url[index+5] )); intermediate = intermediate.Append(url, Rindex, index - Rindex); intermediate = intermediate.Append(c); } catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException { throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); } Rindex = index + 6 ; //update the 'seen' length } else { // we have a hex character. if (url.Length - index < 3) // example: "%4d" is 3 chars long throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); try { char c = (char)(Hex.ConvertHexDigit( url[index+1] ) << 4 | Hex.ConvertHexDigit( url[index+2] )); intermediate = intermediate.Append(url, Rindex, index - Rindex); intermediate = intermediate.Append(c); } catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException { throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); } Rindex = index + 3; // update the 'seen' length } } while (true); return StringBuilderCache.GetStringAndRelease(intermediate); } // Helper Function for ParseString: // Search for the end of the protocol info and grab the actual protocol string // ex. http://www.microsoft.com/complus would have a protocol string of http private String ParseProtocol(String url) { String temp; int index = url.IndexOf( ':' ); if (index == 0) { throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); } else if (index == -1) { m_protocol = m_defaultProtocol; temp = url; } else if (url.Length > index + 1) { if (index == m_defaultProtocol.Length && String.Compare(url, 0, m_defaultProtocol, 0, index, StringComparison.OrdinalIgnoreCase) == 0) { m_protocol = m_defaultProtocol; temp = url.Substring( index + 1 ); // Since an explicit file:// URL could be immediately followed by a host name, we will be // conservative and assume that it is on a share rather than a potentally relative local // URL. m_isUncShare = true; } else if (url[index+1] != '\\') { #if !PLATFORM_UNIX if (url.Length > index + 2 && url[index+1] == '/' && url[index+2] == '/') #else if (url.Length > index + 1 && url[index+1] == '/' ) // UNIX style "file:/home/me" is allowed, so account for that #endif // !PLATFORM_UNIX { m_protocol = url.Substring( 0, index ); for (int i = 0; i < m_protocol.Length; ++i) { char c = m_protocol[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '+') || (c == '.') || (c == '-')) { continue; } else { throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); } } #if !PLATFORM_UNIX temp = url.Substring( index + 3 ); #else // In UNIX, we don't know how many characters we'll have to skip past. // Skip past \, /, and : // for ( int j=index ; j<url.Length ; j++ ) { if ( url[j] != '\\' && url[j] != '/' && url[j] != ':' ) { index = j; break; } } temp = url.Substring( index ); #endif // !PLATFORM_UNIX } else { throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); } } else { m_protocol = m_defaultProtocol; temp = url; } } else { throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); } return temp; } private String ParsePort(String url) { String temp = url; char[] separators = new char[] { ':', '/' }; int Rindex = 0; int userpassIndex = temp.IndexOf('@'); if (userpassIndex != -1) { if (temp.IndexOf('/',0,userpassIndex) == -1) { // this is a user:pass type of string m_userpass = temp.Substring(0,userpassIndex); Rindex = userpassIndex + 1; } } int braIndex = -1; int ketIndex = -1; int portIndex = -1; braIndex = url.IndexOf('[',Rindex); if (braIndex != -1) ketIndex = url.IndexOf(']', braIndex); if (ketIndex != -1) { // IPv6 address...ignore the IPv6 block when searching for the port portIndex = temp.IndexOfAny(separators,ketIndex); } else { portIndex = temp.IndexOfAny(separators,Rindex); } if (portIndex != -1 && temp[portIndex] == ':') { // make sure it really is a port, and has a number after the : if ( temp[portIndex+1] >= '0' && temp[portIndex+1] <= '9' ) { int tempIndex = temp.IndexOf( '/', Rindex); if (tempIndex == -1) { m_port = Int32.Parse( temp.Substring(portIndex + 1), CultureInfo.InvariantCulture ); if (m_port < 0) throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); temp = temp.Substring( Rindex, portIndex - Rindex ); } else if (tempIndex > portIndex) { m_port = Int32.Parse( temp.Substring(portIndex + 1, tempIndex - portIndex - 1), CultureInfo.InvariantCulture ); temp = temp.Substring( Rindex, portIndex - Rindex ) + temp.Substring( tempIndex ); } else throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); } else throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); } else { // Chop of the user/pass portion if any temp = temp.Substring(Rindex); } return temp; } // This does three things: // 1. It makes the following modifications to the start of the string: // a. \\?\ and \\?/ => <empty> // b. \\.\ and \\./ => <empty> // 2. If isFileUrl is true, converts all slashes to front slashes and strips leading // front slashes. See comment by code. // 3. Throws a PathTooLongException if the length of the resulting URL is >= MAX_PATH. // This is done to prevent security issues due to canonicalization truncations. // Remove this method when the Path class supports "\\?\" internal static string PreProcessForExtendedPathRemoval(string url, bool isFileUrl) { return PreProcessForExtendedPathRemoval(checkPathLength: true, url: url, isFileUrl: isFileUrl); } internal static string PreProcessForExtendedPathRemoval(bool checkPathLength, string url, bool isFileUrl) { bool isUncShare = false; return PreProcessForExtendedPathRemoval(checkPathLength: checkPathLength, url: url, isFileUrl: isFileUrl, isUncShare: ref isUncShare); } // Keeping this signature to avoid reflection breaks private static string PreProcessForExtendedPathRemoval(string url, bool isFileUrl, ref bool isUncShare) { return PreProcessForExtendedPathRemoval(checkPathLength: true, url: url, isFileUrl: isFileUrl, isUncShare: ref isUncShare); } private static string PreProcessForExtendedPathRemoval(bool checkPathLength, string url, bool isFileUrl, ref bool isUncShare) { // This is the modified URL that we will return StringBuilder modifiedUrl = new StringBuilder(url); // ITEM 1 - remove extended path characters. { // Keep track of where we are in both the comparison and altered strings. int curCmpIdx = 0; int curModIdx = 0; // If all the '\' have already been converted to '/', just check for //?/ or //./ if ((url.Length - curCmpIdx) >= 4 && (String.Compare(url, curCmpIdx, "//?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(url, curCmpIdx, "//./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0)) { modifiedUrl.Remove(curModIdx, 4); curCmpIdx += 4; } else { if (isFileUrl) { // We need to handle an indefinite number of leading front slashes for file URLs since we could // get something like: // file://\\?\ // file:/\\?\ // file:\\?\ // etc... while (url[curCmpIdx] == '/') { curCmpIdx++; curModIdx++; } } // Remove the extended path characters if ((url.Length - curCmpIdx) >= 4 && (String.Compare(url, curCmpIdx, "\\\\?\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(url, curCmpIdx, "\\\\?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(url, curCmpIdx, "\\\\.\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(url, curCmpIdx, "\\\\./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0)) { modifiedUrl.Remove(curModIdx, 4); curCmpIdx += 4; } } } // ITEM 2 - convert all slashes to forward slashes, and strip leading slashes. if (isFileUrl) { int slashCount = 0; bool seenFirstBackslash = false; while (slashCount < modifiedUrl.Length && (modifiedUrl[slashCount] == '/' || modifiedUrl[slashCount] == '\\')) { // Look for sets of consecutive backslashes. We can't just look for these at the start // of the string, since file:// might come first. Instead, once we see the first \, look // for a second one following it. if (!seenFirstBackslash && modifiedUrl[slashCount] == '\\') { seenFirstBackslash = true; if (slashCount + 1 < modifiedUrl.Length && modifiedUrl[slashCount + 1] == '\\') isUncShare = true; } slashCount++; } modifiedUrl.Remove(0, slashCount); modifiedUrl.Replace('\\', '/'); } // ITEM 3 - If the path is greater than or equal (due to terminating NULL in windows) MAX_PATH, we throw. if (checkPathLength) { // This needs to be a separate method to avoid hitting the static constructor on AppContextSwitches CheckPathTooLong(modifiedUrl); } // Create the result string from the StringBuilder return modifiedUrl.ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] private static void CheckPathTooLong(StringBuilder path) { if (path.Length >= ( #if FEATURE_PATHCOMPAT AppContextSwitches.BlockLongPaths ? PathInternal.MaxShortPath : #endif PathInternal.MaxLongPath)) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } } // Do any misc massaging of data in the URL private String PreProcessURL(String url, bool isFileURL) { #if !PLATFORM_UNIX if (isFileURL) { // Remove when the Path class supports "\\?\" url = PreProcessForExtendedPathRemoval(url, true, ref m_isUncShare); } else { url = url.Replace('\\', '/'); } return url; #else // Remove superfluous '/' // For UNIX, the file path would look something like: // file:///home/johndoe/here // file:/home/johndoe/here // file:../johndoe/here // file:~/johndoe/here String temp = url; int nbSlashes = 0; while(nbSlashes<temp.Length && '/'==temp[nbSlashes]) nbSlashes++; // if we get a path like file:///directory/name we need to convert // this to /directory/name. if(nbSlashes > 2) temp = temp.Substring(nbSlashes-1, temp.Length - (nbSlashes-1)); else if (2 == nbSlashes) /* it's a relative path */ temp = temp.Substring(nbSlashes, temp.Length - nbSlashes); return temp; #endif // !PLATFORM_UNIX } private void ParseFileURL(String url) { String temp = url; #if !PLATFORM_UNIX int index = temp.IndexOf( '/'); if (index != -1 && ((index == 2 && temp[index-1] != ':' && temp[index-1] != '|') || index != 2) && index != temp.Length - 1) { // Also, if it is a UNC share, we want m_localSite to // be of the form "computername/share", so if the first // fileEnd character found is a slash, do some more parsing // to find the proper end character. int tempIndex = temp.IndexOf( '/', index+1); if (tempIndex != -1) index = tempIndex; else index = -1; } String localSite; if (index == -1) localSite = temp; else localSite = temp.Substring(0,index); if (localSite.Length == 0) throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); int i; bool spacesAllowed; if (localSite[0] == '\\' && localSite[1] == '\\') { spacesAllowed = true; i = 2; } else { i = 0; spacesAllowed = false; } bool useSmallCharToUpper = true; for (; i < localSite.Length; ++i) { char c = localSite[i]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '-') || (c == '/') || (c == ':') || (c == '|') || (c == '.') || (c == '*') || (c == '$') || (spacesAllowed && c == ' ')) { continue; } else { useSmallCharToUpper = false; break; } } if (useSmallCharToUpper) localSite = String.SmallCharToUpper( localSite ); else localSite = localSite.ToUpper(CultureInfo.InvariantCulture); m_localSite = new LocalSiteString( localSite ); if (index == -1) { if (localSite[localSite.Length-1] == '*') m_directory = new DirectoryString( "*", false ); else m_directory = new DirectoryString(); } else { String directoryString = temp.Substring( index + 1 ); if (directoryString.Length == 0) { m_directory = new DirectoryString(); } else { m_directory = new DirectoryString( directoryString, true); } } #else // !PLATFORM_UNIX m_directory = new DirectoryString( temp, true); #endif // !PLATFORM_UNIX m_siteString = null; return; } private void ParseNonFileURL(String url) { String temp = url; int index = temp.IndexOf('/'); if (index == -1) { #if !PLATFORM_UNIX m_localSite = null; // for drive letter #endif // !PLATFORM_UNIX m_siteString = new SiteString( temp ); m_directory = new DirectoryString(); } else { #if !PLATFORM_UNIX String site = temp.Substring( 0, index ); m_localSite = null; m_siteString = new SiteString( site ); String directoryString = temp.Substring( index + 1 ); if (directoryString.Length == 0) { m_directory = new DirectoryString(); } else { m_directory = new DirectoryString( directoryString, false ); } #else String directoryString = temp.Substring( index + 1 ); String site = temp.Substring( 0, index ); m_directory = new DirectoryString( directoryString, false ); m_siteString = new SiteString( site ); #endif //!PLATFORM_UNIX } return; } void DoFastChecks( String url ) { if (url == null) { throw new ArgumentNullException( "url" ); } Contract.EndContractBlock(); if (url.Length == 0) { throw new FormatException(Environment.GetResourceString("Format_StringZeroLength")); } } // NOTE: // 1. We support URLs that follow the common Internet scheme syntax // (<scheme>://user:pass@<host>:<port>/<url-path>) and all windows file URLs. // 2. In the general case we parse of the site and create a SiteString out of it // (which supports our wildcarding scheme). In the case of files we don't support // wildcarding and furthermore SiteString doesn't like ':' and '|' which can appear // in file urls so we just keep that info in a separate string and set the // SiteString to null. // // ex. http://www.microsoft.com/complus -> m_siteString = "www.microsoft.com" m_localSite = null // ex. file:///c:/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:" // ex. file:///c|/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:" void ParseString( String url, bool parsed ) { // If there are any escaped hex or unicode characters in the url, translate those // into the proper character. if (!parsed) { url = UnescapeURL(url); } // Identify the protocol and strip the protocol info from the string, if present. String temp = ParseProtocol(url); bool fileProtocol = (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0); // handle any special preocessing...removing extra characters, etc. temp = PreProcessURL(temp, fileProtocol); if (fileProtocol) { ParseFileURL(temp); } else { // Check if there is a port number and parse that out. temp = ParsePort(temp); ParseNonFileURL(temp); // Note: that we allow DNS and Netbios names for non-file protocols (since sitestring will check // that the hostname satisfies these two protocols. DNS-only checking can theoretically be added // here but that would break all the programs that use '_' (which is fairly common, yet illegal). // If this needs to be done at any point, add a call to m_siteString.IsLegalDNSName(). } } public String Scheme { get { DoDeferredParse(); return m_protocol; } } public String Host { get { DoDeferredParse(); if (m_siteString != null) { return m_siteString.ToString(); } else { #if !PLATFORM_UNIX return m_localSite.ToString(); #else return ""; #endif // !PLATFORM_UNIX } } } public String Port { get { DoDeferredParse(); if (m_port == -1) return null; else return m_port.ToString(CultureInfo.InvariantCulture); } } public String Directory { get { DoDeferredParse(); return m_directory.ToString(); } } /// <summary> /// Make a best guess at determining if this is URL refers to a file with a relative path. Since /// this is a guess to help out users of UrlMembershipCondition who may accidentally supply a /// relative URL, we'd rather err on the side of absolute than relative. (We'd rather accept some /// meaningless membership conditions rather than reject meaningful ones). /// /// In order to be a relative file URL, the URL needs to have a protocol of file, and not be on a /// UNC share. /// /// If both of the above are true, then the heuristics we'll use to detect an absolute URL are: /// 1. A host name which is: /// a. greater than one character and ends in a colon (representing the drive letter) OR /// b. ends with a * (so we match any file with the given prefix if any) /// 2. Has a directory name (cannot be simply file://c:) /// </summary> public bool IsRelativeFileUrl { get { DoDeferredParse(); if (String.Equals(m_protocol, "file", StringComparison.OrdinalIgnoreCase) && !m_isUncShare) { #if !PLATFORM_UNIX string host = m_localSite != null ? m_localSite.ToString() : null; // If the host name ends with the * character, treat this as an absolute URL since the * // could represent the rest of the full path. if (host.EndsWith('*')) return false; #endif // !PLATFORM_UNIX string directory = m_directory != null ? m_directory.ToString() : null; #if !PLATFORM_UNIX return host == null || host.Length < 2 || !host.EndsWith(':') || String.IsNullOrEmpty(directory); #else return String.IsNullOrEmpty(directory); #endif // !PLATFORM_UNIX } // Since this is not a local URL, it cannot be relative return false; } } public String GetFileName() { DoDeferredParse(); #if !PLATFORM_UNIX if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) return null; String intermediateDirectory = this.Directory.Replace( '/', '\\' ); String directory = this.Host.Replace( '/', '\\' ); int directorySlashIndex = directory.IndexOf( '\\' ); if (directorySlashIndex == -1) { if (directory.Length != 2 || !(directory[1] == ':' || directory[1] == '|')) { directory = "\\\\" + directory; } } else if (directorySlashIndex != 2 || (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|')) { directory = "\\\\" + directory; } directory += "\\" + intermediateDirectory; return directory; #else // In Unix, directory contains the full pathname // (this is what we get in Win32) if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0) return null; return this.Directory; #endif // !PLATFORM_UNIX } public String GetDirectoryName() { DoDeferredParse(); #if !PLATFORM_UNIX if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0) return null; String intermediateDirectory = this.Directory.Replace( '/', '\\' ); int slashIndex = 0; for (int i = intermediateDirectory.Length; i > 0; i--) { if (intermediateDirectory[i-1] == '\\') { slashIndex = i; break; } } String directory = this.Host.Replace( '/', '\\' ); int directorySlashIndex = directory.IndexOf( '\\' ); if (directorySlashIndex == -1) { if (directory.Length != 2 || !(directory[1] == ':' || directory[1] == '|')) { directory = "\\\\" + directory; } } else if (directorySlashIndex > 2 || (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|')) { directory = "\\\\" + directory; } directory += "\\"; if (slashIndex > 0) { directory += intermediateDirectory.Substring( 0, slashIndex ); } return directory; #else if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) return null; String directory = this.Directory.ToString(); int slashIndex = 0; for (int i = directory.Length; i > 0; i--) { if (directory[i-1] == '/') { slashIndex = i; break; } } if (slashIndex > 0) { directory = directory.Substring( 0, slashIndex ); } return directory; #endif // !PLATFORM_UNIX } public override SiteString Copy() { return new URLString( m_urlOriginal, m_parsedOriginal ); } public override bool IsSubsetOf( SiteString site ) { if (site == null) { return false; } URLString url = site as URLString; if (url == null) { return false; } DoDeferredParse(); url.DoDeferredParse(); URLString normalUrl1 = this.SpecialNormalizeUrl(); URLString normalUrl2 = url.SpecialNormalizeUrl(); if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) == 0 && normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory )) { #if !PLATFORM_UNIX if (normalUrl1.m_localSite != null) { // We do a little extra processing in here for local files since we allow // both <drive_letter>: and <drive_letter>| forms of urls. return normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ); } else #endif // !PLATFORM_UNIX { if (normalUrl1.m_port != normalUrl2.m_port) return false; return normalUrl2.m_siteString != null && normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ); } } else { return false; } } public override String ToString() { return m_urlOriginal; } public override bool Equals(Object o) { DoDeferredParse(); if (o == null || !(o is URLString)) return false; else return this.Equals( (URLString)o ); } public override int GetHashCode() { DoDeferredParse(); TextInfo info = CultureInfo.InvariantCulture.TextInfo; int accumulator = 0; if (this.m_protocol != null) accumulator = info.GetCaseInsensitiveHashCode( this.m_protocol ); #if !PLATFORM_UNIX if (this.m_localSite != null) { accumulator = accumulator ^ this.m_localSite.GetHashCode(); } else { accumulator = accumulator ^ this.m_siteString.GetHashCode(); } accumulator = accumulator ^ this.m_directory.GetHashCode(); #else accumulator = accumulator ^ info.GetCaseInsensitiveHashCode(this.m_urlOriginal); #endif // !PLATFORM_UNIX return accumulator; } public bool Equals( URLString url ) { return CompareUrls( this, url ); } public static bool CompareUrls( URLString url1, URLString url2 ) { if (url1 == null && url2 == null) return true; if (url1 == null || url2 == null) return false; url1.DoDeferredParse(); url2.DoDeferredParse(); URLString normalUrl1 = url1.SpecialNormalizeUrl(); URLString normalUrl2 = url2.SpecialNormalizeUrl(); // Compare protocol (case insensitive) if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) != 0) return false; // Do special processing for file urls if (String.Compare( normalUrl1.m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0) { #if !PLATFORM_UNIX if (!normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ) || !normalUrl2.m_localSite.IsSubsetOf( normalUrl1.m_localSite )) return false; #else return url1.IsSubsetOf( url2 ) && url2.IsSubsetOf( url1 ); #endif // !PLATFORM_UNIX } else { if (String.Compare( normalUrl1.m_userpass, normalUrl2.m_userpass, StringComparison.Ordinal) != 0) return false; if (!normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ) || !normalUrl2.m_siteString.IsSubsetOf( normalUrl1.m_siteString )) return false; if (url1.m_port != url2.m_port) return false; } if (!normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ) || !normalUrl2.m_directory.IsSubsetOf( normalUrl1.m_directory )) return false; return true; } internal String NormalizeUrl() { DoDeferredParse(); StringBuilder builtUrl = StringBuilderCache.Acquire(); if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0) { #if !PLATFORM_UNIX builtUrl = builtUrl.AppendFormat("FILE:///{0}/{1}", m_localSite.ToString(), m_directory.ToString()); #else builtUrl = builtUrl.AppendFormat("FILE:///{0}", m_directory.ToString()); #endif // !PLATFORM_UNIX } else { builtUrl = builtUrl.AppendFormat("{0}://{1}{2}", m_protocol, m_userpass, m_siteString.ToString()); if (m_port != -1) builtUrl = builtUrl.AppendFormat("{0}",m_port); builtUrl = builtUrl.AppendFormat("/{0}", m_directory.ToString()); } return StringBuilderCache.GetStringAndRelease(builtUrl).ToUpper(CultureInfo.InvariantCulture); } #if !PLATFORM_UNIX [System.Security.SecuritySafeCritical] // auto-generated internal URLString SpecialNormalizeUrl() { // Under WinXP, file protocol urls can be mapped to // drives that aren't actually file protocol underneath // due to drive mounting. This code attempts to figure // out what a drive is mounted to and create the // url is maps to. DoDeferredParse(); if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) { return this; } else { String localSite = m_localSite.ToString(); if (localSite.Length == 2 && (localSite[1] == '|' || localSite[1] == ':')) { String deviceName = null; GetDeviceName(localSite, JitHelpers.GetStringHandleOnStack(ref deviceName)); if (deviceName != null) { if (deviceName.IndexOf( "://", StringComparison.Ordinal ) != -1) { URLString u = new URLString( deviceName + "/" + this.m_directory.ToString() ); u.DoDeferredParse(); // Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL return u; } else { URLString u = new URLString( "file://" + deviceName + "/" + this.m_directory.ToString() ); u.DoDeferredParse();// Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL return u; } } else return this; } else { return this; } } } [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName ); #else internal URLString SpecialNormalizeUrl() { return this; } #endif // !PLATFORM_UNIX } [Serializable] internal class DirectoryString : SiteString { private bool m_checkForIllegalChars; private new static char[] m_separators = { '/' }; // From KB #Q177506, file/folder illegal characters are \ / : * ? " < > | protected static char[] m_illegalDirectoryCharacters = { '\\', ':', '*', '?', '"', '<', '>', '|' }; public DirectoryString() { m_site = ""; m_separatedSite = new ArrayList(); } public DirectoryString( String directory, bool checkForIllegalChars ) { m_site = directory; m_checkForIllegalChars = checkForIllegalChars; m_separatedSite = CreateSeparatedString(directory); } private ArrayList CreateSeparatedString(String directory) { if (directory == null || directory.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); } Contract.EndContractBlock(); ArrayList list = new ArrayList(); String[] separatedArray = directory.Split(m_separators); for (int index = 0; index < separatedArray.Length; ++index) { if (separatedArray[index] == null || separatedArray[index].Equals( "" )) { // this case is fine, we just ignore it the extra separators. } else if (separatedArray[index].Equals( "*" )) { if (index != separatedArray.Length-1) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); } list.Add( separatedArray[index] ); } else if (m_checkForIllegalChars && separatedArray[index].IndexOfAny( m_illegalDirectoryCharacters ) != -1) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); } else { list.Add( separatedArray[index] ); } } return list; } public virtual bool IsSubsetOf( DirectoryString operand ) { return this.IsSubsetOf( operand, true ); } public virtual bool IsSubsetOf( DirectoryString operand, bool ignoreCase ) { if (operand == null) { return false; } else if (operand.m_separatedSite.Count == 0) { return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; } else if (this.m_separatedSite.Count == 0) { return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; } else { return base.IsSubsetOf( operand, ignoreCase ); } } } #if !PLATFORM_UNIX [Serializable] internal class LocalSiteString : SiteString { private new static char[] m_separators = { '/' }; public LocalSiteString( String site ) { m_site = site.Replace( '|', ':'); if (m_site.Length > 2 && m_site.IndexOf( ':' ) != -1) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); m_separatedSite = CreateSeparatedString(m_site); } private ArrayList CreateSeparatedString(String directory) { if (directory == null || directory.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); } Contract.EndContractBlock(); ArrayList list = new ArrayList(); String[] separatedArray = directory.Split(m_separators); for (int index = 0; index < separatedArray.Length; ++index) { if (separatedArray[index] == null || separatedArray[index].Equals( "" )) { if (index < 2 && directory[index] == '/') { list.Add( "//" ); } else if (index != separatedArray.Length-1) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); } } else if (separatedArray[index].Equals( "*" )) { if (index != separatedArray.Length-1) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); } list.Add( separatedArray[index] ); } else { list.Add( separatedArray[index] ); } } return list; } public virtual bool IsSubsetOf( LocalSiteString operand ) { return this.IsSubsetOf( operand, true ); } public virtual bool IsSubsetOf( LocalSiteString operand, bool ignoreCase ) { if (operand == null) { return false; } else if (operand.m_separatedSite.Count == 0) { return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; } else if (this.m_separatedSite.Count == 0) { return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; } else { return base.IsSubsetOf( operand, ignoreCase ); } } } #endif // !PLATFORM_UNIX }
/* ==================================================================== Copyright 2002-2004 Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.UserModel { using System; using System.IO; using System.Collections; using NPOI.SS.UserModel; using NPOI.HSSF.Record; /// <summary> /// Excel can Get cranky if you give it files containing too /// many (especially duplicate) objects, and this class can /// help to avoid those. /// In general, it's much better to make sure you don't /// duplicate the objects in your code, as this is likely /// to be much faster than creating lots and lots of /// excel objects+records, only to optimise them down to /// many fewer at a later stage. /// However, sometimes this is too hard / tricky to do, which /// is where the use of this class comes in. /// </summary> internal class HSSFOptimiser { /// <summary> /// Goes through the Workbook, optimising the fonts by /// removing duplicate ones. /// For now, only works on fonts used in HSSFCellStyle /// and HSSFRichTextString. Any other font uses /// (eg charts, pictures) may well end up broken! /// This can be a slow operation, especially if you have /// lots of cells, cell styles or rich text strings /// </summary> /// <param name="workbook">The workbook in which to optimise the fonts</param> public static void OptimiseFonts(HSSFWorkbook workbook) { // Where each font has ended up, and if we need to // delete the record for it. Start off with no change short[] newPos = new short[workbook.Workbook.NumberOfFontRecords + 1]; bool[] zapRecords = new bool[newPos.Length]; for (int i = 0; i < newPos.Length; i++) { newPos[i] = (short)i; zapRecords[i] = false; } // Get each font record, so we can do deletes // without Getting confused FontRecord[] frecs = new FontRecord[newPos.Length]; for (int i = 0; i < newPos.Length; i++) { // There is no 4! if (i == 4) continue; frecs[i] = workbook.Workbook.GetFontRecordAt(i); } // Loop over each font, seeing if it is the same // as an earlier one. If it is, point users of the // later duplicate copy to the earlier one, and // mark the later one as needing deleting // Note - don't change built in fonts (those before 5) for (int i = 5; i < newPos.Length; i++) { // Check this one for being a duplicate // of an earlier one int earlierDuplicate = -1; for (int j = 0; j < i && earlierDuplicate == -1; j++) { if (j == 4) continue; FontRecord frCheck = workbook.Workbook.GetFontRecordAt(j); if (frCheck.SameProperties(frecs[i])) { earlierDuplicate = j; } } // If we got a duplicate, mark it as such if (earlierDuplicate != -1) { newPos[i] = (short)earlierDuplicate; zapRecords[i] = true; } } // Update the new positions based on // deletes that have occurred between // the start and them // Only need to worry about user fonts for (int i = 5; i < newPos.Length; i++) { // Find the number deleted to that // point, and adjust short preDeletePos = newPos[i]; short newPosition = preDeletePos; for (int j = 0; j < preDeletePos; j++) { if (zapRecords[j]) newPosition--; } // Update the new position newPos[i] = newPosition; } // Zap the un-needed user font records for (int i = 5; i < newPos.Length; i++) { if (zapRecords[i]) { workbook.Workbook.RemoveFontRecord( frecs[i] ); } } // Tell HSSFWorkbook that it needs to // re-start its HSSFFontCache workbook.ResetFontCache(); // Update the cell styles to point at the // new locations of the fonts for (int i = 0; i < workbook.Workbook.NumExFormats; i++) { ExtendedFormatRecord xfr = workbook.Workbook.GetExFormatAt(i); xfr.FontIndex = ( newPos[xfr.FontIndex] ); } // Update the rich text strings to point at // the new locations of the fonts // Remember that one underlying unicode string // may be shared by multiple RichTextStrings! ArrayList doneUnicodeStrings = new ArrayList(); for (int sheetNum = 0; sheetNum < workbook.NumberOfSheets; sheetNum++) { NPOI.SS.UserModel.ISheet s = workbook.GetSheetAt(sheetNum); IEnumerator rIt = s.GetRowEnumerator(); while (rIt.MoveNext()) { HSSFRow row = (HSSFRow)rIt.Current; IEnumerator cIt = row.GetEnumerator(); while (cIt.MoveNext()) { ICell cell = (HSSFCell)cIt.Current; if (cell.CellType == NPOI.SS.UserModel.CellType.STRING) { HSSFRichTextString rtr = (HSSFRichTextString)cell.RichStringCellValue; UnicodeString u = rtr.RawUnicodeString; // Have we done this string already? if (!doneUnicodeStrings.Contains(u)) { // Update for each new position for (short i = 5; i < newPos.Length; i++) { if (i != newPos[i]) { u.SwapFontUse(i, newPos[i]); } } // Mark as done doneUnicodeStrings.Add(u); } } } } } } /// <summary> /// Goes through the Wokrbook, optimising the cell styles /// by removing duplicate ones. /// For best results, optimise the fonts via a call to /// OptimiseFonts(HSSFWorkbook) first /// </summary> /// <param name="workbook">The workbook in which to optimise the cell styles</param> public static void OptimiseCellStyles(HSSFWorkbook workbook) { // Where each style has ended up, and if we need to // delete the record for it. Start off with no change short[] newPos = new short[workbook.Workbook.NumExFormats]; bool[] zapRecords = new bool[newPos.Length]; for (int i = 0; i < newPos.Length; i++) { newPos[i] = (short)i; zapRecords[i] = false; } // Get each style record, so we can do deletes // without Getting confused ExtendedFormatRecord[] xfrs = new ExtendedFormatRecord[newPos.Length]; for (int i = 0; i < newPos.Length; i++) { xfrs[i] = workbook.Workbook.GetExFormatAt(i); } // Loop over each style, seeing if it is the same // as an earlier one. If it is, point users of the // later duplicate copy to the earlier one, and // mark the later one as needing deleting // Only work on user added ones, which come after 20 for (int i = 21; i < newPos.Length; i++) { // Check this one for being a duplicate // of an earlier one int earlierDuplicate = -1; for (int j = 0; j < i && earlierDuplicate == -1; j++) { ExtendedFormatRecord xfCheck = workbook.Workbook.GetExFormatAt(j); if (xfCheck.Equals(xfrs[i])) { earlierDuplicate = j; } } // If we got a duplicate, mark it as such if (earlierDuplicate != -1) { newPos[i] = (short)earlierDuplicate; zapRecords[i] = true; } } // Update the new positions based on // deletes that have occurred between // the start and them // Only work on user added ones, which come after 20 for (int i = 21; i < newPos.Length; i++) { // Find the number deleted to that // point, and adjust short preDeletePos = newPos[i]; short newPosition = preDeletePos; for (int j = 0; j < preDeletePos; j++) { if (zapRecords[j]) newPosition--; } // Update the new position newPos[i] = newPosition; } // Zap the un-needed user style records for (int i = 21; i < newPos.Length; i++) { if (zapRecords[i]) { workbook.Workbook.RemoveExFormatRecord( xfrs[i] ); } } // Finally, update the cells to point at // their new extended format records for (int sheetNum = 0; sheetNum < workbook.NumberOfSheets; sheetNum++) { HSSFSheet s = (HSSFSheet)workbook.GetSheetAt(sheetNum); IEnumerator rIt = s.GetRowEnumerator(); while (rIt.MoveNext()) { HSSFRow row = (HSSFRow)rIt.Current; IEnumerator cIt = row.GetEnumerator(); while (cIt.MoveNext()) { ICell cell = (HSSFCell)cIt.Current; short oldXf = ((HSSFCell)cell).CellValueRecord.XFIndex; NPOI.SS.UserModel.ICellStyle newStyle = workbook.GetCellStyleAt( newPos[oldXf] ); cell.CellStyle = (newStyle); } } } } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using KYC.Web.Models.Identity; namespace KYC.Web.Migrations.ApplicationDb { [DbContext(typeof(ApplicationDbContext))] [Migration("20160309000234_identity")] partial class identity { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348"); modelBuilder.Entity("KYC.Web.Models.Identity.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("KYC.Web.Models.Identity.UserAddress", b => { b.Property<int>("UserAddressId") .ValueGeneratedOnAdd(); b.Property<string>("Addressee") .IsRequired(); b.Property<string>("CityOrTown") .IsRequired(); b.Property<string>("Country") .IsRequired(); b.Property<string>("LineOne") .IsRequired(); b.Property<string>("LineTwo"); b.Property<string>("StateOrProvince") .IsRequired(); b.Property<string>("UserId") .IsRequired(); b.Property<string>("ZipOrPostalCode") .IsRequired(); b.HasKey("UserAddressId"); b.HasAnnotation("Relational:TableName", "AspNetUserAddresses"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("KYC.Web.Models.Identity.UserAddress", b => { b.HasOne("KYC.Web.Models.Identity.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("KYC.Web.Models.Identity.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("KYC.Web.Models.Identity.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("KYC.Web.Models.Identity.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// 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 Xunit; public class GCTests { [Fact] public static void ValidCollectionGenerations() { Assert.Throws<ArgumentOutOfRangeException>(() => GC.Collect(-1)); for (int i = 0; i < GC.MaxGeneration + 10; i++) { GC.Collect(i); } } [Fact] public static void CollectionCountDefault() { VerifyCollectionCount(GCCollectionMode.Default); } [Fact] public static void CollectionCountForced() { VerifyCollectionCount(GCCollectionMode.Forced); } private static void VerifyCollectionCount(GCCollectionMode mode) { for (int gen = 0; gen <= 2; gen++) { byte[] b = new byte[1024 * 1024 * 10]; int oldCollectionCount = GC.CollectionCount(gen); b = null; GC.Collect(gen, GCCollectionMode.Default); Assert.True(GC.CollectionCount(gen) > oldCollectionCount); } } [Fact] public static void InvalidCollectionModes() { Assert.Throws<ArgumentOutOfRangeException>(() => GC.Collect(2, (GCCollectionMode)(GCCollectionMode.Default - 1))); Assert.Throws<ArgumentOutOfRangeException>(() => GC.Collect(2, (GCCollectionMode)(GCCollectionMode.Optimized + 1))); } [Fact] public static void Finalizer() { FinalizerTest.Run(); } private class FinalizerTest { public static void Run() { var obj = new TestObject(); obj = null; GC.Collect(); // Make sure Finalize() is called GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void KeepAlive() { KeepAliveTest.Run(); } private class KeepAliveTest { public static void Run() { var keepAlive = new KeepAliveObject(); var doNotKeepAlive = new DoNotKeepAliveObject(); doNotKeepAlive = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(DoNotKeepAliveObject.Finalized); Assert.False(KeepAliveObject.Finalized); GC.KeepAlive(keepAlive); } private class KeepAliveObject { public static bool Finalized { get; private set; } ~KeepAliveObject() { Finalized = true; } } private class DoNotKeepAliveObject { public static bool Finalized { get; private set; } ~DoNotKeepAliveObject() { Finalized = true; } } } [Fact] public static void KeepAliveNull() { KeepAliveNullTest.Run(); } private class KeepAliveNullTest { public static void Run() { var obj = new TestObject(); obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.KeepAlive(obj); Assert.True(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void KeepAliveRecursive() { KeepAliveRecursiveTest.Run(); } private class KeepAliveRecursiveTest { public static void Run() { int recursionCount = 0; RunWorker(new TestObject(), ref recursionCount); } private static void RunWorker(object obj, ref int recursionCount) { if (recursionCount++ == 10) return; GC.Collect(); GC.WaitForPendingFinalizers(); RunWorker(obj, ref recursionCount); Assert.False(TestObject.Finalized); GC.KeepAlive(obj); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void SuppressFinalizer() { SuppressFinalizerTest.Run(); } private class SuppressFinalizerTest { public static void Run() { var obj = new TestObject(); GC.SuppressFinalize(obj); obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void ReRegisterForFinalize() { ReRegisterForFinalizeTest.Run(); } private class ReRegisterForFinalizeTest { public static void Run() { TestObject.Finalized = false; CreateObject(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private static void CreateObject() { using (var obj = new TestObject()) { GC.SuppressFinalize(obj); } } private class TestObject : IDisposable { public static bool Finalized { get; set; } ~TestObject() { Finalized = true; } public void Dispose() { GC.ReRegisterForFinalize(this); } } } [Fact] public static void GetTotalMemoryTest_NoForceCollection() { GC.Collect(); byte[] bytes = new byte[50000]; int genBefore = GC.GetGeneration(bytes); Assert.True(GC.GetTotalMemory(false) >= bytes.Length); Assert.True(GC.GetGeneration(bytes) == genBefore); } [Fact] public static void GetTotalMemoryTest_ForceCollection() { GC.Collect(); byte[] bytes = new byte[50000]; int genBeforeGC = GC.GetGeneration(bytes); Assert.True(GC.GetTotalMemory(true) >= bytes.Length); Assert.True(GC.GetGeneration(bytes) > genBeforeGC); } [Fact] public static void GetGenerationTest() { GC.Collect(); Version obj = new Version(1, 2); for (int i = 0; i <= GC.MaxGeneration; i++) { Assert.Equal(i, GC.GetGeneration(obj)); GC.Collect(); } } }
using System; using System.IO; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Tests { /// <remarks>Basic test class for the AES cipher vectors from FIPS-197</remarks> [TestFixture] public class AesTest : BaseBlockCipherTest { internal static readonly string[] cipherTests = { "128", "000102030405060708090a0b0c0d0e0f", "00112233445566778899aabbccddeeff", "69c4e0d86a7b0430d8cdb78070b4c55a", "192", "000102030405060708090a0b0c0d0e0f1011121314151617", "00112233445566778899aabbccddeeff", "dda97ca4864cdfe06eaf70a0ec0d7191", "256", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "00112233445566778899aabbccddeeff", "8ea2b7ca516745bfeafc49904b496089", }; public AesTest() : base("AES") { } [Test] public void TestCiphers() { for (int i = 0; i != cipherTests.Length; i += 4) { doCipherTest(int.Parse(cipherTests[i]), Hex.Decode(cipherTests[i + 1]), Hex.Decode(cipherTests[i + 2]), Hex.Decode(cipherTests[i + 3])); } } [Test] public void TestOids() { string[] oids = { NistObjectIdentifiers.IdAes128Ecb.Id, NistObjectIdentifiers.IdAes128Cbc.Id, NistObjectIdentifiers.IdAes128Ofb.Id, NistObjectIdentifiers.IdAes128Cfb.Id, NistObjectIdentifiers.IdAes192Ecb.Id, NistObjectIdentifiers.IdAes192Cbc.Id, NistObjectIdentifiers.IdAes192Ofb.Id, NistObjectIdentifiers.IdAes192Cfb.Id, NistObjectIdentifiers.IdAes256Ecb.Id, NistObjectIdentifiers.IdAes256Cbc.Id, NistObjectIdentifiers.IdAes256Ofb.Id, NistObjectIdentifiers.IdAes256Cfb.Id }; string[] names = { "AES/ECB/PKCS7Padding", "AES/CBC/PKCS7Padding", "AES/OFB/NoPadding", "AES/CFB/NoPadding", "AES/ECB/PKCS7Padding", "AES/CBC/PKCS7Padding", "AES/OFB/NoPadding", "AES/CFB/NoPadding", "AES/ECB/PKCS7Padding", "AES/CBC/PKCS7Padding", "AES/OFB/NoPadding", "AES/CFB/NoPadding" }; oidTest(oids, names, 4); } [Test] public void TestWrap() { byte[] kek1 = Hex.Decode("000102030405060708090a0b0c0d0e0f"); byte[] in1 = Hex.Decode("00112233445566778899aabbccddeeff"); byte[] out1 = Hex.Decode("1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5"); wrapTest(1, "AESWrap", kek1, in1, out1); } [Test] public void TestWrapOids() { string[] wrapOids = { NistObjectIdentifiers.IdAes128Wrap.Id, NistObjectIdentifiers.IdAes192Wrap.Id, NistObjectIdentifiers.IdAes256Wrap.Id }; wrapOidTest(wrapOids, "AESWrap"); } private void doCipherTest( int strength, byte[] keyBytes, byte[] input, byte[] output) { KeyParameter key = ParameterUtilities.CreateKeyParameter("AES", keyBytes); IBufferedCipher inCipher = CipherUtilities.GetCipher("AES/ECB/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("AES/ECB/NoPadding"); try { outCipher.Init(true, key); } catch (Exception e) { Fail("AES failed initialisation - " + e, e); } try { inCipher.Init(false, key); } catch (Exception e) { Fail("AES failed initialisation - " + e, e); } // // encryption pass // MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { Fail("AES failed encryption - " + e, e); } byte[] bytes = bOut.ToArray(); if (!AreEqual(bytes, output)) { Fail("AES failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes)); } // // decryption pass // MemoryStream bIn = new MemoryStream(bytes, false); CipherStream cIn = new CipherStream(bIn, inCipher, null); try { // DataInputStream dIn = new DataInputStream(cIn); BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { // bytes[i] = (byte)dIn.read(); bytes[i] = dIn.ReadByte(); } int remaining = bytes.Length - input.Length / 2; // dIn.readFully(bytes, input.Length / 2, remaining); byte[] extra = dIn.ReadBytes(remaining); if (extra.Length < remaining) throw new EndOfStreamException(); extra.CopyTo(bytes, input.Length / 2); } catch (Exception e) { Fail("AES failed encryption - " + e, e); } if (!AreEqual(bytes, input)) { Fail("AES failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } } [Test] public void TestEax() { byte[] K = Hex.Decode("233952DEE4D5ED5F9B9C6D6FF80FF478"); byte[] N = Hex.Decode("62EC67F9C3A4A407FCB2A8C49031A8B3"); byte[] P = Hex.Decode("68656c6c6f20776f726c642121"); byte[] C = Hex.Decode("2f9f76cb7659c70e4be11670a3e193ae1bc6b5762a"); KeyParameter key = ParameterUtilities.CreateKeyParameter("AES", K); IBufferedCipher inCipher = CipherUtilities.GetCipher("AES/EAX/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("AES/EAX/NoPadding"); inCipher.Init(true, new ParametersWithIV(key, N)); byte[] enc = inCipher.DoFinal(P); if (!AreEqual(enc, C)) { Fail("ciphertext doesn't match in EAX"); } outCipher.Init(false, new ParametersWithIV(key, N)); byte[] dec = outCipher.DoFinal(C); if (!AreEqual(dec, P)) { Fail("plaintext doesn't match in EAX"); } try { inCipher = CipherUtilities.GetCipher("AES/EAX/PKCS5Padding"); Fail("bad padding missed in EAX"); } catch (SecurityUtilityException) { // expected } } [Test] public void TestCcm() { byte[] K = Hex.Decode("404142434445464748494a4b4c4d4e4f"); byte[] N = Hex.Decode("10111213141516"); byte[] P = Hex.Decode("68656c6c6f20776f726c642121"); byte[] C = Hex.Decode("39264f148b54c456035de0a531c8344f46db12b388"); KeyParameter key = ParameterUtilities.CreateKeyParameter("AES", K); IBufferedCipher inCipher = CipherUtilities.GetCipher("AES/CCM/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("AES/CCM/NoPadding"); inCipher.Init(true, new ParametersWithIV(key, N)); byte[] enc = inCipher.DoFinal(P); if (!AreEqual(enc, C)) { Fail("ciphertext doesn't match in CCM"); } outCipher.Init(false, new ParametersWithIV(key, N)); byte[] dec = outCipher.DoFinal(C); if (!AreEqual(dec, P)) { Fail("plaintext doesn't match in CCM"); } try { inCipher = CipherUtilities.GetCipher("AES/CCM/PKCS5Padding"); Fail("bad padding missed in CCM"); } catch (SecurityUtilityException) { // expected } } [Test] public void TestGcm() { // Test Case 15 from McGrew/Viega byte[] K = Hex.Decode( "feffe9928665731c6d6a8f9467308308" + "feffe9928665731c6d6a8f9467308308"); byte[] P = Hex.Decode( "d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" + "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b391aafd255"); byte[] N = Hex.Decode("cafebabefacedbaddecaf888"); string T = "b094dac5d93471bdec1a502270e3cc6c"; byte[] C = Hex.Decode( "522dc1f099567d07f47f37a32a84427d" + "643a8cdcbfe5c0c97598a2bd2555d1aa" + "8cb08e48590dbb3da7b08b1056828838" + "c5f61e6393ba7a0abcc9f662898015ad" + T); KeyParameter key = ParameterUtilities.CreateKeyParameter("AES", K); IBufferedCipher inCipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); inCipher.Init(true, new ParametersWithIV(key, N)); byte[] enc = inCipher.DoFinal(P); if (!AreEqual(enc, C)) { Fail("ciphertext doesn't match in GCM"); } outCipher.Init(false, new ParametersWithIV(key, N)); byte[] dec = outCipher.DoFinal(C); if (!AreEqual(dec, P)) { Fail("plaintext doesn't match in GCM"); } try { inCipher = CipherUtilities.GetCipher("AES/GCM/PKCS5Padding"); Fail("bad padding missed in GCM"); } catch (SecurityUtilityException) { // expected } } public override void PerformTest() { TestCiphers(); TestWrap(); TestOids(); TestWrapOids(); TestEax(); TestCcm(); TestGcm(); } public static void Main( string[] args) { RunTest(new AesTest()); } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Trace.V1 { /// <summary> /// Settings for a <see cref="TraceServiceClient"/>. /// </summary> public sealed partial class TraceServiceSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="TraceServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="TraceServiceSettings"/>. /// </returns> public static TraceServiceSettings GetDefault() => new TraceServiceSettings(); /// <summary> /// Constructs a new <see cref="TraceServiceSettings"/> object with default settings. /// </summary> public TraceServiceSettings() { } private TraceServiceSettings(TraceServiceSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); PatchTracesSettings = existing.PatchTracesSettings; GetTraceSettings = existing.GetTraceSettings; ListTracesSettings = existing.ListTracesSettings; OnCopy(existing); } partial void OnCopy(TraceServiceSettings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="TraceServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="TraceServiceClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 1000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.2</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(1000), delayMultiplier: 1.2 ); /// <summary> /// "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Maximum timeout: 30000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(20000), maxDelay: TimeSpan.FromMilliseconds(30000), delayMultiplier: 1.5 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>TraceServiceClient.PatchTraces</c> and <c>TraceServiceClient.PatchTracesAsync</c>. /// </summary> /// <remarks> /// The default <c>TraceServiceClient.PatchTraces</c> and /// <c>TraceServiceClient.PatchTracesAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 45000 milliseconds. /// </remarks> public CallSettings PatchTracesSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>TraceServiceClient.GetTrace</c> and <c>TraceServiceClient.GetTraceAsync</c>. /// </summary> /// <remarks> /// The default <c>TraceServiceClient.GetTrace</c> and /// <c>TraceServiceClient.GetTraceAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 45000 milliseconds. /// </remarks> public CallSettings GetTraceSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>TraceServiceClient.ListTraces</c> and <c>TraceServiceClient.ListTracesAsync</c>. /// </summary> /// <remarks> /// The default <c>TraceServiceClient.ListTraces</c> and /// <c>TraceServiceClient.ListTracesAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 45000 milliseconds. /// </remarks> public CallSettings ListTracesSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="TraceServiceSettings"/> object.</returns> public TraceServiceSettings Clone() => new TraceServiceSettings(this); } /// <summary> /// TraceService client wrapper, for convenient use. /// </summary> public abstract partial class TraceServiceClient { /// <summary> /// The default endpoint for the TraceService service, which is a host of "cloudtrace.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("cloudtrace.googleapis.com", 443); /// <summary> /// The default TraceService scopes. /// </summary> /// <remarks> /// The default TraceService scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// <item><description>"https://www.googleapis.com/auth/trace.append"</description></item> /// <item><description>"https://www.googleapis.com/auth/trace.readonly"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/trace.append", "https://www.googleapis.com/auth/trace.readonly", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="TraceServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="TraceServiceClient"/>.</returns> public static async Task<TraceServiceClient> CreateAsync(ServiceEndpoint endpoint = null, TraceServiceSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="TraceServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param> /// <returns>The created <see cref="TraceServiceClient"/>.</returns> public static TraceServiceClient Create(ServiceEndpoint endpoint = null, TraceServiceSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="TraceServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param> /// <returns>The created <see cref="TraceServiceClient"/>.</returns> public static TraceServiceClient Create(Channel channel, TraceServiceSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); TraceService.TraceServiceClient grpcClient = new TraceService.TraceServiceClient(channel); return new TraceServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, TraceServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, TraceServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, TraceServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, TraceServiceSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC TraceService client. /// </summary> public virtual TraceService.TraceServiceClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> /// <param name="projectId"> /// ID of the Cloud project where the trace data is stored. /// </param> /// <param name="traces"> /// The body of the message. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task PatchTracesAsync( string projectId, Traces traces, CallSettings callSettings = null) => PatchTracesAsync( new PatchTracesRequest { ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Traces = GaxPreconditions.CheckNotNull(traces, nameof(traces)), }, callSettings); /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> /// <param name="projectId"> /// ID of the Cloud project where the trace data is stored. /// </param> /// <param name="traces"> /// The body of the message. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task PatchTracesAsync( string projectId, Traces traces, CancellationToken cancellationToken) => PatchTracesAsync( projectId, traces, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> /// <param name="projectId"> /// ID of the Cloud project where the trace data is stored. /// </param> /// <param name="traces"> /// The body of the message. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void PatchTraces( string projectId, Traces traces, CallSettings callSettings = null) => PatchTraces( new PatchTracesRequest { ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Traces = GaxPreconditions.CheckNotNull(traces, nameof(traces)), }, callSettings); /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task PatchTracesAsync( PatchTracesRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void PatchTraces( PatchTracesRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets a single trace by its ID. /// </summary> /// <param name="projectId"> /// ID of the Cloud project where the trace data is stored. /// </param> /// <param name="traceId"> /// ID of the trace to return. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Trace> GetTraceAsync( string projectId, string traceId, CallSettings callSettings = null) => GetTraceAsync( new GetTraceRequest { ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), TraceId = GaxPreconditions.CheckNotNullOrEmpty(traceId, nameof(traceId)), }, callSettings); /// <summary> /// Gets a single trace by its ID. /// </summary> /// <param name="projectId"> /// ID of the Cloud project where the trace data is stored. /// </param> /// <param name="traceId"> /// ID of the trace to return. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Trace> GetTraceAsync( string projectId, string traceId, CancellationToken cancellationToken) => GetTraceAsync( projectId, traceId, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets a single trace by its ID. /// </summary> /// <param name="projectId"> /// ID of the Cloud project where the trace data is stored. /// </param> /// <param name="traceId"> /// ID of the trace to return. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Trace GetTrace( string projectId, string traceId, CallSettings callSettings = null) => GetTrace( new GetTraceRequest { ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), TraceId = GaxPreconditions.CheckNotNullOrEmpty(traceId, nameof(traceId)), }, callSettings); /// <summary> /// Gets a single trace by its ID. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Trace> GetTraceAsync( GetTraceRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets a single trace by its ID. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Trace GetTrace( GetTraceRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> /// <param name="projectId"> /// ID of the Cloud project where the trace data is stored. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Trace"/> resources. /// </returns> public virtual PagedAsyncEnumerable<ListTracesResponse, Trace> ListTracesAsync( string projectId, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) => ListTracesAsync( new ListTracesRequest { ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> /// <param name="projectId"> /// ID of the Cloud project where the trace data is stored. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Trace"/> resources. /// </returns> public virtual PagedEnumerable<ListTracesResponse, Trace> ListTraces( string projectId, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) => ListTraces( new ListTracesRequest { ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Trace"/> resources. /// </returns> public virtual PagedAsyncEnumerable<ListTracesResponse, Trace> ListTracesAsync( ListTracesRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Trace"/> resources. /// </returns> public virtual PagedEnumerable<ListTracesResponse, Trace> ListTraces( ListTracesRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// TraceService client wrapper implementation, for convenient use. /// </summary> public sealed partial class TraceServiceClientImpl : TraceServiceClient { private readonly ApiCall<PatchTracesRequest, Empty> _callPatchTraces; private readonly ApiCall<GetTraceRequest, Trace> _callGetTrace; private readonly ApiCall<ListTracesRequest, ListTracesResponse> _callListTraces; /// <summary> /// Constructs a client wrapper for the TraceService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="TraceServiceSettings"/> used within this client </param> public TraceServiceClientImpl(TraceService.TraceServiceClient grpcClient, TraceServiceSettings settings) { GrpcClient = grpcClient; TraceServiceSettings effectiveSettings = settings ?? TraceServiceSettings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); _callPatchTraces = clientHelper.BuildApiCall<PatchTracesRequest, Empty>( GrpcClient.PatchTracesAsync, GrpcClient.PatchTraces, effectiveSettings.PatchTracesSettings); _callGetTrace = clientHelper.BuildApiCall<GetTraceRequest, Trace>( GrpcClient.GetTraceAsync, GrpcClient.GetTrace, effectiveSettings.GetTraceSettings); _callListTraces = clientHelper.BuildApiCall<ListTracesRequest, ListTracesResponse>( GrpcClient.ListTracesAsync, GrpcClient.ListTraces, effectiveSettings.ListTracesSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(TraceService.TraceServiceClient grpcClient, TraceServiceSettings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC TraceService client. /// </summary> public override TraceService.TraceServiceClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_PatchTracesRequest(ref PatchTracesRequest request, ref CallSettings settings); partial void Modify_GetTraceRequest(ref GetTraceRequest request, ref CallSettings settings); partial void Modify_ListTracesRequest(ref ListTracesRequest request, ref CallSettings settings); /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task PatchTracesAsync( PatchTracesRequest request, CallSettings callSettings = null) { Modify_PatchTracesRequest(ref request, ref callSettings); return _callPatchTraces.Async(request, callSettings); } /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override void PatchTraces( PatchTracesRequest request, CallSettings callSettings = null) { Modify_PatchTracesRequest(ref request, ref callSettings); _callPatchTraces.Sync(request, callSettings); } /// <summary> /// Gets a single trace by its ID. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<Trace> GetTraceAsync( GetTraceRequest request, CallSettings callSettings = null) { Modify_GetTraceRequest(ref request, ref callSettings); return _callGetTrace.Async(request, callSettings); } /// <summary> /// Gets a single trace by its ID. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Trace GetTrace( GetTraceRequest request, CallSettings callSettings = null) { Modify_GetTraceRequest(ref request, ref callSettings); return _callGetTrace.Sync(request, callSettings); } /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Trace"/> resources. /// </returns> public override PagedAsyncEnumerable<ListTracesResponse, Trace> ListTracesAsync( ListTracesRequest request, CallSettings callSettings = null) { Modify_ListTracesRequest(ref request, ref callSettings); return new GrpcPagedAsyncEnumerable<ListTracesRequest, ListTracesResponse, Trace>(_callListTraces, request, callSettings); } /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Trace"/> resources. /// </returns> public override PagedEnumerable<ListTracesResponse, Trace> ListTraces( ListTracesRequest request, CallSettings callSettings = null) { Modify_ListTracesRequest(ref request, ref callSettings); return new GrpcPagedEnumerable<ListTracesRequest, ListTracesResponse, Trace>(_callListTraces, request, callSettings); } } // Partial classes to enable page-streaming public partial class ListTracesRequest : IPageRequest { } public partial class ListTracesResponse : IPageResponse<Trace> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public IEnumerator<Trace> GetEnumerator() => Traces.GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
// 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.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class MinTests { // Get a set of ranges from 0 to each count, with an extra parameter for a minimum where each item is negated (-x). public static IEnumerable<object[]> MinData(int[] counts) { Func<int, int> min = x => 1 - x; foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), min)) { yield return results; } } // // Min // [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Int(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Min()); Assert.Equal(0, query.Select(x => (int?)x).Min()); Assert.Equal(min, query.Min(x => -x)); Assert.Equal(min, query.Min(x => -(int?)x)); } [Theory] [OuterLoop] [MemberData(nameof(MinData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int min) { Min_Int(labeled, count, min); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (int?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(int?)x : null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (int?)null).Min()); Assert.Null(query.Min(x => (int?)null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Long(Labeled<ParallelQuery<int>> labeled, int count, long min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (long)x).Min()); Assert.Equal(0, query.Select(x => (long?)x).Min()); Assert.Equal(min, query.Min(x => -(long)x)); Assert.Equal(min, query.Min(x => -(long?)x)); } [Theory] [OuterLoop] [MemberData(nameof(MinData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long min) { Min_Long(labeled, count, min); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (long?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(long?)x : null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (long?)null).Min()); Assert.Null(query.Min(x => (long?)null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Float(Labeled<ParallelQuery<int>> labeled, int count, float min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (float)x).Min()); Assert.Equal(0, query.Select(x => (float?)x).Min()); Assert.Equal(min, query.Min(x => -(float)x)); Assert.Equal(min, query.Min(x => -(float?)x)); Assert.Equal(float.NegativeInfinity, query.Select(x => x == count / 2 ? float.NegativeInfinity : x).Min()); Assert.Equal(float.NegativeInfinity, query.Select(x => x == count / 2 ? (float?)float.NegativeInfinity : x).Min()); Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? float.NaN : x).Min()); Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? (float?)float.NaN : x).Min()); } [Theory] [OuterLoop] [MemberData(nameof(MinData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float min) { Min_Float(labeled, count, min); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (float?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(float?)x : null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 3 }))] public static void Min_Float_Special(Labeled<ParallelQuery<int>> labeled, int count, float min) { // Null is defined as 'least' when ordered, but is not the minimum. Func<int, float?> translate = x => x % 3 == 0 ? (float?)null : x % 3 == 1 ? float.MinValue : float.NaN; ParallelQuery<int> query = labeled.Item; Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? float.NaN : float.MinValue).Min()); Assert.Equal(float.NaN, query.Select(translate).Min()); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (float?)null).Min()); Assert.Null(query.Min(x => (float?)null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Double(Labeled<ParallelQuery<int>> labeled, int count, double min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (double)x).Min()); Assert.Equal(0, query.Select(x => (double?)x).Min()); Assert.Equal(min, query.Min(x => -(double)x)); Assert.Equal(min, query.Min(x => -(double?)x)); Assert.Equal(double.NegativeInfinity, query.Select(x => x == count / 2 ? double.NegativeInfinity : x).Min()); Assert.Equal(double.NegativeInfinity, query.Select(x => x == count / 2 ? (double?)double.NegativeInfinity : x).Min()); Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? double.NaN : x).Min()); Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? (double?)double.NaN : x).Min()); } [Theory] [OuterLoop] [MemberData(nameof(MinData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double min) { Min_Double(labeled, count, min); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 3 }))] public static void Min_Double_Special(Labeled<ParallelQuery<int>> labeled, int count, double min) { // Null is defined as 'least' when ordered, but is not the minimum. Func<int, double?> translate = x => x % 3 == 0 ? (double?)null : x % 3 == 1 ? double.MinValue : double.NaN; ParallelQuery<int> query = labeled.Item; Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? double.NaN : double.MinValue).Min()); Assert.Equal(double.NaN, query.Select(translate).Min()); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (double?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(double?)x : null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (double?)null).Min()); Assert.Null(query.Min(x => (double?)null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (decimal)x).Min()); Assert.Equal(0, query.Select(x => (decimal?)x).Min()); Assert.Equal(min, query.Min(x => -(decimal)x)); Assert.Equal(min, query.Min(x => -(decimal?)x)); } [Theory] [OuterLoop] [MemberData(nameof(MinData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal min) { Min_Decimal(labeled, count, min); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (decimal?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(decimal?)x : null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (decimal?)null).Min()); Assert.Null(query.Min(x => (decimal?)null)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Other(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => DelgatedComparable.Delegate(x, Comparer<int>.Default)).Min().Value); Assert.Equal(count - 1, query.Select(x => DelgatedComparable.Delegate(x, ReverseComparer.Instance)).Min().Value); } [Theory] [OuterLoop] [MemberData(nameof(MinData), (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Other_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int min) { Min_Other(labeled, count, min); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, }))] public static void Min_NotComparable(Labeled<ParallelQuery<int>> labeled, int count, int min) { NotComparable a = new NotComparable(0); Assert.Equal(a, labeled.Item.Min(x => a)); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Other_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Min(x => x >= count / 2 ? DelgatedComparable.Delegate(x, Comparer<int>.Default) : null).Value); Assert.Equal(count - 1, query.Min(x => x >= count / 2 ? DelgatedComparable.Delegate(x, ReverseComparer.Instance) : null).Value); } [Theory] [MemberData(nameof(MinData), (object)(new int[] { 1, 2, 16 }))] public static void Min_Other_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (string)null).Min()); Assert.Null(query.Min(x => (string)null)); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0 }), MemberType = typeof(UnorderedSources))] public static void Min_EmptyNullable(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Null(labeled.Item.Min(x => (int?)x)); Assert.Null(labeled.Item.Min(x => (long?)x)); Assert.Null(labeled.Item.Min(x => (float?)x)); Assert.Null(labeled.Item.Min(x => (double?)x)); Assert.Null(labeled.Item.Min(x => (decimal?)x)); Assert.Null(labeled.Item.Min(x => new object())); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0 }), MemberType = typeof(UnorderedSources))] public static void Min_InvalidOperationException(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Throws<InvalidOperationException>(() => labeled.Item.Min()); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (long)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (float)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (double)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (decimal)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => new NotComparable(x))); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Min_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (int?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (long)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (long?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (float)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (float?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (double)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (double?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (decimal)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (decimal?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => new NotComparable(x))); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Min_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, int?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, long>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, long?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, float>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, float?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, double>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, double?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, decimal>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, decimal?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, NotComparable>)(x => { throw new DeliberateTestException(); }))); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Min_AggregateException_NotComparable(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<ArgumentException>(() => labeled.Item.Min(x => new NotComparable(x))); } [Fact] public static void Min_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Min((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Min((Func<int?, int?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Min((Func<long, long>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Min((Func<long?, long?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Min((Func<float, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Min((Func<float?, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Min((Func<double, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Min((Func<double?, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Min((Func<decimal, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Min((Func<decimal?, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<NotComparable>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Min((Func<int, NotComparable>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<object>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(new object(), 1).Min((Func<object, object>)null)); } } }
using Lucene.Net.Diagnostics; using System; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Provides support for converting byte sequences to <see cref="string"/>s and back again. /// The resulting <see cref="string"/>s preserve the original byte sequences' sort order. /// <para/> /// The <see cref="string"/>s are constructed using a Base 8000h encoding of the original /// binary data - each char of an encoded <see cref="string"/> represents a 15-bit chunk /// from the byte sequence. Base 8000h was chosen because it allows for all /// lower 15 bits of char to be used without restriction; the surrogate range /// [U+D8000-U+DFFF] does not represent valid chars, and would require /// complicated handling to avoid them and allow use of char's high bit. /// <para/> /// Although unset bits are used as padding in the final char, the original /// byte sequence could contain trailing bytes with no set bits (null bytes): /// padding is indistinguishable from valid information. To overcome this /// problem, a char is appended, indicating the number of encoded bytes in the /// final content char. /// <para/> /// @lucene.experimental /// </summary> [Obsolete("Implement Analysis.TokenAttributes.ITermToBytesRefAttribute and store bytes directly instead. this class will be removed in Lucene 5.0")] public static class IndexableBinaryStringTools // LUCENENET specific - made static { private static readonly CodingCase[] CODING_CASES = new CodingCase[] { // CodingCase(int initialShift, int finalShift) new CodingCase(7, 1), // CodingCase(int initialShift, int middleShift, int finalShift) new CodingCase(14, 6, 2), new CodingCase(13, 5, 3), new CodingCase(12, 4, 4), new CodingCase(11, 3, 5), new CodingCase(10, 2, 6), new CodingCase(9, 1, 7), new CodingCase(8, 0) }; /// <summary> /// Returns the number of chars required to encode the given <see cref="byte"/>s. /// </summary> /// <param name="inputArray"> Byte sequence to be encoded </param> /// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param> /// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param> /// <returns> The number of chars required to encode the number of <see cref="byte"/>s. </returns> // LUCENENET specific overload for CLS compliance public static int GetEncodedLength(byte[] inputArray, int inputOffset, int inputLength) { // Use long for intermediaries to protect against overflow return (int)((8L * inputLength + 14L) / 15L) + 1; } /// <summary> /// Returns the number of chars required to encode the given <see cref="sbyte"/>s. /// </summary> /// <param name="inputArray"> <see cref="sbyte"/> sequence to be encoded </param> /// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param> /// <param name="inputLength"> Number of sbytes in <paramref name="inputArray"/> </param> /// <returns> The number of chars required to encode the number of <see cref="sbyte"/>s. </returns> [CLSCompliant(false)] public static int GetEncodedLength(sbyte[] inputArray, int inputOffset, int inputLength) { // Use long for intermediaries to protect against overflow return (int)((8L * inputLength + 14L) / 15L) + 1; } /// <summary> /// Returns the number of <see cref="byte"/>s required to decode the given char sequence. /// </summary> /// <param name="encoded"> Char sequence to be decoded </param> /// <param name="offset"> Initial offset </param> /// <param name="length"> Number of characters </param> /// <returns> The number of <see cref="byte"/>s required to decode the given char sequence </returns> public static int GetDecodedLength(char[] encoded, int offset, int length) { int numChars = length - 1; if (numChars <= 0) { return 0; } else { // Use long for intermediaries to protect against overflow long numFullBytesInFinalChar = encoded[offset + length - 1]; long numEncodedChars = numChars - 1; return (int)((numEncodedChars * 15L + 7L) / 8L + numFullBytesInFinalChar); } } /// <summary> /// Encodes the input <see cref="byte"/> sequence into the output char sequence. Before /// calling this method, ensure that the output array has sufficient /// capacity by calling <see cref="GetEncodedLength(byte[], int, int)"/>. /// </summary> /// <param name="inputArray"> <see cref="byte"/> sequence to be encoded </param> /// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param> /// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param> /// <param name="outputArray"> <see cref="char"/> sequence to store encoded result </param> /// <param name="outputOffset"> Initial offset into outputArray </param> /// <param name="outputLength"> Length of output, must be GetEncodedLength(inputArray, inputOffset, inputLength) </param> // LUCENENET specific overload for CLS compliance public static void Encode(byte[] inputArray, int inputOffset, int inputLength, char[] outputArray, int outputOffset, int outputLength) { Encode((sbyte[])(Array)inputArray, inputOffset, inputLength, outputArray, outputOffset, outputLength); } /// <summary> /// Encodes the input <see cref="sbyte"/> sequence into the output char sequence. Before /// calling this method, ensure that the output array has sufficient /// capacity by calling <see cref="GetEncodedLength(sbyte[], int, int)"/>. /// </summary> /// <param name="inputArray"> <see cref="sbyte"/> sequence to be encoded </param> /// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param> /// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param> /// <param name="outputArray"> <see cref="char"/> sequence to store encoded result </param> /// <param name="outputOffset"> Initial offset into outputArray </param> /// <param name="outputLength"> Length of output, must be getEncodedLength </param> [CLSCompliant(false)] public static void Encode(sbyte[] inputArray, int inputOffset, int inputLength, char[] outputArray, int outputOffset, int outputLength) { if (Debugging.AssertsEnabled) Debugging.Assert(outputLength == GetEncodedLength(inputArray, inputOffset, inputLength)); if (inputLength > 0) { int inputByteNum = inputOffset; int caseNum = 0; int outputCharNum = outputOffset; CodingCase codingCase; for (; inputByteNum + CODING_CASES[caseNum].numBytes <= inputLength; ++outputCharNum) { codingCase = CODING_CASES[caseNum]; if (2 == codingCase.numBytes) { outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + (((int)((uint)(inputArray[inputByteNum + 1] & 0xFF) >> codingCase.finalShift)) & codingCase.finalMask) & (short)0x7FFF); } // numBytes is 3 else { outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift) + (((int)((uint)(inputArray[inputByteNum + 2] & 0xFF) >> codingCase.finalShift)) & codingCase.finalMask) & (short)0x7FFF); } inputByteNum += codingCase.advanceBytes; if (++caseNum == CODING_CASES.Length) { caseNum = 0; } } // Produce final char (if any) and trailing count chars. codingCase = CODING_CASES[caseNum]; if (inputByteNum + 1 < inputLength) // codingCase.numBytes must be 3 { outputArray[outputCharNum++] = (char)((((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift)) & (short)0x7FFF); // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = (char)1; } else if (inputByteNum < inputLength) { outputArray[outputCharNum++] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) & (short)0x7FFF); // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = caseNum == 0 ? (char)1 : (char)0; } // No left over bits - last char is completely filled. else { // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = (char)1; } } } /// <summary> /// Decodes the input <see cref="char"/> sequence into the output <see cref="byte"/> sequence. Before /// calling this method, ensure that the output array has sufficient capacity /// by calling <see cref="GetDecodedLength(char[], int, int)"/>. /// </summary> /// <param name="inputArray"> <see cref="char"/> sequence to be decoded </param> /// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param> /// <param name="inputLength"> Number of chars in <paramref name="inputArray"/> </param> /// <param name="outputArray"> <see cref="byte"/> sequence to store encoded result </param> /// <param name="outputOffset"> Initial offset into outputArray </param> /// <param name="outputLength"> Length of output, must be /// GetDecodedLength(inputArray, inputOffset, inputLength) </param> // LUCENENET specific overload for CLS compliance public static void Decode(char[] inputArray, int inputOffset, int inputLength, byte[] outputArray, int outputOffset, int outputLength) { Decode(inputArray, inputOffset, inputLength, (sbyte[])(Array)outputArray, outputOffset, outputLength); } /// <summary> /// Decodes the input char sequence into the output sbyte sequence. Before /// calling this method, ensure that the output array has sufficient capacity /// by calling <see cref="GetDecodedLength(char[], int, int)"/>. /// </summary> /// <param name="inputArray"> <see cref="char"/> sequence to be decoded </param> /// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param> /// <param name="inputLength"> Number of chars in <paramref name="inputArray"/> </param> /// <param name="outputArray"> <see cref="byte"/> sequence to store encoded result </param> /// <param name="outputOffset"> Initial offset into outputArray </param> /// <param name="outputLength"> Length of output, must be /// GetDecodedLength(inputArray, inputOffset, inputLength) </param> [CLSCompliant(false)] public static void Decode(char[] inputArray, int inputOffset, int inputLength, sbyte[] outputArray, int outputOffset, int outputLength) { if (Debugging.AssertsEnabled) Debugging.Assert(outputLength == GetDecodedLength(inputArray, inputOffset, inputLength)); int numInputChars = inputLength - 1; int numOutputBytes = outputLength; if (numOutputBytes > 0) { int caseNum = 0; int outputByteNum = outputOffset; int inputCharNum = inputOffset; short inputChar; CodingCase codingCase; for (; inputCharNum < numInputChars - 1; ++inputCharNum) { codingCase = CODING_CASES[caseNum]; inputChar = (short)inputArray[inputCharNum]; if (2 == codingCase.numBytes) { if (0 == caseNum) { outputArray[outputByteNum] = (sbyte)((short)((ushort)inputChar >> codingCase.initialShift)); } else { outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift)); } outputArray[outputByteNum + 1] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift); } // numBytes is 3 else { outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift)); outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.middleMask) >> codingCase.middleShift)); outputArray[outputByteNum + 2] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift); } outputByteNum += codingCase.advanceBytes; if (++caseNum == CODING_CASES.Length) { caseNum = 0; } } // Handle final char inputChar = (short)inputArray[inputCharNum]; codingCase = CODING_CASES[caseNum]; if (0 == caseNum) { outputArray[outputByteNum] = 0; } outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift)); int bytesLeft = numOutputBytes - outputByteNum; if (bytesLeft > 1) { if (2 == codingCase.numBytes) { outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.finalMask) >> codingCase.finalShift)); } // numBytes is 3 else { outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.middleMask) >> codingCase.middleShift)); if (bytesLeft > 2) { outputArray[outputByteNum + 2] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift); } } } } } internal class CodingCase { internal int numBytes, initialShift, middleShift, finalShift, advanceBytes = 2; internal short middleMask, finalMask; internal CodingCase(int initialShift, int middleShift, int finalShift) { this.numBytes = 3; this.initialShift = initialShift; this.middleShift = middleShift; this.finalShift = finalShift; this.finalMask = (short)((int)((uint)(short)0xFF >> finalShift)); this.middleMask = (short)((short)0xFF << middleShift); } internal CodingCase(int initialShift, int finalShift) { this.numBytes = 2; this.initialShift = initialShift; this.finalShift = finalShift; this.finalMask = (short)((int)((uint)(short)0xFF >> finalShift)); if (finalShift != 0) { advanceBytes = 1; } } } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_830 : MapLoop { public M_830() : base(null) { Content.AddRange(new MapBaseEntity[] { new BFR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new XPO() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new SAC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new CSH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LIN(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, new CTT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } //1000 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2000 public class L_LM : MapLoop { public L_LM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, }); } } //3000 public class L_LIN : MapLoop { public L_LIN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LIN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new UIT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PO3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PRS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new SAC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new ATH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new DD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_SLN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_LM_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_FST(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SDP(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 260 }, new L_SHP(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, }); } } //3100 public class L_SLN : MapLoop { public L_SLN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SLN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //3200 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3300 public class L_LM_1 : MapLoop { public L_LM_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, }); } } //3400 public class L_FST : MapLoop { public L_FST(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new FST() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SDQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 50 }, new L_LM_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3410 public class L_LM_2 : MapLoop { public L_LM_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, }); } } //3500 public class L_SDP : MapLoop { public L_SDP(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SDP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new FST() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 260 }, }); } } //3600 public class L_SHP : MapLoop { public L_SHP(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SHP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Security.Principal; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.DirectoryServices.AccountManagement { internal class AuthZSet : ResultSet { internal AuthZSet( byte[] userSid, NetCred credentials, ContextOptions contextOptions, string flatUserAuthority, StoreCtx userStoreCtx, object userCtxBase) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "AuthZSet: SID={0}, authority={1}, storeCtx={2}", Utils.ByteArrayToString(userSid), flatUserAuthority, userStoreCtx.GetType()); _userType = userStoreCtx.OwningContext.ContextType; _userCtxBase = userCtxBase; _userStoreCtx = userStoreCtx; _credentials = credentials; _contextOptions = contextOptions; // flatUserAuthority is flat domain name if userType == Domain, // flat host name if userType == LocalMachine _flatUserAuthority = flatUserAuthority; // Preload the PrincipalContext cache with the user's PrincipalContext _contexts[flatUserAuthority] = userStoreCtx.OwningContext; IntPtr hUser = IntPtr.Zero; // // Get the SIDs of the groups to which the user belongs // IntPtr pClientContext = IntPtr.Zero; IntPtr pResManager = IntPtr.Zero; IntPtr pBuffer = IntPtr.Zero; try { UnsafeNativeMethods.LUID luid = new UnsafeNativeMethods.LUID(); luid.low = 0; luid.high = 0; _psMachineSid = new SafeMemoryPtr(Utils.GetMachineDomainSid()); _psUserSid = new SafeMemoryPtr(Utils.ConvertByteArrayToIntPtr(userSid)); bool f; int lastError = 0; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Initializing resource manager"); // Create a resource manager f = UnsafeNativeMethods.AuthzInitializeResourceManager( UnsafeNativeMethods.AUTHZ_RM_FLAG.AUTHZ_RM_FLAG_NO_AUDIT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null, out pResManager ); if (f) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting ctx from SID"); // Construct a context for the user based on the user's SID f = UnsafeNativeMethods.AuthzInitializeContextFromSid( 0, // default flags _psUserSid.DangerousGetHandle(), pResManager, IntPtr.Zero, luid, IntPtr.Zero, out pClientContext ); if (f) { int bufferSize = 0; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting info from ctx"); // Extract the group SIDs from the user's context. Determine the size of the buffer we need. f = UnsafeNativeMethods.AuthzGetInformationFromContext( pClientContext, 2, // AuthzContextInfoGroupsSids 0, out bufferSize, IntPtr.Zero ); if (!f && (bufferSize > 0) && (Marshal.GetLastWin32Error() == 122) /*ERROR_INSUFFICIENT_BUFFER*/) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting info from ctx (size={0})", bufferSize); Debug.Assert(bufferSize > 0); // Set up the needed buffer pBuffer = Marshal.AllocHGlobal(bufferSize); // Extract the group SIDs from the user's context, into our buffer.0 f = UnsafeNativeMethods.AuthzGetInformationFromContext( pClientContext, 2, // AuthzContextInfoGroupsSids bufferSize, out bufferSize, pBuffer ); if (f) { // Marshall the native buffer into managed SID_AND_ATTR structures. // The native buffer holds a TOKEN_GROUPS structure: // // struct TOKEN_GROUPS { // DWORD GroupCount; // SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY]; // }; // // Extract TOKEN_GROUPS.GroupCount UnsafeNativeMethods.TOKEN_GROUPS tokenGroups = (UnsafeNativeMethods.TOKEN_GROUPS)Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.TOKEN_GROUPS)); int groupCount = tokenGroups.groupCount; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Found {0} groups", groupCount); // Extract TOKEN_GROUPS.Groups, by iterating over the array and marshalling // each native SID_AND_ATTRIBUTES into a managed SID_AND_ATTR. UnsafeNativeMethods.SID_AND_ATTR[] groups = new UnsafeNativeMethods.SID_AND_ATTR[groupCount]; IntPtr currentItem = new IntPtr(pBuffer.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.TOKEN_GROUPS)) - IntPtr.Size); for (int i = 0; i < groupCount; i++) { groups[i] = (UnsafeNativeMethods.SID_AND_ATTR)Marshal.PtrToStructure(currentItem, typeof(UnsafeNativeMethods.SID_AND_ATTR)); currentItem = new IntPtr(currentItem.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.SID_AND_ATTR))); } _groupSidList = new SidList(groups); } else { lastError = Marshal.GetLastWin32Error(); } } else { lastError = Marshal.GetLastWin32Error(); Debug.Fail("With a zero-length buffer, this should have never succeeded"); } } else { lastError = Marshal.GetLastWin32Error(); } } else { lastError = Marshal.GetLastWin32Error(); } if (!f) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "Failed to retrieve group list, {0}", lastError); throw new PrincipalOperationException( SR.Format( SR.AuthZFailedToRetrieveGroupList, lastError)); } // Save off the buffer since it still holds the native SIDs referenced by SidList _psBuffer = new SafeMemoryPtr(pBuffer); pBuffer = IntPtr.Zero; } catch (Exception e) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "AuthZSet", "Caught exception {0} with message {1}", e.GetType(), e.Message); if (_psBuffer != null && !_psBuffer.IsInvalid) _psBuffer.Close(); if (_psUserSid != null && !_psUserSid.IsInvalid) _psUserSid.Close(); if (_psMachineSid != null && !_psMachineSid.IsInvalid) _psMachineSid.Close(); // We're on a platform that doesn't have the AuthZ library if (e is DllNotFoundException) throw new NotSupportedException(SR.AuthZNotSupported, e); if (e is EntryPointNotFoundException) throw new NotSupportedException(SR.AuthZNotSupported, e); throw; } finally { if (pClientContext != IntPtr.Zero) UnsafeNativeMethods.AuthzFreeContext(pClientContext); if (pResManager != IntPtr.Zero) UnsafeNativeMethods.AuthzFreeResourceManager(pResManager); if (pBuffer != IntPtr.Zero) Marshal.FreeHGlobal(pBuffer); } } internal override object CurrentAsPrincipal { get { Debug.Assert(_currentGroup >= 0 && _currentGroup < _groupSidList.Length); GlobalDebug.WriteLineIf( GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: currentGroup={0}, list length={1}", _currentGroup, _groupSidList.Length); // Convert native SID to byte[] SID IntPtr pSid = _groupSidList[_currentGroup].pSid; byte[] sid = Utils.ConvertNativeSidToByteArray(pSid); // sidIssuerName is null only if SID was not resolved // return a fake principal back if (null == _groupSidList[_currentGroup].sidIssuerName) { string name = _groupSidList[_currentGroup].name; // Create a Principal object to represent it GroupPrincipal g = GroupPrincipal.MakeGroup(_userStoreCtx.OwningContext); g.fakePrincipal = true; g.LoadValueIntoProperty(PropertyNames.PrincipalDisplayName, name); g.LoadValueIntoProperty(PropertyNames.PrincipalName, name); SecurityIdentifier sidObj = new SecurityIdentifier(Utils.ConvertSidToSDDL(sid)); g.LoadValueIntoProperty(PropertyNames.PrincipalSid, sidObj); g.LoadValueIntoProperty(PropertyNames.GroupIsSecurityGroup, true); return g; } GroupPrincipal group = null; // Classify the SID SidType sidType = Utils.ClassifySID(pSid); // It's a fake principal. Construct and respond the corresponding fake Principal object. if (sidType == SidType.FakeObject) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: fake principal {0}", Utils.ByteArrayToString(sid)); return _userStoreCtx.ConstructFakePrincipalFromSID(sid); } // Try to figure out who issued the SID string sidIssuerName = null; if (sidType == SidType.RealObjectFakeDomain) { // BUILTIN principal --> issuer is the same authority as the user's SID GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: builtin principal {0}", Utils.ByteArrayToString(sid)); sidIssuerName = _flatUserAuthority; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: real principal {0}", Utils.ByteArrayToString(sid)); // Is the SID from the same domain as the user? bool sameDomain = false; bool success = UnsafeNativeMethods.EqualDomainSid(_psUserSid.DangerousGetHandle(), pSid, ref sameDomain); // if failed, psUserSid must not be a domain sid if (!success) { #if !SUPPORT_WK_USER_OBJS Debug.Fail("AuthZSet.CurrentAsPrincipal: hit a user with a non-domain SID"); #endif // SUPPORT_WK_USER_OBJS sameDomain = false; } // same domain --> issuer is the same authority as the user's SID if (sameDomain) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: same domain as user ({0})", _flatUserAuthority); sidIssuerName = _flatUserAuthority; } } // The SID comes from another domain. Use the domain name that the OS resolved the SID to. if (sidIssuerName == null) { sidIssuerName = _groupSidList[_currentGroup].sidIssuerName; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: different domain ({0}) than user ({1})", sidIssuerName, _flatUserAuthority); } Debug.Assert(sidIssuerName != null); Debug.Assert(sidIssuerName.Length > 0); // Determine whether it's a local (WinNT) or Active Directory domain (LDAP) group bool isLocalGroup = false; if (_userType == ContextType.Machine) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: local group (user is SAM)"); // Machine local user ---> must be a local group isLocalGroup = true; } else { Debug.Assert(_userType == ContextType.Domain); // Domain user, but the group SID is from the machine domain --> must be a local group // EqualDomainSid will return false if pSid is a BUILTIN SID, but that's okay, we treat those as domain (not local) // groups for domain users. bool inMachineDomain = false; if (UnsafeNativeMethods.EqualDomainSid(_psMachineSid.DangerousGetHandle(), pSid, ref inMachineDomain)) if (inMachineDomain) { // At this point we know that the group was issued by the local machine. Now determine if this machine is // a DC. Cache the results of the read. if (!_localMachineIsDC.HasValue) { _localMachineIsDC = (bool?)Utils.IsMachineDC(null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: IsLocalMachine a DC, localMachineIsDC={0}", _localMachineIsDC.Value); } isLocalGroup = !_localMachineIsDC.Value; } GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: user is non-SAM, isLocalGroup={0}", isLocalGroup); } if (isLocalGroup) { // It's a local group, because either (1) it's a local machine user, and local users can't be a member of a domain group, // or (2) it's a domain user that's a member of a group on the local machine. Pass the default machine context options // If we initially targetted AD then those options will not be valid for the machine store. #if USE_CTX_CACHE PrincipalContext ctx = SDSCache.LocalMachine.GetContext( sidIssuerName, _credentials, DefaultContextOptions.MachineDefaultContextOption); #else PrincipalContext ctx = (PrincipalContext) this.contexts[sidIssuerName]; if (ctx == null) { // Build a PrincipalContext for the machine ctx = new PrincipalContext( ContextType.Machine, sidIssuerName, null, (this.credentials != null ? credentials.UserName : null), (this.credentials != null ? credentials.Password : null), DefaultContextOptions.MachineDefaultContextOption); this.contexts[sidIssuerName] = ctx; } #endif SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Sid, sidObj.ToString()); } else { Debug.Assert((_userType == ContextType.Domain) && !string.Equals(Utils.GetComputerFlatName(), sidIssuerName, StringComparison.OrdinalIgnoreCase)); // It's a domain group, because it's a domain user and the SID issuer isn't the local machine #if USE_CTX_CACHE PrincipalContext ctx = SDSCache.Domain.GetContext( sidIssuerName, _credentials, _contextOptions); #else PrincipalContext ctx = (PrincipalContext) this.contexts[sidIssuerName]; if (ctx == null) { // Determine the domain DNS name // DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY int flags = unchecked((int) (0x40000000 | 0x00000010 | 0x00000100)); UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, sidIssuerName, null, flags); // Build a PrincipalContext for the domain ctx = new PrincipalContext( ContextType.Domain, info.DomainName, null, (this.credentials != null ? credentials.UserName : null), (this.credentials != null ? credentials.Password : null), this.contextOptions); this.contexts[sidIssuerName] = ctx; } #endif // Retrieve the group. We'd normally just do a Group.FindByIdentity here, but // because the AZMan API can return "old" SIDs, we also need to check the SID // history. So we'll use the special FindPrincipalBySID method that the ADStoreCtx // exposes for that purpose. Debug.Assert(ctx.QueryCtx is ADStoreCtx); IdentityReference ir = new IdentityReference(); // convert byte sid to SDDL string. SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); ir.UrnScheme = UrnScheme.SidScheme; ir.UrnValue = sidObj.ToString(); group = (GroupPrincipal)((ADStoreCtx)ctx.QueryCtx).FindPrincipalBySID(typeof(GroupPrincipal), ir, true); } if (group == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "CurrentAsPrincipal: Couldn't find group {0}"); throw new NoMatchingPrincipalException(SR.AuthZCantFindGroup); } return group; } } internal override bool MoveNext() { bool needToRetry; do { needToRetry = false; _currentGroup++; if (_currentGroup >= _groupSidList.Length) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "MoveNext: ran off end of list ({0})", _groupSidList.Length); return false; } // Test for the NONE group for a local user. We recognize it by: // * we're enumerating the authz groups for a local machine user // * it's a domain sid (SidType.RealObject) for the same domain as the user // * it has the RID of the "Domain Users" group, 513 if (_userType == ContextType.Machine) { IntPtr pSid = _groupSidList[_currentGroup].pSid; bool sameDomain = false; if (Utils.ClassifySID(pSid) == SidType.RealObject && UnsafeNativeMethods.EqualDomainSid(_psUserSid.DangerousGetHandle(), pSid, ref sameDomain)) { if (sameDomain) { int lastRid = Utils.GetLastRidFromSid(pSid); if (lastRid == 513) // DOMAIN_GROUP_RID_USERS { // This is the NONE group for a local user. This isn't a real group, and // has no impact on authorization (per ColinBr). Skip it. needToRetry = true; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "MoveNext: found NONE group, skipping"); } } } } } while (needToRetry); return true; } internal override void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Reset"); _currentGroup = -1; } // IDisposable implementation public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Dispose: disposing"); _psBuffer.Close(); _psUserSid.Close(); _psMachineSid.Close(); _disposed = true; } } finally { base.Dispose(); } } // // Private fields // // The user whose groups we're retrieving private readonly SafeMemoryPtr _psUserSid = null; // The SID of the machine domain of the machine we're running on private readonly SafeMemoryPtr _psMachineSid = null; // The user's StoreCtx private readonly StoreCtx _userStoreCtx; // The user's credentials private readonly NetCred _credentials; // The user's options private readonly ContextOptions _contextOptions; // The ctxBase (e.g., DirectoryEntry) from the user's StoreCtx private readonly object _userCtxBase; // The type (domain, local, etc.) of the user private readonly ContextType _userType; // The authority's name (hostname or domainname) private readonly string _flatUserAuthority; // The index (into this.groupSidList) of the group we're currently enumerating private int _currentGroup = -1; // The groups we're enumerating over private readonly SidList _groupSidList; // The native TOKEN_GROUPS returned by AuthzGetInformationFromContext private readonly SafeMemoryPtr _psBuffer = null; // Have we been disposed? private bool _disposed = false; // Maps sidIssuerName --> PrincipalContext private readonly Hashtable _contexts = new Hashtable(); // Contains cached results if the local machine is a DC. private bool? _localMachineIsDC = null; // // Guarantees finalization of the native resources // private sealed class SafeMemoryPtr : SafeHandle { private SafeMemoryPtr() : base(IntPtr.Zero, true) { } internal SafeMemoryPtr(IntPtr handle) : base(IntPtr.Zero, true) { SetHandle(handle); } // for the critial finalizer object public override bool IsInvalid { get { return (handle == IntPtr.Zero); } } protected override bool ReleaseHandle() { if (handle != IntPtr.Zero) Marshal.FreeHGlobal(handle); return true; } } /* // // Holds the list of group SIDs. Also translates them in bulk into domain name and group name. // class SidList { public SidList(UnsafeNativeMethods.SID_AND_ATTR[] groupSidAndAttrs) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: processing {0} SIDs", groupSidAndAttrs.Length); // Build the list of SIDs to resolve int groupCount = groupSidAndAttrs.Length; IntPtr[] pGroupSids = new IntPtr[groupCount]; for (int i=0; i < groupCount; i++) { pGroupSids[i] = groupSidAndAttrs[i].pSid; } // Translate the SIDs in bulk IntPtr pOA = IntPtr.Zero; IntPtr pPolicyHandle = IntPtr.Zero; IntPtr pDomains = IntPtr.Zero; UnsafeNativeMethods.LSA_TRUST_INFORMATION[] domains; IntPtr pNames = IntPtr.Zero; UnsafeNativeMethods.LSA_TRANSLATED_NAME[] names; try { // // Get the policy handle // UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES oa = new UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES(); pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES))); Marshal.StructureToPtr(oa, pOA, false); int err = UnsafeNativeMethods.LsaOpenPolicy( IntPtr.Zero, pOA, 0x800, // POLICY_LOOKUP_NAMES ref pPolicyHandle); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: couldn't get policy handle, err={0}", err); throw new PrincipalOperationException(SR.Format( SR.AuthZErrorEnumeratingGroups, SafeNativeMethods.LsaNtStatusToWinError(err))); } Debug.Assert(pPolicyHandle != IntPtr.Zero); // // Translate the SIDs // err = UnsafeNativeMethods.LsaLookupSids( pPolicyHandle, groupCount, pGroupSids, out pDomains, out pNames); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: LsaLookupSids failed, err={0}", err); throw new PrincipalOperationException(SR.Format( SR.AuthZErrorEnumeratingGroups, SafeNativeMethods.LsaNtStatusToWinError(err))); } // // Get the group names in managed form // names = new UnsafeNativeMethods.LSA_TRANSLATED_NAME[groupCount]; IntPtr pCurrentName = pNames; for (int i=0; i < groupCount; i++) { names[i] = (UnsafeNativeMethods.LSA_TRANSLATED_NAME) Marshal.PtrToStructure(pCurrentName, typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME)); pCurrentName = new IntPtr(pCurrentName.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME))); } // // Get the domain names in managed form // // Extract LSA_REFERENCED_DOMAIN_LIST.Entries int domainCount = Marshal.ReadInt32(pDomains); // Extract LSA_REFERENCED_DOMAIN_LIST.Domains, by iterating over the array and marshalling // each native LSA_TRUST_INFORMATION into a managed LSA_TRUST_INFORMATION. domains = new UnsafeNativeMethods.LSA_TRUST_INFORMATION[domainCount]; IntPtr pCurrentDomain = Marshal.ReadIntPtr(pDomains, Marshal.SizeOf(typeof(Int32))); for (int i=0; i < domainCount; i++) { domains[i] =(UnsafeNativeMethods.LSA_TRUST_INFORMATION) Marshal.PtrToStructure(pCurrentDomain, typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION)); pCurrentDomain = new IntPtr(pCurrentDomain.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION))); } GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: got {0} groups in {1} domains", groupCount, domainCount); // // Build the list of entries // Debug.Assert(names.Length == groupCount); for (int i = 0; i < names.Length; i++) { UnsafeNativeMethods.LSA_TRANSLATED_NAME name = names[i]; // Get the domain associated with this name Debug.Assert(name.domainIndex >= 0); Debug.Assert(name.domainIndex < domains.Length); UnsafeNativeMethods.LSA_TRUST_INFORMATION domain = domains[name.domainIndex]; // Build an entry. Note that LSA_UNICODE_STRING.length is in bytes, // while PtrToStringUni expects a length in characters. SidListEntry entry = new SidListEntry(); Debug.Assert(name.name.length % 2 == 0); entry.name = Marshal.PtrToStringUni(name.name.buffer, name.name.length/2); Debug.Assert(domain.name.length % 2 == 0); entry.sidIssuerName = Marshal.PtrToStringUni(domain.name.buffer, domain.name.length/2); entry.pSid = groupSidAndAttrs[i].pSid; this.entries.Add(entry); } } finally { if (pDomains != IntPtr.Zero) UnsafeNativeMethods.LsaFreeMemory(pDomains); if (pNames != IntPtr.Zero) UnsafeNativeMethods.LsaFreeMemory(pNames); if (pPolicyHandle != IntPtr.Zero) UnsafeNativeMethods.LsaClose(pPolicyHandle); if (pOA != IntPtr.Zero) Marshal.FreeHGlobal(pOA); } } List<SidListEntry> entries = new List<SidListEntry>(); public SidListEntry this[int index] { get { return this.entries[index]; } } public int Length { get { return this.entries.Count; } } } class SidListEntry { public IntPtr pSid; public string name; public string sidIssuerName; } */ } }
// // FormattedText.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2013 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using Xwt.Drawing; using System.Text; using System.Globalization; namespace Xwt { public class FormattedText { List<TextAttribute> attributes = new List<TextAttribute> (); public List<TextAttribute> Attributes { get { return attributes; } } public string Text { get; set; } class SpanInfo: List<TextAttribute> { public string Tag; } public static FormattedText FromMarkup (string markup) { FormattedText t = new FormattedText (); t.ParseMarkup (markup); return t; } void ParseMarkup (string markup) { Stack<SpanInfo> formatStack = new Stack<SpanInfo> (); StringBuilder sb = new StringBuilder (); int last = 0; int i = markup.IndexOf ('<'); while (i != -1) { sb.Append (markup, last, i - last); if (PushSpan (formatStack, markup, sb.Length, ref i)) { last = i; i = markup.IndexOf ('<', i); continue; } if (PopSpan (formatStack, markup, sb.Length, ref i)) { last = i; i = markup.IndexOf ('<', i); continue; } last = i; i = markup.IndexOf ('<', i + 1); } sb.Append (markup, last, markup.Length - last); Text = sb.ToString (); } bool PushSpan (Stack<SpanInfo> formatStack, string markup, int textIndex, ref int i) { // <span kk="jj"> int k = i; k++; // Skip the < string tag; if (!ReadId (markup, ref k, out tag)) return false; SpanInfo span = new SpanInfo (); span.Tag = tag; switch (tag) { case "b": span.Add (new FontWeightTextAttribute () { Weight = FontWeight.Bold }); break; case "i": span.Add (new FontStyleTextAttribute () { Style = FontStyle.Italic }); break; case "s": span.Add (new StrikethroughTextAttribute ()); break; case "u": span.Add (new UnderlineTextAttribute ()); break; case "a": Uri href = null; ReadXmlAttributes (markup, ref k, (name, val) => { if (name == "href") { href = new Uri (val, UriKind.RelativeOrAbsolute); return true; } return false; }); span.Add (new LinkTextAttribute () { Target = href }); break; case "span": ParseAttributes (span, markup, ref k); break; // case "small": // case "big": // case "tt": } if (span.Count == 0) return false; if (!ReadCharToken (markup, '>', ref k)) return false; foreach (var att in span) att.StartIndex = textIndex; formatStack.Push (span); i = k; return true; } bool PopSpan (Stack<SpanInfo> formatStack, string markup, int textIndex, ref int i) { if (formatStack.Count == 0) return false; int k = i; k++; // Skip the < if (!ReadCharToken (markup, '/', ref k)) return false; string tag; if (!ReadId (markup, ref k, out tag)) return false; // Make sure the closing tag matches the opened tag if (!string.Equals (tag, formatStack.Peek ().Tag, StringComparison.InvariantCultureIgnoreCase)) return false; if (!ReadCharToken (markup, '>', ref k)) return false; var span = formatStack.Pop (); foreach (var attr in span) { attr.Count = textIndex - attr.StartIndex; if (attr.Count > 0) attributes.Add (attr); } i = k; return true; } bool ParseAttributes (SpanInfo span, string markup, ref int i) { return ReadXmlAttributes (markup, ref i, (name, val) => { var attr = CreateAttribute (name, val); if (attr != null) { span.Add (attr); return true; } return false; }); } bool ReadXmlAttributes (string markup, ref int i, Func<string,string,bool> callback) { int k = i; while (true) { string name; if (!ReadId (markup, ref k, out name)) return true; // No more attributes if (!ReadCharToken (markup, '=', ref k)) return false; char endChar; if (ReadCharToken (markup, '"', ref k)) endChar = '"'; else if (ReadCharToken (markup, '\'', ref k)) endChar = '\''; else return false; int n = markup.IndexOf (endChar, k); if (n == -1) return false; string val = markup.Substring (k, n - k); if (callback (name, val)) i = n + 1; else return false; k = i; } } TextAttribute CreateAttribute (string name, string val) { switch (name) { case "font": case "font-desc": case "font_desc": return new FontTextAttribute () { Font = Font.FromName (val) }; /* case "size": case "font_size": double s; if (!double.TryParse (val, NumberStyles.Any, CultureInfo.InvariantCulture, out s)) return null; return new FontSizeTextAttribute () { Size = s }; */ case "font_weight": case "font-weight": case "weight": FontWeight w; if (!Enum.TryParse<FontWeight> (val, true, out w)) return null; return new FontWeightTextAttribute () { Weight = w }; case "font_style": case "font-style": FontStyle s; if (!Enum.TryParse<FontStyle> (val, true, out s)) return null; return new FontStyleTextAttribute () { Style = s }; case "foreground": case "fgcolor": case "color": Color c; if (!Color.TryParse (val, out c)) return null; return new ColorTextAttribute () { Color = c }; case "background": case "background-color": case "bgcolor": Color bc; if (!Color.TryParse (val, out bc)) return null; return new BackgroundTextAttribute () { Color = bc }; case "underline": return new UnderlineTextAttribute () { Underline = ParseBool (val, false) }; case "strikethrough": return new StrikethroughTextAttribute () { Strikethrough = ParseBool (val, false) }; } return null; } bool ParseBool (string s, bool defaultValue) { if (s.Length == 0) return defaultValue; return string.Equals (s, "true", StringComparison.OrdinalIgnoreCase); } bool ReadId (string markup, ref int i, out string tag) { tag = null; int k = i; if (!SkipWhitespace (markup, ref k)) return false; var start = k; while (k < markup.Length) { char c = markup [k]; if (!char.IsLetterOrDigit (c) && c != '_' && c != '-') break; k++; } if (start == k) return false; tag = markup.Substring (start, k - start); i = k; return true; } bool ReadCharToken (string markup, char c, ref int i) { int k = i; if (!SkipWhitespace (markup, ref k)) return false; if (markup [k] == c) { i = k + 1; return true; } else return false; } bool SkipWhitespace (string markup, ref int k) { while (k < markup.Length) { if (!char.IsWhiteSpace (markup [k])) return true; k++; } return false; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JCG = J2N.Collections.Generic; namespace YAF.Lucene.Net.Search { /* * 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 ArrayUtil = YAF.Lucene.Net.Util.ArrayUtil; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using IndexReader = YAF.Lucene.Net.Index.IndexReader; using Term = YAF.Lucene.Net.Index.Term; using TermContext = YAF.Lucene.Net.Index.TermContext; using TermsEnum = YAF.Lucene.Net.Index.TermsEnum; using TermState = YAF.Lucene.Net.Index.TermState; internal interface ITopTermsRewrite { int Count { get; } // LUCENENET NOTE: This was size() in Lucene. } /// <summary> /// Base rewrite method for collecting only the top terms /// via a priority queue. /// <para/> /// @lucene.internal - Only public to be accessible by spans package. /// </summary> public abstract class TopTermsRewrite<Q> : TermCollectingRewrite<Q>, ITopTermsRewrite where Q : Query { private readonly int size; /// <summary> /// Create a <see cref="TopTermsRewrite{Q}"/> for /// at most <paramref name="count"/> terms. /// <para/> /// NOTE: if <see cref="BooleanQuery.MaxClauseCount"/> is smaller than /// <paramref name="count"/>, then it will be used instead. /// </summary> public TopTermsRewrite(int count) { this.size = count; } /// <summary> /// Return the maximum priority queue size. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> public virtual int Count => size; /// <summary> /// Return the maximum size of the priority queue (for boolean rewrites this is <see cref="BooleanQuery.MaxClauseCount"/>). </summary> protected abstract int MaxSize { get; } public override Query Rewrite(IndexReader reader, MultiTermQuery query) { int maxSize = Math.Min(size, MaxSize); JCG.PriorityQueue<ScoreTerm> stQueue = new JCG.PriorityQueue<ScoreTerm>(); CollectTerms(reader, query, new TermCollectorAnonymousInnerClassHelper(this, maxSize, stQueue)); var q = GetTopLevelQuery(); ScoreTerm[] scoreTerms = stQueue.ToArray(/*new ScoreTerm[stQueue.size()]*/); ArrayUtil.TimSort(scoreTerms, scoreTermSortByTermComp); foreach (ScoreTerm st in scoreTerms) { Term term = new Term(query.m_field, st.Bytes); Debug.Assert(reader.DocFreq(term) == st.TermState.DocFreq, "reader DF is " + reader.DocFreq(term) + " vs " + st.TermState.DocFreq + " term=" + term); AddClause(q, term, st.TermState.DocFreq, query.Boost * st.Boost, st.TermState); // add to query } return q; } private class TermCollectorAnonymousInnerClassHelper : TermCollector { private readonly TopTermsRewrite<Q> outerInstance; private int maxSize; private JCG.PriorityQueue<ScoreTerm> stQueue; public TermCollectorAnonymousInnerClassHelper(TopTermsRewrite<Q> outerInstance, int maxSize, JCG.PriorityQueue<ScoreTerm> stQueue) { this.outerInstance = outerInstance; this.maxSize = maxSize; this.stQueue = stQueue; maxBoostAtt = Attributes.AddAttribute<IMaxNonCompetitiveBoostAttribute>(); visitedTerms = new Dictionary<BytesRef, ScoreTerm>(); } private readonly IMaxNonCompetitiveBoostAttribute maxBoostAtt; private readonly IDictionary<BytesRef, ScoreTerm> visitedTerms; private TermsEnum termsEnum; private IComparer<BytesRef> termComp; private IBoostAttribute boostAtt; private ScoreTerm st; public override void SetNextEnum(TermsEnum termsEnum) { this.termsEnum = termsEnum; this.termComp = termsEnum.Comparer; Debug.Assert(CompareToLastTerm(null)); // lazy init the initial ScoreTerm because comparer is not known on ctor: if (st == null) { st = new ScoreTerm(this.termComp, new TermContext(m_topReaderContext)); } boostAtt = termsEnum.Attributes.AddAttribute<IBoostAttribute>(); } // for assert: private BytesRef lastTerm; private bool CompareToLastTerm(BytesRef t) { if (lastTerm == null && t != null) { lastTerm = BytesRef.DeepCopyOf(t); } else if (t == null) { lastTerm = null; } else { Debug.Assert(termsEnum.Comparer.Compare(lastTerm, t) < 0, "lastTerm=" + lastTerm + " t=" + t); lastTerm.CopyBytes(t); } return true; } public override bool Collect(BytesRef bytes) { float boost = boostAtt.Boost; // make sure within a single seg we always collect // terms in order Debug.Assert(CompareToLastTerm(bytes)); //System.out.println("TTR.collect term=" + bytes.utf8ToString() + " boost=" + boost + " ord=" + readerContext.ord); // ignore uncompetitive hits if (stQueue.Count == maxSize) { ScoreTerm t = stQueue.Peek(); if (boost < t.Boost) { return true; } if (boost == t.Boost && termComp.Compare(bytes, t.Bytes) > 0) { return true; } } TermState state = termsEnum.GetTermState(); Debug.Assert(state != null); if (visitedTerms.TryGetValue(bytes, out ScoreTerm t2)) { // if the term is already in the PQ, only update docFreq of term in PQ Debug.Assert(t2.Boost == boost, "boost should be equal in all segment TermsEnums"); t2.TermState.Register(state, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } else { // add new entry in PQ, we must clone the term, else it may get overwritten! st.Bytes.CopyBytes(bytes); st.Boost = boost; visitedTerms[st.Bytes] = st; Debug.Assert(st.TermState.DocFreq == 0); st.TermState.Register(state, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); stQueue.Add(st); // possibly drop entries from queue if (stQueue.Count > maxSize) { st = stQueue.Dequeue(); visitedTerms.Remove(st.Bytes); st.TermState.Clear(); // reset the termstate! } else { st = new ScoreTerm(termComp, new TermContext(m_topReaderContext)); } Debug.Assert(stQueue.Count <= maxSize, "the PQ size must be limited to maxSize"); // set maxBoostAtt with values to help FuzzyTermsEnum to optimize if (stQueue.Count == maxSize) { t2 = stQueue.Peek(); maxBoostAtt.MaxNonCompetitiveBoost = t2.Boost; maxBoostAtt.CompetitiveTerm = t2.Bytes; } } return true; } } public override int GetHashCode() { return 31 * size; } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.GetType() != obj.GetType()) { return false; } if (obj is TopTermsRewrite<Q> other) { if (size != other.size) { return false; } return true; } return false; } private static readonly IComparer<ScoreTerm> scoreTermSortByTermComp = new ComparerAnonymousInnerClassHelper(); private class ComparerAnonymousInnerClassHelper : IComparer<ScoreTerm> { public ComparerAnonymousInnerClassHelper() { } public virtual int Compare(ScoreTerm st1, ScoreTerm st2) { Debug.Assert(st1.TermComp == st2.TermComp, "term comparer should not change between segments"); return st1.TermComp.Compare(st1.Bytes, st2.Bytes); } } internal sealed class ScoreTerm : IComparable<ScoreTerm> { public IComparer<BytesRef> TermComp { get; private set; } public BytesRef Bytes { get; private set; } public float Boost { get; set; } public TermContext TermState { get; private set; } public ScoreTerm(IComparer<BytesRef> termComp, TermContext termState) { this.TermComp = termComp; this.TermState = termState; this.Bytes = new BytesRef(); } public int CompareTo(ScoreTerm other) { if (this.Boost == other.Boost) { return TermComp.Compare(other.Bytes, this.Bytes); } else { return this.Boost.CompareTo(other.Boost); } } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Globalization; using System.ComponentModel; using System.Collections.Generic; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Serialization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Schema { /// <summary> /// <para> /// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>. /// </para> /// <note type="caution"> /// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details. /// </note> /// </summary> [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] public class JsonSchemaGenerator { /// <summary> /// Gets or sets how undefined schemas are handled by the serializer. /// </summary> public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; } private IContractResolver _contractResolver; /// <summary> /// Gets or sets the contract resolver. /// </summary> /// <value>The contract resolver.</value> public IContractResolver ContractResolver { get { if (_contractResolver == null) { return DefaultContractResolver.Instance; } return _contractResolver; } set { _contractResolver = value; } } private class TypeSchema { public Type Type { get; private set; } public JsonSchema Schema { get; private set; } public TypeSchema(Type type, JsonSchema schema) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(schema, "schema"); Type = type; Schema = schema; } } private JsonSchemaResolver _resolver; private readonly IList<TypeSchema> _stack = new List<TypeSchema>(); private JsonSchema _currentSchema; private JsonSchema CurrentSchema { get { return _currentSchema; } } private void Push(TypeSchema typeSchema) { _currentSchema = typeSchema.Schema; _stack.Add(typeSchema); _resolver.LoadedSchemas.Add(typeSchema.Schema); } private TypeSchema Pop() { TypeSchema popped = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); TypeSchema newValue = _stack.LastOrDefault(); if (newValue != null) { _currentSchema = newValue.Schema; } else { _currentSchema = null; } return popped; } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type) { return Generate(type, new JsonSchemaResolver(), false); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, JsonSchemaResolver resolver) { return Generate(type, resolver, false); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, bool rootSchemaNullable) { return Generate(type, new JsonSchemaResolver(), rootSchemaNullable); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(resolver, "resolver"); _resolver = resolver; return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false); } private string GetTitle(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title)) { return containerAttribute.Title; } return null; } private string GetDescription(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description)) { return containerAttribute.Description; } #if !(DOTNET || PORTABLE40 || PORTABLE) DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type); if (descriptionAttribute != null) { return descriptionAttribute.Description; } #endif return null; } private string GetTypeId(Type type, bool explicitOnly) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id)) { return containerAttribute.Id; } if (explicitOnly) { return null; } switch (UndefinedSchemaIdHandling) { case UndefinedSchemaIdHandling.UseTypeName: return type.FullName; case UndefinedSchemaIdHandling.UseAssemblyQualifiedName: return type.AssemblyQualifiedName; default: return null; } } private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) { resolvedSchema.Type |= JsonSchemaType.Null; } if (required && resolvedSchema.Required != true) { resolvedSchema.Required = true; } return resolvedSchema; } } // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = ContractResolver.ResolveContract(type); JsonConverter converter; if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) { return converterSchema; } } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) { CurrentSchema.Id = explicitId; } if (required) { CurrentSchema.Required = true; } CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (converter != null) { // todo: Add GetSchema to JsonConverter and use here? CurrentSchema.Type = JsonSchemaType.Any; } else { switch (contract.ContractType) { case JsonContractType.Object: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateObjectSchema(type, (JsonObjectContract)contract); break; case JsonContractType.Array: CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute<JsonArrayAttribute>(type); bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List<JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } break; case JsonContractType.Primitive: CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true)) { CurrentSchema.Enum = new List<JToken>(); IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(type); foreach (EnumValue<long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); } } break; case JsonContractType.String: JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired); CurrentSchema.Type = schemaType; break; case JsonContractType.Dictionary: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { JsonContract keyContract = ContractResolver.ResolveContract(keyType); // can be converted to a string if (keyContract.ContractType == JsonContractType.Primitive) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } break; #if !(DOTNET || PORTABLE || PORTABLE40) case JsonContractType.Serializable: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateISerializableContract(type, (JsonISerializableContract)contract); break; #endif #if !(NET35 || NET20 || PORTABLE40) case JsonContractType.Dynamic: #endif case JsonContractType.Linq: CurrentSchema.Type = JsonSchemaType.Any; break; default: throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } return Pop().Schema; } private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired) { if (valueRequired != Required.Always) { return type | JsonSchemaType.Null; } return type; } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return ((value & flag) == flag); } private void GenerateObjectSchema(Type type, JsonObjectContract contract) { CurrentSchema.Properties = new Dictionary<string, JsonSchema>(); foreach (JsonProperty property in contract.Properties) { if (!property.Ignored) { bool optional = property.NullValueHandling == NullValueHandling.Ignore || HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) || property.ShouldSerialize != null || property.GetIsSpecified != null; JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional); if (property.DefaultValue != null) { propertySchema.Default = JToken.FromObject(property.DefaultValue); } CurrentSchema.Properties.Add(property.PropertyName, propertySchema); } } if (type.IsSealed()) { CurrentSchema.AllowAdditionalProperties = false; } } #if !(DOTNET || PORTABLE || PORTABLE40) private void GenerateISerializableContract(Type type, JsonISerializableContract contract) { CurrentSchema.AllowAdditionalProperties = true; } #endif internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag) { // default value is Any if (value == null) { return true; } bool match = ((value & flag) == flag); if (match) { return true; } // integer is a subset of float if (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float) { return true; } return false; } private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired) { JsonSchemaType schemaType = JsonSchemaType.None; if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type)) { schemaType = JsonSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) { type = Nullable.GetUnderlyingType(type); } } PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type); switch (typeCode) { case PrimitiveTypeCode.Empty: case PrimitiveTypeCode.Object: return schemaType | JsonSchemaType.String; #if !(DOTNET || PORTABLE) case PrimitiveTypeCode.DBNull: return schemaType | JsonSchemaType.Null; #endif case PrimitiveTypeCode.Boolean: return schemaType | JsonSchemaType.Boolean; case PrimitiveTypeCode.Char: return schemaType | JsonSchemaType.String; case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: #if !(PORTABLE || NET35 || NET20) case PrimitiveTypeCode.BigInteger: #endif return schemaType | JsonSchemaType.Integer; case PrimitiveTypeCode.Single: case PrimitiveTypeCode.Double: case PrimitiveTypeCode.Decimal: return schemaType | JsonSchemaType.Float; // convert to string? case PrimitiveTypeCode.DateTime: #if !NET20 case PrimitiveTypeCode.DateTimeOffset: #endif return schemaType | JsonSchemaType.String; case PrimitiveTypeCode.String: case PrimitiveTypeCode.Uri: case PrimitiveTypeCode.Guid: case PrimitiveTypeCode.TimeSpan: case PrimitiveTypeCode.Bytes: return schemaType | JsonSchemaType.String; default: throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); } } } }
/*============================================================================ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================ */ #region Using directives using System; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; using Microsoft.PowerShell.Commands; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// Enables the user to subscribe to indications using Filter Expression or /// Query Expression. /// -SourceIdentifier is a name given to the subscription /// The Cmdlet should return a PS EventSubscription object that can be used to /// cancel the subscription /// Should we have the second parameter set with a -Query? /// </summary> [Cmdlet(VerbsLifecycle.Register, "CimIndicationEvent", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227960")] public class RegisterCimIndicationCommand : ObjectEventRegistrationBase { #region parameters /// <summary> /// <para> /// The following is the definition of the input parameter "Namespace". /// Specifies the NameSpace under which to look for the specified class name. /// </para> /// <para> /// Default value is root\cimv2 /// </para> /// </summary> [Parameter] public String Namespace { get { return nameSpace; } set { nameSpace = value; } } private String nameSpace; /// <summary> /// The following is the definition of the input parameter "ClassName". /// Specifies the Class Name to register the indication on. /// </summary> [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter(Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] public String ClassName { get { return className; } set { className = value; this.SetParameter(value, nameClassName); } } private String className; /// <summary> /// The following is the definition of the input parameter "Query". /// The Query Expression to pass. /// </summary> [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] public String Query { get { return query; } set { query = value; this.SetParameter(value, nameQuery); } } private String query; /// <summary> /// <para> /// The following is the definition of the input parameter "QueryDialect". /// Specifies the dialect used by the query Engine that interprets the Query /// string. /// </para> /// </summary> [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] public String QueryDialect { get { return queryDialect; } set { queryDialect = value; this.SetParameter(value, nameQueryDialect); } } private String queryDialect; /// <summary> /// The following is the definition of the input parameter "OperationTimeoutSec". /// Enables the user to specify the operation timeout in Seconds. This value /// overwrites the value specified by the CimSession Operation timeout. /// </summary> [Alias(CimBaseCommand.AliasOT)] [Parameter] public UInt32 OperationTimeoutSec { get { return operationTimeout; } set { operationTimeout = value; } } private UInt32 operationTimeout; /// <summary> /// The following is the definition of the input parameter "Session". /// Uses a CimSession context. /// </summary> [Parameter( Mandatory = true, ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] [Parameter( Mandatory = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] public CimSession CimSession { get { return cimSession; } set { cimSession = value; this.SetParameter(value, nameCimSession); } } private CimSession cimSession; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Specifies the computer on which the commands associated with this session /// will run. The default value is LocalHost. /// </summary> [Alias(CimBaseCommand.AliasCN, CimBaseCommand.AliasServerName)] [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] [Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)] public String ComputerName { get { return computername; } set { computername = value; this.SetParameter(value, nameComputerName); } } private String computername; #endregion /// <summary> /// Returns the object that generates events to be monitored /// </summary> protected override Object GetSourceObject() { CimIndicationWatcher watcher = null; string parameterSetName = null; try { parameterSetName = this.parameterBinder.GetParameterSet(); } finally { this.parameterBinder.reset(); } string tempQueryExpression = string.Empty; switch (parameterSetName) { case CimBaseCommand.QueryExpressionSessionSet: case CimBaseCommand.QueryExpressionComputerSet: tempQueryExpression = this.Query; break; case CimBaseCommand.ClassNameSessionSet: case CimBaseCommand.ClassNameComputerSet: // validate the classname this.CheckArgument(); tempQueryExpression = String.Format(CultureInfo.CurrentCulture, "Select * from {0}", this.ClassName); break; } switch (parameterSetName) { case CimBaseCommand.QueryExpressionSessionSet: case CimBaseCommand.ClassNameSessionSet: { watcher = new CimIndicationWatcher(this.CimSession, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); } break; case CimBaseCommand.QueryExpressionComputerSet: case CimBaseCommand.ClassNameComputerSet: { watcher = new CimIndicationWatcher(this.ComputerName, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); } break; } if (watcher != null) { watcher.SetCmdlet(this); } return watcher; } /// <summary> /// Returns the event name to be monitored on the input object /// </summary> protected override String GetSourceObjectEventName() { return "CimIndicationArrived"; } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { DebugHelper.WriteLogEx(); base.EndProcessing(); // Register for the "Unsubscribed" event so that we can stop the // Cimindication event watcher. PSEventSubscriber newSubscriber = NewSubscriber; if (newSubscriber != null) { DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4); newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed); } }//End EndProcessing() /// <summary> /// <para> /// Handler to handle unsubscribe event /// </para> /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void newSubscriber_Unsubscribed( object sender, PSEventUnsubscribedEventArgs e) { DebugHelper.WriteLogEx(); CimIndicationWatcher watcher = sender as CimIndicationWatcher; if (watcher != null) { watcher.Stop(); } } #region private members /// <summary> /// check argument value /// </summary> private void CheckArgument() { this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); } /// <summary> /// Parameter binder used to resolve parameter set name /// </summary> private ParameterBinder parameterBinder = new ParameterBinder( parameters, parameterSets); /// <summary> /// Set the parameter /// </summary> /// <param name="parameterName"></param> private void SetParameter(object value, string parameterName) { if (value == null) { return; } this.parameterBinder.SetParameter(parameterName, true); } #region const string of parameter names internal const string nameClassName = "ClassName"; internal const string nameQuery = "Query"; internal const string nameQueryDialect = "QueryDialect"; internal const string nameCimSession = "CimSession"; internal const string nameComputerName = "ComputerName"; #endregion /// <summary> /// static parameter definition entries /// </summary> static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>> { { nameClassName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), } }, { nameQuery, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, true), } }, { nameQueryDialect, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false), } }, { nameCimSession, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), } }, { nameComputerName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), } }, }; /// <summary> /// static parameter set entries /// </summary> static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry> { { CimBaseCommand.QueryExpressionSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.QueryExpressionComputerSet, new ParameterSetEntry(1) }, { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, }; #endregion }//End Class }//End namespace
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Reflection; using System.Configuration; using System.Diagnostics; using System.Threading; using DDay.Update.Configuration; using DDay.Update.WinForms; using System.Net; namespace DDay.Update.ConfigurationTool.Forms { public partial class MainForm : Form { #region Private Fields private DeploymentManifest _DeploymentManifest; private OptionsForm _OptionsForm; #endregion #region Public Properties public DeploymentManifest DeploymentManifest { get { return _DeploymentManifest; } set { _DeploymentManifest = value; if (_DeploymentManifest != null) { panel1.Visible = true; // Show the description of the deployment manifest descUC.Description = _DeploymentManifest.Description; // Show the preferred update URI if (_DeploymentManifest.Deployment != null && _DeploymentManifest.Deployment.DeploymentProvider != null) txtUpdateURI.Text = _DeploymentManifest.Deployment.DeploymentProvider.CodeBase; else txtUpdateURI.Text = _DeploymentManifest.Uri.AbsoluteUri; } else { panel1.Visible = false; // Empty some fields descUC.Description = null; txtUpdateURI.Text = string.Empty; cbUpdateNotifier.SelectedIndex = -1; txtDestinationFolder.Text = string.Empty; _OptionsForm = new OptionsForm(); } } } #endregion #region Constructors public MainForm() { InitializeComponent(); _OptionsForm = new OptionsForm(); LoadUpdateNotifiers(); LoadRecentManifestList(); } #endregion #region Private Methods private string CopyAssemblyToDestination(string assemblyName, string targetName, string targetDir, bool deleteTargetInstead) { // Get the assembly information Assembly assembly = Assembly.Load(assemblyName); if (assembly != null) { // Get the filename of the assembly Uri codeBase = new Uri(assembly.CodeBase); string srcFilename = codeBase.LocalPath; // Determine the target name of the assembly if (string.IsNullOrEmpty(targetName)) targetName = Path.GetFileName(srcFilename); // Determine the target path string targetFilename = Path.Combine(targetDir, targetName); // Create the directory if it doesn't exist if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir); // Delete the file if it already existed if (File.Exists(targetFilename)) File.Delete(targetFilename); // Copy the file if (!deleteTargetInstead) File.Copy(srcFilename, targetFilename); return srcFilename; } return null; } private void CopyAssemblies(string targetFilename, string targetDir) { // Copy the DDay.Update assembly to the target CopyAssemblyToDestination("DDay.Update", null, targetDir, false); // Copy the update notifier to the target ComboBoxItem cbi = cbUpdateNotifier.SelectedItem as ComboBoxItem; Type type = Type.GetType(cbi.Value.ToString()); CopyAssemblyToDestination(type.Assembly.FullName, null, targetDir, false); // Copy or delete the log4net assembly, if update logging is enabled/disabled CopyAssemblyToDestination("log4net", null, targetDir, !_OptionsForm.EnableUpdateLogging); // Try to automatically determine the entry point for the application. // Download it if necessary, so we can inherit the properties of the entry point. string execPath = null, iconPath = null; // Determine the path where items will be downloaded if necessary string downloadFolder = Path.Combine( Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), DeploymentManifest.Description.Product); if (!Directory.Exists(downloadFolder)) Directory.CreateDirectory(downloadFolder); if (rbUseDistribution.Checked) { if (DeploymentManifest != null) { DeploymentManifest.LoadApplicationManifest(); WindowsForms2UpdateNotifier updateNotifier = new WindowsForms2UpdateNotifier(); updateNotifier.BeginUpdate(DeploymentManifest); AutoResetEvent evt = new AutoResetEvent(false); Thread thread = new Thread(new ThreadStart( delegate { List<FileDownloader> fileDownloaders = new List<FileDownloader>(); foreach (IDownloadableFile df in DeploymentManifest.ApplicationManifest.DownloadableFiles) { // If the file is the main executable, or it is an // icon file, then let's download it! FileDownloader fd = df.GetDownloader(); if (fd.DestinationName.Equals(targetFilename) || fd.DestinationName.EndsWith(".ico") || fd.DestinationName.EndsWith(".icl")) { fileDownloaders.Add(fd); } } // Determine the total download size long totalSize = 0; foreach(FileDownloader fd in fileDownloaders) totalSize += fd.DownloadSize; // Notify of the update size updateNotifier.NotifyTotalUpdateSize(totalSize); foreach (FileDownloader fd in fileDownloaders) { AutoResetEvent downloaded = new AutoResetEvent(false); fd.Completed += new EventHandler( delegate(object sender, EventArgs e) { downloaded.Set(); }); fd.Cancelled += new EventHandler( delegate(object sender, EventArgs e) { throw new Exception("Download was cancelled."); }); fd.Error += new EventHandler<ExceptionEventArgs>( delegate(object sender, ExceptionEventArgs e) { throw e.Exception; }); fd.Download(updateNotifier); downloaded.WaitOne(); fd.DestinationFolder = downloadFolder; fd.Save(); if (File.Exists(fd.DestinationPath)) { if (fd.DestinationName.Equals(targetFilename)) execPath = fd.DestinationPath; else iconPath = fd.DestinationPath; } } evt.Set(); })); thread.SetApartmentState(ApartmentState.STA); thread.Start(); evt.WaitOne(); updateNotifier.EndUpdate(); } } else { execPath = txtMainExec.Text; iconPath = txtIconFile.Text; } // Ensure the executable path exists before passing // it along to the compiler. if (!File.Exists(execPath)) execPath = null; // Ensure the icon exists at the path before passing // it along to the compiler if (!File.Exists(iconPath)) iconPath = null; // Compile the bootstrap file string targetPath = Compiler.CompileBootstrap( execPath, targetFilename, targetDir, iconPath); if (targetPath != null) { string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string sandboxDir = Path.Combine(dir, "Sandbox"); // Copy bootstrap configuration files from source to destination string cfgFilename = "Bootstrap.exe.config"; if (File.Exists( Path.Combine( sandboxDir, "New.exe.config"))) cfgFilename = "New.exe.config"; // Get the config filenames for source and target string srcConfigFilename = Path.Combine( sandboxDir, cfgFilename); string targetConfigFilename = targetPath + ".config"; if (File.Exists(targetConfigFilename)) File.Delete(targetConfigFilename); File.Copy(srcConfigFilename, targetConfigFilename); } // Delete the download folder if (Directory.Exists(downloadFolder)) Directory.Delete(downloadFolder, true); } private void WriteConfigurationValues(string exeFilename) { System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(exeFilename); DDayUpdateConfigurationSection cfg = configuration.GetSection("DDay.Update") as DDayUpdateConfigurationSection; // Set the update notifier in the configuration file ComboBoxItem cbi = cbUpdateNotifier.SelectedItem as ComboBoxItem; cfg.NotifierString = cbi.Value.ToString(); // Set the update uri in the configuration file cfg.Uri = new Uri(txtUpdateURI.Text); // Save the configuration file configuration.Save(); } private void LoadUpdateNotifiers() { cbUpdateNotifier.Items.Clear(); string[] files = Directory.GetFiles(".", "*.dll"); foreach (string file in files) { string fullPath = Path.GetFullPath(file); Assembly assembly = Assembly.LoadFile(fullPath); if (assembly != null) { foreach (Type type in assembly.GetTypes()) { if (type.IsClass && typeof(IUpdateNotifier).IsAssignableFrom(type)) { // Determine if a [Description] attribute // was placed on the class. If so, display // its value instead of the type name of the class. DescriptionAttribute[] desc = type.GetCustomAttributes(typeof(DescriptionAttribute), true) as DescriptionAttribute[]; if (desc.Length > 0) { // A description was found, display it instead. cbUpdateNotifier.Items.Add( new ComboBoxItem(desc[0].Description, type.AssemblyQualifiedName)); } else { // No description was found, simply show the type name // of the class. cbUpdateNotifier.Items.Add( new ComboBoxItem(type.Name, type.AssemblyQualifiedName)); } } } } } } private void LoadRecentManifestList() { string localAppPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DDay.Update" ); string recentManifestPath = Path.Combine( localAppPath, "RecentManifests.txt" ); tsmiRecent.DropDownItems.Clear(); List<string> lines = new List<string>(); if (File.Exists(recentManifestPath)) { FileStream fs = new FileStream(recentManifestPath, FileMode.Open, FileAccess.Read); if (fs != null) { StreamReader sr = new StreamReader(fs); while (!sr.EndOfStream) lines.Add(sr.ReadLine()); sr.Close(); } } if (lines.Count > 0) { tsmiRecent.Enabled = true; foreach (string line in lines) { ToolStripMenuItem tsmi = new ToolStripMenuItem(line); tsmi.Click += new EventHandler(tsmiRecentItem_Click); tsmiRecent.DropDownItems.Add(tsmi); } } else { tsmiRecent.Enabled = false; } } private void AddToRecentManifests(string manifestUri) { string localAppPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DDay.Update" ); string recentManifestPath = Path.Combine( localAppPath, "RecentManifests.txt" ); if (!Directory.Exists(localAppPath)) Directory.CreateDirectory(localAppPath); List<string> lines = new List<string>(); FileStream fs = null; if (File.Exists(recentManifestPath)) { // Read the contents of the current file fs = new FileStream(recentManifestPath, FileMode.Open, FileAccess.Read); if (fs != null) { StreamReader sr = new StreamReader(fs); while (!sr.EndOfStream) lines.Add(sr.ReadLine()); sr.Close(); } } // Remove a previous matching entry, if found int index = lines.IndexOf(manifestUri); if (index >= 0) lines.RemoveAt(index); // Insert the entry as the first item in the list lines.Insert(0, manifestUri); // Only track the last 10 items if (lines.Count > 10) lines.RemoveRange(10, lines.Count - 10); // Write the file fs = new FileStream(recentManifestPath, FileMode.Create, FileAccess.Write); if (fs != null) { StreamWriter sw = new StreamWriter(fs); foreach (string line in lines) sw.WriteLine(line); sw.Close(); } } #endregion #region Event Handlers #region Menu Strip private void tsmiFileOpenDepManFromURL_Click(object sender, EventArgs e) { LoadFromURIForm loadFromURI = new LoadFromURIForm(); if (loadFromURI.ShowDialog() == DialogResult.OK) { DeploymentManifest = loadFromURI.DeploymentManifest; AddToRecentManifests(DeploymentManifest.Uri.AbsoluteUri); LoadRecentManifestList(); } } void tsmiRecentItem_Click(object sender, EventArgs e) { ToolStripMenuItem tsmi = sender as ToolStripMenuItem; if (tsmi != null) { try { DeploymentManifest = Program.ValidateUpdateUri(null, tsmi.Text); DialogResult = DialogResult.OK; } catch { MessageBox.Show("A valid deployment manifest could not be found at the location provided, or you did not have access to the manifest."); } } } private void tsmiFileExit_Click(object sender, EventArgs e) { Close(); } private void tsmiAbout_Click(object sender, EventArgs e) { AboutForm af = new AboutForm(); af.ShowDialog(this); } #endregion private void btnVerifyURI_Click(object sender, EventArgs e) { try { // Validate the update uri if (Program.ValidateUpdateUri(DeploymentManifest, txtUpdateURI.Text) == null) throw new Exception("Could not validate the update uri."); MessageBox.Show("Validation succeeded!", "Success"); } catch (Exception ex) { MessageBox.Show("Validation failed:\n" + ex.Message, "Failure"); } } private void btnCreateBootstrap_Click(object sender, EventArgs e) { if (cbUpdateNotifier.SelectedIndex < 0) { MessageBox.Show("Please select an Update Notifier.", "Choose an Update Notifier"); } else if (string.IsNullOrEmpty(txtUpdateURI.Text)) { MessageBox.Show("Please select an Update URI", "Choose an Update URI"); } else if ( string.IsNullOrEmpty(txtDestinationFolder.Text) || !Directory.Exists(txtDestinationFolder.Text)) { MessageBox.Show("Please choose a valid destination folder", "Choose a destination folder"); } else { try { Program.ValidateUpdateUri(DeploymentManifest, txtUpdateURI.Text); } catch { if (MessageBox.Show("The Update URI does not successfully validate; are you sure you want to create a bootstrap?", "Are you sure?", MessageBoxButtons.YesNo) != DialogResult.Yes) return; } if (rbManualConfig.Checked && ( string.IsNullOrEmpty(txtMainExec.Text) || !File.Exists(txtMainExec.Text) )) { if (MessageBox.Show(@"You have not provided a main executable for your application. It is recommended that you provide a main executable for the bootstrap to mimic, so the bootstrap looks as much like your application as possible. Are you sure you want to continue?", "Are you sure?", MessageBoxButtons.YesNo) != DialogResult.Yes) return; } // Ensure we have a deployment manifest if (DeploymentManifest != null) { // Make sure the application manifest is loaded DeploymentManifest.LoadApplicationManifest(); if (DeploymentManifest.ApplicationManifest != null) { // Get the assembly identity for the application manifest string targetFilename = DeploymentManifest.ApplicationManifest.AssemblyIdentity.Name; // Copy the bootstrap assembly to the target filename CopyAssemblies(targetFilename, txtDestinationFolder.Text); string targetPath = Path.Combine( txtDestinationFolder.Text, targetFilename); // Write the configuration values to the application config file WriteConfigurationValues(targetPath); MessageBox.Show("Bootstrap successfully written!", "Success"); // Open the folder after success Process openFolder = new Process(); openFolder.StartInfo = new ProcessStartInfo(txtDestinationFolder.Text); openFolder.Start(); DeploymentManifest = null; return; } } MessageBox.Show("An error occurred while creating the bootstrap.", "Failure"); } } private void btnBrowse_Click(object sender, EventArgs e) { if (folderBrowserDialog.ShowDialog() == DialogResult.OK) txtDestinationFolder.Text = folderBrowserDialog.SelectedPath; } private void btnBrowseExec_Click(object sender, EventArgs e) { openFileDialog.Filter = "Executable Files (*.exe)|*.exe"; if (DeploymentManifest != null) { try { DeploymentManifest.LoadApplicationManifest(); if (DeploymentManifest.ApplicationManifest != null) { string entryPointName = DeploymentManifest.ApplicationManifest.AssemblyIdentity.Name; openFileDialog.Filter = entryPointName + "|" + entryPointName; } } catch { } } if (openFileDialog.ShowDialog() == DialogResult.OK) { txtMainExec.Text = openFileDialog.FileName; } } private void btnBrowseIcon_Click(object sender, EventArgs e) { openFileDialog.Filter = "Icon Files (*.ico)|*.ico|Icon Library Files (*.icl)|*.icl"; if (openFileDialog.ShowDialog() == DialogResult.OK) txtIconFile.Text = openFileDialog.FileName; } private void rbFileInfo_CheckedChanged(object sender, EventArgs e) { if (rbManualConfig.Checked) { panelManualInfo.Enabled = true; } else { panelManualInfo.Enabled = false; txtMainExec.Text = string.Empty; txtIconFile.Text = string.Empty; } } private void btnOptions_Click(object sender, EventArgs e) { OptionsForm optForm = _OptionsForm.Clone(); if (optForm.ShowDialog() == DialogResult.OK) { _OptionsForm = optForm; } } #endregion #region Overrides protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); // FIXME: check if everything is OK to close, prompt to save, etc. } #endregion #region Internal Classes internal class ComboBoxItem { private string _Text; private object _Value; public object Value { get { return _Value; } set { _Value = value; } } public string Text { get { return _Text; } set { _Text = value; } } public ComboBoxItem(string text, object value) { Text = text; Value = value; } } #endregion } }
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #if EXPERIMENTAL namespace OpenTK.Compute.CL10 { using System; using System.Text; using System.Runtime.InteropServices; #pragma warning disable 0649 #pragma warning disable 3019 #pragma warning disable 1591 partial class CL { internal static partial class Delegates { [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int BuildProgram(IntPtr program, uint num_devices, IntPtr* device_list, String options, IntPtr pfn_notify, IntPtr user_data); internal unsafe static BuildProgram clBuildProgram; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateBuffer(IntPtr context, MemFlags flags, IntPtr size, IntPtr host_ptr, [OutAttribute] OpenTK.Compute.CL10.ErrorCode* errcode_ret); internal unsafe static CreateBuffer clCreateBuffer; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateCommandQueue(IntPtr context, IntPtr device, CommandQueueFlags properties, [OutAttribute] OpenTK.Compute.CL10.ErrorCode* errcode_ret); internal unsafe static CreateCommandQueue clCreateCommandQueue; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateContext(IntPtr* properties, uint num_devices, IntPtr* devices, IntPtr pfn_notify, IntPtr user_data, [OutAttribute] OpenTK.Compute.CL10.ErrorCode* errcode_ret); internal unsafe static CreateContext clCreateContext; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateContextFromType(IntPtr* properties, DeviceTypeFlags device_type, IntPtr pfn_notify, IntPtr user_data, [OutAttribute] OpenTK.Compute.CL10.ErrorCode* errcode_ret); internal unsafe static CreateContextFromType clCreateContextFromType; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateImage2D(IntPtr context, MemFlags flags, ImageFormat* image_format, IntPtr image_width, IntPtr image_height, IntPtr image_row_pitch, IntPtr host_ptr, [OutAttribute] int* errcode_ret); internal unsafe static CreateImage2D clCreateImage2D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateImage3D(IntPtr context, MemFlags flags, ImageFormat* image_format, IntPtr image_width, IntPtr image_height, IntPtr image_depth, IntPtr image_row_pitch, IntPtr image_slice_pitch, IntPtr host_ptr, [OutAttribute] int* errcode_ret); internal unsafe static CreateImage3D clCreateImage3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateKernel(IntPtr program, String kernel_name, [OutAttribute] OpenTK.Compute.CL10.ErrorCode* errcode_ret); internal unsafe static CreateKernel clCreateKernel; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int CreateKernelsInProgram(IntPtr program, uint num_kernels, IntPtr* kernels, [OutAttribute] uint* num_kernels_ret); internal unsafe static CreateKernelsInProgram clCreateKernelsInProgram; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateProgramWithBinary(IntPtr context, uint num_devices, IntPtr* device_list, IntPtr* lengths, byte** binaries, int* binary_status, [OutAttribute] OpenTK.Compute.CL10.ErrorCode* errcode_ret); internal unsafe static CreateProgramWithBinary clCreateProgramWithBinary; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateProgramWithSource(IntPtr context, uint count, String[] strings, IntPtr* lengths, [OutAttribute] OpenTK.Compute.CL10.ErrorCode* errcode_ret); internal unsafe static CreateProgramWithSource clCreateProgramWithSource; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateSampler(IntPtr context, bool normalized_coords, AddressingMode addressing_mode, FilterMode filter_mode, [OutAttribute] int* errcode_ret); internal unsafe static CreateSampler clCreateSampler; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int EnqueueBarrier(IntPtr command_queue); internal static EnqueueBarrier clEnqueueBarrier; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueCopyBuffer(IntPtr command_queue, IntPtr src_buffer, IntPtr dst_buffer, IntPtr src_offset, IntPtr dst_offset, IntPtr cb, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueCopyBuffer clEnqueueCopyBuffer; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueCopyBufferToImage(IntPtr command_queue, IntPtr src_buffer, IntPtr dst_image, IntPtr src_offset, IntPtr** dst_origin, IntPtr** region, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueCopyBufferToImage clEnqueueCopyBufferToImage; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueCopyImage(IntPtr command_queue, IntPtr src_image, IntPtr dst_image, IntPtr** src_origin, IntPtr** dst_origin, IntPtr** region, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueCopyImage clEnqueueCopyImage; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueCopyImageToBuffer(IntPtr command_queue, IntPtr src_image, IntPtr dst_buffer, IntPtr** src_origin, IntPtr** region, IntPtr dst_offset, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate System.IntPtr EnqueueMapBuffer(IntPtr command_queue, IntPtr buffer, bool blocking_map, MapFlags map_flags, IntPtr offset, IntPtr cb, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event, [OutAttribute] int* errcode_ret); internal unsafe static EnqueueMapBuffer clEnqueueMapBuffer; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate System.IntPtr EnqueueMapImage(IntPtr command_queue, IntPtr image, bool blocking_map, MapFlags map_flags, IntPtr** origin, IntPtr** region, IntPtr* image_row_pitch, IntPtr* image_slice_pitch, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event, [OutAttribute] int* errcode_ret); internal unsafe static EnqueueMapImage clEnqueueMapImage; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueMarker(IntPtr command_queue, IntPtr* @event); internal unsafe static EnqueueMarker clEnqueueMarker; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueNativeKernel(IntPtr command_queue, IntPtr user_func, IntPtr args, IntPtr cb_args, uint num_mem_objects, IntPtr* mem_list, IntPtr args_mem_loc, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueNativeKernel clEnqueueNativeKernel; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueNDRangeKernel(IntPtr command_queue, IntPtr kernel, uint work_dim, IntPtr* global_work_offset, IntPtr* global_work_size, IntPtr* local_work_size, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueNDRangeKernel clEnqueueNDRangeKernel; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueReadBuffer(IntPtr command_queue, IntPtr buffer, bool blocking_read, IntPtr offset, IntPtr cb, IntPtr ptr, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueReadBuffer clEnqueueReadBuffer; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueReadImage(IntPtr command_queue, IntPtr image, bool blocking_read, IntPtr** origin, IntPtr** region, IntPtr row_pitch, IntPtr slice_pitch, IntPtr ptr, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueReadImage clEnqueueReadImage; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueTask(IntPtr command_queue, IntPtr kernel, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueTask clEnqueueTask; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueUnmapMemObject(IntPtr command_queue, IntPtr memobj, IntPtr mapped_ptr, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueUnmapMemObject clEnqueueUnmapMemObject; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueWaitForEvents(IntPtr command_queue, uint num_events, IntPtr* event_list); internal unsafe static EnqueueWaitForEvents clEnqueueWaitForEvents; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueWriteBuffer(IntPtr command_queue, IntPtr buffer, bool blocking_write, IntPtr offset, IntPtr cb, IntPtr ptr, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueWriteBuffer clEnqueueWriteBuffer; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int EnqueueWriteImage(IntPtr command_queue, IntPtr image, bool blocking_write, IntPtr** origin, IntPtr** region, IntPtr input_row_pitch, IntPtr input_slice_pitch, IntPtr ptr, uint num_events_in_wait_list, IntPtr* event_wait_list, IntPtr* @event); internal unsafe static EnqueueWriteImage clEnqueueWriteImage; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int Finish(IntPtr command_queue); internal static Finish clFinish; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int Flush(IntPtr command_queue); internal static Flush clFlush; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetCommandQueueInfo(IntPtr command_queue, CommandQueueInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetCommandQueueInfo clGetCommandQueueInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetContextInfo(IntPtr context, ContextInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetContextInfo clGetContextInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetDeviceIDs(IntPtr platform, DeviceTypeFlags device_type, uint num_entries, IntPtr* devices, uint* num_devices); internal unsafe static GetDeviceIDs clGetDeviceIDs; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetDeviceInfo(IntPtr device, DeviceInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetDeviceInfo clGetDeviceInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetEventInfo(IntPtr @event, EventInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetEventInfo clGetEventInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetEventProfilingInfo(IntPtr @event, ProfilingInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetEventProfilingInfo clGetEventProfilingInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetImageInfo(IntPtr image, ImageInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetImageInfo clGetImageInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetKernelInfo(IntPtr kernel, KernelInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetKernelInfo clGetKernelInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetKernelWorkGroupInfo(IntPtr kernel, IntPtr device, KernelWorkGroupInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetKernelWorkGroupInfo clGetKernelWorkGroupInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetMemObjectInfo(IntPtr memobj, MemInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetMemObjectInfo clGetMemObjectInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetPlatformIDs(uint num_entries, IntPtr* platforms, uint* num_platforms); internal unsafe static GetPlatformIDs clGetPlatformIDs; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetPlatformInfo(IntPtr platform, PlatformInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetPlatformInfo clGetPlatformInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetProgramBuildInfo(IntPtr program, IntPtr device, ProgramBuildInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetProgramBuildInfo clGetProgramBuildInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetProgramInfo(IntPtr program, ProgramInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetProgramInfo clGetProgramInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetSamplerInfo(IntPtr sampler, SamplerInfo param_name, IntPtr param_value_size, IntPtr param_value, [OutAttribute] IntPtr* param_value_size_ret); internal unsafe static GetSamplerInfo clGetSamplerInfo; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetSupportedImageFormats(IntPtr context, MemFlags flags, MemObjectType image_type, uint num_entries, ImageFormat* image_formats, uint* num_image_formats); internal unsafe static GetSupportedImageFormats clGetSupportedImageFormats; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleaseCommandQueue(IntPtr command_queue); internal static ReleaseCommandQueue clReleaseCommandQueue; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleaseContext(IntPtr context); internal static ReleaseContext clReleaseContext; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleaseEvent(IntPtr @event); internal static ReleaseEvent clReleaseEvent; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleaseKernel(IntPtr kernel); internal static ReleaseKernel clReleaseKernel; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleaseMemObject(IntPtr memobj); internal static ReleaseMemObject clReleaseMemObject; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleaseProgram(IntPtr program); internal static ReleaseProgram clReleaseProgram; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleaseSampler(IntPtr sampler); internal static ReleaseSampler clReleaseSampler; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int RetainCommandQueue(IntPtr command_queue); internal static RetainCommandQueue clRetainCommandQueue; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int RetainContext(IntPtr context); internal static RetainContext clRetainContext; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int RetainEvent(IntPtr @event); internal static RetainEvent clRetainEvent; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int RetainKernel(IntPtr kernel); internal static RetainKernel clRetainKernel; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int RetainMemObject(IntPtr memobj); internal static RetainMemObject clRetainMemObject; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int RetainProgram(IntPtr program); internal static RetainProgram clRetainProgram; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int RetainSampler(IntPtr sampler); internal static RetainSampler clRetainSampler; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int SetCommandQueueProperty(IntPtr command_queue, CommandQueueFlags properties, bool enable, CommandQueueFlags* old_properties); internal unsafe static SetCommandQueueProperty clSetCommandQueueProperty; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int SetKernelArg(IntPtr kernel, uint arg_index, IntPtr arg_size, IntPtr arg_value); internal static SetKernelArg clSetKernelArg; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int UnloadCompiler(); internal static UnloadCompiler clUnloadCompiler; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int WaitForEvents(uint num_events, IntPtr* event_list); internal unsafe static WaitForEvents clWaitForEvents; } } } #endif
using System.Data; using System.Data.Common; using System.Net.Sockets; using Miningcore.Configuration; using Miningcore.Extensions; using Miningcore.Mining; using Miningcore.Persistence; using Miningcore.Persistence.Model; using Miningcore.Persistence.Repositories; using Miningcore.Util; using NLog; using Polly; using Contract = Miningcore.Contracts.Contract; namespace Miningcore.Payments.PaymentSchemes; /// <summary> /// PROP payout scheme implementation /// </summary> // ReSharper disable once InconsistentNaming public class PROPPaymentScheme : IPayoutScheme { public PROPPaymentScheme(IConnectionFactory cf, IShareRepository shareRepo, IBlockRepository blockRepo, IBalanceRepository balanceRepo) { Contract.RequiresNonNull(cf, nameof(cf)); Contract.RequiresNonNull(shareRepo, nameof(shareRepo)); Contract.RequiresNonNull(blockRepo, nameof(blockRepo)); Contract.RequiresNonNull(balanceRepo, nameof(balanceRepo)); this.cf = cf; this.shareRepo = shareRepo; this.blockRepo = blockRepo; this.balanceRepo = balanceRepo; BuildFaultHandlingPolicy(); } private readonly IBalanceRepository balanceRepo; private readonly IBlockRepository blockRepo; private readonly IConnectionFactory cf; private readonly IShareRepository shareRepo; private static readonly ILogger logger = LogManager.GetLogger("PROP Payment", typeof(PROPPaymentScheme)); private const int RetryCount = 4; private IAsyncPolicy shareReadFaultPolicy; private class Config { public decimal Factor { get; set; } } #region IPayoutScheme public async Task UpdateBalancesAsync(IDbConnection con, IDbTransaction tx, IMiningPool pool, IPayoutHandler payoutHandler, Block block, decimal blockReward, CancellationToken ct) { var poolConfig = pool.Config; var shares = new Dictionary<string, double>(); var rewards = new Dictionary<string, decimal>(); var shareCutOffDate = await CalculateRewardsAsync(pool, payoutHandler, block, blockReward, shares, rewards, ct); // update balances foreach(var address in rewards.Keys) { var amount = rewards[address]; if(amount > 0) { logger.Info(() => $"Adding {payoutHandler.FormatAmount(amount)} to balance of {address} for {FormatUtil.FormatQuantity(shares[address])} ({shares[address]}) shares for block {block.BlockHeight}"); await balanceRepo.AddAmountAsync(con, tx, poolConfig.Id, address, amount, $"Reward for {FormatUtil.FormatQuantity(shares[address])} shares for block {block.BlockHeight}"); } } // delete discarded shares if(shareCutOffDate.HasValue) { var cutOffCount = await shareRepo.CountSharesBeforeCreatedAsync(con, tx, poolConfig.Id, shareCutOffDate.Value); if(cutOffCount > 0) { await LogDiscardedSharesAsync(poolConfig, block, shareCutOffDate.Value); logger.Info(() => $"Deleting {cutOffCount} discarded shares before {shareCutOffDate.Value:O}"); await shareRepo.DeleteSharesBeforeCreatedAsync(con, tx, poolConfig.Id, shareCutOffDate.Value); } } // diagnostics var totalShareCount = shares.Values.ToList().Sum(x => new decimal(x)); var totalRewards = rewards.Values.ToList().Sum(x => x); if(totalRewards > 0) logger.Info(() => $"{FormatUtil.FormatQuantity((double) totalShareCount)} ({Math.Round(totalShareCount, 2)}) shares contributed to a total payout of {payoutHandler.FormatAmount(totalRewards)} ({totalRewards / blockReward * 100:0.00}% of block reward) to {rewards.Keys.Count} addresses"); } private async Task LogDiscardedSharesAsync(PoolConfig poolConfig, Block block, DateTime value) { var before = value; var pageSize = 100000; var currentPage = 0; var shares = new Dictionary<string, double>(); while(true) { logger.Info(() => $"Fetching page {currentPage} of discarded shares for pool {poolConfig.Id}, block {block.BlockHeight}"); var page = await shareReadFaultPolicy.ExecuteAsync(() => cf.Run(con => shareRepo.ReadSharesBeforeCreatedAsync(con, poolConfig.Id, before, false, pageSize))); currentPage++; for(var i = 0; i < page.Length; i++) { var share = page[i]; var address = share.Miner; // record attributed shares for diagnostic purposes if(!shares.ContainsKey(address)) shares[address] = share.Difficulty; else shares[address] += share.Difficulty; } if(page.Length < pageSize) break; before = page[^1].Created; } if(shares.Keys.Count > 0) { // sort addresses by shares var addressesByShares = shares.Keys.OrderByDescending(x => shares[x]); logger.Info(() => $"{FormatUtil.FormatQuantity(shares.Values.Sum())} ({shares.Values.Sum()}) total discarded shares, block {block.BlockHeight}"); foreach(var address in addressesByShares) logger.Info(() => $"{address} = {FormatUtil.FormatQuantity(shares[address])} ({shares[address]}) discarded shares, block {block.BlockHeight}"); } } #endregion // IPayoutScheme private async Task<DateTime?> CalculateRewardsAsync(IMiningPool pool, IPayoutHandler payoutHandler, Block block, decimal blockReward, Dictionary<string, double> shares, Dictionary<string, decimal> rewards, CancellationToken ct) { var poolConfig = pool.Config; var done = false; var before = block.Created; var inclusive = true; var pageSize = 100000; var currentPage = 0; var accumulatedScore = 0.0m; var blockRewardRemaining = blockReward; DateTime? shareCutOffDate = null; var scores = new Dictionary<string, decimal>(); while(!done && !ct.IsCancellationRequested) { logger.Info(() => $"Fetching page {currentPage} of shares for pool {poolConfig.Id}, block {block.BlockHeight}"); var page = await shareReadFaultPolicy.ExecuteAsync(() => cf.Run(con => shareRepo.ReadSharesBeforeCreatedAsync(con, poolConfig.Id, before, inclusive, pageSize))); inclusive = false; currentPage++; for(var i = 0; i < page.Length; i++) { var share = page[i]; var address = share.Miner; var shareDiffAdjusted = payoutHandler.AdjustShareDifficulty(share.Difficulty); // record attributed shares for diagnostic purposes if(!shares.ContainsKey(address)) shares[address] = shareDiffAdjusted; else shares[address] += shareDiffAdjusted; var score = (decimal) (shareDiffAdjusted / share.NetworkDifficulty); if(!scores.ContainsKey(address)) scores[address] = score; else scores[address] += score; accumulatedScore += score; // set the cutoff date to clean up old shares after a successful payout if(shareCutOffDate == null || share.Created > shareCutOffDate) shareCutOffDate = share.Created; } if(page.Length < pageSize) { done = true; break; } before = page[^1].Created; done = page.Length <= 0; } if(accumulatedScore > 0) { var rewardPerScorePoint = blockReward / accumulatedScore; // build rewards for all addresses that contributed to the round foreach(var address in scores.Select(x => x.Key).Distinct()) { // loop all scores for the current addres foreach(var score in scores.Where(x => x.Key == address)) { var reward = score.Value * rewardPerScorePoint; if(reward > 0) { // accumulate miner reward if(!rewards.ContainsKey(address)) rewards[address] = reward; else rewards[address] += reward; } blockRewardRemaining -= reward; } } } // this should never happen if(blockRewardRemaining <= 0 && !done) throw new OverflowException("blockRewardRemaining < 0"); logger.Info(() => $"Balance-calculation for pool {poolConfig.Id}, block {block.BlockHeight} completed with accumulated score {accumulatedScore:0.####} ({accumulatedScore * 100:0.#}%)"); return shareCutOffDate; } private void BuildFaultHandlingPolicy() { var retry = Policy .Handle<DbException>() .Or<SocketException>() .Or<TimeoutException>() .RetryAsync(RetryCount, OnPolicyRetry); shareReadFaultPolicy = retry; } private static void OnPolicyRetry(Exception ex, int retry, object context) { logger.Warn(() => $"Retry {retry} due to {ex.Source}: {ex.GetType().Name} ({ex.Message})"); } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenSim.Framework; using Amib.Threading; using System.Threading; using log4net; using System.Reflection; namespace InWorldz.Data.Assets.Stratus { /// <summary> /// Implements an asset connector for Rackspace Cloud Files /// </summary> public class CloudFilesAssetClient : IAssetServer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// How long to let a thread sit in the pool without being used /// </summary> const int THREADPOOL_IDLE_TIMEOUT = 2 * 60 * 1000; /// <summary> /// When the simulator is being stopped, this is how long to wait on the threadpool /// to process asset requests before forcing a shutdown /// </summary> const int SHUTDOWN_WAIT_TIMEOUT = 5 * 1000; /// <summary> /// The maximum amount of time to wait for a synchronous asset request /// </summary> const int ASSET_WAIT_TIMEOUT = 45 * 1000; /// <summary> /// The amount of time between cache maintenance checks /// </summary> const int MAINTENANCE_INTERVAL = 5 * 60 * 1000; /// <summary> /// The maximum age of an idle cache entry before it will be purged /// </summary> const int MAX_IDLE_CACHE_ENTRY_AGE = MAINTENANCE_INTERVAL * 2; /// <summary> /// We use a threadpool to enable communication with cloudfiles for multiple requests /// </summary> private SmartThreadPool _threadPool; /// <summary> /// Collection of available asset clients /// </summary> private ObjectPool<CloudFilesAssetWorker> _asyncAssetWorkers; /// <summary> /// Object that gets the callback for an async request /// </summary> private IAssetReceiver _receiver; /// <summary> /// Our asset cache /// </summary> private Cache.Cache _assetCache; /// <summary> /// Stores written assets on disk when a cloud files write times out /// </summary> private Cache.DiskWriteBackCache _diskWriteBack; private int _readTimeout = CloudFilesAssetWorker.DEFAULT_READ_TIMEOUT; private int _writeTimeout = CloudFilesAssetWorker.DEFAULT_WRITE_TIMEOUT; private Timer _maintTimer; public CloudFilesAssetClient() { } /// <summary> /// For unit testing /// </summary> internal Cache.DiskWriteBackCache DiskWriteBackCache { get { return _diskWriteBack; } } public void Initialize(ConfigSettings settings) { //if this is being called, we were loaded as a plugin instead of the StratusAssetClient //we shouldnt be loaded like this, throw. throw new Exception("CloudFilesAssetClient should not be loaded directly as a plugin"); } public void Start() { STPStartInfo START_INFO = new STPStartInfo { WorkItemPriority = Amib.Threading.WorkItemPriority.Normal, MinWorkerThreads = 0, MaxWorkerThreads = Config.Settings.Instance.CFWorkerThreads, IdleTimeout = THREADPOOL_IDLE_TIMEOUT, }; _threadPool = new SmartThreadPool(START_INFO); _threadPool.Name = "Cloudfiles"; Func<CloudFilesAssetWorker> ctorFunc = () => { return new CloudFilesAssetWorker(_readTimeout, _writeTimeout); }; _asyncAssetWorkers = new ObjectPool<CloudFilesAssetWorker>(Config.Settings.Instance.CFWorkerThreads * 2, ctorFunc); _assetCache = new Cache.Cache(MAX_IDLE_CACHE_ENTRY_AGE); if (!Config.Settings.Instance.DisableWritebackCache) { _diskWriteBack = new Cache.DiskWriteBackCache(); _diskWriteBack.Start(); } //start maintaining the cache _maintTimer = new Timer(this.Maintain, null, MAINTENANCE_INTERVAL, MAINTENANCE_INTERVAL); } /// <summary> /// Should be called by the maintenance timer to maintain the cache /// </summary> /// <param name="unused"></param> private void Maintain(object unused) { _maintTimer.Change(MAINTENANCE_INTERVAL, Timeout.Infinite); lock (_assetCache) { try { _assetCache.Maintain(); } catch (Exception e) { m_log.ErrorFormat("[InWorldz.Stratus] Error during cache maintenance {0}", e); } } _maintTimer.Change(MAINTENANCE_INTERVAL, MAINTENANCE_INTERVAL); } public void Stop() { _threadPool.WaitForIdle(SHUTDOWN_WAIT_TIMEOUT); _threadPool.Shutdown(); if (_diskWriteBack != null) _diskWriteBack.Stop(); _maintTimer.Dispose(); } public void SetReceiver(IAssetReceiver receiver) { _receiver = receiver; } /// <summary> /// Requests and asset and responds asynchronously /// </summary> /// <param name="assetID"></param> /// <param name="args"></param> public void RequestAsset(OpenMetaverse.UUID assetID, AssetRequestInfo args) { _threadPool.QueueWorkItem(() => { try { AssetBase asset = GetAssetInternal(assetID); if (asset != null) { _receiver.AssetReceived(asset, args); } else { _receiver.AssetNotFound(assetID, args); } } catch (Exception e) { _receiver.AssetError(assetID, e, args); } }); } /// <summary> /// Requests an asset and response synchronously /// </summary> /// <param name="assetID"></param> /// <returns></returns> public AssetBase RequestAssetSync(OpenMetaverse.UUID assetID) { ManualResetEventSlim syncEvent = new ManualResetEventSlim(); AssetBase asset = null; Exception thrown = null; _threadPool.QueueWorkItem(() => { try { asset = GetAssetInternal(assetID); } catch (Exception e) { thrown = e; } syncEvent.Set(); }); if (syncEvent.Wait(ASSET_WAIT_TIMEOUT)) { syncEvent.Dispose(); } else { m_log.WarnFormat("[InWorldz.Stratus]: Timout waiting for synchronous asset request for {0}", assetID); } if (thrown != null) throw new AssetServerException(thrown.Message, thrown); return asset; } /// <summary> /// Requests asset metadata and response synchronously /// </summary> /// <param name="assetID"></param> /// <returns></returns> public Dictionary<string, string> RequestAssetMetadataSync(OpenMetaverse.UUID assetID) { ManualResetEventSlim syncEvent = new ManualResetEventSlim(); Dictionary<string,string> meta = null; Exception thrown = null; _threadPool.QueueWorkItem(() => { try { meta = RequestAssetMetadataInternal(assetID); } catch (Exception e) { thrown = e; } syncEvent.Set(); }); if (syncEvent.Wait(ASSET_WAIT_TIMEOUT)) { syncEvent.Dispose(); } else { m_log.WarnFormat("[InWorldz.Stratus]: Timout waiting for synchronous metadata request for {0}", assetID); } if (thrown != null) throw new AssetServerException(thrown.Message, thrown); return meta; } private Dictionary<string, string> RequestAssetMetadataInternal(OpenMetaverse.UUID assetID) { Dictionary<string, string> meta = null; Util.Retry(2, new List<Type> { typeof(UnrecoverableAssetServerException) }, () => { CloudFilesAssetWorker worker = null; try { try { //nothing in the cache. request from CF worker = _asyncAssetWorkers.LeaseObject(); } catch (Exception e) { //bail out now if we couldn't lease a connection throw new UnrecoverableAssetServerException(e.Message, e); } meta = worker.GetAssetMetadata(assetID); } catch (net.openstack.Core.Exceptions.Response.ItemNotFoundException) { //not an exceptional case. this will happen meta = null; } finally { if (worker != null) _asyncAssetWorkers.ReturnObject(worker); } }); return meta; } // Asset FetchStore counters private uint statTotal = 0; // Reads/Fetches private uint statGet = 0; private uint statGetInit = 0; private uint statGetHit = 0; private uint statGetFetches = 0; private uint statGetNotFound = 0; // Writes/Stores private uint statPut = 0; private uint statPutInit = 0; private uint statPutCached = 0; private uint statPutExists = 0; private uint statPutTO = 0; // timeout private uint statPutNTO = 0; // .NET conn timeout private uint statPutExceptWeb = 0; private uint statPutExceptIO = 0; private uint statPutExcept = 0; // other exceptions // Cache updates (ignored by CacheAssetIfAppropriate) private uint statBigAsset = 0; // private uint statBigStream = 0; private uint statDupUpdate = 0; private FixedSizeMRU<float> statGets = new FixedSizeMRU<float>(1000); private FixedSizeMRU<float> statPuts = new FixedSizeMRU<float>(1000); private AssetBase GetAssetInternal(OpenMetaverse.UUID assetID) { // Quick exit for null ID case. statTotal++; statGet++; if (assetID == OpenMetaverse.UUID.Zero) { statGetHit++; return null; } //cache? Cache.CacheEntry cacheObject = null; lock (_assetCache) { _assetCache.TryGetAsset(assetID, out cacheObject); } StratusAsset rawAsset = null; if (cacheObject != null) { statGetHit++; //stream cache or asset cache? if (cacheObject.FullAsset != null) { rawAsset = cacheObject.FullAsset; } else { using (System.IO.MemoryStream stream = new System.IO.MemoryStream(cacheObject.Data, 0, cacheObject.Size)) { rawAsset = DeserializeAssetFromStream(assetID, stream); } } } else { StratusAsset diskAsset = null; if (! Config.Settings.Instance.DisableWritebackCache) diskAsset = _diskWriteBack.GetAsset(assetID.Guid); if (diskAsset != null) { rawAsset = diskAsset; } else { Util.Retry(2, new List<Type> { typeof(UnrecoverableAssetServerException) }, () => { ulong start = Util.GetLongTickCount(); CloudFilesAssetWorker worker = null; try { try { //nothing on the local disk, request from CF worker = _asyncAssetWorkers.LeaseObject(); } catch (Exception e) { //exception here is unrecoverable since this is construction statGetInit++; throw new UnrecoverableAssetServerException(e.Message, e); } using (System.IO.MemoryStream stream = worker.GetAsset(assetID)) { statGetFetches++; stream.Position = 0; rawAsset = DeserializeAssetFromStream(assetID, stream); //if we're using the cache, we need to put the raw data in there now stream.Position = 0; this.CacheAssetIfAppropriate(assetID, stream, rawAsset); } } catch (net.openstack.Core.Exceptions.Response.ItemNotFoundException) { statGetNotFound++; //not an exceptional case. this will happen rawAsset = null; } finally { ulong elapsed = Util.GetLongTickCount() - start; statGets.Add(elapsed); if (worker != null) _asyncAssetWorkers.ReturnObject(worker); } }); } } //nothing? if (rawAsset == null) return null; //convert return rawAsset.ToAssetBase(); } private static StratusAsset DeserializeAssetFromStream(OpenMetaverse.UUID assetId, System.IO.MemoryStream stream) { StratusAsset rawAsset = ProtoBuf.Serializer.Deserialize<StratusAsset>(stream); if (rawAsset == null || rawAsset.Data == null) { throw new InvalidOperationException(String.Format("Asset deserialization failed. Asset ID: {0}, Stream Len: {1}", assetId, stream.Length)); } return rawAsset; } // Returns true if it added it to the cache private bool CacheAssetIfAppropriate(OpenMetaverse.UUID assetId, System.IO.MemoryStream stream, StratusAsset asset) { if (!Config.Settings.Instance.CFUseCache) return false; if (stream.Length > Config.Constants.MAX_CACHEABLE_ASSET_SIZE) { statBigStream++; return false; } if (asset.Data.Length > Config.Constants.MAX_CACHEABLE_ASSET_SIZE) { statBigAsset++; return false; } lock (_assetCache) { if (!_assetCache.HasAsset(assetId)) { //we do not yet have this asset. we need to make a determination if caching the stream //or caching the asset would be more beneficial if (stream.Length > Config.Constants.MAX_STREAM_CACHE_SIZE) { //asset is too big for caching the stream to have any theoretical benefit. //instead we cache the asset itself _assetCache.CacheAssetData(assetId, asset); } else { //caching the stream should make for faster retrival and collection _assetCache.CacheAssetData(assetId, stream); } return true; // now cached, in one form or the other } } statDupUpdate++; return false; } private Dictionary<string, string> GetAssetMetadata(OpenMetaverse.UUID assetId, CloudFilesAssetWorker worker) { try { return worker.GetAssetMetadata(assetId); } catch (net.openstack.Core.Exceptions.Response.ItemNotFoundException) { return null; } } public void StoreAsset(AssetBase asset) { if (asset == null) throw new ArgumentNullException("asset cannot be null"); if (asset.FullID == OpenMetaverse.UUID.Zero) throw new ArgumentException("assets must not have a null ID"); bool isRetry = false; StratusAsset wireAsset = StratusAsset.FromAssetBase(asset); //for now we're not going to use compression etc, so set to zero wireAsset.StorageFlags = 0; statTotal++; statPut++; Util.Retry(2, new List<Type> { typeof(AssetAlreadyExistsException), typeof(UnrecoverableAssetServerException) }, () => { CloudFilesAssetWorker worker; System.IO.MemoryStream assetStream = null; ulong start = Util.GetLongTickCount(); try { worker = _asyncAssetWorkers.LeaseObject(); } catch (Exception e) { statPutInit++; throw new UnrecoverableAssetServerException(e.Message, e); } try { if (Config.Settings.Instance.UnitTest_ThrowTimeout) { throw new System.Net.WebException("Timeout for unit testing", System.Net.WebExceptionStatus.Timeout); } using (assetStream = worker.StoreAsset(wireAsset)) { //cache the stored asset to eliminate roudtripping when //someone performs an upload if (this.CacheAssetIfAppropriate(asset.FullID, assetStream, wireAsset)) statPutCached++; } } catch (AssetAlreadyExistsException) { if (!isRetry) //don't throw if this is a retry. this can happen if a write times out and then succeeds { statPutExists++; throw; } } catch (System.Net.WebException e) { if (e.Status == System.Net.WebExceptionStatus.Timeout || e.Status == System.Net.WebExceptionStatus.RequestCanceled) { statPutTO++; DoTimeout(asset, wireAsset, e); } else { statPutExceptWeb++; ReportThrowStorageError(asset, e); } } catch (System.IO.IOException e) { //this sucks, i think timeouts on writes are causing .net to claim the connection //was forcibly closed by the remote host. if (e.Message.Contains("forcibly closed")) { statPutNTO++; DoTimeout(asset, wireAsset, e); } else { statPutExceptIO++; ReportThrowStorageError(asset, e); } } catch (Exception e) { statPutExcept++; m_log.ErrorFormat("[InWorldz.Stratus]: Unable to store asset {0}: {1}", asset.FullID, e); throw new AssetServerException(String.Format("Unable to store asset {0}: {1}", asset.FullID, e.Message), e); } finally { ulong elapsed = Util.GetLongTickCount() - start; statPuts.Add(elapsed); isRetry = true; _asyncAssetWorkers.ReturnObject(worker); } }); } private static void ReportThrowStorageError(AssetBase asset, Exception e) { m_log.ErrorFormat("[InWorldz.Stratus]: Unable to store asset {0}: {1}", asset.FullID, e); throw new AssetServerException(String.Format("Unable to store asset {0}: {1}", asset.FullID, e.Message), e); } private void DoTimeout(AssetBase asset, StratusAsset wireAsset, Exception e) { if (!Config.Settings.Instance.DisableWritebackCache) { //eat the exception and write locally m_log.ErrorFormat("[InWorldz.Stratus]: Timeout attempting to store asset {0}. Storing locally.", asset.FullID); _diskWriteBack.StoreAsset(wireAsset); } else { m_log.ErrorFormat("[InWorldz.Stratus]: Timeout attempting to store asset {0}: {1}", asset.FullID, e); throw new AssetServerException(String.Format("Timeout attempting to store asset {0}: {1}", asset.FullID, e.Message), e); } } public void UpdateAsset(AssetBase asset) { this.StoreAsset(asset); } /// <summary> /// Requests that an asset be removed from storage and does not return until the operation completes /// </summary> /// <param name="assetID"></param> /// <returns></returns> public void PurgeAssetSync(OpenMetaverse.UUID assetID) { ManualResetEventSlim syncEvent = new ManualResetEventSlim(); Exception thrown = null; _threadPool.QueueWorkItem(() => { CloudFilesAssetWorker worker = null; try { worker = _asyncAssetWorkers.LeaseObject(); worker.PurgeAsset(assetID); } catch (Exception e) { thrown = e; } finally { if (worker != null) _asyncAssetWorkers.ReturnObject(worker); } syncEvent.Set(); }); if (syncEvent.Wait(ASSET_WAIT_TIMEOUT)) { syncEvent.Dispose(); } else { m_log.WarnFormat("[InWorldz.Stratus]: Timout waiting for synchronous asset purge for {0}", assetID); } if (thrown != null) throw new AssetServerException(thrown.Message, thrown); } public AssetStats GetStats(bool resetStats) { if (resetStats) { statTotal = statGet = statGetInit = statGetHit = statGetFetches = statGetNotFound = 0; statPut = statPutInit = statPutCached = statPutExists = statPutTO = statPutNTO = 0; statPutExceptWeb = statPutExceptIO = statPutExcept = statBigAsset = statBigStream = statDupUpdate = 0; statGets.Clear(); statPuts.Clear(); } AssetStats result = new AssetStats("CF"); // Asset FetchStore counters result.nTotal = statTotal; // Reads/Fetches result.nGet = statGet; result.nGetInit = statGetInit; result.nGetHit = statGetHit; result.nGetFetches = statGetFetches; result.nGetNotFound = statGetNotFound; // Writes/Stores result.nPut = statPut; result.nPutInit = statPutInit; result.nPutCached = statPutCached; result.nPutExists = statPutExists; result.nPutTO = statPutTO; // timeout result.nPutNTO = statPutNTO; // .NET conn timeout result.nPutExceptWeb = statPutExceptWeb; result.nPutExceptIO = statPutExceptIO; result.nPutExcept = statPutExcept; // other exceptions // Update stats (ignored by CacheAssetIfAppropriate) result.nBigAsset = statBigAsset; result.nBigStream = statBigStream; result.nDupUpdate = statDupUpdate; result.allGets = statGets.ToArray(); result.allPuts = statPuts.ToArray(); return result; } public string Version { get { return "1.0"; } } public string Name { get { return "InWorldz.Data.Assets.Stratus.CloudFilesAssetClient"; } } public void Initialize() { } public void Dispose() { } } }
// -------------------------------------------------------------------------------------------- #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.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Windows.Forms; using HearThis.Properties; using HearThis.Script; using HearThis.UI; using L10NSharp; using SIL.Linq; namespace HearThis.Publishing { public partial class PublishDialog : Form, ILocalizable { private readonly PublishingModel _model; private readonly IScrProjectSettings _scrProjectSettings; private readonly bool _projectHasNestedQuotes; private enum State { InitialDisplay, Working, Success, Failure } private State _state = State.InitialDisplay; private BackgroundWorker _worker; private const char kAudioFormatRadioPrefix = '_'; private const string kAudioFormatRadioSuffix = "Radio"; public PublishDialog(Project project) { InitializeComponent(); if (ReallyDesignMode) return; _scrProjectSettings = project.ScrProjectSettings; _projectHasNestedQuotes = project.HasNestedQuotes; _model = new PublishingModel(project); _logBox.ShowDetailsMenuItem = true; _logBox.ShowCopyToClipboardMenuItem = true; var defaultAudioFormat = tableLayoutPanelAudioFormat.Controls.OfType<RadioButton>().FirstOrDefault( b => b.Name == kAudioFormatRadioPrefix + Settings.Default.PublishAudioFormat + kAudioFormatRadioSuffix); if (defaultAudioFormat != null) defaultAudioFormat.Checked = true; if (Settings.Default.PublishVerseIndexFormat == _includePhraseLevelLabels.Name) { _audacityLabelFile.Checked = true; _includePhraseLevelLabels.Enabled = true; _includePhraseLevelLabels.Checked = true; } else { var defaultVerseIndexFormat = tableLayoutPanelVerseIndexFormat.Controls.OfType<RadioButton>() .FirstOrDefault(b => b.Name == Settings.Default.PublishVerseIndexFormat); if (defaultVerseIndexFormat != null) defaultVerseIndexFormat.Checked = true; } _none.Tag = PublishingModel.VerseIndexFormatType.None; _cueSheet.Tag = PublishingModel.VerseIndexFormatType.CueSheet; _audacityLabelFile.Tag = PublishingModel.VerseIndexFormatType.AudacityLabelFileVerseLevel; _rdoCurrentBook.Checked = _model.PublishOnlyCurrentBook; UpdateDisplay(); Program.RegisterLocalizable(this); HandleStringsLocalized(); } public void HandleStringsLocalized() { _rdoCurrentBook.Text = string.Format(_rdoCurrentBook.Text, _model.PublishingInfoProvider.CurrentBookName); _audacityLabelFile.Text = string.Format(_audacityLabelFile.Text, _scrAppBuilderRadio.Text, "Audacity"); } protected bool ReallyDesignMode { get { return (DesignMode || GetService(typeof (IDesignerHost)) != null) || (LicenseManager.UsageMode == LicenseUsageMode.Designtime); } } private void UpdateDisplay(State state) { _state = state; UpdateDisplay(); } private void UpdateDisplay() { switch (_state) { case State.InitialDisplay: _destinationLabel.Text = _model.PublishThisProjectPath; Debug.Assert(_publishButton.Enabled, "Button state should already be correct. Display should never revert to this state."); break; case State.Working: _publishButton.Enabled = false; _changeDestinationLink.Enabled = false; tableLayoutPanelAudioFormat.Controls.OfType<RadioButton>().ForEach(b => b.Enabled = false); tableLayoutPanelVerseIndexFormat.Controls.OfType<RadioButton>().ForEach(b => b.Enabled = false); _tableLayoutPanelBooksToPublish.Controls.OfType<RadioButton>().ForEach(b => b.Enabled = false); break; case State.Success: case State.Failure: _cancelButton.Text = LocalizationManager.GetString("PublishDialog.Close", "&Close", "Cancel Button text changes to this after publishing."); _openFolderLink.Text = _model.PublishThisProjectPath; _openFolderLink.Visible = true; break; default: throw new ArgumentOutOfRangeException(); } } private void _publishButton_Click(object sender, EventArgs e) { _model.AudioFormat = tableLayoutPanelAudioFormat.Controls.OfType<RadioButton>().Single(b => b.Checked).Name. TrimStart(kAudioFormatRadioPrefix).Replace(kAudioFormatRadioSuffix, string.Empty); if (_includePhraseLevelLabels.Checked) { Settings.Default.PublishVerseIndexFormat = _includePhraseLevelLabels.Name; _model.VerseIndexFormat = PublishingModel.VerseIndexFormatType.AudacityLabelFilePhraseLevel; } else { var selectedVerseIndexButton = tableLayoutPanelVerseIndexFormat.Controls.OfType<RadioButton>().Single(b => b.Checked); Settings.Default.PublishVerseIndexFormat = selectedVerseIndexButton.Name; _model.VerseIndexFormat = (PublishingModel.VerseIndexFormatType) selectedVerseIndexButton.Tag; } _model.PublishOnlyCurrentBook = _rdoCurrentBook.Checked; UpdateDisplay(State.Working); _worker = new BackgroundWorker(); _worker.DoWork += _worker_DoWork; _worker.RunWorkerCompleted += _worker_RunWorkerCompleted; _worker.WorkerSupportsCancellation = true; _worker.RunWorkerAsync(); } private void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { UpdateDisplay(); } private void _worker_DoWork(object sender, DoWorkEventArgs e) { _state = _model.Publish(_logBox) ? State.Success : State.Failure; } private void _openFolderLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start(_model.PublishThisProjectPath); } private void _cancelButton_Click(object sender, EventArgs e) { if (_worker == null || !_worker.IsBusy) { Close(); return; } _logBox.CancelRequested = true; if (_worker != null) _worker.CancelAsync(); } private void _changeDestinationLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { using (var dlg = new FolderBrowserDialog()) { dlg.SelectedPath = _model.PublishRootPath; if (dlg.ShowDialog() == DialogResult.OK) { _model.PublishRootPath = dlg.SelectedPath; UpdateDisplay(); } } } private void _scrAppBuilderRadio_CheckedChanged(object sender, EventArgs e) { if (_scrAppBuilderRadio.Checked) _audacityLabelFile.Checked = true; } private void _audacityLabelFile_CheckedChanged(object sender, EventArgs e) { _includePhraseLevelLabels.Enabled = _audacityLabelFile.Checked; if (!_includePhraseLevelLabels.Enabled) _includePhraseLevelLabels.Checked = false; } protected override void OnShown(EventArgs e) { base.OnShown(e); WarnAboutConflictBetweenQuoteBreakingAndSAB(); } private void _includePhraseLevelLabels_CheckedChanged(object sender, EventArgs e) { if (IsHandleCreated) WarnAboutConflictBetweenQuoteBreakingAndSAB(); } private void WarnAboutConflictBetweenQuoteBreakingAndSAB() { if (_includePhraseLevelLabels.Checked && _projectHasNestedQuotes && _model.PublishingInfoProvider.BreakQuotesIntoBlocks && _scrProjectSettings != null && !_scrProjectSettings.FirstLevelQuotesAreUnique) { var msg = string.Format(LocalizationManager.GetString("PublishDialog.PossibleIncompatibilityWithSAB", "This project has first-level quotes broken out into separate blocks, but it looks like the first-level" + " quotation marks may also be used for other levels (nested quotations). If you publish phrase-level labels," + " Scripture App Builder will need to be configured to include the first-level quotation marks ({0} and {1})" + " as phrase-ending punctuation, but Scripture App Builder might not be able to distinguish first-level quotes" + " (which should be considered as separate phrases) from other levels (which should not)." + " Are you sure you want to publish phrase-level labels?", "Param 0 is first-level start quotation mark;" + " Param 1 is first-level ending quotation mark"), _scrProjectSettings.FirstLevelStartQuotationMark, _scrProjectSettings.FirstLevelEndQuotationMark); if (DialogResult.No == MessageBox.Show(this, msg, ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)) _includePhraseLevelLabels.Checked = false; } } protected override void OnResize(EventArgs e) { base.OnResize(e); _openFolderLink.MaximumSize = new Size(_publishButton.Location.X - _openFolderLink.Location.X - _publishButton.Margin.Left - _openFolderLink.Margin.Right, _openFolderLink.MaximumSize.Height); _destinationLabel.MaximumSize = _openFolderLink.MaximumSize; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Composite Swagger Client that represents merging body complex and /// complex model swagger clients /// </summary> public partial class AzureCompositeModel : ServiceClient<AzureCompositeModel>, IAzureCompositeModel, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription ID. /// </summary> public string SubscriptionId { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IBasicOperations. /// </summary> public virtual IBasicOperations Basic { get; private set; } /// <summary> /// Gets the IPrimitiveOperations. /// </summary> public virtual IPrimitiveOperations Primitive { get; private set; } /// <summary> /// Gets the IArrayOperations. /// </summary> public virtual IArrayOperations Array { get; private set; } /// <summary> /// Gets the IDictionaryOperations. /// </summary> public virtual IDictionaryOperations Dictionary { get; private set; } /// <summary> /// Gets the IInheritanceOperations. /// </summary> public virtual IInheritanceOperations Inheritance { get; private set; } /// <summary> /// Gets the IPolymorphismOperations. /// </summary> public virtual IPolymorphismOperations Polymorphism { get; private set; } /// <summary> /// Gets the IPolymorphicrecursiveOperations. /// </summary> public virtual IPolymorphicrecursiveOperations Polymorphicrecursive { get; private set; } /// <summary> /// Gets the IReadonlypropertyOperations. /// </summary> public virtual IReadonlypropertyOperations Readonlyproperty { get; private set; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AzureCompositeModel(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AzureCompositeModel(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AzureCompositeModel(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AzureCompositeModel(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AzureCompositeModel(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AzureCompositeModel(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Basic = new BasicOperations(this); Primitive = new PrimitiveOperations(this); Array = new ArrayOperations(this); Dictionary = new DictionaryOperations(this); Inheritance = new InheritanceOperations(this); Polymorphism = new PolymorphismOperations(this); Polymorphicrecursive = new PolymorphicrecursiveOperations(this); Readonlyproperty = new ReadonlypropertyOperations(this); BaseUri = new System.Uri("http://localhost"); SubscriptionId = "123456"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Fish>("fishtype")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Fish>("fishtype")); CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Product Types /// </summary> /// <remarks> /// The Products endpoint returns information about the Uber products offered /// at a given location. The response includes the display name and other /// details about each product, and lists the products in the proper display /// order. /// </remarks> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<CatalogArray>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<CatalogArray>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<CatalogArray>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create products /// </summary> /// <remarks> /// Resets products. /// </remarks> /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productDictionaryOfArray'> /// Dictionary of Array of product /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<CatalogDictionary>> CreateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, IDictionary<string, IList<Product>> productDictionaryOfArray = default(IDictionary<string, IList<Product>>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogDictionaryOfArray bodyParameter = new CatalogDictionaryOfArray(); if (productDictionaryOfArray != null) { bodyParameter.ProductDictionaryOfArray = productDictionaryOfArray; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(bodyParameter != null) { _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<CatalogDictionary>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<CatalogDictionary>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update products /// </summary> /// <remarks> /// Resets products. /// </remarks> /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productArrayOfDictionary'> /// Array of dictionary of products /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<CatalogArray>> UpdateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, IList<IDictionary<string, Product>> productArrayOfDictionary = default(IList<IDictionary<string, Product>>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogArrayOfDictionary bodyParameter = new CatalogArrayOfDictionary(); if (productArrayOfDictionary != null) { bodyParameter.ProductArrayOfDictionary = productArrayOfDictionary; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(bodyParameter != null) { _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<CatalogArray>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<CatalogArray>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
#region License /* Copyright (c) 2003-2015 Llewellyn Pritchard * All rights reserved. * This source code is subject to terms and conditions of the BSD License. * See license.txt. */ #endregion using System; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using IronScheme.Editor.ComponentModel; using IronScheme.Editor.Build; using System.IO; namespace IronScheme.Editor.Controls { class Wizard : Form { private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; internal PictureComboBox prjtype = new PictureComboBox(); const string DBLCLICKFORFOLDER = "double click to browse for folder"; TextBox name; TextBox loc; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Wizard() { // // Required for Windows Form Designer support // InitializeComponent(); Font = SystemInformation.MenuFont; Size = new Size(312, 170); button3.Enabled = false; button2.Text = "Create"; Text = "Create new project..."; Label p = new Label(); p.TextAlign = ContentAlignment.MiddleLeft; p.Location = new Point(2,2); p.Size = new Size(100, 32); p.Text = "Project type"; Controls.Add(p); prjtype.Location = new Point(102,2); prjtype.Width = 200; Controls.Add(prjtype); p = new Label(); p.TextAlign = ContentAlignment.MiddleLeft; p.Location = new Point(2,37); p.Size = new Size(100, 30); p.Text = "Name"; Controls.Add(p); p = new Label(); p.TextAlign = ContentAlignment.MiddleLeft; p.Location = new Point(2,66); p.Size = new Size(100, 30); p.Text = "Location"; Controls.Add(p); name = new TextBox(); name.Location = new Point(102,37); name.Width = 200; Controls.Add(name); loc = new TextBox(); loc.Location = new Point(102,66); loc.Width = 200; loc.Text = DBLCLICKFORFOLDER; loc.ReadOnly = true; loc.DoubleClick +=new EventHandler(loc_DoubleClick); Controls.Add(loc); button2.Click +=new EventHandler(button2_Click); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button1.Location = new System.Drawing.Point(415, 327); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(80, 24); this.button1.TabIndex = 0; this.button1.Text = "Cancel"; // // button2 // this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button2.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button2.Location = new System.Drawing.Point(319, 327); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(80, 24); this.button2.TabIndex = 1; this.button2.Text = "Next"; // // button3 // this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button3.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button3.Location = new System.Drawing.Point(223, 327); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(80, 24); this.button3.TabIndex = 2; this.button3.Text = "Back"; // // Wizard // this.AcceptButton = this.button2; this.CancelButton = this.button1; this.ClientSize = new System.Drawing.Size(511, 359); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Wizard"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Wizard"; this.ResumeLayout(false); } #endregion void loc_DoubleClick(object sender, EventArgs e) { loc.ReadOnly = false; FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description = "Select the location to create the new project"; fbd.SelectedPath = Environment.CurrentDirectory; if (fbd.ShowDialog(this) == DialogResult.OK) { loc.Text = fbd.SelectedPath; } } void button2_Click(object sender, EventArgs e) { if (loc.Text.Trim() == string.Empty || name.Text.Trim() == string.Empty || prjtype.SelectedItem == null) { return; } if (loc.Text == DBLCLICKFORFOLDER) { loc.Text = Environment.CurrentDirectory; } if (!Directory.Exists(loc.Text)) { if(DialogResult.OK == MessageBox.Show(ServiceHost.Window.MainForm, "Directory does not exist, do you want to create it?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)) { Directory.CreateDirectory(loc.Text); } else { return; } } Project p = ServiceHost.Project.Create(prjtype.SelectedItem as Type, name.Text, loc.Text); if (loc.Text == DBLCLICKFORFOLDER) { p.RootDirectory = Environment.CurrentDirectory; } else { p.RootDirectory = loc.Text; } p.ProjectName = name.Text; p.Location = p.RootDirectory + System.IO.Path.DirectorySeparatorChar + name.Text + ".xacc"; Tag = p; DialogResult = DialogResult.OK; Close(); } } class NewFileWizard : Form { Button button1; Button button2; Button button3; internal PictureComboBox prjtype = new PictureComboBox(); const string DBLCLICKFORFOLDER = "double click to browse for folder"; internal TextBox name; internal TextBox loc; /// <summary> /// Required designer variable. /// </summary> Container components = null; public NewFileWizard() { // // Required for Windows Form Designer support // InitializeComponent(); Font = SystemInformation.MenuFont; Size = new Size(312, 200); button3.Enabled = false; button2.Text = "Create"; Text = "Create new file..."; prjtype.Location = new Point(102,2); prjtype.Width = 200; Controls.Add(prjtype); Label p = new Label(); p.TextAlign = ContentAlignment.MiddleLeft; p.Location = new Point(2,2); p.Size = new Size(100, 30); p.Text = "File type"; Controls.Add(p); p = new Label(); p.TextAlign = ContentAlignment.MiddleLeft; p.Location = new Point(2,32); p.Size = new Size(100, 30); p.Text = "Name"; Controls.Add(p); p = new Label(); p.TextAlign = ContentAlignment.MiddleLeft; p.Location = new Point(2,62); p.Size = new Size(100, 30); p.Text = "Location"; Controls.Add(p); name = new TextBox(); name.Location = new Point(102,32); name.Width = 200; Controls.Add(name); loc = new TextBox(); loc.Location = new Point(102,62); loc.Width = 200; loc.Text = DBLCLICKFORFOLDER; loc.DoubleClick +=new EventHandler(loc_DoubleClick); Controls.Add(loc); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button1.Location = new System.Drawing.Point(415, 327); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(80, 24); this.button1.TabIndex = 0; this.button1.Text = "Cancel"; // // button2 // this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button2.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button2.Location = new System.Drawing.Point(319, 327); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(80, 24); this.button2.TabIndex = 1; this.button2.Text = "Next"; this.button2.Click +=new EventHandler(button2_Click); // // button3 // this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button3.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button3.Location = new System.Drawing.Point(223, 327); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(80, 24); this.button3.TabIndex = 2; this.button3.Text = "Back"; // // Wizard // this.AcceptButton = this.button2; this.CancelButton = this.button1; this.ClientSize = new System.Drawing.Size(511, 359); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Wizard"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Wizard"; this.ResumeLayout(false); } #endregion void loc_DoubleClick(object sender, EventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description = "Select the location to create the new project"; fbd.SelectedPath = Environment.CurrentDirectory; if (fbd.ShowDialog(this) == DialogResult.OK) { loc.Text = fbd.SelectedPath; } } void button2_Click(object sender, EventArgs e) { if (name.Text == null || name.Text == string.Empty || prjtype.SelectedItem == null) { return; } if (loc.Text == DBLCLICKFORFOLDER) { loc.Text = Environment.CurrentDirectory; } if (!Directory.Exists(loc.Text)) { if(DialogResult.OK == MessageBox.Show(ServiceHost.Window.MainForm, "Directory does not exist, do you want to create it?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)) { Directory.CreateDirectory(loc.Text); } else { return; } } DialogResult = DialogResult.OK; Close(); } } }
using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using StreamCompanion.Common.Extensions; namespace osu_StreamCompanion.Code.Modules.TokensPreview { public partial class TokensPreviewSettings : UserControl { private CancellationTokenSource _cts = new CancellationTokenSource(); public TokensPreviewSettings() { InitializeComponent(); _ = UpdateLiveTokens(_cts.Token); } protected override void Dispose(bool disposing) { if (disposing) { _cts.TryCancel(); _cts.Dispose(); components?.Dispose(); } base.Dispose(disposing); } private async Task UpdateLiveTokens(CancellationToken token) { try { while (true) { if (liveTokens != null && this.IsHandleCreated) Invoke((MethodInvoker)(() => { ProcessReplacements(liveTokens, 5, 35); })); token.ThrowIfCancellationRequested(); await Task.Delay(50, token); } } catch { //ignored //Sometimes throws after exiting setting tab } } private List<KeyValuePair<string, IToken>> liveTokens = null; public void Add(Dictionary<string, IToken> replacements) { if (InvokeRequired) { BeginInvoke((MethodInvoker) (() => { Add(replacements); })); return; } var notHidden = replacements.Where(x => (x.Value.Type & TokenType.Hidden) == 0).ToList(); var normal = notHidden.Where(t => t.Value.Type == TokenType.Normal).ToList(); var live = notHidden.Where(t => t.Value.Type == TokenType.Live).ToList(); DrawingControl.SuspendDrawing(this); try { var currentRect = new Size(0, 25); currentRect += AddHeader("Live tokens (not always avaliable, not saved to files on disk)", currentRect.Height); currentRect += DrawTokens(live, currentRect.Height); currentRect.Height += 10; currentRect += AddHeader("Regular tokens", currentRect.Height); currentRect += DrawTokens(normal, currentRect.Height); liveTokens = live; label_ListedNum.Text = notHidden.Count.ToString(); } finally { DrawingControl.ResumeDrawing(this); } } private Size DrawTokens(IEnumerable<KeyValuePair<string, IToken>> tokens, int startHeight) { var size = new Size(0, 0); var tokensByPlugin = tokens.GroupBy(kv => kv.Value.PluginName).OrderBy(k => k.Key); foreach (var tokensGroup in tokensByPlugin) { size.Height += 2; size += DrawSection($"plugin: {tokensGroup.Key}", tokensGroup.ToList(), size.Height + startHeight); } return size; } private Size DrawSection(string sectionName, IEnumerable<KeyValuePair<string, IToken>> tokens, int startHeight) { var size = AddHeader(sectionName, startHeight); size.Height += 2; size += ProcessReplacements(tokens, 5, startHeight + size.Height); return size; } private Size ProcessReplacements(IEnumerable<KeyValuePair<string, IToken>> replacements, int xPosition = 30, int yPosition = 30) { var replacementsCopy = replacements.ToDictionary(k => k.Key, v => v.Value); var startYPosition = yPosition; List<int> lineWidths = new List<int>(); //first iteration - create labels and buttons Size buttonRect = new Size(); foreach (var tokenKv in replacementsCopy) { buttonRect = AddEditTextBox(tokenKv.Value, tokenKv.Key, xPosition, yPosition); string labelName = "L" + tokenKv.Key; var labelRect = AddLabel(labelName, tokenKv.Key, buttonRect.Width + xPosition, yPosition + 2); lineWidths.Add(labelRect.Width + buttonRect.Width); yPosition += Math.Max(labelRect.Height, buttonRect.Height); AddSeparator(tokenKv.Key, yPosition); } var maxLabelWidth = lineWidths.Count > 0 ? lineWidths.Max() : 0; yPosition = startYPosition; //second iteration - create value fields foreach (var tokenKv in replacementsCopy) { string labelName = "V" + tokenKv.Key; var value = tokenKv.Value.FormatedValue; if (value.Length > 150) value = value.Substring(0, 150)+"...(Preview truncated)"; var labelRect = AddLabel(labelName, value, maxLabelWidth + 10, yPosition + 2); lineWidths.Add(labelRect.Width); yPosition += Math.Max(labelRect.Height, buttonRect.Height); } return new Size(lineWidths.Count > 0 ? lineWidths.Max() : 0, yPosition - startYPosition); } private (Size Size, T Control, bool AlreadyExisted) AddControl<T>(string name, string text, int xPosition, int yPosition, bool autosize = true, int width = 20, int height = 20) where T : Control, new() { T control; bool alreadyExisted = false; if (p.Controls.ContainsKey(name)) { control = (T)p.Controls[name]; alreadyExisted = true; } else { p.VerticalScroll.Value = 0; control = new T { Location = new Point(xPosition, yPosition), Name = name, Size = new Size(width, height), AutoSize = autosize, }; p.Controls.Add(control); } if (control.Text != text) { control.Text = text; } return (control.Size, control, alreadyExisted); } private Size AddEditTextBox(IToken token, string name, int xPosition, int yPosition) { var ret = AddControl<TextBox>($"T{name}", token.Format, xPosition, yPosition); if (!ret.AlreadyExisted) { ret.Control.Size = new Size(100, 20); ret.Control.TextChanged += (sender, args) => { token.Format = ret.Control.Text; p.Controls["V" + name].Text = token.FormatedValue; }; } return ret.Control.Size; } private Size AddLabel(string name, string text, int xPosition, int yPosition) { return AddControl<Label>(name, text, xPosition, yPosition).Size; } private Size AddHeader(string headerText, int yPosition, int width = 500) { var controlName = "L" + headerText; Label label; Size separatorSize; if (p.Controls.ContainsKey(controlName)) { label = (Label)p.Controls[controlName]; label.Width = width; separatorSize = p.Controls[$"S{controlName}"].Size; } else { p.VerticalScroll.Value = 0; label = new Label { Location = new Point(2, yPosition), Name = controlName, Text = headerText, Size = new Size(width, 13) }; p.Controls.Add(label); separatorSize = AddSeparator(controlName, yPosition + label.Height + 1); } return new Size(label.Width, label.Height + separatorSize.Height); } private Size AddSeparator(string name, int yPos) { var ret = AddControl<Label>($"S{name}", "", 2, yPos, false, 660, 2); if (!ret.AlreadyExisted) { ret.Control.BorderStyle = BorderStyle.Fixed3D; ret.Control.Anchor = AnchorStyles.Left | AnchorStyles.Right | ret.Control.Anchor; } return ret.Control.Size; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace PhoneManagementSystem.WebApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using ActionsProvider; using ActionsProvider.AMS; using ActionsProvider.Entities; using ActionsProvider.K8S; using ActionsProvider.UnifiedResponse; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host; using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; namespace WaterMarkingActions { public static class WaterMArkActions { //Share Watermarking Storage Connection by Controller private static Microsoft.WindowsAzure.Storage.CloudStorageAccount _WaterMarkStorage; private static Microsoft.WindowsAzure.Storage.CloudStorageAccount SingleWaterMarkStorageAccInstanceController { get { string strConn = System.Configuration.ConfigurationManager.AppSettings["Storageconn"]; _WaterMarkStorage = _WaterMarkStorage ?? Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(strConn); return _WaterMarkStorage; } } [FunctionName("StartNewJob")] public static async Task<HttpResponseMessage> StartNewJob([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { var watch = System.Diagnostics.Stopwatch.StartNew(); dynamic BodyData = await req.Content.ReadAsAsync<object>(); string AssetID = BodyData.AssetID; string JobID = BodyData.JobID; string[] EmbebedCodes = BodyData.EmbebedCodes.ToObject<string[]>(); bool LockedAsset = false; //Save Status IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); try { //Lock to avoid multiples process start at same time (miliseconds of difference) LockedAsset= await myActions.GetAssetProcessLock(AssetID, JobID, TimeSpan.FromMinutes(1),TimeSpan.FromMilliseconds(1000)); if (!LockedAsset) { //Error to Lock asset, so start process will fail. var LockException= new Exception($"[{JobID}] Failed to lock Asset {AssetID}, Timeout! Check Trafic light table for this assets"); log.Error($"{LockException.Message}"); return req.CreateResponse(HttpStatusCode.InternalServerError, LockException, JsonMediaTypeFormatter.DefaultMediaType); } log.Info($"[{JobID}] Locked"); //Star Process var status = await myActions.StartNewProcess(AssetID, JobID, EmbebedCodes); //Unlock trafic light to other process to StarNewProcess await myActions.ReleaseAssetProcessLock(AssetID, JobID); log.Info($"[{JobID}] unLocked"); watch.Stop(); log.Info($"[Time] Method StartNewJob {watch.ElapsedMilliseconds} [ms]"); return req.CreateResponse(HttpStatusCode.OK, status, JsonMediaTypeFormatter.DefaultMediaType); } catch (Exception X) { if (LockedAsset) { await myActions.ReleaseAssetProcessLock(AssetID, JobID); log.Info($"[{JobID}] unLocked on exception"); } log.Error($"{X.Message}"); return req.CreateResponse(HttpStatusCode.InternalServerError, X, JsonMediaTypeFormatter.DefaultMediaType); } } [FunctionName("GetPreprocessorJobData")] public static async Task<HttpResponseMessage> GetJobManifest([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { dynamic BodyData = await req.Content.ReadAsAsync<object>(); string AssetId = BodyData.AssetId; string JobID = BodyData.JobID; List<string> codes = BodyData.Codes.ToObject<List<string>>(); IAMSProvider myAMS = AMSProviderFactory.CreateAMSProvider(SingleWaterMarkStorageAccInstanceController); try { ManifestInfo jobdata = await myAMS.GetK8SJobManifestAsync(AssetId, JobID, codes); return req.CreateResponse(HttpStatusCode.OK, jobdata, JsonMediaTypeFormatter.DefaultMediaType); } catch (Exception X) { return req.CreateResponse(HttpStatusCode.InternalServerError, X, JsonMediaTypeFormatter.DefaultMediaType); } } [FunctionName("UpdateMMRKStatus")] public static async Task<HttpResponseMessage> UpdateMMRKStatus([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { dynamic BodyData = await req.Content.ReadAsAsync<object>(); //Create JobStatus from body data MMRKStatus MMRK = BodyData.ToObject<MMRKStatus>(); //Save Status IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); if (MMRK.FileURL == "{NO UPDATE}") { string jobRender = $"[{MMRK.JobID}]{MMRK.FileName}"; var currentMMRKStatus =await myActions.GetMMRKStatus(MMRK.AssetID, jobRender); string url = currentMMRKStatus.FileURL; MMRK.FileURL = url; } await myActions.UpdateMMRKStatus(MMRK); return req.CreateResponse(HttpStatusCode.OK, MMRK, JsonMediaTypeFormatter.DefaultMediaType); } [FunctionName("EvalAssetStatus")] public static async Task<HttpResponseMessage> EvalAssetStatus([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { dynamic BodyData = await req.Content.ReadAsAsync<object>(); UnifiedProcessStatus manifest = BodyData.ToObject<UnifiedProcessStatus>(); IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); //1. Update EvalPreprocessorNotifications int nNotification = await myActions.EvalPreprocessorNotifications(manifest.JobStatus.JobID); //2. Eval Asset Status var OriginalAssetStatus = manifest.AssetStatus.State; manifest.AssetStatus = myActions.EvalAssetStatus(manifest.AssetStatus.AssetId); if (OriginalAssetStatus != manifest.AssetStatus.State) { //3. Update Manifest/ all process await myActions.UpdateUnifiedProcessStatus(manifest); //4. Log and replay log.Info($"[{manifest.JobStatus.JobID}] Preprocessor Notifications processed {nNotification} / Updated AssetId {manifest.AssetStatus.AssetId} Status {manifest.AssetStatus.State.ToString()} / previus status {OriginalAssetStatus}"); } else { log.Info($"[{manifest.JobStatus.JobID}] Preprocessor Notifications processed {nNotification} / No Change AssetId {manifest.AssetStatus.AssetId} Status {OriginalAssetStatus}"); } return req.CreateResponse(HttpStatusCode.OK, manifest, JsonMediaTypeFormatter.DefaultMediaType); } [FunctionName("UpdateWaterMarkCode")] public static async Task<HttpResponseMessage> UpdateWaterMarkCode([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); dynamic BodyData = await req.Content.ReadAsAsync<object>(); try { EnbebedCode myCode = BodyData.EnbebedCode.ToObject<EnbebedCode>(); string ParentAssetID = BodyData.ParentAssetID; List<WaterMarkedRender> RenderList = new List<WaterMarkedRender>(); foreach (var info in myCode.MP4WatermarkedURL) { WaterMarkedRender data = new WaterMarkedRender() { Details = "Submited", EmbebedCodeValue = myCode.EmbebedCode, MP4URL = info.WaterMarkedMp4, RenderName = info.FileName, ParentAssetID = ParentAssetID, State = ExecutionStatus.Running }; RenderList.Add(data); } //Update all renders in a single call await myActions.UpdateWaterMarkedRender(RenderList); } catch (Exception X) { return req.CreateResponse(HttpStatusCode.InternalServerError, new { Error = X.Message }, JsonMediaTypeFormatter.DefaultMediaType); } return req.CreateResponse(HttpStatusCode.OK, new { Status = ExecutionStatus.Finished.ToString() }, JsonMediaTypeFormatter.DefaultMediaType); } [FunctionName("EvalEnbebedCodes")] public static async Task<HttpResponseMessage> EvalEnbebedCodes([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { var watch = System.Diagnostics.Stopwatch.StartNew(); IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); dynamic BodyData = await req.Content.ReadAsAsync<object>(); UnifiedProcessStatus manifest = BodyData.ToObject<UnifiedProcessStatus>(); string ParentAssetID = manifest.AssetStatus.AssetId; try { //1. Process Embbeded Notifications (From share Queue) int nNotification = await myActions.EvalPEmbeddedNotifications(manifest.JobStatus.JobID); log.Info($"Embedded Notifications processed {nNotification}"); //2. Eval Each Watermark Render status List<WaterMarkedAssetInfo> UpdatedInfo = new List<WaterMarkedAssetInfo>(); foreach (var item in manifest.EmbebedCodesList) { //2.1 EvalWatermarkeAssetInfo var watermarkedRender = myActions.EvalWaterMarkedAssetInfo(ParentAssetID, item.EmbebedCodeValue); UpdatedInfo.Add(watermarkedRender); } //Replace New WaterMarkAssetInfo manifest.EmbebedCodesList = UpdatedInfo; await myActions.UpdateUnifiedProcessStatus(manifest); } catch (Exception X) { log.Error($"[{manifest.JobStatus.JobID}] Error on EvalEnbebedCodes {X.Message}"); return req.CreateResponse(HttpStatusCode.InternalServerError, manifest, JsonMediaTypeFormatter.DefaultMediaType); } watch.Stop(); log.Info($"[Time] Method EvalEnbebedCodes {watch.ElapsedMilliseconds} [ms]"); return req.CreateResponse(HttpStatusCode.OK, manifest, JsonMediaTypeFormatter.DefaultMediaType); } [FunctionName("CreateWaterMArkedAssets")] public static async Task<HttpResponseMessage> CreateWaterMArkedAssets([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { var watch = System.Diagnostics.Stopwatch.StartNew(); IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); dynamic BodyData = await req.Content.ReadAsAsync<object>(); UnifiedProcessStatus manifest = BodyData.ToObject<UnifiedProcessStatus>(); string ParentAssetID = manifest.AssetStatus.AssetId; try { IAMSProvider help = AMSProviderFactory.CreateAMSProvider(_WaterMarkStorage); //Max number of Asset to create per iteration, to avoid Function Time out. int maxAssetCreate = int.Parse(System.Configuration.ConfigurationManager.AppSettings["maxAssetCreate"] ?? "10"); int accAssetCreate = 0; //List only Finished without AsstID foreach (var watermarkedInfo in manifest.EmbebedCodesList) { bool swError = false; if ((watermarkedInfo.State == ExecutionStatus.Finished) && (string.IsNullOrEmpty(watermarkedInfo.AssetID) && (accAssetCreate<=maxAssetCreate))) { var watchAsset = System.Diagnostics.Stopwatch.StartNew(); ////Inject all Renders on New asset var AssetWatermarkedRenders = myActions.GetWaterMarkedRenders(ParentAssetID, watermarkedInfo.EmbebedCodeValue); if (AssetWatermarkedRenders.Count()>0) { //Create new asset per embbeded code var watchCreateAsset= System.Diagnostics.Stopwatch.StartNew(); var xx = await help.CreateEmptyWatermarkedAsset(manifest.JobStatus.JobID, ParentAssetID, watermarkedInfo.EmbebedCodeValue); watermarkedInfo.AssetID = xx.WMAssetId; watchCreateAsset.Stop(); log.Info($"[{manifest.JobStatus.JobID}] Created Asset {watermarkedInfo.AssetID} on {watchCreateAsset.ElapsedMilliseconds} [ms]"); //Renders exist, so Process //Creat all togheter var all = await help.AddWatermarkedRendersFiletoAsset(watermarkedInfo.AssetID, AssetWatermarkedRenders, watermarkedInfo.EmbebedCodeValue); var onlyError = all.Where(r => r.Status != "MMRK File Added"); if (onlyError.Count() >0) { //Error watermarkedInfo.State = ExecutionStatus.Error; foreach (var renderResult in onlyError) { watermarkedInfo.Details += $"Error adding {renderResult.Status} deatils: {renderResult.StatusMessage}"; } //Delete Asset help.DeleteAsset(watermarkedInfo.AssetID); watermarkedInfo.AssetID = ""; log.Error($"[{manifest.JobStatus.JobID}] Asset deleted {watermarkedInfo.Details}"); swError = true; } //If not Error Create Manifest if (!swError) { //Create New Manifest and set it as primary file. var manifestResult=await help.GenerateManifest(watermarkedInfo.AssetID); if (manifestResult.Status!= "OK") { //Error Creating Manifest help.DeleteAsset(watermarkedInfo.AssetID); watermarkedInfo.State = ExecutionStatus.Error; watermarkedInfo.Details = $"Error Creating MAnifest deatils: {manifestResult.StatusMessage}"; log.Error($"[{manifest.JobStatus.JobID}] Error at GenerateManifest {watermarkedInfo.Details}"); } else { //Delete Watermarked MP4 renders await myActions.DeleteWatermarkedRenderTmpInfo(AssetWatermarkedRenders); //One Asset created accAssetCreate += 1; } } } else { //Watermarked Copy error, It has not renders. watermarkedInfo.State = ExecutionStatus.Error; watermarkedInfo.Details = $"Error adding {watermarkedInfo.EmbebedCodeValue} renders deatils: Has not renders MP4"; watermarkedInfo.AssetID = ""; log.Error($"[{manifest.JobStatus.JobID}] Error processing Wateramark copy {watermarkedInfo.EmbebedCodeValue} error: {watermarkedInfo.Details}"); } //Update WatermarkedCopy myActions.UpdateWaterMarkedAssetInfo(watermarkedInfo, manifest.AssetStatus.AssetId); //TimeTrack watchAsset.Stop(); log.Info($"[Time][{manifest.JobStatus.JobID}] Asset Creation {watchAsset.ElapsedMilliseconds} [ms] code {watermarkedInfo.EmbebedCodeValue} assetID: {watermarkedInfo.AssetID}"); } if (watch.ElapsedMilliseconds>=100000) { log.Warning($"[{manifest.JobStatus.JobID}] Asset Creation time limite achieved, break loop with {accAssetCreate-1} copies"); break; } } } catch (Exception X) { log.Error($"{X.Message}"); return req.CreateResponse(HttpStatusCode.InternalServerError, X, JsonMediaTypeFormatter.DefaultMediaType); } watch.Stop(); log.Info($"[Time] Method CreateWaterMArkedAssets {watch.ElapsedMilliseconds} [ms]"); return req.CreateResponse(HttpStatusCode.OK, manifest, JsonMediaTypeFormatter.DefaultMediaType); } [FunctionName("EvalJobProgress")] public static async Task<HttpResponseMessage> EvalJobProgress([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { var watch = System.Diagnostics.Stopwatch.StartNew(); dynamic BodyData = await req.Content.ReadAsAsync<object>(); UnifiedProcessStatus myProcessStatus = BodyData.ToObject<UnifiedProcessStatus>(); IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); int watingCopies = 0; //Check AssetStatus log.Info($"[{myProcessStatus.JobStatus.JobID}] Job Status: {myProcessStatus.JobStatus.State.ToString()} / Asset Status {myProcessStatus.AssetStatus.State.ToString()}"); switch (myProcessStatus.AssetStatus.State) { case ExecutionStatus.Error: //Finished with error myProcessStatus.JobStatus.State = ExecutionStatus.Error; myProcessStatus.JobStatus.FinishTime = DateTime.Now; myProcessStatus.JobStatus.Duration = DateTime.Now.Subtract(myProcessStatus.JobStatus.StartTime); await myActions.UpdateUnifiedProcessStatus(myProcessStatus); break; case ExecutionStatus.Running: //Same status for JOB //No Action myProcessStatus.JobStatus.State = ExecutionStatus.Running; var mmrklist = myActions.GetMMRKStatusList(myProcessStatus.AssetStatus.AssetId); int mmrkTotal = mmrklist.Count(); int mmrkFinished = mmrklist.Where(m => m.State == ExecutionStatus.Finished).Count(); myProcessStatus.JobStatus.Details = $"Generating MMRK files {mmrkFinished} of {mmrkTotal}, last update {DateTime.Now.ToString()}"; await myActions.UpdateUnifiedProcessStatus(myProcessStatus); break; case ExecutionStatus.Finished: //Check EmbebedCodeList, Count running renders plus Finished render without AssetID (not created asset yet) int nRunning = myProcessStatus.EmbebedCodesList.Where(emc => (emc.State == ExecutionStatus.Running) || ((emc.AssetID=="") &&(emc.State==ExecutionStatus.Finished))).Count(); //Check Errros int nErrors = myProcessStatus.EmbebedCodesList.Where(emc => emc.State == ExecutionStatus.Error).Count(); //Total int total = myProcessStatus.EmbebedCodesList.Count(); log.Info($"Current EMC Running {nRunning}"); if (nRunning == 0) { myProcessStatus.JobStatus.State = ExecutionStatus.Finished; myProcessStatus.JobStatus.FinishTime = DateTime.Now; myProcessStatus.JobStatus.Duration = DateTime.Now.Subtract(myProcessStatus.JobStatus.StartTime); myProcessStatus.JobStatus.Details = $"Process Finished. Total Watermarked copies {total}, Success {total-nErrors} & Errors {nErrors}"; } else { myProcessStatus.JobStatus.State = ExecutionStatus.Running; myProcessStatus.JobStatus.Details = $"Process Running. Total Watermark copies {total}, Success {total - nRunning - nErrors} & Errors {nErrors}"; watingCopies = myProcessStatus.EmbebedCodesList.Where(emc => ((emc.AssetID == "") && (emc.State == ExecutionStatus.Finished))).Count(); } await myActions.UpdateUnifiedProcessStatus(myProcessStatus); log.Info($"Updated Manifest JOB Status {myProcessStatus.JobStatus.State.ToString()}"); break; } //Control Signal to LogicApp, to accelearete var myResponse = req.CreateResponse(HttpStatusCode.OK, myProcessStatus, JsonMediaTypeFormatter.DefaultMediaType); myResponse.Headers.Add("watingCopies", watingCopies.ToString()); watch.Stop(); log.Info($"[Time] Method EvalJobProgress {watch.ElapsedMilliseconds} [ms]"); return myResponse; } [FunctionName("GetUnifiedProcessStatus")] public static async Task<HttpResponseMessage> GetUnifiedProcessStatus([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { var watch = System.Diagnostics.Stopwatch.StartNew(); dynamic BodyData = await req.Content.ReadAsAsync<object>(); IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); string AssetId = BodyData.AssetId; string JobID = BodyData.JobID; UnifiedProcessStatus myProcessStatus = null; try { myProcessStatus = myActions.GetUnifiedProcessStatus(AssetId, JobID); } catch (Exception X) { log.Error(X.Message); return req.CreateResponse(HttpStatusCode.NotFound, X, JsonMediaTypeFormatter.DefaultMediaType); } watch.Stop(); log.Info($"[Time] GetUnifiedProcessStatus {watch.ElapsedMilliseconds} [ms]"); return req.CreateResponse(HttpStatusCode.OK, myProcessStatus, JsonMediaTypeFormatter.DefaultMediaType); } [FunctionName("SubmiteWaterMarkJob")] public static async Task<HttpResponseMessage> SubmiteWaterMarkJob([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log, ExecutionContext context) { IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); dynamic BodyData = await req.Content.ReadAsAsync<object>(); ManifestInfo manifest = BodyData.ToObject<ManifestInfo>(); int K8SJobAggregation = int.Parse(System.Configuration.ConfigurationManager.AppSettings["K8SJobAggregation"]); int K8SJobAggregationOnlyEmb = int.Parse(System.Configuration.ConfigurationManager.AppSettings["K8SJobAggregationOnlyEmb"] ?? "1"); try { //Get JOBList to Send to K8S cluster List<ManifestInfo> jobList = myActions.GetK8SManifestInfo(K8SJobAggregation, K8SJobAggregationOnlyEmb, manifest); //Sumbite to K8S cluster int jobSubId = 1; foreach (var job in jobList) { var ret = await myActions.SubmiteJobK8S(job, jobSubId); log.Info($"{job.VideoInformation.FirstOrDefault().FileName} CODE {ret.Code.ToString()}"); jobSubId += 1; if (!ret.IsSuccessStatusCode) { log.Error($"K8S Summition Error {ret.Code.ToString()} {ret.Content}"); throw new Exception($"K8S Summition Error {ret.Code.ToString()} {ret.Content}"); } } return req.CreateResponse(HttpStatusCode.OK, jobList, JsonMediaTypeFormatter.DefaultMediaType); } catch (Exception X) { return req.CreateResponse(HttpStatusCode.InternalServerError, X, JsonMediaTypeFormatter.DefaultMediaType); } } [FunctionName("UpdateJob")] public static async Task<HttpResponseMessage> UpdateJob([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log, ExecutionContext context) { dynamic BodyData = await req.Content.ReadAsAsync<object>(); IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); UnifiedProcessStatus Manifest = BodyData.Manifest.ToObject<UnifiedProcessStatus>(); ExecutionStatus AssetStatus = BodyData.AssetStatus.ToObject<ExecutionStatus>(); ExecutionStatus JobState = BodyData.JobState.ToObject<ExecutionStatus>(); string JobStateDetails = BodyData.JobStateDetails; ExecutionStatus WaterMarkCopiesStatus = BodyData.WaterMarkCopiesStatus.ToObject<ExecutionStatus>(); string WaterMarkCopiesStatusDetails = BodyData.WaterMarkCopiesStatusDetails; switch (Manifest.AssetStatus.State) { case ExecutionStatus.Finished: AssetStatus = ExecutionStatus.Finished; break; case ExecutionStatus.Error: break; case ExecutionStatus.Running: break; case ExecutionStatus.New: break; case ExecutionStatus.Aborted: break; default: break; } var updatedManifest = await myActions.UpdateJob(Manifest, AssetStatus, JobState, JobStateDetails, WaterMarkCopiesStatus, WaterMarkCopiesStatusDetails); return req.CreateResponse(HttpStatusCode.OK, Manifest, JsonMediaTypeFormatter.DefaultMediaType); } [FunctionName("DeleteWatermarkedRenders")] public static async Task<HttpResponseMessage> DeleteWatermarkedRenders([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log, ExecutionContext context) { var watch = System.Diagnostics.Stopwatch.StartNew(); dynamic BodyData = await req.Content.ReadAsAsync<object>(); IAMSProvider myAMShelp = AMSProviderFactory.CreateAMSProvider(SingleWaterMarkStorageAccInstanceController); string AssetId = BodyData.AssetId; string JobId = BodyData.JobId; try { string KeepWatermakedBlobs = System.Configuration.ConfigurationManager.AppSettings["KeepWatermakedBlobs"] ?? "false"; int DeletedBlobs = 0; if (!(KeepWatermakedBlobs != "false")) { //Delete all information generated by the Job DeletedBlobs=await myAMShelp.DeleteWatermakedBlobRendersAsync(JobId,AssetId); } else log.Info($"[{JobId}]Blob not deleted {AssetId}"); watch.Stop(); log.Info($"[Time] Method DeleteWatermarkedRenders {watch.ElapsedMilliseconds} [ms]"); return req.CreateResponse(HttpStatusCode.OK, new { DeletedBlob = DeletedBlobs }, JsonMediaTypeFormatter.DefaultMediaType); } catch (Exception X) { return req.CreateResponse(HttpStatusCode.InternalServerError, X, JsonMediaTypeFormatter.DefaultMediaType); } } [FunctionName("DeleteSucceededPods")] public static async Task<HttpResponseMessage> DeleteSucceededPods([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log, ExecutionContext context) { var watch = System.Diagnostics.Stopwatch.StartNew(); HttpResponseMessage myResponse = null; bool DeleteSucceededPods = int.Parse(System.Configuration.ConfigurationManager.AppSettings["DeleteSucceededPods"] ?? "1")==1; if (DeleteSucceededPods) { dynamic BodyData = await req.Content.ReadAsAsync<object>(); string JobId = BodyData.JobId; IK8SClient k = K8SClientFactory.Create(); try { var r = await k.DeleteJobs(JobId); myResponse= req.CreateResponse(r.Code, r, JsonMediaTypeFormatter.DefaultMediaType); } catch (Exception X) { myResponse= req.CreateResponse(HttpStatusCode.InternalServerError, X, JsonMediaTypeFormatter.DefaultMediaType); } } else { return req.CreateResponse(HttpStatusCode.OK, new { mesagge="Ignored"} , JsonMediaTypeFormatter.DefaultMediaType); } watch.Stop(); log.Info($"[Time] Method GetK8SProcessLog {watch.ElapsedMilliseconds} [ms]"); return myResponse; } [FunctionName("GetK8SProcessLog")] public static async Task<HttpResponseMessage> GetK8SProcessLog([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage req, TraceWriter log, ExecutionContext context) { var watch = System.Diagnostics.Stopwatch.StartNew(); HttpResponseMessage myResponse = null; string JobId = req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "JobId", true) == 0).Value; if (string.IsNullOrEmpty(JobId)) { return req.CreateResponse(HttpStatusCode.InternalServerError, new { Error = "Parameter JobId is null" }, JsonMediaTypeFormatter.DefaultMediaType); } var K8S = K8SClientFactory.Create(); try { var ResultList = await K8S.GetK8SJobLog(JobId); if (ResultList.Count == 0) { //Not Found myResponse= req.CreateResponse(HttpStatusCode.NotFound, ResultList, JsonMediaTypeFormatter.DefaultMediaType); } else { //LOG myResponse= req.CreateResponse(HttpStatusCode.OK, ResultList, JsonMediaTypeFormatter.DefaultMediaType); } } catch (Exception X) { log.Error(X.Message); myResponse= req.CreateResponse(HttpStatusCode.InternalServerError, X, JsonMediaTypeFormatter.DefaultMediaType); } watch.Stop(); log.Info($"[Time] Method GetK8SProcessLog {watch.ElapsedMilliseconds} [ms]"); return myResponse; } [FunctionName("CancelJobTimeOut")] public static async Task<HttpResponseMessage> CancelJobTimeOut([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log, ExecutionContext context) { var watch = System.Diagnostics.Stopwatch.StartNew(); dynamic BodyData = await req.Content.ReadAsAsync<object>(); IActionsProvider myActions = ActionProviderFactory.GetActionProvider(SingleWaterMarkStorageAccInstanceController); UnifiedProcessStatus myProcessStatus = BodyData.ToObject<UnifiedProcessStatus>(); try { myProcessStatus = myActions.GetUnifiedProcessStatus(myProcessStatus.AssetStatus.AssetId, myProcessStatus.JobStatus.JobID); myProcessStatus.JobStatus.State = ExecutionStatus.Finished; myProcessStatus.JobStatus.Details = $"Embedder copies time out, check copies status."; myProcessStatus.JobStatus.FinishTime = DateTime.Now; myProcessStatus.JobStatus.Duration = DateTime.Now.Subtract(myProcessStatus.JobStatus.StartTime); //Update all running copies like Errro time out foreach (var copy in myProcessStatus.EmbebedCodesList.Where(c=>(c.State==ExecutionStatus.Running))) { copy.State = ExecutionStatus.Error; copy.Details = $"Timeout error: {copy.Details}"; } //Update All Finished copies without AssetID (No ASSET copy created) foreach (var copy in myProcessStatus.EmbebedCodesList.Where(c => (c.State == ExecutionStatus.Finished) && (string.IsNullOrEmpty(c.AssetID)))) { copy.State = ExecutionStatus.Error; copy.Details = $"Timeout error: {copy.Details}"; } await myActions.UpdateUnifiedProcessStatus(myProcessStatus); } catch (Exception X) { return req.CreateResponse(HttpStatusCode.InternalServerError, X, JsonMediaTypeFormatter.DefaultMediaType); } watch.Stop(); log.Info($"[Time] Method CancelJobTimeOut {watch.ElapsedMilliseconds} [ms]"); return req.CreateResponse(HttpStatusCode.OK, myProcessStatus, JsonMediaTypeFormatter.DefaultMediaType); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventHub { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ConsumerGroupsOperations operations. /// </summary> internal partial class ConsumerGroupsOperations : IServiceOperations<EventHubManagementClient>, IConsumerGroupsOperations { /// <summary> /// Initializes a new instance of the ConsumerGroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ConsumerGroupsOperations(EventHubManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the EventHubManagementClient /// </summary> public EventHubManagementClient Client { get; private set; } /// <summary> /// Creates or updates an Event Hubs consumer group as a nested resource within /// a Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639498.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> /// <param name='parameters'> /// Parameters supplied to create or update a consumer group resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ConsumerGroupResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, ConsumerGroupCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (eventHubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "eventHubName"); } if (eventHubName != null) { if (eventHubName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "eventHubName", 50); } if (eventHubName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "eventHubName", 1); } } if (consumerGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "consumerGroupName"); } if (consumerGroupName != null) { if (consumerGroupName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "consumerGroupName", 50); } if (consumerGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "consumerGroupName", 1); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("eventHubName", eventHubName); tracingParameters.Add("consumerGroupName", consumerGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/consumergroups/{consumerGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{eventHubName}", System.Uri.EscapeDataString(eventHubName)); _url = _url.Replace("{consumerGroupName}", System.Uri.EscapeDataString(consumerGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ConsumerGroupResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ConsumerGroupResource>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a consumer group from the specified Event Hub and resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639491.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (eventHubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "eventHubName"); } if (eventHubName != null) { if (eventHubName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "eventHubName", 50); } if (eventHubName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "eventHubName", 1); } } if (consumerGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "consumerGroupName"); } if (consumerGroupName != null) { if (consumerGroupName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "consumerGroupName", 50); } if (consumerGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "consumerGroupName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("eventHubName", eventHubName); tracingParameters.Add("consumerGroupName", consumerGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/consumergroups/{consumerGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{eventHubName}", System.Uri.EscapeDataString(eventHubName)); _url = _url.Replace("{consumerGroupName}", System.Uri.EscapeDataString(consumerGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a description for the specified consumer group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639488.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ConsumerGroupResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (eventHubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "eventHubName"); } if (eventHubName != null) { if (eventHubName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "eventHubName", 50); } if (eventHubName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "eventHubName", 1); } } if (consumerGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "consumerGroupName"); } if (consumerGroupName != null) { if (consumerGroupName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "consumerGroupName", 50); } if (consumerGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "consumerGroupName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("eventHubName", eventHubName); tracingParameters.Add("consumerGroupName", consumerGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/consumergroups/{consumerGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{eventHubName}", System.Uri.EscapeDataString(eventHubName)); _url = _url.Replace("{consumerGroupName}", System.Uri.EscapeDataString(consumerGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ConsumerGroupResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ConsumerGroupResource>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the consumer groups in a Namespace. An empty feed is returned if /// no consumer group exists in the Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639503.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ConsumerGroupResource>>> ListAllWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (eventHubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "eventHubName"); } if (eventHubName != null) { if (eventHubName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "eventHubName", 50); } if (eventHubName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "eventHubName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("eventHubName", eventHubName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/consumergroups").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{eventHubName}", System.Uri.EscapeDataString(eventHubName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ConsumerGroupResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ConsumerGroupResource>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the consumer groups in a Namespace. An empty feed is returned if /// no consumer group exists in the Namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639503.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ConsumerGroupResource>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ConsumerGroupResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ConsumerGroupResource>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
#region File Description //----------------------------------------------------------------------------- // AnimatingSprite.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregion namespace RolePlayingGameData { /// <summary> /// A sprite sheet with flipbook-style animations. /// </summary> public class AnimatingSprite : ContentObject { #region Graphics Data /// <summary> /// The content path and name of the texture for this spell animation. /// </summary> private string textureName; /// <summary> /// The content path and name of the texture for this spell animation. /// </summary> public string TextureName { get { return textureName; } set { textureName = value; } } /// <summary> /// The texture for this spell animation. /// </summary> private Texture2D texture; /// <summary> /// The texture for this spell animation. /// </summary> [ContentSerializerIgnore] public Texture2D Texture { get { return texture; } set { texture = value; } } #endregion #region Frame Data /// <summary> /// The dimensions of a single frame of animation. /// </summary> private Point frameDimensions; /// <summary> /// The width of a single frame of animation. /// </summary> public Point FrameDimensions { get { return frameDimensions; } set { frameDimensions = value; frameOrigin.X = frameDimensions.X / 2; frameOrigin.Y = frameDimensions.Y / 2; } } /// <summary> /// The origin of the sprite, within a frame. /// </summary> private Point frameOrigin; /// <summary> /// The number of frames in a row in this sprite. /// </summary> private int framesPerRow; /// <summary> /// The number of frames in a row in this sprite. /// </summary> public int FramesPerRow { get { return framesPerRow; } set { framesPerRow = value; } } /// <summary> /// The offset of this sprite from the position it's drawn at. /// </summary> private Vector2 sourceOffset; /// <summary> /// The offset of this sprite from the position it's drawn at. /// </summary> [ContentSerializer(Optional=true)] public Vector2 SourceOffset { get { return sourceOffset; } set { sourceOffset = value; } } #endregion #region Animation Data /// <summary> /// The animations defined for this sprite. /// </summary> private List<Animation> animations = new List<Animation>(); /// <summary> /// The animations defined for this sprite. /// </summary> public List<Animation> Animations { get { return animations; } set { animations = value; } } /// <summary> /// Enumerate the animations on this animated sprite. /// </summary> /// <param name="animationName">The name of the animation.</param> /// <returns>The animation if found; null otherwise.</returns> public Animation this[string animationName] { get { if (String.IsNullOrEmpty(animationName)) { return null; } foreach (Animation animation in animations) { if (String.Compare(animation.Name, animationName, StringComparison.OrdinalIgnoreCase) == 0) { return animation; } } return null; } } /// <summary> /// Add the animation to the list, checking for name collisions. /// </summary> /// <returns>True if the animation was added to the list.</returns> public bool AddAnimation(Animation animation) { if ((animation != null) && (this[animation.Name] == null)) { animations.Add(animation); return true; } return false; } #endregion #region Playback /// <summary> /// The animation currently playing back on this sprite. /// </summary> private Animation currentAnimation = null; /// <summary> /// The current frame in the current animation. /// </summary> private int currentFrame; /// <summary> /// The elapsed time since the last frame switch. /// </summary> private float elapsedTime; /// <summary> /// The source rectangle of the current frame of animation. /// </summary> private Rectangle sourceRectangle; /// <summary> /// The source rectangle of the current frame of animation. /// </summary> public Rectangle SourceRectangle { get { return sourceRectangle; } } /// <summary> /// Play the given animation on the sprite. /// </summary> /// <remarks>The given animation may be null, to clear any animation.</remarks> public void PlayAnimation(Animation animation) { // start the new animation, ignoring redundant Plays if (animation != currentAnimation) { currentAnimation = animation; ResetAnimation(); } } /// <summary> /// Play an animation given by index. /// </summary> public void PlayAnimation(int index) { // check the parameter if ((index < 0) || (index >= animations.Count)) { throw new ArgumentOutOfRangeException("index"); } PlayAnimation(this.animations[index]); } /// <summary> /// Play an animation given by name. /// </summary> public void PlayAnimation(string name) { // check the parameter if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } PlayAnimation(this[name]); } /// <summary> /// Play a given animation name, with the given direction suffix. /// </summary> /// <example> /// For example, passing "Walk" and Direction.South will play the animation /// named "WalkSouth". /// </example> public void PlayAnimation(string name, Direction direction) { // check the parameter if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } PlayAnimation(name + direction.ToString()); } /// <summary> /// Reset the animation back to its starting position. /// </summary> public void ResetAnimation() { elapsedTime = 0f; if (currentAnimation != null) { currentFrame = currentAnimation.StartingFrame; // calculate the source rectangle by updating the animation UpdateAnimation(0f); } } /// <summary> /// Advance the current animation to the final sprite. /// </summary> public void AdvanceToEnd() { if (currentAnimation != null) { currentFrame = currentAnimation.EndingFrame; // calculate the source rectangle by updating the animation UpdateAnimation(0f); } } /// <summary> /// Stop any animation playing on the sprite. /// </summary> public void StopAnimation() { currentAnimation = null; } /// <summary> /// Returns true if playback on the current animation is complete, or if /// there is no animation at all. /// </summary> public bool IsPlaybackComplete { get { return ((currentAnimation == null) || (!currentAnimation.IsLoop && (currentFrame > currentAnimation.EndingFrame))); } } #endregion #region Updating /// <summary> /// Update the current animation. /// </summary> public void UpdateAnimation(float elapsedSeconds) { if (IsPlaybackComplete) { return; } // loop the animation if needed if (currentAnimation.IsLoop && (currentFrame > currentAnimation.EndingFrame)) { currentFrame = currentAnimation.StartingFrame; } // update the source rectangle int column = (currentFrame - 1) / framesPerRow; sourceRectangle = new Rectangle( (currentFrame - 1 - (column * framesPerRow)) * frameDimensions.X, column * frameDimensions.Y, frameDimensions.X, frameDimensions.Y); // update the elapsed time elapsedTime += elapsedSeconds; // advance to the next frame if ready while (elapsedTime * 1000f > (float)currentAnimation.Interval) { currentFrame++; elapsedTime -= (float)currentAnimation.Interval / 1000f; } } #endregion #region Drawing /// <summary> /// Draw the sprite at the given position. /// </summary> /// <param name="spriteBatch">The SpriteBatch object used to draw.</param> /// <param name="position">The position of the sprite on-screen.</param> /// <param name="layerDepth">The depth at which the sprite is drawn.</param> public void Draw(SpriteBatch spriteBatch, Vector2 position, float layerDepth) { Draw(spriteBatch, position, layerDepth, SpriteEffects.None); } /// <summary> /// Draw the sprite at the given position. /// </summary> /// <param name="spriteBatch">The SpriteBatch object used to draw.</param> /// <param name="position">The position of the sprite on-screen.</param> /// <param name="layerDepth">The depth at which the sprite is drawn.</param> /// <param name="spriteEffect">The sprite-effect applied.</param> public void Draw(SpriteBatch spriteBatch, Vector2 position, float layerDepth, SpriteEffects spriteEffect) { // check the parameters if (spriteBatch == null) { throw new ArgumentNullException("spriteBatch"); } if (texture != null) { spriteBatch.Draw(texture, position, sourceRectangle, Color.White, 0f, sourceOffset , ScaledVector2.DrawFactor, spriteEffect, MathHelper.Clamp(layerDepth, 0f, 1f)); } } #endregion #region Content Type Reader /// <summary> /// Read an AnimatingSprite object from the content pipeline. /// </summary> public class AnimatingSpriteReader : ContentTypeReader<AnimatingSprite> { /// <summary> /// Read an AnimatingSprite object from the content pipeline. /// </summary> protected override AnimatingSprite Read(ContentReader input, AnimatingSprite existingInstance) { AnimatingSprite animatingSprite = existingInstance; if (animatingSprite == null) { animatingSprite = new AnimatingSprite(); } animatingSprite.AssetName = input.AssetName; animatingSprite.TextureName = input.ReadString(); Texture2D asset = null; asset = input.ContentManager.Load<Texture2D>(System.IO.Path.Combine(@"Textures", animatingSprite.TextureName)); animatingSprite.Texture = asset; animatingSprite.FrameDimensions = input.ReadObject<Point>(); animatingSprite.FramesPerRow = input.ReadInt32(); animatingSprite.SourceOffset = input.ReadObject<Vector2>(); animatingSprite.Animations.AddRange( input.ReadObject<List<Animation>>()); return animatingSprite; } } #endregion #region ICloneable Members /// <summary> /// Creates a clone of this object. /// </summary> public object Clone() { AnimatingSprite animatingSprite = new AnimatingSprite(); animatingSprite.animations.AddRange(animations); animatingSprite.currentAnimation = currentAnimation; animatingSprite.currentFrame = currentFrame; animatingSprite.elapsedTime = elapsedTime; animatingSprite.frameDimensions = frameDimensions; animatingSprite.frameOrigin = frameOrigin; animatingSprite.framesPerRow = framesPerRow; animatingSprite.sourceOffset = sourceOffset; animatingSprite.sourceRectangle = sourceRectangle; animatingSprite.texture = texture; animatingSprite.textureName = textureName; return animatingSprite; } #endregion } }
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // 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 ConnectQl.Results { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; /// <summary> /// The row builder. /// </summary> internal class RowBuilder : IRowFieldResolver { /// <summary> /// Translates fields to their display names. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly FieldMapping fieldMapping; /// <summary> /// The field names. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly List<string> fieldNames = new List<string>(); /// <summary> /// The fields. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Dictionary<string, int> fields = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Initializes a new instance of the <see cref="RowBuilder"/> class. /// </summary> public RowBuilder() { } /// <summary> /// Initializes a new instance of the <see cref="RowBuilder"/> class. /// </summary> /// <param name="fieldMapping"> /// The field mapping. /// </param> public RowBuilder(FieldMapping fieldMapping) { this.fieldMapping = fieldMapping; } /// <summary> /// Initializes a new instance of the <see cref="RowBuilder"/> class. /// </summary> /// <param name="alias"> /// The alias that will be prepended to all fields. /// </param> public RowBuilder(string alias) { this.Alias = alias; } /// <summary> /// Gets the alias. /// </summary> public string Alias { get; } /// <summary> /// Gets the fields. /// </summary> public IReadOnlyList<string> Fields => this.fieldMapping?.Fields ?? this.fieldNames; /// <summary> /// Attaches the row to the current builder. /// </summary> /// <param name="row"> /// The row to attach. /// </param> /// <returns> /// The <paramref name="row"/> if it was already attached to the builder, or a copy otherwise. /// </returns> public Row Attach([NotNull] Row row) { if (row == null) { throw new ArgumentNullException(nameof(row)); } return row.Resolver == this ? row : row.Clone(this); } /// <summary> /// Deserializes the row. /// </summary> /// <param name="id"> /// The id. /// </param> /// <param name="values"> /// The values. /// </param> /// <returns> /// The row. /// </returns> Row IRowFieldResolver.DeserializeRow(object id, IDictionary<string, object> values) { return Row.Create(this, id, values); } /// <summary> /// Serializes a row. /// </summary> /// <param name="row">The row.</param> /// <returns>The id and values of the row.</returns> Tuple<object, IDictionary<string, object>> IRowFieldResolver.SerializeRow([NotNull] Row row) { var values = row.ToDictionary(); if (this.fieldMapping != null) { values = values.ToDictionary(kv => this.fieldMapping[kv.Key], kv => kv.Value); } return Tuple.Create(row.UniqueId, values); } /// <summary> /// Combines two rows. /// </summary> /// <param name="first"> /// The first row. /// </param> /// <param name="second"> /// The second row. /// </param> /// <returns> /// The combined rows or <c>null</c> if both rows were <c>null</c>. /// </returns> public Row CombineRows([CanBeNull] Row first, [CanBeNull] Row second) { return first == null ? this.Attach(second) : (second == null ? this.Attach(first) : first.CombineWith(this, second)); } /// <summary> /// Creates a row. /// </summary> /// <param name="uniqueId"> /// The unique id of the row. /// </param> /// <param name="values"> /// The key/values in the row. /// </param> /// <typeparam name="T"> /// The type of the unique id of the row. /// </typeparam> /// <returns> /// The <see cref="Row"/>. /// </returns> public Row CreateRow<T>(T uniqueId, IEnumerable<KeyValuePair<string, object>> values) { return Row.Create(this, uniqueId, this.Alias == null ? values : values.Select(kv => new KeyValuePair<string, object>($"{this.Alias}.{kv.Key}", kv.Value))); } /// <summary> /// Gets the index for the field in the row. /// </summary> /// <param name="field"> /// The field to get the index for. /// </param> /// <returns> /// The index or <c>null</c> if the field wasn't found. /// </returns> public int? GetIndex(string field) { return this.fields.TryGetValue(this.fieldMapping == null ? field : this.fieldMapping[field], out var index) ? (int?)index : null; } /// <summary> /// Gets the indices for the fields and their values. /// </summary> /// <param name="values"> /// The values to get the indices for. /// </param> /// <returns> /// A list of tuples, containing the index and the object at that index, the largest index first. /// </returns> [NotNull] public IList<Tuple<int, object>> GetIndices([NotNull] IEnumerable<KeyValuePair<string, object>> values) { var result = new List<Tuple<int, object>>(); var missing = new List<Tuple<string, int>>(); foreach (var keyValuePair in values) { var index = this.fields.TryGetValue(keyValuePair.Key, out var fieldIndex) ? (int?)fieldIndex : null; if (index == null) { missing.Add(Tuple.Create(keyValuePair.Key, result.Count)); } result.Add(Tuple.Create(index.GetValueOrDefault(), keyValuePair.Value)); } if (missing.Count > 0) { foreach (var field in missing.Select(m => m.Item1)) { this.fields.Add(field, this.fields.Count); this.fieldNames.Add(field); } this.fieldMapping?.AddRowFields(missing.Select(m => m.Item1)); foreach (var tuple in missing) { result[tuple.Item2] = Tuple.Create(this.fields[tuple.Item1], result[tuple.Item2].Item2); } } result.Sort((left, right) => Comparer<int>.Default.Compare(right.Item1, left.Item1)); return result; } /// <summary> /// Gets the index for the field with the internal name in the row. /// </summary> /// <param name="internalName"> /// The internal name of the field to get the index for. /// </param> /// <returns> /// The index or <c>null</c> if the field wasn't found. /// </returns> public int? GetInternalNameIndex(string internalName) { return this.fields.TryGetValue(internalName, out var index) ? (int?)index : null; } } }
// 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. #if XMLSERIALIZERGENERATOR namespace Microsoft.XmlSerializer.Generator #else namespace System.Xml.Serialization #endif { using System.Configuration; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.IO; using System; using System.Text; using System.Xml; using System.Threading; using System.Security; using System.Xml.Serialization.Configuration; using System.Diagnostics; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; using System.Xml.Extensions; using System.Linq; using System.Xml.Serialization; internal class TempAssembly { internal const string GeneratedAssemblyNamespace = "Microsoft.Xml.Serialization.GeneratedAssembly"; private Assembly _assembly = null; private XmlSerializerImplementation _contract = null; private IDictionary _writerMethods; private IDictionary _readerMethods; private TempMethodDictionary _methods; private Hashtable _assemblies = new Hashtable(); internal class TempMethod { internal MethodInfo writeMethod; internal MethodInfo readMethod; internal string name; internal string ns; internal bool isSoap; internal string methodKey; } private TempAssembly() { } internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract) { _assembly = assembly; InitAssemblyMethods(xmlMappings); _contract = contract; } internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location) { #if !FEATURE_SERIALIZATION_UAPAOT bool containsSoapMapping = false; for (int i = 0; i < xmlMappings.Length; i++) { xmlMappings[i].CheckShallow(); if (xmlMappings[i].IsSoap) { containsSoapMapping = true; } } // We will make best effort to use RefEmit for assembly generation bool fallbackToCSharpAssemblyGeneration = false; if (!containsSoapMapping && !TempAssembly.UseLegacySerializerGeneration) { #if !XMLSERIALIZERGENERATOR try { _assembly = GenerateRefEmitAssembly(xmlMappings, types, defaultNamespace); } // Only catch and handle known failures with RefEmit catch (CodeGeneratorConversionException) { fallbackToCSharpAssemblyGeneration = true; } // Add other known exceptions here... // #endif } else { fallbackToCSharpAssemblyGeneration = true; } if (fallbackToCSharpAssemblyGeneration) { throw new PlatformNotSupportedException("Compiling JScript/CSharp scripts is not supported"); } #endif #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (_assembly == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Failed to generate XmlSerializer assembly, but did not throw")); #endif InitAssemblyMethods(xmlMappings); } internal static bool UseLegacySerializerGeneration { get { return false; } } internal XmlSerializerImplementation Contract { get { if (_contract == null) { _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly, "XmlSerializerContract")); } return _contract; } } internal void InitAssemblyMethods(XmlMapping[] xmlMappings) { _methods = new TempMethodDictionary(); for (int i = 0; i < xmlMappings.Length; i++) { TempMethod method = new TempMethod(); method.isSoap = xmlMappings[i].IsSoap; method.methodKey = xmlMappings[i].Key; XmlTypeMapping xmlTypeMapping = xmlMappings[i] as XmlTypeMapping; if (xmlTypeMapping != null) { method.name = xmlTypeMapping.ElementName; method.ns = xmlTypeMapping.Namespace; } _methods.Add(xmlMappings[i].Key, method); } } /// <devdoc> /// <para> /// Attempts to load pre-generated serialization assembly. /// First check for the [XmlSerializerAssembly] attribute /// </para> /// </devdoc> // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract) { Assembly serializer = null; contract = null; string serializerName = null; // check to see if we loading explicit pre-generated assembly object[] attrs = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlSerializerAssemblyAttribute), false); if (attrs.Length == 0) { // Guess serializer name: if parent assembly signed use strong name AssemblyName name = type.Assembly.GetName(); serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace); // use strong name name.Name = serializerName; name.CodeBase = null; name.CultureInfo = CultureInfo.InvariantCulture; try { serializer = Assembly.LoadFile(Path.GetFullPath(serializerName) + ".dll"); } catch (Exception e) { if (e is OutOfMemoryException) { throw; } byte[] token = name.GetPublicKeyToken(); if (token != null && token.Length > 0) { // the parent assembly was signed, so do not try to LoadWithPartialName return null; } } if (serializer == null) { return null; } } else { System.Xml.Serialization.XmlSerializerAssemblyAttribute assemblyAttribute = (System.Xml.Serialization.XmlSerializerAssemblyAttribute)attrs[0]; if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null) throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase")); // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer if (assemblyAttribute.AssemblyName != null) { serializerName = assemblyAttribute.AssemblyName; #pragma warning disable 618 serializer = Assembly.LoadWithPartialName(serializerName); #pragma warning restore 618 } else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0) { serializerName = assemblyAttribute.CodeBase; serializer = Assembly.LoadFrom(serializerName); } else { serializerName = type.Assembly.FullName; serializer = type.Assembly; } if (serializer == null) { throw new FileNotFoundException(null, serializerName); } } Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract"); contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType); if (contract.CanSerialize(type)) return serializer; return null; } #if XMLSERIALIZERGENERATOR internal static class ThisAssembly { internal const string Version = "1.0.0.0"; internal const string InformationalVersion = "1.0.0.0"; } private static string GenerateAssemblyId(Type type) { Module[] modules = type.Assembly.GetModules(); var list = new ArrayList(); for (int i = 0; i < modules.Length; i++) { list.Add(modules[i].ModuleVersionId.ToString()); } list.Sort(); var sb = new StringBuilder(); for (int i = 0; i < list.Count; i++) { sb.Append(list[i].ToString()); sb.Append(","); } return sb.ToString(); } internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Assembly assembly, Hashtable assemblies, Stream stream) { var compiler = new Compiler(); try { var scopeTable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) scopeTable[mapping.Scope] = mapping; var scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); assemblies.Clear(); var importedTypes = new Hashtable(); foreach (TypeScope scope in scopes) { foreach (Type t in scope.Types) { compiler.AddImport(t, importedTypes); Assembly a = t.Assembly; string name = a.FullName; if (assemblies[name] != null) { continue; } if (!a.GlobalAssemblyCache) { assemblies[name] = a; } } } for (int i = 0; i < types.Length; i++) { compiler.AddImport(types[i], importedTypes); } compiler.AddImport(typeof(object).Assembly); compiler.AddImport(typeof(System.Xml.Serialization.XmlSerializer).Assembly); var writer = new IndentedWriter(compiler.Source, false); writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); if (assembly != null && types.Length > 0) { for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) { continue; } if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i].FullName)); } } writer.Write("[assembly:"); writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); if (defaultNamespace != null) { writer.Write(", Namespace="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); } writer.WriteLine(")]"); } var classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {"); writer.Indent++; writer.WriteLine(); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); var writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } writerCodeGen.GenerateEnd(); writer.WriteLine(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); var readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Hashtable(); for (int i = 0; i < xmlMappings.Length; i++) { if (serializers[xmlMappings[i].Key] == null) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); string codecontent = compiler.Source.ToString(); Byte[] info = new UTF8Encoding(true).GetBytes(codecontent); stream.Write(info, 0, info.Length); stream.Flush(); return true; } finally { compiler.Close(); } } #endif #if !XMLSERIALIZERGENERATOR #if !FEATURE_SERIALIZATION_UAPAOT [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "It is safe because the serialization assembly is generated by the framework code, not by the user.")] internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace) { var scopeTable = new Dictionary<TypeScope, XmlMapping>(); foreach (XmlMapping mapping in xmlMappings) scopeTable[mapping.Scope] = mapping; TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); string assemblyName = "Microsoft.GeneratedCode"; AssemblyBuilder assemblyBuilder = CodeGenerator.CreateAssemblyBuilder(assemblyName); // Add AssemblyVersion attribute to match parent accembly version if (types != null && types.Length > 0 && types[0] != null) { ConstructorInfo AssemblyVersionAttribute_ctor = typeof(AssemblyVersionAttribute).GetConstructor( new Type[] { typeof(String) } ); string assemblyVersion = types[0].Assembly.GetName().Version.ToString(); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AssemblyVersionAttribute_ctor, new Object[] { assemblyVersion })); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } ModuleBuilder moduleBuilder = CodeGenerator.CreateModuleBuilder(assemblyBuilder, assemblyName); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); XmlSerializationWriterILGen writerCodeGen = new XmlSerializationWriterILGen(scopes, "public", writerClass); writerCodeGen.ModuleBuilder = moduleBuilder; writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } Type writerType = writerCodeGen.GenerateEnd(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); XmlSerializationReaderILGen readerCodeGen = new XmlSerializationReaderILGen(scopes, "public", readerClass); readerCodeGen.ModuleBuilder = moduleBuilder; readerCodeGen.CreatedTypes.Add(writerType.Name, writerType); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Dictionary<string, string>(); for (int i = 0; i < xmlMappings.Length; i++) { if (!serializers.ContainsKey(xmlMappings[i].Key)) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); return writerType.Assembly; } #endif #endif private static MethodInfo GetMethodFromType(Type type, string methodName) { MethodInfo method = type.GetMethod(methodName); if (method != null) return method; // Not support pregen. Workaround SecurityCritical required for assembly.CodeBase api. MissingMethodException missingMethod = new MissingMethodException(type.FullName + "::" + methodName); throw missingMethod; } internal static Type GetTypeFromAssembly(Assembly assembly, string typeName) { typeName = GeneratedAssemblyNamespace + "." + typeName; Type type = assembly.GetType(typeName); if (type == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingType, typeName, assembly.FullName)); return type; } internal bool CanRead(XmlMapping mapping, XmlReader xmlReader) { if (mapping == null) return false; if (mapping.Accessor.Any) { return true; } TempMethod method = _methods[mapping.Key]; return xmlReader.IsStartElement(method.name, method.ns); } private string ValidateEncodingStyle(string encodingStyle, string methodKey) { if (encodingStyle != null && encodingStyle.Length > 0) { if (_methods[methodKey].isSoap) { if (encodingStyle != Soap.Encoding && encodingStyle != Soap12.Encoding) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncoding3, encodingStyle, Soap.Encoding, Soap12.Encoding)); } } else { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } } else { if (_methods[methodKey].isSoap) { encodingStyle = Soap.Encoding; } } return encodingStyle; } internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle) { XmlSerializationReader reader = null; try { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); reader = Contract.Reader; reader.Init(xmlReader, events, encodingStyle, this); if (_methods[mapping.Key].readMethod == null) { if (_readerMethods == null) { _readerMethods = Contract.ReadMethods; } string methodName = (string)_readerMethods[mapping.Key]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } _methods[mapping.Key].readMethod = GetMethodFromType(reader.GetType(), methodName); } return _methods[mapping.Key].readMethod.Invoke(reader, Array.Empty<object>()); } catch (SecurityException e) { throw new InvalidOperationException(SR.XmlNoPartialTrust, e); } finally { if (reader != null) reader.Dispose(); } } internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { XmlSerializationWriter writer = null; try { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); writer = Contract.Writer; writer.Init(xmlWriter, namespaces, encodingStyle, id, this); if (_methods[mapping.Key].writeMethod == null) { if (_writerMethods == null) { _writerMethods = Contract.WriteMethods; } string methodName = (string)_writerMethods[mapping.Key]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } _methods[mapping.Key].writeMethod = GetMethodFromType(writer.GetType(), methodName); } _methods[mapping.Key].writeMethod.Invoke(writer, new object[] { o }); } catch (SecurityException e) { throw new InvalidOperationException(SR.XmlNoPartialTrust, e); } finally { if (writer != null) writer.Dispose(); } } internal sealed class TempMethodDictionary : Dictionary<string, TempMethod> { } } internal class TempAssemblyCacheKey { private string _ns; private object _type; internal TempAssemblyCacheKey(string ns, object type) { _type = type; _ns = ns; } public override bool Equals(object o) { TempAssemblyCacheKey key = o as TempAssemblyCacheKey; if (key == null) return false; return (key._type == _type && key._ns == _ns); } public override int GetHashCode() { return ((_ns != null ? _ns.GetHashCode() : 0) ^ (_type != null ? _type.GetHashCode() : 0)); } } internal class TempAssemblyCache { private Dictionary<TempAssemblyCacheKey, TempAssembly> _cache = new Dictionary<TempAssemblyCacheKey, TempAssembly>(); internal TempAssembly this[string ns, object o] { get { TempAssembly tempAssembly; _cache.TryGetValue(new TempAssemblyCacheKey(ns, o), out tempAssembly); return tempAssembly; } } internal void Add(string ns, object o, TempAssembly assembly) { TempAssemblyCacheKey key = new TempAssemblyCacheKey(ns, o); lock (this) { TempAssembly tempAssembly; if (_cache.TryGetValue(key, out tempAssembly) && tempAssembly == assembly) return; _cache = new Dictionary<TempAssemblyCacheKey, TempAssembly>(_cache); // clone _cache[key] = assembly; } } } }
using System; using System.Collections; using Gtk; using Mono.Unix; namespace Stetic { internal class WidgetActionBar: Gtk.Toolbar { ProjectBackend project; Stetic.Wrapper.Widget rootWidget; WidgetTreeCombo combo; ToolItem comboItem; Stetic.Wrapper.Widget selection; Stetic.Wrapper.Container.ContainerChild packingSelection; Hashtable editors, wrappers; Hashtable sensitives, invisibles; ArrayList toggles; Gtk.Tooltips tips = new Gtk.Tooltips (); bool disposed; bool updating; bool allowBinding; WidgetDesignerFrontend frontend; public WidgetActionBar (WidgetDesignerFrontend frontend, Stetic.Wrapper.Widget rootWidget) { this.frontend = frontend; editors = new Hashtable (); wrappers = new Hashtable (); sensitives = new Hashtable (); invisibles = new Hashtable (); toggles = new ArrayList (); IconSize = IconSize.Menu; Orientation = Orientation.Horizontal; ToolbarStyle = ToolbarStyle.BothHoriz; combo = new WidgetTreeCombo (); comboItem = new ToolItem (); comboItem.Add (combo); comboItem.ShowAll (); Insert (comboItem, -1); ShowAll (); RootWidget = rootWidget; } public override void Dispose () { if (disposed) return; disposed = true; combo.Destroy (); combo = null; RootWidget = null; Clear (); base.Dispose (); } public bool AllowWidgetBinding { get { return allowBinding; } set { allowBinding = value; } } public Stetic.Wrapper.Widget RootWidget { get { return rootWidget; } set { if (project != null) { project.SelectionChanged -= OnSelectionChanged; project = null; } rootWidget = value; if (combo != null) combo.RootWidget = rootWidget; if (rootWidget != null) { project = (Stetic.ProjectBackend) rootWidget.Project; UpdateSelection (Wrapper.Widget.Lookup (project.Selection)); project.SelectionChanged += OnSelectionChanged; } } } void Clear () { if (selection != null) { selection.Notify -= Notified; if (packingSelection != null) packingSelection.Notify -= Notified; } selection = null; packingSelection = null; editors.Clear (); wrappers.Clear (); sensitives.Clear (); invisibles.Clear (); toggles.Clear (); foreach (Gtk.Widget child in Children) if (child != comboItem) { Remove (child); child.Destroy (); } } void OnSelectionChanged (object s, Wrapper.WidgetEventArgs args) { UpdateSelection (args.WidgetWrapper); } void UpdateSelection (Wrapper.Widget w) { Clear (); selection = w; if (selection == null) { combo.SetSelection (null); return; } // Look for the root widget, and only update the bar if the selected // widget is a child of the root widget while (w != null && !w.IsTopLevel) { w = Stetic.Wrapper.Container.LookupParent ((Gtk.Widget) w.Wrapped); } if (w == null || w != rootWidget) return; combo.SetSelection (selection); selection.Notify += Notified; packingSelection = Stetic.Wrapper.Container.ChildWrapper (selection); if (packingSelection != null) packingSelection.Notify += Notified; AddWidgetCommands (selection); UpdateSensitivity (); } protected virtual void AddWidgetCommands (ObjectWrapper wrapper) { if (allowBinding && wrapper != RootWidget) { // Show the Bind to Field button only for children of the root container. ToolButton bindButton = new ToolButton (null, Catalog.GetString ("Bind to Field")); bindButton.IsImportant = true; bindButton.Clicked += delegate { frontend.NotifyBindField (); }; bindButton.Show (); Insert (bindButton, -1); } AddCommands (wrapper); } void AddCommands (ObjectWrapper wrapper) { foreach (ItemGroup igroup in wrapper.ClassDescriptor.ItemGroups) { foreach (ItemDescriptor desc in igroup) { if ((desc is CommandDescriptor) && desc.SupportsGtkVersion (project.TargetGtkVersion)) AppendCommand ((CommandDescriptor) desc, wrapper); } } Stetic.Wrapper.Widget widget = wrapper as Stetic.Wrapper.Widget; if (widget != null) { Stetic.Wrapper.Container.ContainerChild packingSelection = Stetic.Wrapper.Container.ChildWrapper (widget); if (packingSelection != null) AddCommands (packingSelection); } } void AppendCommand (CommandDescriptor cmd, ObjectWrapper widget) { Gtk.ToolButton button; if (cmd.IsToggleCommand (widget.Wrapped)) { button = new Gtk.ToggleToolButton (); ((Gtk.ToggleToolButton)button).Active = cmd.IsToogled (widget.Wrapped); toggles.Add (cmd); editors[cmd.Name] = button; } else { button = new Gtk.ToolButton (null, null); } Gtk.Image img = cmd.GetImage (); if (img != null) { button.IconWidget = img; button.Label = cmd.Label; if (cmd.Label != null && cmd.Label.Length > 0) button.SetTooltip (tips, cmd.Label, ""); } else { button.Label = cmd.Label; button.IsImportant = true; } button.Clicked += delegate (object o, EventArgs args) { if (!updating) cmd.Run (widget.Wrapped); }; button.ShowAll (); Insert (button, -1); if (cmd.HasDependencies) { editors[cmd.Name] = button; sensitives[cmd] = cmd; } if (cmd.HasVisibility) { editors[cmd.Name] = button; invisibles[cmd] = cmd; } wrappers [cmd] = widget; } void Notified (object s, string propertyName) { UpdateSensitivity (); } void UpdateSensitivity () { foreach (ItemDescriptor item in sensitives.Keys) { Widget w = editors[item.Name] as Widget; if (w != null) { ObjectWrapper wrapper = wrappers [item] as ObjectWrapper; object ob = sensitives.Contains (item) ? wrapper.Wrapped : null; w.Sensitive = item.EnabledFor (ob); } } foreach (ItemDescriptor item in invisibles.Keys) { Widget w = editors[item.Name] as Widget; if (w != null) { ObjectWrapper wrapper = wrappers [item] as ObjectWrapper; object ob = invisibles.Contains (item) ? wrapper.Wrapped : null; w.Visible = item.VisibleFor (ob); } } foreach (CommandDescriptor cmd in toggles) { ToggleToolButton w = editors[cmd.Name] as ToggleToolButton; if (w != null) { ObjectWrapper wrapper = wrappers [cmd] as ObjectWrapper; updating = true; w.Active = cmd.IsToogled (wrapper.Wrapped); updating = false; } } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Timers; using OpenMetaverse; using Timer = System.Timers.Timer; namespace Aurora.Framework { #region TimedCacheKey Class internal class TimedCacheKey<TKey> : IComparable<TKey> { private readonly TKey key; private readonly bool slidingExpiration; private readonly TimeSpan slidingExpirationWindowSize; private DateTime expirationDate; public TimedCacheKey(TKey key, DateTime expirationDate) { this.key = key; this.slidingExpiration = false; this.expirationDate = expirationDate; } public TimedCacheKey(TKey key, TimeSpan slidingExpirationWindowSize) { this.key = key; this.slidingExpiration = true; this.slidingExpirationWindowSize = slidingExpirationWindowSize; Accessed(); } public DateTime ExpirationDate { get { return expirationDate; } } public TKey Key { get { return key; } } public bool SlidingExpiration { get { return slidingExpiration; } } public TimeSpan SlidingExpirationWindowSize { get { return slidingExpirationWindowSize; } } #region IComparable<TKey> Members public int CompareTo(TKey other) { return key.GetHashCode().CompareTo(other.GetHashCode()); } #endregion public void Accessed() { if (slidingExpiration) expirationDate = DateTime.Now.Add(slidingExpirationWindowSize); } } #endregion /// <summary> /// List that has an expiring built in /// </summary> /// <typeparam name = "TKey"></typeparam> public sealed class ExpiringList<TKey> { private const double CACHE_PURGE_HZ = 1.0; private const int MAX_LOCK_WAIT = 5000; // milliseconds #region Private fields /// <summary> /// For thread safety /// </summary> private readonly object isPurging = new object(); /// <summary> /// For thread safety /// </summary> private readonly object syncRoot = new object(); private readonly List<TimedCacheKey<TKey>> timedStorage = new List<TimedCacheKey<TKey>>(); private readonly Dictionary<TKey, TimedCacheKey<TKey>> timedStorageIndex = new Dictionary<TKey, TimedCacheKey<TKey>>(); private readonly Timer timer = new Timer(TimeSpan.FromSeconds(CACHE_PURGE_HZ).TotalMilliseconds); private double DefaultTime; #endregion #region Constructor public ExpiringList() { timer.Elapsed += PurgeCache; timer.Start(); } #endregion #region Public methods public TKey this[int i] { get { TKey o; if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { if (timedStorage.Count > i) { TimedCacheKey<TKey> tkey = timedStorage[i]; o = tkey.Key; timedStorage.Remove(tkey); tkey.Accessed(); timedStorage.Insert(i, tkey); return o; } else { throw new ArgumentException("Key not found in the cache"); } } finally { Monitor.Exit(syncRoot); } } set { AddOrUpdate(value, DefaultTime); } } public int Count { get { return timedStorage.Count; } } public void SetDefaultTime(double time) { DefaultTime = time; } public bool Add(TKey key, double expirationSeconds) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { // This is the actual adding of the key if (timedStorageIndex.ContainsKey(key)) { return false; } else { TimedCacheKey<TKey> internalKey = new TimedCacheKey<TKey>(key, DateTime.UtcNow + TimeSpan.FromSeconds(expirationSeconds)); timedStorage.Add(internalKey); timedStorageIndex.Add(key, internalKey); return true; } } finally { Monitor.Exit(syncRoot); } } public bool Add(TKey key, TimeSpan slidingExpiration) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { // This is the actual adding of the key if (timedStorageIndex.ContainsKey(key)) { return false; } else { TimedCacheKey<TKey> internalKey = new TimedCacheKey<TKey>(key, slidingExpiration); timedStorage.Add(internalKey); timedStorageIndex.Add(key, internalKey); return true; } } finally { Monitor.Exit(syncRoot); } } public bool AddOrUpdate(TKey key, double expirationSeconds) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { if (Contains(key)) { Update(key, expirationSeconds); return false; } else { Add(key, expirationSeconds); return true; } } finally { Monitor.Exit(syncRoot); } } public bool AddOrUpdate(TKey key, TimeSpan slidingExpiration) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { if (Contains(key)) { Update(key, slidingExpiration); return false; } else { Add(key, slidingExpiration); return true; } } finally { Monitor.Exit(syncRoot); } } public void Clear() { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { timedStorage.Clear(); timedStorageIndex.Clear(); } finally { Monitor.Exit(syncRoot); } } public bool Contains(TKey key) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { return timedStorageIndex.ContainsKey(key); } finally { Monitor.Exit(syncRoot); } } public bool Remove(TKey key) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { if (timedStorageIndex.ContainsKey(key)) { timedStorage.Remove(timedStorageIndex[key]); timedStorageIndex.Remove(key); return true; } else { return false; } } finally { Monitor.Exit(syncRoot); } } public bool Update(TKey key) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { if (timedStorageIndex.ContainsKey(key)) { timedStorage.Remove(timedStorageIndex[key]); timedStorageIndex[key].Accessed(); timedStorage.Add(timedStorageIndex[key]); return true; } else { return false; } } finally { Monitor.Exit(syncRoot); } } public bool Update(TKey key, double expirationSeconds) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { if (timedStorageIndex.ContainsKey(key)) { timedStorage.Remove(timedStorageIndex[key]); timedStorageIndex.Remove(key); } else { return false; } TimedCacheKey<TKey> internalKey = new TimedCacheKey<TKey>(key, DateTime.UtcNow + TimeSpan.FromSeconds(expirationSeconds)); timedStorage.Add(internalKey); timedStorageIndex.Add(key, internalKey); return true; } finally { Monitor.Exit(syncRoot); } } public bool Update(TKey key, TimeSpan slidingExpiration) { if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { if (timedStorageIndex.ContainsKey(key)) { timedStorage.Remove(timedStorageIndex[key]); timedStorageIndex.Remove(key); } else { return false; } TimedCacheKey<TKey> internalKey = new TimedCacheKey<TKey>(key, slidingExpiration); timedStorage.Add(internalKey); timedStorageIndex.Add(key, internalKey); return true; } finally { Monitor.Exit(syncRoot); } } public void CopyTo(Array array, int startIndex) { // Error checking if (array == null) { throw new ArgumentNullException("array"); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", "startIndex must be >= 0."); } if (array.Rank > 1) { throw new ArgumentException("array must be of Rank 1 (one-dimensional)", "array"); } if (startIndex >= array.Length) { throw new ArgumentException("startIndex must be less than the length of the array.", "startIndex"); } if (Count > array.Length - startIndex) { throw new ArgumentException( "There is not enough space from startIndex to the end of the array to accomodate all items in the cache."); } // Copy the data to the array (in a thread-safe manner) if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { foreach (object o in timedStorage) { array.SetValue(o, startIndex); startIndex++; } } finally { Monitor.Exit(syncRoot); } } #endregion #region Private methods /// <summary> /// Purges expired objects from the cache. Called automatically by the purge timer. /// </summary> private void PurgeCache(object sender, ElapsedEventArgs e) { // Only let one thread purge at once - a buildup could cause a crash // This could cause the purge to be delayed while there are lots of read/write ops // happening on the cache if (!Monitor.TryEnter(isPurging)) return; DateTime signalTime = DateTime.UtcNow; try { // If we fail to acquire a lock on the synchronization root after MAX_LOCK_WAIT, skip this purge cycle if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) return; try { Lazy<List<object>> expiredItems = new Lazy<List<object>>(); #if (!ISWIN) foreach (TimedCacheKey<TKey> timedKey in timedStorage) { if (timedKey.ExpirationDate < signalTime) { // Mark the object for purge expiredItems.Value.Add(timedKey.Key); } } #else foreach (TimedCacheKey<TKey> timedKey in timedStorage.Where(timedKey => timedKey.ExpirationDate < signalTime)) { // Mark the object for purge expiredItems.Value.Add(timedKey.Key); } #endif if (expiredItems.IsValueCreated) { foreach (TimedCacheKey<TKey> timedKey in from TKey key in expiredItems.Value select timedStorageIndex[key]) { timedStorageIndex.Remove(timedKey.Key); timedStorage.Remove(timedKey); } } } finally { Monitor.Exit(syncRoot); } } finally { Monitor.Exit(isPurging); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Configuration.ConfigurationManagerTest.cs - Unit tests // for System.Configuration.ConfigurationManager. // // Author: // Chris Toshok <toshok@ximian.com> // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2005-2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Specialized; using System.Configuration; using System.IO; using Xunit; using SysConfig = System.Configuration.Configuration; namespace MonoTests.System.Configuration { using Util; public class ConfigurationManagerTest { [Fact] // OpenExeConfiguration (ConfigurationUserLevel) [ActiveIssue("dotnet/corefx #19384", TargetFrameworkMonikers.NetFramework)] public void OpenExeConfiguration1_UserLevel_None() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal(TestUtil.ThisConfigFileName, fi.Name); } [Fact] public void OpenExeConfiguration1_UserLevel_PerUserRoaming() { string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // If there is not ApplicationData folder PerUserRoaming won't work if (string.IsNullOrEmpty(applicationData)) return; SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); Assert.False(string.IsNullOrEmpty(config.FilePath), "should have some file path"); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("user.config", fi.Name); } [Fact] [ActiveIssue(15065, TestPlatforms.AnyUnix)] public void OpenExeConfiguration1_UserLevel_PerUserRoamingAndLocal() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("user.config", fi.Name); } [Fact] // OpenExeConfiguration (String) public void OpenExeConfiguration2() { using (var temp = new TempDirectory()) { string exePath; SysConfig config; exePath = Path.Combine(temp.Path, "DoesNotExist.whatever"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); exePath = Path.Combine(temp.Path, "SomeExecutable.exe"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); exePath = Path.Combine(temp.Path, "Foo.exe.config"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); } } [Fact] // OpenExeConfiguration (String) public void OpenExeConfiguration2_ExePath_DoesNotExist() { using (var temp = new TempDirectory()) { string exePath = Path.Combine(temp.Path, "DoesNotExist.exe"); ConfigurationErrorsException ex = Assert.Throws<ConfigurationErrorsException>( () => ConfigurationManager.OpenExeConfiguration(exePath)); // An error occurred loading a configuration file: // The parameter 'exePath' is invalid Assert.Equal(typeof(ConfigurationErrorsException), ex.GetType()); Assert.Null(ex.Filename); Assert.NotNull(ex.InnerException); Assert.Equal(0, ex.Line); Assert.NotNull(ex.Message); // The parameter 'exePath' is invalid ArgumentException inner = ex.InnerException as ArgumentException; Assert.NotNull(inner); Assert.Equal(typeof(ArgumentException), inner.GetType()); Assert.Null(inner.InnerException); Assert.NotNull(inner.Message); Assert.Equal("exePath", inner.ParamName); } } [Fact] [ActiveIssue("dotnet/corefx #18831", TargetFrameworkMonikers.NetFramework)] public void exePath_UserLevelNone() { string name = TestUtil.ThisApplicationPath; SysConfig config = ConfigurationManager.OpenExeConfiguration(name); Assert.Equal(TestUtil.ThisApplicationPath + ".config", config.FilePath); } [Fact] public void exePath_UserLevelPerRoaming() { string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // If there is not ApplicationData folder PerUserRoaming won't work if (string.IsNullOrEmpty(applicationData)) return; Assert.True(Directory.Exists(applicationData), "application data should exist"); SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); string filePath = config.FilePath; Assert.False(string.IsNullOrEmpty(filePath), "should have some file path"); Assert.True(filePath.StartsWith(applicationData), "#1:" + filePath); Assert.Equal("user.config", Path.GetFileName(filePath)); } [Fact] [ActiveIssue(15066, TestPlatforms.AnyUnix)] public void exePath_UserLevelPerRoamingAndLocal() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); string filePath = config.FilePath; string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); Assert.True(filePath.StartsWith(applicationData), "#1:" + filePath); Assert.Equal("user.config", Path.GetFileName(filePath)); } [Fact] public void mapped_UserLevelNone() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("execonfig", fi.Name); } [Fact] public void mapped_UserLevelPerRoaming() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.RoamingUserConfigFilename = "roaminguser"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("roaminguser", fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoaming_no_execonfig() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.RoamingUserConfigFilename = "roaminguser"; AssertExtensions.Throws<ArgumentException>("fileMap.ExeConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming)); } [Fact] public void mapped_UserLevelPerRoamingAndLocal() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.RoamingUserConfigFilename = "roaminguser"; map.LocalUserConfigFilename = "localuser"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("localuser", fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoamingAndLocal_no_execonfig() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.RoamingUserConfigFilename = "roaminguser"; map.LocalUserConfigFilename = "localuser"; AssertExtensions.Throws<ArgumentException>("fileMap.ExeConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal)); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoamingAndLocal_no_roaminguser() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.LocalUserConfigFilename = "localuser"; AssertExtensions.Throws<ArgumentException>("fileMap.RoamingUserConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal)); } [Fact] public void MachineConfig() { SysConfig config = ConfigurationManager.OpenMachineConfiguration(); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machine.config", fi.Name); } [Fact] public void mapped_MachineConfig() { ConfigurationFileMap map = new ConfigurationFileMap(); map.MachineConfigFilename = "machineconfig"; SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration(map); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machineconfig", fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] [ActiveIssue("dotnet/corefx #19384", TargetFrameworkMonikers.NetFramework)] public void mapped_ExeConfiguration_null() { SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(null, ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal(TestUtil.ThisConfigFileName, fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_MachineConfig_null() { SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration(null); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machine.config", fi.Name); } [Fact] public void GetSectionReturnsNativeObject() { Assert.True(ConfigurationManager.GetSection("appSettings") is NameValueCollection); } [Fact] // Test for bug #3412 // Doesn't pass on Mono // [Category("NotWorking")] public void TestAddRemoveSection() { const string name = "testsection"; var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // ensure not present if (config.Sections.Get(name) != null) { config.Sections.Remove(name); } // add config.Sections.Add(name, new TestSection()); // remove var section = config.Sections.Get(name); Assert.NotNull(section); Assert.NotNull(section as TestSection); config.Sections.Remove(name); // add config.Sections.Add(name, new TestSection()); // remove section = config.Sections.Get(name); Assert.NotNull(section); Assert.NotNull(section as TestSection); config.Sections.Remove(name); } [Fact] public void TestFileMap() { using (var temp = new TempDirectory()) { string configPath = Path.Combine(temp.Path, Path.GetRandomFileName() + ".config"); Assert.False(File.Exists(configPath)); var map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var config = ConfigurationManager.OpenMappedExeConfiguration( map, ConfigurationUserLevel.None); config.Sections.Add("testsection", new TestSection()); config.Save(); Assert.True(File.Exists(configPath), "#1"); Assert.True(File.Exists(Path.GetFullPath(configPath)), "#2"); } } [Fact] public void TestContext() { var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); const string name = "testsection"; // ensure not present if (config.GetSection(name) != null) config.Sections.Remove(name); var section = new TestContextSection(); // Can't access EvaluationContext .... Assert.Throws<ConfigurationErrorsException>(() => section.TestContext(null)); // ... until it's been added to a section. config.Sections.Add(name, section); section.TestContext("#2"); // Remove ... config.Sections.Remove(name); // ... and it doesn't lose its context section.TestContext(null); } [Fact] public void TestContext2() { using (var temp = new TempDirectory()) { string configPath = Path.Combine(temp.Path, Path.GetRandomFileName() + ".config"); Assert.False(File.Exists(configPath)); var map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var config = ConfigurationManager.OpenMappedExeConfiguration( map, ConfigurationUserLevel.None); config.Sections.Add("testsection", new TestSection()); config.Sections.Add("testcontext", new TestContextSection()); config.Save(); Assert.True(File.Exists(configPath), "#1"); } } class TestSection : ConfigurationSection { } class TestContextSection : ConfigurationSection { public void TestContext(string label) { Assert.NotNull(EvaluationContext); } } [Fact] public void BadConfig() { using (var temp = new TempDirectory()) { string xml = @" badXml"; var file = Path.Combine(temp.Path, "badConfig.config"); File.WriteAllText(file, xml); var fileMap = new ConfigurationFileMap(file); Assert.Equal(file, Assert.Throws<ConfigurationErrorsException>(() => ConfigurationManager.OpenMappedMachineConfiguration(fileMap)).Filename); } } } }
using System; namespace Godot { public static class Mathf { public const float PI = 3.14159274f; public const float Epsilon = 1e-06f; private const float Deg2RadConst = 0.0174532924f; private const float Rad2DegConst = 57.29578f; public static float abs(float s) { return Math.Abs(s); } public static float acos(float s) { return (float)Math.Acos(s); } public static float asin(float s) { return (float)Math.Asin(s); } public static float atan(float s) { return (float)Math.Atan(s); } public static float atan2(float x, float y) { return (float)Math.Atan2(x, y); } public static float ceil(float s) { return (float)Math.Ceiling(s); } public static float clamp(float val, float min, float max) { if (val < min) { return min; } else if (val > max) { return max; } return val; } public static float cos(float s) { return (float)Math.Cos(s); } public static float cosh(float s) { return (float)Math.Cosh(s); } public static int decimals(float step) { return decimals(step); } public static int decimals(decimal step) { return BitConverter.GetBytes(decimal.GetBits(step)[3])[2]; } public static float deg2rad(float deg) { return deg * Deg2RadConst; } public static float ease(float s, float curve) { if (s < 0f) { s = 0f; } else if (s > 1.0f) { s = 1.0f; } if (curve > 0f) { if (curve < 1.0f) { return 1.0f - pow(1.0f - s, 1.0f / curve); } return pow(s, curve); } else if (curve < 0f) { if (s < 0.5f) { return pow(s * 2.0f, -curve) * 0.5f; } return (1.0f - pow(1.0f - (s - 0.5f) * 2.0f, -curve)) * 0.5f + 0.5f; } return 0f; } public static float exp(float s) { return (float)Math.Exp(s); } public static float floor(float s) { return (float)Math.Floor(s); } public static float fposmod(float x, float y) { if (x >= 0f) { return x % y; } else { return y - (-x % y); } } public static float lerp(float from, float to, float weight) { return from + (to - from) * clamp(weight, 0f, 1f); } public static float log(float s) { return (float)Math.Log(s); } public static int max(int a, int b) { return (a > b) ? a : b; } public static float max(float a, float b) { return (a > b) ? a : b; } public static int min(int a, int b) { return (a < b) ? a : b; } public static float min(float a, float b) { return (a < b) ? a : b; } public static int nearest_po2(int val) { val--; val |= val >> 1; val |= val >> 2; val |= val >> 4; val |= val >> 8; val |= val >> 16; val++; return val; } public static float pow(float x, float y) { return (float)Math.Pow(x, y); } public static float rad2deg(float rad) { return rad * Rad2DegConst; } public static float round(float s) { return (float)Math.Round(s); } public static float sign(float s) { return (s < 0f) ? -1f : 1f; } public static float sin(float s) { return (float)Math.Sin(s); } public static float sinh(float s) { return (float)Math.Sinh(s); } public static float sqrt(float s) { return (float)Math.Sqrt(s); } public static float stepify(float s, float step) { if (step != 0f) { s = floor(s / step + 0.5f) * step; } return s; } public static float tan(float s) { return (float)Math.Tan(s); } public static float tanh(float s) { return (float)Math.Tanh(s); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using DequeNet.Debugging; using DequeNet.Extensions; namespace DequeNet { /// <summary> /// Represents a double-ended queue, also known as deque (pronounced "deck"). /// Items can be appended to/removed from both ends of the deque. /// </summary> /// <typeparam name="T">Specifies the type of the elements in the deque.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(DequeDebugView<>))] public class Deque<T> : IDeque<T> { private const int DefaultCapacity = 4; private static readonly T[] EmptyBuffer = new T[0]; private int _version; private object _syncRoot; /// <summary> /// Ring buffer that holds the items. /// </summary> private T[] _buffer; /// <summary> /// The offset used to calculate the position of the leftmost item in the buffer. /// </summary> private int _leftIndex; /// <summary> /// Initializes a new instance of the <see cref="Deque{T}"/> class. /// </summary> public Deque() { _buffer = EmptyBuffer; } /// <summary> /// Initializes a new instance of the <see cref="Deque{T}"/> class with the specified capacity. /// </summary> /// <param name="capacity">The deque's initial capacity.</param> /// <exception cref="ArgumentOutOfRangeException">Capacity cannot be less than 0.</exception> public Deque(int capacity) { if(capacity < 0) throw new ArgumentOutOfRangeException("capacity", "capacity was less than zero."); _buffer = capacity == 0 ? EmptyBuffer : new T[capacity]; } /// <summary> /// Initializes a new instance of the <see cref="Deque{T}"/> class that contains elements copied from the specified collection. /// </summary> /// <param name="collection">The collection whose elements are copied to the deque.</param> public Deque(IEnumerable<T> collection) { if(collection == null) throw new ArgumentNullException("collection"); InitializeFromCollection(collection); } private void InitializeFromCollection(IEnumerable<T> enumerable) { var collection = enumerable as ICollection<T> ?? enumerable.ToArray(); var count = collection.Count; //initialize buffer if (count == 0) _buffer = EmptyBuffer; else { _buffer = new T[count]; collection.CopyTo(_buffer, 0); Count = count; } } /// <summary> /// Adds an item to the right end of the <see cref="Deque{T}"/>. /// </summary> /// <param name="item">The item to be added to the <see cref="Deque{T}"/>.</param> public void PushRight(T item) { EnsureCapacity(Count + 1); //inc count Count ++; //insert item Right = item; _version++; } /// <summary> /// Adds an item to the left end of the <see cref="Deque{T}"/>. /// </summary> /// <param name="item">The item to be added to the <see cref="Deque{T}"/>.</param> public void PushLeft(T item) { EnsureCapacity(Count + 1); //decrement left index and increment count LeftIndex --; Count++; //insert item Left = item; _version++; } /// <summary> /// Attempts to remove and return an item from the right end of the <see cref="Deque{T}"/>. /// </summary> /// <returns>The rightmost item.</returns> /// <exception cref="InvalidOperationException">The deque is empty.</exception> public T PopRight() { if (IsEmpty) throw new InvalidOperationException("The deque is empty"); //retrieve rightmost item and clean buffer slot var right = Right; Right = default(T); //dec count Count--; _version++; return right; } /// <summary> /// Attempts to remove and return an item from the left end of the <see cref="Deque{T}"/>. /// </summary> /// <returns>The leftmost item.</returns> /// <exception cref="InvalidOperationException">The deque is empty.</exception> public T PopLeft() { if (IsEmpty) throw new InvalidOperationException("The deque is empty"); //retrieve leftmost item and clean buffer slot var left = Left; Left = default(T); //increment left index and decrement count LeftIndex++; Count--; _version++; return left; } /// <summary> /// Attempts to return the rightmost item of the <see cref="Deque{T}"/> /// without removing it. /// </summary> /// <returns>The rightmost item.</returns> /// <exception cref="InvalidOperationException">The deque is empty.</exception> public T PeekRight() { if (IsEmpty) throw new InvalidOperationException("The deque is empty"); //retrieve rightmost item return Right; } /// <summary> /// Attempts to return the leftmost item of the <see cref="Deque{T}"/> /// without removing it. /// </summary> /// <returns>The leftmost item.</returns> /// <exception cref="InvalidOperationException">The deque is empty.</exception> public T PeekLeft() { if (IsEmpty) throw new InvalidOperationException("The deque is empty"); //retrieve leftmost item return Left; } /// <summary> /// Removes all items from the <see cref="Deque{T}"/>. /// </summary> public void Clear() { //clear the ring buffer to allow the GC to reclaim the references if (LoopsAround) { //clear both halves Array.Clear(_buffer, LeftIndex, Capacity - LeftIndex); Array.Clear(_buffer, 0, LeftIndex + (Count - Capacity)); } else //clear the whole array Array.Clear(_buffer, LeftIndex, Count); Count = 0; LeftIndex = 0; _version++; } /// <summary> /// Returns an enumerator that iterates through the deque. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the deque. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the deque. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the deque. /// </returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a deque. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the deque. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <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> /// <remarks>For <see cref="Deque{T}"/>, this operation will add the item to the right end of the deque.</remarks> void ICollection<T>.Add(T item) { PushRight(item); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>. /// </summary> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. /// This method also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>. /// </returns> /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> bool ICollection<T>.Remove(T item) { //find the index of the item to be removed in the deque var comp = EqualityComparer<T>.Default; int virtualIndex = -1; int counter = 0; foreach (var dequeItem in this) { if (comp.Equals(item, dequeItem)) { virtualIndex = counter; break; } counter++; } //return false if the item wasn't found if (virtualIndex == -1) return false; //if the removal should be performed on one of the ends, use the corresponding Pop operation instead if (virtualIndex == 0) PopLeft(); else if (virtualIndex == Count - 1) PopRight(); else { if (virtualIndex < Count/2) //If the item is located towards the left end of the deque { //move the items to the left of 'item' one index to the right for (int i = virtualIndex - 1; i >= 0; i--) this[i + 1] = this[i]; //clean leftmost item Left = default(T); //increase left LeftIndex++; Count--; } else //If the item is located towards the right end of the deque { //move the items to the right of 'item' one index to the left for (int i = virtualIndex + 1; i < Count; i++) this[i - 1] = this[i]; //clean rightmost item Right = default(T); //decrease count Count--; } _version++; } return true; } /// <summary> /// Determines whether the <see cref="Deque{T}"/> contains a specific value. /// </summary> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="Deque{T}"/>; otherwise, false. /// </returns> /// <param name="item">The object to locate in the <see cref="Deque{T}"/>.</param> public bool Contains(T item) { return this.Contains(item, EqualityComparer<T>.Default); } /// <summary> /// Copies the elements of the <see cref="Deque{T}"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="Deque{T}"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0 or greater than the <paramref name="array"/>'s upper bound.</exception> /// <exception cref="ArgumentException">The number of elements in the source <see cref="Deque{T}"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.</exception> public void CopyTo(T[] array, int arrayIndex) { ((ICollection) this).CopyTo(array , arrayIndex); } void ICollection.CopyTo(Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException("Only single dimensional arrays are supported for the requested action."); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", "Index was less than the array's lower bound."); if (arrayIndex >= array.Length) throw new ArgumentOutOfRangeException("arrayIndex", "Index was greater than the array's upper bound."); if (Count == 0) return; if (array.Length - arrayIndex < Count) throw new ArgumentException("Destination array was not long enough"); try { //if the elements are stored sequentially (i.e., left+count doesn't "wrap around" the array's boundary), //copy the array as a whole if (!LoopsAround) { Array.Copy(_buffer, LeftIndex, array, arrayIndex, Count); } else { //copy both halves to a new array Array.Copy(_buffer, LeftIndex, array, arrayIndex, Capacity - LeftIndex); Array.Copy(_buffer, 0, array, arrayIndex + Capacity - LeftIndex, LeftIndex + (Count - Capacity)); } } catch (ArrayTypeMismatchException) { throw new ArgumentException("Target array type is not compatible with the type of items in the collection."); } } /// <summary> /// Sets the capacity to the actual number of elements in the <see cref="Deque{T}"/>. /// </summary> /// <remarks> /// This method can be used to minimize a deque's memory overhead once it is known that no /// new elements will be added to the deque. To completely clear a deque and /// release all memory referenced by the deque, execute <see cref="Clear"/> followed by <see cref="TrimExcess"/>. /// </remarks> public void TrimExcess() { Capacity = Count; } /// <summary> /// Ensures that the capacity of this list is at least the given minimum /// value. If the currect capacity of the list is less than min, the /// capacity is increased to twice the current capacity or to min, /// whichever is larger. /// </summary> /// <param name="min">The minimum capacity required.</param> private void EnsureCapacity(int min) { if (Capacity < min) { var newCapacity = Capacity == 0 ? DefaultCapacity : Capacity*2; newCapacity = Math.Max(newCapacity, min); Capacity = newCapacity; } } /// <summary> /// Uses modular arithmetic to calculate the correct ring buffer index for a given (possibly out-of-bounds) index. /// If <paramref name="position"/> is over the array's upper boundary, the returned index "wraps/loops around" the upper boundary. /// </summary> /// <param name="position">The possibly out-of-bounds index.</param> /// <returns>The ring buffer index.</returns> private int CalcIndex(int position) { //put 'position' in the range [0, Capacity-1] using modular arithmetic if (Capacity != 0) return position.Mod(Capacity); //if capacity is 0, _leftIndex must always be 0 Debug.Assert(_leftIndex == 0); return 0; } /// <summary> /// Calculates the ring buffer index corresponding to a given "virtual index". /// A virtual index is the index of an item as seen from an enumerator's perspective, i.e., as if the items were laid out sequentially starting at index 0. /// As such, a virtual index is in the range [0, Count - 1]. /// </summary> /// <param name="index">The virtual index.</param> /// <returns>A ring buffer index</returns> private int VirtualIndexToBufferIndex(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", "Index was out of range. Must be non-negative and less than the size of the collection."); //Apply LeftIndex offset and modular arithmetic return CalcIndex(LeftIndex + index); } /// <summary> /// Gets the number of elements contained in the <see cref="Deque{T}"/>. /// </summary> public int Count { get; private set; } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns> /// true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false. /// For <see cref="Deque{T}"/>, this property always returns false. /// </returns> bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns> /// An object that can be used to synchronize access to the <see cref="ICollection"/>. /// </returns> object ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } } /// <summary> /// Gets a value that indicates whether the <see cref="Deque{T}"/> is empty. /// </summary> public bool IsEmpty { get { return Count == 0; } } bool ICollection<T>.IsReadOnly { get { return false; } } /// <summary> /// Gets or sets the total number of elements the internal data structure can hold without resizing. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><see cref="Capacity"/> cannot be set to a value less than <see cref="Count"/>.</exception> public int Capacity { get { return _buffer.Length; } set { if (value < Count) throw new ArgumentOutOfRangeException("value", "capacity was less than the current size."); if (value == Capacity) return; T[] newBuffer = new T[value]; CopyTo(newBuffer, 0); LeftIndex = 0; _buffer = newBuffer; } } /// <summary> /// Determines whether the deque "loops around" the array's boundary, i.e., whether the rightmost's index is lower than the leftmost's. /// </summary> /// <returns>true if the deque loops around the array's boundary; false otherwise.</returns> private bool LoopsAround { get { return Count > (Capacity - LeftIndex); } } private int LeftIndex { get { return _leftIndex; } set { _leftIndex = CalcIndex(value); } } private T Left { get { return this[0]; } set { this[0] = value; } } private T Right { get { return this[Count - 1]; } set { this[Count - 1] = value; } } /// <summary> /// Gets or sets the item at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <returns>The element at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException">Index was out of range. Must be non-negative and less than <see cref="ICollection{T}.Count"/>.</exception> public T this[int index] { get { return _buffer[VirtualIndexToBufferIndex(index)]; } set { _buffer[VirtualIndexToBufferIndex(index)] = value; } } /// <summary> /// Supports a simple iteration over a generic <see cref="Deque{T}"/>. /// </summary> public struct Enumerator : IEnumerator<T> { private readonly Deque<T> _deque; private readonly int _version; private T _current; //the index of the current item in the deque private int _virtualIndex; internal Enumerator(Deque<T> deque) { _deque = deque; _version = _deque._version; _current = default(T); _virtualIndex = -1; } /// <summary> /// Advances the enumerator to the next element of the deque. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public bool MoveNext() { Validate(); if (_virtualIndex == _deque.Count -1) return false; _virtualIndex++; _current = _deque[_virtualIndex]; return true; } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> void IEnumerator.Reset() { Validate(); _virtualIndex = -1; _current = default(T); } /// <summary> /// Gets the element in the <see cref="Deque{T}"/> at the current position of the enumerator. /// </summary> public T Current { get { return _current; } } object IEnumerator.Current { get { return Current; } } /// <summary> /// Releases the enumerator's resources. /// </summary> public void Dispose() { } /// <summary> /// Verify that the deque hasn't been modified. /// </summary> private void Validate() { if (_version != _deque._version) throw new InvalidOperationException("Collection was modified; enumeration operation may not execute."); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using MSBuild = Microsoft.Build.BuildEngine; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using System.Runtime.InteropServices; using System.Reflection; using System.Windows.Forms; using System.Globalization; using System.Linq; using Microsoft.Build.Construction; namespace Microsoft.VisualStudio.FSharp.ProjectSystem { /// <summary> /// Creates projects within the solution /// </summary> internal abstract class ProjectFactory : Microsoft.VisualStudio.Shell.Flavor.FlavoredProjectFactoryBase , IVsProjectUpgradeViaFactory, IVsProjectUpgradeViaFactory4 { private Microsoft.VisualStudio.Shell.Package package; private System.IServiceProvider site; private Microsoft.Build.Evaluation.ProjectCollection buildEngine; private Microsoft.Build.Evaluation.Project buildProject; public Microsoft.VisualStudio.Shell.Package Package { get { return this.package; } } public System.IServiceProvider Site { get { return this.site; } } /// <summary> /// The msbuild engine that we are going to use. /// </summary> public Microsoft.Build.Evaluation.ProjectCollection BuildEngine { get { return this.buildEngine; } } /// <summary> /// The msbuild project for the temporary project file. /// </summary> public Microsoft.Build.Evaluation.Project BuildProject { get { return this.buildProject; } set { this.buildProject = value; } } public ProjectFactory(Microsoft.VisualStudio.Shell.Package package) { this.package = package; this.site = package; this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine); } protected abstract ProjectNode CreateProject(); /// <summary> /// Rather than directly creating the project, ask VS to initate the process of /// creating an aggregated project in case we are flavored. We will be called /// on the IVsAggregatableProjectFactory to do the real project creation. /// </summary> /// <param name="fileName">Project file</param> /// <param name="location">Path of the project</param> /// <param name="name">Project Name</param> /// <param name="flags">Creation flags</param> /// <param name="projectGuid">Guid of the project</param> /// <param name="project">Project that end up being created by this method</param> /// <param name="canceled">Was the project creation canceled</param> protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled) { project = IntPtr.Zero; canceled = 0; if ((flags & ((uint)__VSCREATEPROJFLAGS2.CPF_DEFERREDSAVE)) != 0) { throw new NotSupportedException(SR.GetString(SR.NoZeroImpactProjects)); } #if FX_ATLEAST_45 if ((flags & ((uint)__VSCREATEPROJFLAGS.CPF_OPENFILE)) != 0) { if (new ProjectInspector(fileName).IsPoisoned(Site)) { // error out int ehr = unchecked((int)0x80042003); // VS_E_INCOMPATIBLEPROJECT ErrorHandler.ThrowOnFailure(ehr); } } #endif // Get the list of GUIDs from the project/template string guidsList = this.ProjectTypeGuids(fileName); // Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation) IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject)); int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project); if (hr == VSConstants.E_ABORT) canceled = 1; ErrorHandler.ThrowOnFailure(hr); this.buildProject = null; } /// <summary> /// Instantiate the project class, but do not proceed with the /// initialization just yet. /// Delegate to CreateProject implemented by the derived class. /// </summary> protected override object PreCreateForOuter(IntPtr outerProjectIUnknown) { Debug.Assert(this.buildProject != null, "The build project should have been initialized before calling PreCreateForOuter."); // Please be very carefull what is initialized here on the ProjectNode. Normally this should only instantiate and return a project node. // The reason why one should very carefully add state to the project node here is that at this point the aggregation has not yet been created and anything that would cause a CCW for the project to be created would cause the aggregation to fail // Our reasoning is that there is no other place where state on the project node can be set that is known by the Factory and has to execute before the Load method. ProjectNode node = this.CreateProject(); Debug.Assert(node != null, "The project failed to be created"); node.BuildEngine = this.buildEngine; node.BuildProject = this.buildProject; node.Package = this.package as ProjectPackage; node.ProjectEventsProvider = GetProjectEventsProvider(); return node; } /// <summary> /// Retrives the list of project guids from the project file. /// If you don't want your project to be flavorable, override /// to only return your project factory Guid: /// return this.GetType().GUID.ToString("B"); /// </summary> /// <param name="file">Project file to look into to find the Guid list</param> /// <returns>List of semi-colon separated GUIDs</returns> protected override string ProjectTypeGuids(string file) { // Load the project so we can extract the list of GUIDs this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject); // Retrieve the list of GUIDs, if it is not specify, make it our GUID string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids); if (String.IsNullOrEmpty(guids)) guids = this.GetType().GUID.ToString("B"); return guids; } #if FX_ATLEAST_45 private class ProjectInspector { private Microsoft.Build.Construction.ProjectRootElement xmlProj; private const string MinimumVisualStudioVersion = "MinimumVisualStudioVersion"; public ProjectInspector(string filename) { try { xmlProj = Microsoft.Build.Construction.ProjectRootElement.Open(filename); } catch (Microsoft.Build.BuildEngine.InvalidProjectFileException) { // leave xmlProj non-initialized, other methods will check its state in prologue } } /// we consider project to be Dev10- if it doesn't have any imports that belong to higher versions public bool IsLikeDev10MinusProject() { if (xmlProj == null) return false; const string fsharpFS45TargetsPath = @"$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets"; const string fsharpPortableDev11TargetsPath = @"$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.Portable.FSharp.Targets"; // Dev12+ projects import *.targets files using property const string fsharpDev12PlusImportsValue = @"$(FSharpTargetsPath)"; foreach(var import in xmlProj.Imports) { if ( IsEqual(import.Project, fsharpFS45TargetsPath) || IsEqual(import.Project, fsharpPortableDev11TargetsPath) || IsEqual(import.Project, fsharpDev12PlusImportsValue) ) { return false; } } return true; } private bool IsEqual(string s1, string s2) { return string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase); } public bool IsPoisoned(System.IServiceProvider sp) { if (xmlProj == null) return false; // use IVsAppCompat service to determine current VS version var appCompatService = (IVsAppCompat)sp.GetService(typeof(SVsSolution)); string currentDesignTimeCompatVersionString = null; appCompatService.GetCurrentDesignTimeCompatVersion(out currentDesignTimeCompatVersionString); // currentDesignTimeCompatVersionString can look like 12.0 // code in vsproject\vsproject\vsprjfactory.cpp uses _wtoi that will ignore part of string after dot // we'll do the same trick var indexOfDot = currentDesignTimeCompatVersionString.IndexOf('.'); if (indexOfDot != -1) { currentDesignTimeCompatVersionString = currentDesignTimeCompatVersionString.Substring(0, indexOfDot); } var currentDesignTimeCompatVersion = int.Parse(currentDesignTimeCompatVersionString); foreach (var pg in xmlProj.PropertyGroups) { foreach (var p in pg.Properties) { if (string.CompareOrdinal(p.Name, MinimumVisualStudioVersion) == 0) { var s = p.Value; if (!string.IsNullOrEmpty(s)) { int ver; int.TryParse(s, out ver); if (ver > currentDesignTimeCompatVersion) return true; } } } } return false; } } #endif private IProjectEvents GetProjectEventsProvider() { ProjectPackage projectPackage = this.package as ProjectPackage; Debug.Assert(projectPackage != null, "Package not inherited from framework"); if (projectPackage != null) { foreach (SolutionListener listener in projectPackage.SolutionListeners) { IProjectEvents projectEvents = listener as IProjectEvents; if (projectEvents != null) { return projectEvents; } } } return null; } private string m_lastUpgradedProjectFile; private const string SCC_PROJECT_NAME = "SccProjectName"; private string m_sccProjectName; private const string SCC_AUX_PATH = "SccAuxPath"; private string m_sccAuxPath; private const string SCC_LOCAL_PATH = "SccLocalPath"; private string m_sccLocalPath; private const string SCC_PROVIDER = "SccProvider"; private string m_sccProvider; public virtual int GetSccInfo(string projectFileName, out string sccProjectName, out string sccAuxPath, out string sccLocalPath, out string provider) { // we should only be asked for SCC info on a project that we have just upgraded. if (!String.Equals(this.m_lastUpgradedProjectFile, projectFileName, StringComparison.OrdinalIgnoreCase)) { sccProjectName = ""; sccAuxPath = ""; sccLocalPath = ""; provider = ""; return VSConstants.E_FAIL; } sccProjectName = this.m_sccProjectName; sccAuxPath = this.m_sccAuxPath; sccLocalPath = this.m_sccLocalPath; provider = this.m_sccProvider; return VSConstants.S_OK; } int IVsProjectUpgradeViaFactory.UpgradeProject_CheckOnly(string projectFileName, IVsUpgradeLogger upgradeLogger, out int upgradeRequired, out Guid newProjectFactory, out uint upgradeCapabilityFlags) { __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS upgradeRequiredFlag; var hr = DoUpgradeProject_CheckOnly(projectFileName, upgradeLogger, out upgradeRequiredFlag, out newProjectFactory, out upgradeCapabilityFlags); upgradeRequired = upgradeRequiredFlag != __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR ? 1 : 0; return hr; } void IVsProjectUpgradeViaFactory4.UpgradeProject_CheckOnly(string projectFileName, IVsUpgradeLogger upgradeLogger, out uint upgradeRequired, out Guid newProjectFactory, out uint upgradeCapabilityFlags) { __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS upgradeRequiredFlag; DoUpgradeProject_CheckOnly(projectFileName, upgradeLogger, out upgradeRequiredFlag, out newProjectFactory, out upgradeCapabilityFlags); upgradeRequired = (uint)upgradeRequiredFlag; } public virtual int DoUpgradeProject_CheckOnly(string projectFileName, IVsUpgradeLogger upgradeLogger, out __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS upgradeRequired, out Guid newProjectFactory, out uint upgradeCapabilityFlags) { newProjectFactory = GetType().GUID; var project = ProjectRootElement.Open(projectFileName); // enable Side-by-Side and CopyBackup support upgradeCapabilityFlags = (uint)(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP); #if FX_ATLEAST_45 if (this.buildEngine.GetLoadedProjects(projectFileName).Count > 0) { // project has already been loaded upgradeRequired = __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; return VSConstants.S_OK; } var projectInspector = new ProjectInspector(projectFileName); if (projectInspector.IsPoisoned(Site)) { // poisoned project cannot be opened (does not require upgrade) upgradeRequired = __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; return VSConstants.S_OK; } #endif // only upgrade known tool versions. #if FX_ATLEAST_45 if (string.Equals("4.0", project.ToolsVersion, StringComparison.Ordinal)) { // For 4.0, we need to take a deeper look. The logic is in // vsproject\xmake\XMakeConversion\ProjectFileConverter.cs var projectConverter = new Microsoft.Build.Conversion.ProjectFileConverter(); projectConverter.OldProjectFile = projectFileName; projectConverter.NewProjectFile = projectFileName; if (projectConverter.FSharpSpecificConversions(false)) { upgradeRequired = projectInspector.IsLikeDev10MinusProject() ? __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_ONEWAYUPGRADE : __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_SAFEREPAIR; return VSConstants.S_OK; } else { upgradeRequired = __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; return VSConstants.S_OK; } } else #endif if (string.Equals("3.5", project.ToolsVersion, StringComparison.Ordinal) || string.Equals("2.0", project.ToolsVersion, StringComparison.Ordinal)) { // For 3.5 or 2.0, we always need to upgrade. upgradeRequired = __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_ONEWAYUPGRADE; return VSConstants.S_OK; } upgradeRequired = __VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; return VSConstants.S_OK; } private int NormalizeUpgradeFlag(uint upgradeFlag, out __VSPPROJECTUPGRADEVIAFACTORYFLAGS flag, ref string copyLocation) { flag = (__VSPPROJECTUPGRADEVIAFACTORYFLAGS)upgradeFlag; // normalize flags switch (flag) { case __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP: case __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP: break; default: // ignore unknown flags flag &= (__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP); break; } //if copy upgrade, then we need a copy location that ends in a backslash. if (HasCopyBackupFlag(flag)) { if (string.IsNullOrEmpty(copyLocation) || copyLocation[copyLocation.Length - 1] != '\\') { if (HasSxSBackupFlag(flag)) { //if both SxS AND CopyBack were specified, then fall back to SxS flag &= ~__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP; } else { //Only CopyBackup was specified and an invalid backup location was given, so bail return VSConstants.E_INVALIDARG; } } else { //Favor copy backup to SxS backup flag &= ~__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP; } } return VSConstants.S_OK; } public virtual int UpgradeProject( string projectFilePath, uint upgradeFlag, string initialCopyLocation, out string upgradeFullyQualifiedFileName, IVsUpgradeLogger upgradeLogger, out int upgradeRequired, out Guid newProjectFactory ) { // initialize out params in case of failure upgradeFullyQualifiedFileName = null; upgradeRequired = 0; newProjectFactory = Guid.Empty; __VSPPROJECTUPGRADEVIAFACTORYFLAGS flag; string copyLocation = initialCopyLocation; var r = NormalizeUpgradeFlag(upgradeFlag, out flag, ref copyLocation); if (r != VSConstants.S_OK) { return r; } string projectName = Path.GetFileNameWithoutExtension(projectFilePath); var logger = new ProjectUpgradeLogger(upgradeLogger, projectName, projectFilePath); uint ignore; ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly(projectFilePath, upgradeLogger, out upgradeRequired, out newProjectFactory, out ignore); // no upgrade required and not 'copy-backup' if (upgradeRequired == 0 && !HasCopyBackupFlag(flag)) { //Write an informational message "No upgrade required for project foo"? logger.LogInfo(SR.GetString(SR.ProjectConversionNotRequired)); logger.LogInfo(SR.GetString(SR.ConversionNotRequired)); upgradeFullyQualifiedFileName = projectFilePath; return VSConstants.S_OK; } // upgrade is not required but backup may still be needed var projectFileName = Path.GetFileName(projectFilePath); upgradeFullyQualifiedFileName = projectFilePath; if (HasSxSBackupFlag(flag)) { // for SxS call use location near the original file copyLocation = Path.GetDirectoryName(projectFilePath); } // workflow is taken from vsprjfactory.cpp (vsproject\vsproject) // 1. convert the project (in-memory) // 2. save SCC related info // 3. use data stored on step 2 in GetSccInfo calls (during QueryEditFiles) // 4. if succeeded - save project on disk // F# doesn't use .user file so all related code is skipped try { // load MSBuild project in memory: this will be needed in all cases not depending whether upgrade is required or not // we use this project to determine the set of files to copy ProjectRootElement convertedProject = ConvertProject(projectFilePath, logger); if (convertedProject == null) { throw new ProjectUpgradeFailedException(); } // OK, we need upgrade, save SCC info and ask if project file can be edited if (upgradeRequired != 0) { // 2. save SCC related info this.m_lastUpgradedProjectFile = projectFilePath; foreach (var property in convertedProject.Properties) { switch (property.Name) { case SCC_LOCAL_PATH: this.m_sccLocalPath = property.Value; break; case SCC_AUX_PATH: this.m_sccAuxPath = property.Value; break; case SCC_PROVIDER: this.m_sccProvider = property.Value; break; case SCC_PROJECT_NAME: this.m_sccProjectName = property.Value; break; default: break; } } // 3. Query for edit (this call may query information stored on previous step) IVsQueryEditQuerySave2 queryEdit = site.GetService(typeof(SVsQueryEditQuerySave)) as IVsQueryEditQuerySave2; if (queryEdit != null) { uint editVerdict; uint queryEditMoreInfo; const tagVSQueryEditFlags tagVSQueryEditFlags_QEF_AllowUnopenedProjects = (tagVSQueryEditFlags)0x80; int hr = queryEdit.QueryEditFiles( (uint)(tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting | tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | tagVSQueryEditFlags_QEF_AllowUnopenedProjects), 1, new[] { projectFilePath }, null, null, out editVerdict, out queryEditMoreInfo); if (ErrorHandler.Failed(hr)) { throw new ProjectUpgradeFailedException(); } if (editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new ProjectUpgradeFailedException(SR.GetString(SR.UpgradeCannotOpenProjectFileForEdit)); } // If file was modified during the checkout, maybe upgrade is not needed if ((queryEditMoreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly(projectFilePath, upgradeLogger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { if (logger != null) { logger.LogInfo(SR.GetString(SR.UpgradeNoNeedToUpgradeAfterCheckout)); } return VSConstants.S_OK; } } } } // 3.1 copy backup BackupProjectFilesIfNeeded(projectFilePath, logger, flag, copyLocation, convertedProject); // 4. if we have performed upgrade - save project to disk if (upgradeRequired != 0) { try { convertedProject.Save(projectFilePath); } catch (Exception ex) { throw new ProjectUpgradeFailedException(ex.Message, ex); } } // 821083: "Converted" should NOT be localized - it is referenced in the XSLT used to display the UpgradeReport logger.LogStatus("Converted"); } catch (ProjectUpgradeFailedException ex) { var exception = ex.InnerException ?? ex; if (exception != null && !string.IsNullOrEmpty(exception.Message)) logger.LogError(exception.Message); upgradeFullyQualifiedFileName = ""; m_lastUpgradedProjectFile = null; return VSConstants.E_FAIL; } return VSConstants.S_OK; } private void BackupProjectFilesIfNeeded( string projectFilePath, ProjectUpgradeLogger logger, __VSPPROJECTUPGRADEVIAFACTORYFLAGS flag, string copyLocation, ProjectRootElement convertedProject ) { var projectName = Path.GetFileNameWithoutExtension(projectFilePath); var projectFileName = Path.GetFileName(projectFilePath); if (HasCopyBackupFlag(flag) || HasSxSBackupFlag(flag)) { if (HasSxSBackupFlag(flag) && !Directory.Exists(copyLocation)) { Debug.Assert(false, "Env should create the directory for us"); throw new ProjectUpgradeFailedException(); } // copy project file { var targetFilePath = Path.Combine(copyLocation, projectFileName); if (HasSxSBackupFlag(flag)) { bool ignored; targetFilePath = GetUniqueFileName(targetFilePath + ".old", out ignored); } try { File.Copy(projectFilePath, targetFilePath); logger.LogInfo(SR.GetString(SR.ProjectBackupSuccessful, targetFilePath)); } catch (Exception ex) { var message = SR.GetString(SR.ErrorMakingProjectBackup, targetFilePath); throw new ProjectUpgradeFailedException(string.Format("{0} : {1}", message, ex.Message)); } } if (HasCopyBackupFlag(flag)) { //Now iterate through the project items and copy them to the new location //All projects under the solution retain its folder hierarchy var types = new[] { "Compile", "None", "Content", "EmbeddedResource", "Resource", "BaseApplicationManifest", "ApplicationDefinition", "Page" }; var metadataLookup = convertedProject .Items .GroupBy(i => i.ItemType) .ToDictionary(x => x.Key); var sourceProjectDir = Path.GetDirectoryName(projectFilePath); foreach (var ty in types) { if (metadataLookup.ContainsKey(ty)) { foreach (var item in metadataLookup[ty]) { var linkMetadataElement = item.Metadata.FirstOrDefault(me => me.Name == "Link"); string linked = linkMetadataElement != null && !string.IsNullOrEmpty(linkMetadataElement.Value) ? linkMetadataElement.Value : null; var include = item.Include; Debug.Assert(!string.IsNullOrEmpty(include)); string sourceFilePath; var targetFileName = Path.Combine(copyLocation, linked ?? include); if (Path.IsPathRooted(include)) { //if the path is fully qualified already, then just use it sourceFilePath = include; } else { //otherwise tack the filename on to the path sourceFilePath = Path.Combine(sourceProjectDir, include); } if (linked != null && include[0] == '.') { //if linked file up a level (or more), then turn it into a path without the ..\ in the middle sourceFilePath = Path.GetFullPath(sourceFilePath); } bool initiallyUnique; targetFileName = GetUniqueFileName(targetFileName, out initiallyUnique); if (!initiallyUnique) { logger.LogInfo(SR.GetString(SR.BackupNameConflict, targetFileName)); } //Warn user in upgrade log if linked files are used "project may not build" if (linked != null && HasCopyBackupFlag(flag)) { logger.LogWarning(SR.GetString(SR.ProjectContainsLinkedFile, targetFileName)); } // ensure target folder exists Directory.CreateDirectory(Path.GetDirectoryName(targetFileName)); try { File.Copy(sourceFilePath, targetFileName); logger.LogInfo(SR.GetString(SR.BackupSuccessful, targetFileName)); } catch (Exception ex) { var message = SR.GetString(SR.ErrorMakingBackup, targetFileName); logger.LogError(string.Format("{0} : {1}", message, ex.Message)); } } } } } } } /// <summary> /// Allows to avoid repeatable checks if logger exists + provides more convinient interface /// </summary> private class ProjectUpgradeLogger { private Action<__VSUL_ERRORLEVEL, string> write; public ProjectUpgradeLogger(IVsUpgradeLogger logger, string projectName, string projectFileName) { if (logger != null) { write = (errLevel, message) => logger.LogMessage((uint)errLevel, projectName, projectFileName, message) ; } else { write = delegate { }; } } public void LogInfo(string message) { write(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, message); } public void LogWarning(string message) { write(__VSUL_ERRORLEVEL.VSUL_WARNING, message); } public void LogError(string message) { write(__VSUL_ERRORLEVEL.VSUL_ERROR, message); } public void LogStatus(string message) { write(__VSUL_ERRORLEVEL.VSUL_STATUSMSG, message); } } private class ProjectUpgradeFailedException : Exception { public ProjectUpgradeFailedException() : base() { } public ProjectUpgradeFailedException(string message) : base(message) { } public ProjectUpgradeFailedException(string message, Exception inner) : base(message, inner) { } } /// <summary> /// Performs in-memory conversion of the project with a given path /// </summary> /// <returns>Root element of the converted project or <c>null</c> if conversion failed.</returns> private ProjectRootElement ConvertProject(string projectFileName, ProjectUpgradeLogger logger) { var projectConverter = new Microsoft.Build.Conversion.ProjectFileConverter(); projectConverter.OldProjectFile = projectFileName; projectConverter.NewProjectFile = projectFileName; ProjectRootElement convertedProject = null; try { convertedProject = projectConverter.ConvertInMemory(); } catch (Exception ex) { logger.LogInfo(ex.Message); } return convertedProject; } /// <summary> /// Helper for checking if flag has PUVFF_SXSBACKUP value /// </summary> private static bool HasSxSBackupFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS flag) { return flag.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP); } /// <summary> /// Helper for checking if flag has PUVFF_COPYBACKUP value /// </summary> private static bool HasCopyBackupFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS flag) { return flag.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP); } /// <summary> /// Generates unique name for the given path by appending 0..n to the file name /// </summary> /// <param name="initialPath">Initial location</param> /// <param name="initiallyUnique"><c>true</c> if original file name was already unique, otherwise - <c>false</c></param> /// <returns>Unique file path</returns> private string GetUniqueFileName(string initialPath, out bool initiallyUnique) { initiallyUnique = true; if (!File.Exists(initialPath)) return initialPath; initiallyUnique = false; var originalExtension = Path.GetExtension(initialPath); var pathSansExtension = Path.Combine(Path.GetDirectoryName(initialPath), Path.GetFileNameWithoutExtension(initialPath)); var i = 1; while(true) { var f = string.Format("{0}{1}{2}", pathSansExtension, i, originalExtension); if (!File.Exists(f)) return f; i++; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogical128BitLaneUInt641() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt64); private const int RetElementCount = VectorSize / sizeof(UInt64); private static UInt64[] _data = new UInt64[Op1ElementCount]; private static Vector128<UInt64> _clsVar; private Vector128<UInt64> _fld; private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable; static SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)8; } _dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftLeftLogical128BitLane( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneUInt641(); var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { if (result[0] != 2048) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 2048) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical128BitLane)}<UInt64>(Vector128<UInt64><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
namespace PokerTell.Statistics.Tests.ViewModels.Analyzation { using System; using System.Collections.Generic; using System.Linq; using Infrastructure.Enumerations.PokerHand; using Infrastructure.Interfaces.PokerHand; using Infrastructure.Services; using Interfaces; using Machine.Specifications; using Moq; using Statistics.ViewModels.Analyzation; using Tools.FunctionalCSharp; using Tools.Interfaces; using It = Machine.Specifications.It; // ReSharper disable InconsistentNaming public abstract class DetailedRaiseReactionStatisticsViewModelSpecs { protected static Mock<IAnalyzablePokerPlayer> _analyzablePokerPlayerStub; protected static Dictionary<int, int> _emptyCountsDictionary; protected static Dictionary<int, int> _emptyPercentageDictionary; protected static Mock<IRepositoryHandBrowserViewModel> _handBrowserViewModelMock; protected static string _playerName; protected static Constructor<IRaiseReactionAnalyzer> _raiseReactionAnalyzerMake; protected static Mock<IRaiseReactionAnalyzer> _raiseReactionAnalyzerStub; protected static Mock<IRaiseReactionDescriber<double>> _raiseReactionDescriberStub; protected static Mock<IRaiseReactionStatisticsBuilder> _raiseReactionStatisticsBuilderMock; protected static Mock<IRaiseReactionStatistics> _raiseReactionStatisticsStub; protected static DetailedRaiseReactionStatisticsViewModelImpl _sut; protected static ActionSequences _validActionSequence; protected static IAnalyzablePokerPlayer[] _validAnalyzablePokerPlayersStub; protected static ITuple<double, double> _validBetSizes; protected static bool _considerOpponentsRaiseSize; protected static Streets _validStreet; Establish context = () => { _playerName = "somePlayer"; _validStreet = Streets.Flop; _validActionSequence = ActionSequences.HeroB; _validBetSizes = Tuple.New(0.5, 0.7); _analyzablePokerPlayerStub = new Mock<IAnalyzablePokerPlayer>(); _validAnalyzablePokerPlayersStub = new[] { _analyzablePokerPlayerStub.Object }; _considerOpponentsRaiseSize = false; _raiseReactionStatisticsStub = new Mock<IRaiseReactionStatistics>(); _emptyPercentageDictionary = new Dictionary<int, int>(); _emptyCountsDictionary = new Dictionary<int, int>(); _raiseReactionStatisticsStub.SetupGet(r => r.PercentagesDictionary).Returns( new Dictionary<ActionTypes, IDictionary<int, int>> { { ActionTypes.F, _emptyPercentageDictionary }, { ActionTypes.C, _emptyPercentageDictionary }, { ActionTypes.R, _emptyPercentageDictionary } }); _raiseReactionStatisticsStub.SetupGet(r => r.TotalCountsByColumnDictionary) .Returns(_emptyCountsDictionary); _raiseReactionAnalyzerStub = new Mock<IRaiseReactionAnalyzer>(); _raiseReactionAnalyzerMake = new Constructor<IRaiseReactionAnalyzer>(() => _raiseReactionAnalyzerStub.Object); _handBrowserViewModelMock = new Mock<IRepositoryHandBrowserViewModel>(); _raiseReactionStatisticsBuilderMock = new Mock<IRaiseReactionStatisticsBuilder>(); _raiseReactionStatisticsBuilderMock .Setup(b => b.Build(_validAnalyzablePokerPlayersStub, _validActionSequence, _validStreet, _considerOpponentsRaiseSize)) .Returns(_raiseReactionStatisticsStub.Object); _raiseReactionDescriberStub = new Mock<IRaiseReactionDescriber<double>>(); _sut = new DetailedRaiseReactionStatisticsViewModelImpl( _handBrowserViewModelMock.Object, _raiseReactionStatisticsBuilderMock.Object, _raiseReactionDescriberStub.Object); }; } public class DetailedRaiseReactionStatisticsViewModelImpl : DetailedRaiseReactionStatisticsViewModel<double> { public DetailedRaiseReactionStatisticsViewModelImpl(IRepositoryHandBrowserViewModel handBrowserViewModel, IRaiseReactionStatisticsBuilder raiseReactionStatisticsBuilder, IRaiseReactionDescriber<double> raiseReactionDescriber) : base(handBrowserViewModel, raiseReactionStatisticsBuilder, raiseReactionDescriber) { } internal List<IAnalyzablePokerPlayer> SelectedAnalyzablePlayersSet { private get; set; } protected override IEnumerable<IAnalyzablePokerPlayer> SelectedAnalyzablePlayers { get { return SelectedAnalyzablePlayersSet; } } } public abstract class Ctx_DetailedRaiseReactionStatisticsViewModel_Initialized : DetailedRaiseReactionStatisticsViewModelSpecs { Establish context = () => _sut.InitializeWith(_validAnalyzablePokerPlayersStub, _validBetSizes, _playerName, _validActionSequence, _validStreet); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Initialization")] public class given_0_analyzable_players : DetailedRaiseReactionStatisticsViewModelSpecs { static Exception exception; Because of = () => exception = Catch.Exception( () => _sut.InitializeWith(Enumerable.Empty<IAnalyzablePokerPlayer>(), _validBetSizes, _playerName, _validActionSequence, _validStreet)); It should_throw_an_ArgumentException = () => exception.ShouldBeOfType<ArgumentException>(); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Initialization")] public class given_valid_data : DetailedRaiseReactionStatisticsViewModelSpecs { static string description; Establish context = () => { description = "some description"; _raiseReactionDescriberStub.Setup( d => d.Describe(_playerName, _validAnalyzablePokerPlayersStub.First(), _validStreet, _validBetSizes)) .Returns(description); }; Because of = () => _sut.InitializeWith(_validAnalyzablePokerPlayersStub, _validBetSizes, _playerName, _validActionSequence, _validStreet); It should_build_raise_reaction_statistics_for_it = () => _raiseReactionStatisticsBuilderMock.Verify(b => b.Build(_validAnalyzablePokerPlayersStub, _validActionSequence, _validStreet, _considerOpponentsRaiseSize)); It should_get_statistics_description_from_raise_reaction_describer = () => _sut.StatisticsDescription.ShouldEqual(description); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Initialization")] public class given_valid_data_and_valid_RaiseReactionStatistics : DetailedRaiseReactionStatisticsViewModelSpecs { Establish context = () => { _emptyPercentageDictionary.Add(1, 0); _emptyPercentageDictionary.Add(2, 0); _raiseReactionStatisticsStub.SetupGet(r => r.PercentagesDictionary).Returns( new Dictionary<ActionTypes, IDictionary<int, int>> { { ActionTypes.F, _emptyPercentageDictionary }, { ActionTypes.C, _emptyPercentageDictionary }, { ActionTypes.R, _emptyPercentageDictionary } }); }; Because of = () => _sut.InitializeWith(_validAnalyzablePokerPlayersStub, _validBetSizes, _playerName, _validActionSequence, _validStreet); It should_create_4_rows = () => _sut.Rows.Count().ShouldEqual(4); It should_create_one_column_for_each_item_in_the_statistics_PercentagesDictionary = () => _sut.Rows.First().Cells.Count.ShouldEqual(_emptyPercentageDictionary.Count); It should_create_the_first_second_and_third_row_with_percentage_unit = () => { _sut.Rows.First().Unit.ShouldEqual("%"); _sut.Rows.ElementAt(1).Unit.ShouldEqual("%"); _sut.Rows.ElementAt(2).Unit.ShouldEqual("%"); }; It should_create_the_fourth_row_without_a_unit_since_it_shows_the_counts = () => _sut.Rows.Last().Unit.ShouldBeEmpty(); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Initialization")] public class given_the_PercentagesDictionary_has_value_0_at_0_0_and_value_50_at_1_1 : DetailedRaiseReactionStatisticsViewModelSpecs { Establish context = () => _raiseReactionStatisticsStub.SetupGet(r => r.PercentagesDictionary).Returns( new Dictionary<ActionTypes, IDictionary<int, int>> { { ActionTypes.F, new Dictionary<int, int> { { 1, 0 }, { 2, 0 } } }, { ActionTypes.C, new Dictionary<int, int> { { 1, 0 }, { 2, 50 } } }, { ActionTypes.R, _emptyPercentageDictionary } }); Because of = () => _sut.InitializeWith(_validAnalyzablePokerPlayersStub, _validBetSizes, _playerName, _validActionSequence, _validStreet); It should_have_value_0_at_row_0_col_0 = () => _sut.Rows.ElementAt(0).Cells[0].Value.ShouldEqual("0"); It should_have_value_50_at_row_1_col_1 = () => _sut.Rows.ElementAt(1).Cells[1].Value.ShouldEqual("50"); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Initialization")] public class given_the_TotalCountsDictionary_has_value_0_in_col_0_and_value_1_in_col_1 : DetailedRaiseReactionStatisticsViewModelSpecs { Establish context = () => _raiseReactionStatisticsStub.SetupGet(r => r.TotalCountsByColumnDictionary).Returns( new Dictionary<int, int> { { 1, 0 }, { 2, 1 } }); Because of = () => _sut.InitializeWith(_validAnalyzablePokerPlayersStub, _validBetSizes, _playerName, _validActionSequence, _validStreet); It should_have_value_0_in_the_counts_row_at_col_0 = () => _sut.Rows.Last().Cells[0].Value.ShouldEqual("0"); It should_have_value_1_in_the_counts_row_at_col_1 = () => _sut.Rows.Last().Cells[1].Value.ShouldEqual("1"); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Browse hands command")] public class given_no_cell_has_been_selected : Ctx_DetailedRaiseReactionStatisticsViewModel_Initialized { It should_not_be_executable = () => _sut.BrowseHandsCommand.CanExecute(null).ShouldBeFalse(); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Browse hands command")] public class given_one_cell_has_been_selected_but_it_contains_no_analyzable_players : Ctx_DetailedRaiseReactionStatisticsViewModel_Initialized { Establish context = () => { _sut.AddToSelection(0, 0); _sut.SelectedAnalyzablePlayersSet = new List<IAnalyzablePokerPlayer>(); }; It should_not_be_executable = () => _sut.BrowseHandsCommand.CanExecute(null).ShouldBeFalse(); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Browse hands command")] public class given_one_cell_is_selected_and_it_contains_analyzable_players : Ctx_DetailedRaiseReactionStatisticsViewModel_Initialized { Establish context = () => { _sut.AddToSelection(0, 0); _sut.SelectedAnalyzablePlayersSet = _validAnalyzablePokerPlayersStub.ToList(); }; It should_be_executable = () => _sut.BrowseHandsCommand.CanExecute(null).ShouldBeTrue(); } [Subject(typeof(DetailedRaiseReactionStatisticsViewModel<double>), "Browse hands command")] public class given_one_cell_is_selected_and_the_user_executes_the_command : Ctx_DetailedRaiseReactionStatisticsViewModel_Initialized { Establish context = () => { _sut.AddToSelection(0, 0); _sut.SelectedAnalyzablePlayersSet = _validAnalyzablePokerPlayersStub.ToList(); }; Because of = () => _sut.BrowseHandsCommand.Execute(null); It should_initialize_HandBrowserViewModel_with_the_analyzable_players_who_correspond_to_the_cell_and_the_playerName = () => _handBrowserViewModelMock.Verify(hb => hb.InitializeWith(_validAnalyzablePokerPlayersStub, _playerName)); It should_set_its_ChildViewModel_to_the_HandBrowserViewModel = () => _sut.ChildViewModel.ShouldEqual(_handBrowserViewModelMock.Object); } // ReSharper restore InconsistentNaming }
// 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.Diagnostics; using System.Drawing; using System.Globalization; using System.Windows.Forms; namespace OpenLiveWriter.CoreServices.Layout { public class LayoutHelper { public static void FixupOKCancel(Button buttonOK, Button buttonCancel) { EqualizeButtonWidthsHoriz(AnchorStyles.Right, buttonCancel.Width, int.MaxValue, buttonOK, buttonCancel); } public static void FixupGroupBox(GroupBox groupBox) { FixupGroupBox(8, groupBox); } public static void FixupGroupBox(int pixelsBetween, GroupBox groupBox) { NaturalizeHeightAndDistribute(pixelsBetween, groupBox.Controls); AutoSizeGroupBox(groupBox); } public static void AutoSizeGroupBox(GroupBox groupBox) { ArrayList childControls = new ArrayList(groupBox.Controls); if (childControls.Count < 1) return; childControls.Sort(new SortByVerticalPosition()); groupBox.Height = ((Control) childControls[childControls.Count - 1]).Bottom + 12; } /// <summary> /// Naturalizes height, then distributes vertically ACCORDING TO THEIR Y COORDINATE /// </summary> public static void NaturalizeHeightAndDistribute(int pixelsBetween, Control.ControlCollection controls) { Control[] carr = (Control[])new ArrayList(controls).ToArray(typeof (Control)); NaturalizeHeight(carr); DistributeVertically(pixelsBetween, true, carr); } /// <summary> /// Naturalizes height, then distributes vertically ACCORDING TO THE ORDER YOU PASSED THEM IN /// </summary> public static void NaturalizeHeightAndDistribute(int pixelsBetween, params object[] controls) { NaturalizeHeight(controls); DistributeVertically(pixelsBetween, false, controls); } /// <param name="controls">Objects of type Control or ControlGroup</param> public static void NaturalizeHeight(params object[] controls) { foreach (object o in controls) { if (!(o is ControlGroup)) { Control c = (Control) o; // TODO: Fix Windows Forms RTL mirroring! // This alignRight code below is incorrect and may cause a control's location to inadvertently change! Unfortunately, // I'm leaving it there for backwards compatibility. Its very hard to figure out if a control should be aligned right // by just looking at its RightToLeft and Anchor property. For instance: // // Form form1 = new Form(); // form1.RightToLeft = RightToLeft.Yes; // form1.RightToLeftLayout = true; // // Label label1 = new Label(); // label1.Anchor = AnchorStyles.Left; // label1.RightToLeft = RightToLeft.Yes; // // Panel panel1 = new Panel(); // panel1.RightToLeft = RightToLeft.Yes; // // Label label2 = new Label(); // label2.Anchor = AnchorStyles.Left; // label2.RightToLeft = RightToLeft.Yes; // // form1.Controls.Add(label1); // panel1.Controls.Add(label2); // form1.Controls.Add(panel1); // // BidiHelper.RtlLayoutFixup(form1); // Basically a no-op, we'll let the form be auto-mirrored by WinForms. // BidiHelper.RtlLayoutFixup(panel1); // We'll do work in here to fix up the panel. // // // label1's parent is a Form with Form.RightToLeftLayout == true so it will be automatically mirrored by // // WinForms. It's Anchor won't actually change value, but when WinForms lays it out, it will *act* like it // // has its Anchor set to AnchorStyles.Right. // Debug.Assert(label1.Parent == form1); // Debug.Assert(label1.Anchor == AnchorStyles.Left); // // // label2's parent is a Panel whose parent is a Form with Form.RightToLeftLayout == true, however the // // controls inside panel1 will *not* get automatically mirrored by WinForms. In the call to // // BidiHelper.RtlLayoutFixup we'll manually flip label2's Anchor property to force it to act like it's RTL. // Debug.Assert(label2.Parent == panel1); // Debug.Assert(panel1.Parent == form1); // Debug.Assert(label2.Anchor == AnchorStyles.Right); // // See http://www.microsoft.com/middleeast/msdn/WinFormsAndArabic.aspx#_Toc136842131 for more information regarding // the interesting side effects of RTL in WinForms. bool alignRight; if (c.RightToLeft != RightToLeft.Yes) alignRight = (c.Anchor & (AnchorStyles.Right | AnchorStyles.Left)) == AnchorStyles.Right; else alignRight = (c.Anchor & (AnchorStyles.Right | AnchorStyles.Left)) != AnchorStyles.Left; Size newSize = GetNaturalSize(c); int deltaW = c.Width - newSize.Width; c.Size = newSize; if (alignRight) c.Left += deltaW; } } } public static void DistributeVertically(int pixelsBetween, params object[] controls) { DistributeVertically(pixelsBetween, false, controls); } public static void DistributeVertically(int pixelsBetween, bool sortByVerticalPosition, params object[] controls) { if (controls.Length < 2) return; /* Control parent = controls[0].Parent; #if DEBUG for (int i = 1; i < controls.Length; i++) if (parent != controls[i].Parent) Debug.Fail("LayoutHelper.DistributeVertically() called on controls with different parents"); #endif */ pixelsBetween = Ceil(DisplayHelper.ScaleY(pixelsBetween)); if (sortByVerticalPosition) Array.Sort(controls, new SortByVerticalPosition()); int pos = ControlAdapter.Create(controls[0]).Bottom + pixelsBetween; for (int i = 1; i < controls.Length; i++) { ControlAdapter ca = ControlAdapter.Create(controls[i]); if (ca.Visible || !sortByVerticalPosition) { ca.Top = pos; pos = ca.Bottom + pixelsBetween; } } } public static void DistributeHorizontally(int pixelsBetween, params object[] controls) { if (controls.Length < 2) return; /* Control parent = controls[0].Parent; #if DEBUG for (int i = 1; i < controls.Length; i++) if (parent != controls[i].Parent) Debug.Fail("LayoutHelper.DistributeHorizontally() called on controls with different parents"); #endif */ pixelsBetween = Ceil(DisplayHelper.ScaleX(pixelsBetween)); Array.Sort(controls, new SortByHorizontalPosition()); int pos = ControlAdapter.Create(controls[0]).Right + pixelsBetween; for (int i = 1; i < controls.Length; i++) { ControlAdapter ca = ControlAdapter.Create(controls[i]); if (ca.Visible) { ca.Left = pos; pos = ca.Right + pixelsBetween; } } } public static Size GetNaturalSize(object o) { // TODO: Reimplement our usage of Windows Forms! // This method is just a band-aid over the real problem that we don't properly use Windows Forms. By using // TextRender.MeasureText, we are estimating the size of the WinForms control, but our estimate can be wrong if // the control is drawn with different TextFormatFlags than the ones used to measure the control. This entire // method is really just an educated guess of the size of the control. We should not be calling this method on the // same control multiple times and it should NOT be called during a control's OnLoad (which we do in many places) // due to performance issues. We should be able to work around this by using the Control.AutoSize property along // with anchoring and docking in TableLayoutPanels and FlowLayoutPanels. Debug.Assert(o is Control || o is ControlGroup, "GetNaturalSize called with invalid value"); if (o is ControlGroup) { return ((ControlGroup) o).Size; } Control c = (Control) o; if (!(c is CheckBox || c is RadioButton || c is Label)) { return c.Size; } int width = -1; bool useGdi; TextFormatFlags formatFlags = TextFormatFlags.WordBreak; int minHeight = 0; int measuredWidthPadding = 0; int measuredHeightPadding = 0; if (c is CheckBox || c is RadioButton) { width = c.Width; useGdi = !((ButtonBase)c).UseCompatibleTextRendering || ((ButtonBase) c).FlatStyle == FlatStyle.System; Size proposedSize = new Size(c.Width, int.MaxValue); Size prefSize = c.GetPreferredSize(proposedSize); minHeight = prefSize.Height; Size textOnly; if (useGdi) textOnly = TextRenderer.MeasureText(c.Text, c.Font); else { Debug.Assert(useGdi, "Use FlatStyle.System for control " + c.Name); using (Graphics g = c.CreateGraphics()) textOnly = Size.Ceiling(g.MeasureString(c.Text, c.Font)); } measuredWidthPadding = prefSize.Width - textOnly.Width; measuredHeightPadding = (prefSize.Height - textOnly.Height); width -= measuredWidthPadding; } else if (c is LinkLabel) { // In .NET 1.1, LinkLabel was always GDI+. // In .NET 2.0, LinkLabel: // - Is always GDI+ if the link area doesn't cover the whole link // - Is always GDI+ if UseCompatibleTextRendering is true // Both LinkLabel and Label do c.GetPreferredSize without wrapping if FlatStyle = FlatStyle.System LinkLabel link = (LinkLabel)c; if (link.FlatStyle != FlatStyle.System) return c.GetPreferredSize(new Size(c.Width, 0)); useGdi = !link.UseCompatibleTextRendering; } else if (c is Label) { // Both LinkLabel and Label do c.GetPreferredSize without wrapping if FlatStyle = FlatStyle.System // if (((Label)c).FlatStyle != FlatStyle.System) return c.GetPreferredSize(new Size(c.Width, 0)); useGdi = true; if (!((Label)c).UseMnemonic) formatFlags |= TextFormatFlags.NoPrefix; } else { Debug.Fail("This should never happen"); throw new ArgumentException("This should never happen"); } if (width < 0) width = c.Width; Font font = c.Font; string text = c.Text; Size measuredSize; if (!useGdi) { Debug.Fail(string.Format(CultureInfo.InvariantCulture, "Control {0} is unexpectedly using GDI+.", c.Name)); // using (Graphics g = c.CreateGraphics()) // measuredSize = GetNaturalSizeInternal(g, text, font, width); } measuredSize = TextRenderer.MeasureText(text, font, new Size(width, 0), formatFlags); // The +1 is because Windows Forms likes to be sneaky and shrink Labels by 1 pixel when the label becomes visible, // which is just enough to make the label force a line break when measuring text with TextFormatFlags.TextBoxControl // specified. This adds an extra line of whitespace below the Label, which is not what we want. To work around this, // we allow the measuredSize to grow the control by at most one pixel, otherwise we will remeasure the control and // force it to stay within the width we have provided. if (measuredSize.Width > width + 1) { Debug.WriteLine("BUG: TextRenderer.MeasureText returned a larger width than expected: " + new StackTrace()); // WinLive 116755: Using the following flags forces the TextRenderer to measure text with correct character-wrapping. // Without these flags, its possible for the TextRenderer to return a width wider than the proposed width if the text // contains a very long word. I used the TextFormatFlags Utility (TextRendering.exe) from the March 2006 MSDN Magazine // article "Build World-Ready Apps Using Complex Scripts In Windows Forms Controls" to help visualize what each flag // does: http://download.microsoft.com/download/f/2/7/f279e71e-efb0-4155-873d-5554a0608523/TextRendering.exe formatFlags |= TextFormatFlags.TextBoxControl | TextFormatFlags.NoPadding; measuredSize = TextRenderer.MeasureText(text, font, new Size(width, 0), formatFlags); Debug.Assert(measuredSize.Width <= width, "TextRenderer.MeasureText returned a larger width than expected, text may be clipped!"); } measuredSize.Height = Math.Max(minHeight, measuredSize.Height + measuredHeightPadding); return new Size(measuredSize.Width + measuredWidthPadding, measuredSize.Height); } public static IDisposable SuspendAnchoring(params Control[] controls) { return new AnchorSuspension(controls); } private class AnchorSuspension : IDisposable { private Control[] _controls; private readonly AnchorStyles[] _anchorStyles; public AnchorSuspension(Control[] controls) { _anchorStyles = new AnchorStyles[controls.Length]; _controls = controls; for (int i = 0; i < _controls.Length; i++) { Control c = _controls[i]; if (c != null) { _anchorStyles[i] = c.Anchor; c.Anchor = AnchorStyles.Left | AnchorStyles.Top; } } } public void Dispose() { Control[] controls = _controls; _controls = null; if (controls != null) { for (int i = 0; i < controls.Length; i++) { Control c = controls[i]; if (c != null) { c.Anchor = _anchorStyles[i]; } } } } } private static Size GetNaturalSizeInternal(Graphics graphics, string text, Font font, int width) { return Size.Ceiling(graphics.MeasureString(text, font, width)); } private static int Ceil(float f) { return (int) Math.Ceiling(f); } private class SortByVerticalPosition : IComparer { public int Compare(object x, object y) { return ControlAdapter.Create(x).Top - ControlAdapter.Create(y).Top; } } private class SortByHorizontalPosition : IComparer { public int Compare(object x, object y) { return ControlAdapter.Create(x).Left - ControlAdapter.Create(y).Left; } } public static void FitControlsBelow(int pixelPadding, Control c) { ArrayList controls = new ArrayList(c.Parent.Controls); controls.Sort(new SortByVerticalPosition()); int cIndex = controls.IndexOf(c); if (cIndex < 0) { Debug.Fail("Invalid call to FitControlsBelow, the control was not found in the provided control collection"); } else { if (cIndex == controls.Count - 1) { // control is the bottommost control return; } Control oneDown = (Control)controls[cIndex + 1]; int delta = (c.Bottom + pixelPadding) - oneDown.Top; for (int i = cIndex + 1; i < controls.Count; i++) { ((Control) controls[i]).Top += delta; } } } public static void EqualizeButtonWidthsVert(AnchorStyles anchorStyles, int minWidth, int maxWidth, params Button[] buttons) { switch (anchorStyles) { case AnchorStyles.Left: case AnchorStyles.Right: break; default: Trace.Fail("Invalid anchorStyles specified"); throw new ArgumentException("Invalid anchorStyles specified"); } int newWidth = DisplayHelper.GetMaxDesiredButtonWidth(false, buttons); newWidth = Math.Max(minWidth, Math.Min(maxWidth, newWidth)); for (int i = 0; i < buttons.Length; i++) { Button button = buttons[i]; int delta = newWidth - button.Width; button.Width = newWidth; if (anchorStyles == AnchorStyles.Right) button.Left -= delta; } } public static void EqualizeButtonWidthsHoriz(AnchorStyles anchorStyles, int minWidth, int maxWidth, params Button[] buttons) { switch (anchorStyles) { case AnchorStyles.Left: case AnchorStyles.Right: case AnchorStyles.None: break; default: Trace.Fail("Invalid anchorStyles specified"); throw new ArgumentException("Invalid anchorStyles specified"); } int newWidth = DisplayHelper.GetMaxDesiredButtonWidth(false, buttons); newWidth = Math.Max(minWidth, Math.Min(maxWidth, newWidth)); int[] deltas = new int[buttons.Length]; for (int i = 0; i < buttons.Length; i++) { Button button = buttons[i]; deltas[i] = newWidth - button.Width; button.Width = newWidth; } if (anchorStyles == AnchorStyles.Left) { int total = 0; for (int i = 0; i < buttons.Length; i++) { buttons[i].Left += total; total += deltas[i]; } } else if (anchorStyles == AnchorStyles.Right) { int total = 0; for (int i = buttons.Length - 1; i >= 0; i--) { total += deltas[i]; buttons[i].Left -= total; } } } public static int AutoFitLabels(params Label[] labels) { ControlGroup cg = new ControlGroup(labels); int startWidth = cg.Width; foreach (Label label in labels) DisplayHelper.AutoFitSystemLabel(label, 0, int.MaxValue); return cg.Width - startWidth; } } }
using System; using System.Text; namespace Platform.VirtualFileSystem.Providers { [Serializable] public class GenericNodeAddress : AbstractNodeAddress { /// <summary> /// Sets/Gets UserName /// </summary> public virtual string UserName { get { return m_UserName; } } /// <remarks> /// <see cref="UserName"/> /// </remarks> private string m_UserName; /// <summary> /// Sets/Gets HostName /// </summary> public virtual string HostName { get { return m_HostName; } } /// <remarks> /// <see cref="HostName"/> /// </remarks> private string m_HostName; /// <summary> /// Sets/Gets Port /// </summary> public virtual int Port { get { return m_Port; } } /// <remarks> /// <see cref="Port"/> /// </remarks> private int m_Port; /// <summary> /// Sets/Gets Password /// </summary> public virtual string Password { get { return m_Password; } } /// <remarks> /// <see cref="Password"/> /// </remarks> private string m_Password; /// <summary> /// Sets/Gets DefaultPort /// </summary> public virtual int DefaultPort { get { return m_DefaultPort; } } /// <remarks> /// <see cref="DefaultPort"/> /// </remarks> private int m_DefaultPort; private string m_RootPath; public string RootPath { get { return m_RootPath; } } public GenericNodeAddress(string scheme, string hostName, int defaultPort, int port, string userName, string password, string path) : this(scheme, hostName, defaultPort, port, userName, password, "", path) { } /// <summary> /// Initialises a new <c>GenericFileName</c>. /// </summary> /// <param name="scheme"></param> /// <param name="hostName"></param> /// <param name="port"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="path"></param> public GenericNodeAddress(string scheme, string hostName, int defaultPort, int port, string userName, string password, string rootPath, string path) : base(scheme, path) { m_HostName = hostName; m_Port = port; m_DefaultPort = defaultPort; m_RootPath = rootPath; m_UserName = userName; m_Password = password; if (m_UserName == null) { m_UserName = ""; } if (m_Password == null) { m_Password = ""; } } public static GenericNodeAddress Parse(string uri) { return Parse(uri, -1); } /// <summary> /// Parses a <c>GenericFileName</c>. /// </summary> /// <param name="uri"></param> /// <param name="defaultPort"> /// The default port if no port is specified in the URI and the URI scheme is unknown. /// If the URI scheme is known, the default port for that scheme is used. /// </param> /// <returns></returns> public static GenericNodeAddress Parse(string uri, int defaultPort) { Uri sysUri; try { // For the moment use the Uri class to do parsing... sysUri = new Uri(uri); } catch (Exception e) { throw new MalformedUriException(e.Message, e); } int x; string username = sysUri.UserInfo, password = ""; x = username.IndexOf('@'); if (x > 0) { username = username.Substring(0, x); password = username.Substring(x + 1); } if (defaultPort == -1) { if (sysUri.IsDefaultPort) { defaultPort = sysUri.Port; } } return new GenericNodeAddress(sysUri.Scheme, sysUri.Host, defaultPort, sysUri.Port, username, password, sysUri.PathAndQuery); } /// <summary> /// <see cref="AbstractFileName.CreateName()"/> /// </summary> protected override INodeAddress CreateName(string absolutePath) { return new GenericNodeAddress(this.Scheme, this.HostName, this.DefaultPort, this.Port, this.UserName, this.Password, this.m_RootPath, absolutePath); } /// <summary> /// <see cref="AbstractFileName.GetRootUri()"/> /// </summary> protected override string GetRootUri() { StringBuilder builder = new StringBuilder(64); builder.Append(this.Scheme).Append("://"); if (m_UserName.Length > 0) { builder.Append(m_UserName); if (m_Password.Length > 0) { builder.Append(':').Append(m_Password); } builder.Append('@'); } builder.Append(m_HostName); if (this.Port != this.DefaultPort && m_Port >= 0) { builder.Append(':'); builder.Append(m_Port); } if (m_RootPath != "") { builder.Append(m_RootPath); } return builder.ToString(); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Contact Links Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KPCLDataSet : EduHubDataSet<KPCL> { /// <inheritdoc /> public override string Name { get { return "KPCL"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KPCLDataSet(EduHubContext Context) : base(Context) { Index_CONTACT = new Lazy<NullDictionary<string, IReadOnlyList<KPCL>>>(() => this.ToGroupedNullDictionary(i => i.CONTACT)); Index_CONTACT_TYPE = new Lazy<NullDictionary<string, IReadOnlyList<KPCL>>>(() => this.ToGroupedNullDictionary(i => i.CONTACT_TYPE)); Index_KPCLKEY = new Lazy<Dictionary<int, KPCL>>(() => this.ToDictionary(i => i.KPCLKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KPCL" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KPCL" /> fields for each CSV column header</returns> internal override Action<KPCL, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KPCL, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KPCLKEY": mapper[i] = (e, v) => e.KPCLKEY = int.Parse(v); break; case "LINK": mapper[i] = (e, v) => e.LINK = v; break; case "SOURCE": mapper[i] = (e, v) => e.SOURCE = v; break; case "CONTACT": mapper[i] = (e, v) => e.CONTACT = v; break; case "CONTACT_TYPE": mapper[i] = (e, v) => e.CONTACT_TYPE = v; break; case "CONTACT_PREFERENCE": mapper[i] = (e, v) => e.CONTACT_PREFERENCE = v == null ? (short?)null : short.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KPCL" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KPCL" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KPCL" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KPCL}"/> of entities</returns> internal override IEnumerable<KPCL> ApplyDeltaEntities(IEnumerable<KPCL> Entities, List<KPCL> DeltaEntities) { HashSet<int> Index_KPCLKEY = new HashSet<int>(DeltaEntities.Select(i => i.KPCLKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KPCLKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KPCLKEY.Remove(entity.KPCLKEY); if (entity.KPCLKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<KPCL>>> Index_CONTACT; private Lazy<NullDictionary<string, IReadOnlyList<KPCL>>> Index_CONTACT_TYPE; private Lazy<Dictionary<int, KPCL>> Index_KPCLKEY; #endregion #region Index Methods /// <summary> /// Find KPCL by CONTACT field /// </summary> /// <param name="CONTACT">CONTACT value used to find KPCL</param> /// <returns>List of related KPCL entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KPCL> FindByCONTACT(string CONTACT) { return Index_CONTACT.Value[CONTACT]; } /// <summary> /// Attempt to find KPCL by CONTACT field /// </summary> /// <param name="CONTACT">CONTACT value used to find KPCL</param> /// <param name="Value">List of related KPCL entities</param> /// <returns>True if the list of related KPCL entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCONTACT(string CONTACT, out IReadOnlyList<KPCL> Value) { return Index_CONTACT.Value.TryGetValue(CONTACT, out Value); } /// <summary> /// Attempt to find KPCL by CONTACT field /// </summary> /// <param name="CONTACT">CONTACT value used to find KPCL</param> /// <returns>List of related KPCL entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KPCL> TryFindByCONTACT(string CONTACT) { IReadOnlyList<KPCL> value; if (Index_CONTACT.Value.TryGetValue(CONTACT, out value)) { return value; } else { return null; } } /// <summary> /// Find KPCL by CONTACT_TYPE field /// </summary> /// <param name="CONTACT_TYPE">CONTACT_TYPE value used to find KPCL</param> /// <returns>List of related KPCL entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KPCL> FindByCONTACT_TYPE(string CONTACT_TYPE) { return Index_CONTACT_TYPE.Value[CONTACT_TYPE]; } /// <summary> /// Attempt to find KPCL by CONTACT_TYPE field /// </summary> /// <param name="CONTACT_TYPE">CONTACT_TYPE value used to find KPCL</param> /// <param name="Value">List of related KPCL entities</param> /// <returns>True if the list of related KPCL entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCONTACT_TYPE(string CONTACT_TYPE, out IReadOnlyList<KPCL> Value) { return Index_CONTACT_TYPE.Value.TryGetValue(CONTACT_TYPE, out Value); } /// <summary> /// Attempt to find KPCL by CONTACT_TYPE field /// </summary> /// <param name="CONTACT_TYPE">CONTACT_TYPE value used to find KPCL</param> /// <returns>List of related KPCL entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KPCL> TryFindByCONTACT_TYPE(string CONTACT_TYPE) { IReadOnlyList<KPCL> value; if (Index_CONTACT_TYPE.Value.TryGetValue(CONTACT_TYPE, out value)) { return value; } else { return null; } } /// <summary> /// Find KPCL by KPCLKEY field /// </summary> /// <param name="KPCLKEY">KPCLKEY value used to find KPCL</param> /// <returns>Related KPCL entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KPCL FindByKPCLKEY(int KPCLKEY) { return Index_KPCLKEY.Value[KPCLKEY]; } /// <summary> /// Attempt to find KPCL by KPCLKEY field /// </summary> /// <param name="KPCLKEY">KPCLKEY value used to find KPCL</param> /// <param name="Value">Related KPCL entity</param> /// <returns>True if the related KPCL entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKPCLKEY(int KPCLKEY, out KPCL Value) { return Index_KPCLKEY.Value.TryGetValue(KPCLKEY, out Value); } /// <summary> /// Attempt to find KPCL by KPCLKEY field /// </summary> /// <param name="KPCLKEY">KPCLKEY value used to find KPCL</param> /// <returns>Related KPCL entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KPCL TryFindByKPCLKEY(int KPCLKEY) { KPCL value; if (Index_KPCLKEY.Value.TryGetValue(KPCLKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KPCL table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KPCL]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KPCL]( [KPCLKEY] int IDENTITY NOT NULL, [LINK] varchar(10) NULL, [SOURCE] varchar(3) NULL, [CONTACT] varchar(10) NULL, [CONTACT_TYPE] varchar(10) NULL, [CONTACT_PREFERENCE] smallint NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KPCL_Index_KPCLKEY] PRIMARY KEY CLUSTERED ( [KPCLKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KPCL_Index_CONTACT] ON [dbo].[KPCL] ( [CONTACT] ASC ); CREATE NONCLUSTERED INDEX [KPCL_Index_CONTACT_TYPE] ON [dbo].[KPCL] ( [CONTACT_TYPE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KPCL]') AND name = N'KPCL_Index_CONTACT') ALTER INDEX [KPCL_Index_CONTACT] ON [dbo].[KPCL] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KPCL]') AND name = N'KPCL_Index_CONTACT_TYPE') ALTER INDEX [KPCL_Index_CONTACT_TYPE] ON [dbo].[KPCL] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KPCL]') AND name = N'KPCL_Index_CONTACT') ALTER INDEX [KPCL_Index_CONTACT] ON [dbo].[KPCL] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KPCL]') AND name = N'KPCL_Index_CONTACT_TYPE') ALTER INDEX [KPCL_Index_CONTACT_TYPE] ON [dbo].[KPCL] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KPCL"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KPCL"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KPCL> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_KPCLKEY = new List<int>(); foreach (var entity in Entities) { Index_KPCLKEY.Add(entity.KPCLKEY); } builder.AppendLine("DELETE [dbo].[KPCL] WHERE"); // Index_KPCLKEY builder.Append("[KPCLKEY] IN ("); for (int index = 0; index < Index_KPCLKEY.Count; index++) { if (index != 0) builder.Append(", "); // KPCLKEY var parameterKPCLKEY = $"@p{parameterIndex++}"; builder.Append(parameterKPCLKEY); command.Parameters.Add(parameterKPCLKEY, SqlDbType.Int).Value = Index_KPCLKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KPCL data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KPCL data set</returns> public override EduHubDataSetDataReader<KPCL> GetDataSetDataReader() { return new KPCLDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KPCL data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KPCL data set</returns> public override EduHubDataSetDataReader<KPCL> GetDataSetDataReader(List<KPCL> Entities) { return new KPCLDataReader(new EduHubDataSetLoadedReader<KPCL>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KPCLDataReader : EduHubDataSetDataReader<KPCL> { public KPCLDataReader(IEduHubDataSetReader<KPCL> Reader) : base (Reader) { } public override int FieldCount { get { return 9; } } public override object GetValue(int i) { switch (i) { case 0: // KPCLKEY return Current.KPCLKEY; case 1: // LINK return Current.LINK; case 2: // SOURCE return Current.SOURCE; case 3: // CONTACT return Current.CONTACT; case 4: // CONTACT_TYPE return Current.CONTACT_TYPE; case 5: // CONTACT_PREFERENCE return Current.CONTACT_PREFERENCE; case 6: // LW_DATE return Current.LW_DATE; case 7: // LW_TIME return Current.LW_TIME; case 8: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // LINK return Current.LINK == null; case 2: // SOURCE return Current.SOURCE == null; case 3: // CONTACT return Current.CONTACT == null; case 4: // CONTACT_TYPE return Current.CONTACT_TYPE == null; case 5: // CONTACT_PREFERENCE return Current.CONTACT_PREFERENCE == null; case 6: // LW_DATE return Current.LW_DATE == null; case 7: // LW_TIME return Current.LW_TIME == null; case 8: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KPCLKEY return "KPCLKEY"; case 1: // LINK return "LINK"; case 2: // SOURCE return "SOURCE"; case 3: // CONTACT return "CONTACT"; case 4: // CONTACT_TYPE return "CONTACT_TYPE"; case 5: // CONTACT_PREFERENCE return "CONTACT_PREFERENCE"; case 6: // LW_DATE return "LW_DATE"; case 7: // LW_TIME return "LW_TIME"; case 8: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KPCLKEY": return 0; case "LINK": return 1; case "SOURCE": return 2; case "CONTACT": return 3; case "CONTACT_TYPE": return 4; case "CONTACT_PREFERENCE": return 5; case "LW_DATE": return 6; case "LW_TIME": return 7; case "LW_USER": return 8; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
namespace org.apache.http { [global::MonoJavaBridge.JavaInterface(typeof(global::org.apache.http.HttpMessage_))] public interface HttpMessage : global::MonoJavaBridge.IJavaObject { global::org.apache.http.ProtocolVersion getProtocolVersion(); global::org.apache.http.@params.HttpParams getParams(); void setParams(org.apache.http.@params.HttpParams arg0); global::org.apache.http.Header[] getHeaders(java.lang.String arg0); bool containsHeader(java.lang.String arg0); global::org.apache.http.Header getFirstHeader(java.lang.String arg0); global::org.apache.http.Header getLastHeader(java.lang.String arg0); global::org.apache.http.Header[] getAllHeaders(); void addHeader(org.apache.http.Header arg0); void addHeader(java.lang.String arg0, java.lang.String arg1); void setHeader(java.lang.String arg0, java.lang.String arg1); void setHeader(org.apache.http.Header arg0); void setHeaders(org.apache.http.Header[] arg0); void removeHeader(org.apache.http.Header arg0); void removeHeaders(java.lang.String arg0); global::org.apache.http.HeaderIterator headerIterator(); global::org.apache.http.HeaderIterator headerIterator(java.lang.String arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::org.apache.http.HttpMessage))] public sealed partial class HttpMessage_ : java.lang.Object, HttpMessage { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static HttpMessage_() { InitJNI(); } internal HttpMessage_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getProtocolVersion16200; global::org.apache.http.ProtocolVersion org.apache.http.HttpMessage.getProtocolVersion() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._getProtocolVersion16200)) as org.apache.http.ProtocolVersion; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._getProtocolVersion16200)) as org.apache.http.ProtocolVersion; } internal static global::MonoJavaBridge.MethodId _getParams16201; global::org.apache.http.@params.HttpParams org.apache.http.HttpMessage.getParams() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.@params.HttpParams>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._getParams16201)) as org.apache.http.@params.HttpParams; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.@params.HttpParams>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._getParams16201)) as org.apache.http.@params.HttpParams; } internal static global::MonoJavaBridge.MethodId _setParams16202; void org.apache.http.HttpMessage.setParams(org.apache.http.@params.HttpParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._setParams16202, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._setParams16202, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getHeaders16203; global::org.apache.http.Header[] org.apache.http.HttpMessage.getHeaders(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._getHeaders16203, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._getHeaders16203, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header[]; } internal static global::MonoJavaBridge.MethodId _containsHeader16204; bool org.apache.http.HttpMessage.containsHeader(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._containsHeader16204, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._containsHeader16204, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFirstHeader16205; global::org.apache.http.Header org.apache.http.HttpMessage.getFirstHeader(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._getFirstHeader16205, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._getFirstHeader16205, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header; } internal static global::MonoJavaBridge.MethodId _getLastHeader16206; global::org.apache.http.Header org.apache.http.HttpMessage.getLastHeader(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._getLastHeader16206, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._getLastHeader16206, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header; } internal static global::MonoJavaBridge.MethodId _getAllHeaders16207; global::org.apache.http.Header[] org.apache.http.HttpMessage.getAllHeaders() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._getAllHeaders16207)) as org.apache.http.Header[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._getAllHeaders16207)) as org.apache.http.Header[]; } internal static global::MonoJavaBridge.MethodId _addHeader16208; void org.apache.http.HttpMessage.addHeader(org.apache.http.Header arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._addHeader16208, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._addHeader16208, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _addHeader16209; void org.apache.http.HttpMessage.addHeader(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._addHeader16209, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._addHeader16209, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setHeader16210; void org.apache.http.HttpMessage.setHeader(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._setHeader16210, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._setHeader16210, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setHeader16211; void org.apache.http.HttpMessage.setHeader(org.apache.http.Header arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._setHeader16211, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._setHeader16211, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setHeaders16212; void org.apache.http.HttpMessage.setHeaders(org.apache.http.Header[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._setHeaders16212, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._setHeaders16212, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeHeader16213; void org.apache.http.HttpMessage.removeHeader(org.apache.http.Header arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._removeHeader16213, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._removeHeader16213, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _removeHeaders16214; void org.apache.http.HttpMessage.removeHeaders(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._removeHeaders16214, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._removeHeaders16214, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _headerIterator16215; global::org.apache.http.HeaderIterator org.apache.http.HttpMessage.headerIterator() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HeaderIterator>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._headerIterator16215)) as org.apache.http.HeaderIterator; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HeaderIterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._headerIterator16215)) as org.apache.http.HeaderIterator; } internal static global::MonoJavaBridge.MethodId _headerIterator16216; global::org.apache.http.HeaderIterator org.apache.http.HttpMessage.headerIterator(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HeaderIterator>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_._headerIterator16216, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.HeaderIterator; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HeaderIterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpMessage_.staticClass, global::org.apache.http.HttpMessage_._headerIterator16216, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.HeaderIterator; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::org.apache.http.HttpMessage_.staticClass = @__env.NewGlobalRef(@__env.FindClass("org/apache/http/HttpMessage")); global::org.apache.http.HttpMessage_._getProtocolVersion16200 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;"); global::org.apache.http.HttpMessage_._getParams16201 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "getParams", "()Lorg/apache/http/@params/HttpParams;"); global::org.apache.http.HttpMessage_._setParams16202 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "setParams", "(Lorg/apache/http/@params/HttpParams;)V"); global::org.apache.http.HttpMessage_._getHeaders16203 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;"); global::org.apache.http.HttpMessage_._containsHeader16204 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "containsHeader", "(Ljava/lang/String;)Z"); global::org.apache.http.HttpMessage_._getFirstHeader16205 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;"); global::org.apache.http.HttpMessage_._getLastHeader16206 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;"); global::org.apache.http.HttpMessage_._getAllHeaders16207 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "getAllHeaders", "()[Lorg/apache/http/Header;"); global::org.apache.http.HttpMessage_._addHeader16208 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "addHeader", "(Lorg/apache/http/Header;)V"); global::org.apache.http.HttpMessage_._addHeader16209 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V"); global::org.apache.http.HttpMessage_._setHeader16210 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V"); global::org.apache.http.HttpMessage_._setHeader16211 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "setHeader", "(Lorg/apache/http/Header;)V"); global::org.apache.http.HttpMessage_._setHeaders16212 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "setHeaders", "([Lorg/apache/http/Header;)V"); global::org.apache.http.HttpMessage_._removeHeader16213 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "removeHeader", "(Lorg/apache/http/Header;)V"); global::org.apache.http.HttpMessage_._removeHeaders16214 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "removeHeaders", "(Ljava/lang/String;)V"); global::org.apache.http.HttpMessage_._headerIterator16215 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "headerIterator", "()Lorg/apache/http/HeaderIterator;"); global::org.apache.http.HttpMessage_._headerIterator16216 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpMessage_.staticClass, "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;"); } } }
//#if DESKTOP_GL || WINDOWS #if WINDOWS #define USE_CUSTOM_SHADER #endif using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Utilities; #if FRB_MDX #else using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; #endif namespace FlatRedBall.Graphics { public struct RenderBreak { #region Fields public int ItemNumber; Texture2D mTexture; public PrimitiveType PrimitiveType; public string LayerName; #if DEBUG public object ObjectCausingBreak; /// <summary> /// Debug only: Returns detailed information about this render break. /// </summary> public string Details { get { if (ObjectCausingBreak != null) { string toReturn = ObjectCausingBreak.ToString(); if(ObjectCausingBreak is PositionedObject) { var parent = (ObjectCausingBreak as PositionedObject).Parent; if (parent != null) { toReturn += "\nParent: " + parent.ToString(); } } if(string.IsNullOrEmpty(toReturn)) { toReturn = ObjectCausingBreak.GetType().FullName; } return toReturn; } else { return "Unknown object"; } } } #endif public float Red; public float Green; public float Blue; public ColorOperation ColorOperation; public BlendOperation BlendOperation; public TextureFilter TextureFilter; public Texture2D Texture { get { return mTexture; } } public TextureAddressMode TextureAddressMode; private static TextureFilter _originalTextureFilter; #endregion #region Methods #region Constructors public RenderBreak(int itemNumber, Sprite sprite) { #if DEBUG ObjectCausingBreak = sprite; #endif LayerName = Renderer.CurrentLayerName; ItemNumber = itemNumber; PrimitiveType = PrimitiveType.TriangleList; _originalTextureFilter = TextureFilter.Linear; if (sprite != null) { if (sprite.Texture != null && sprite.Texture.IsDisposed) { throw new ObjectDisposedException("The Sprite with the name \"" + sprite.Name + "\" references a disposed texture of the name " + sprite.Texture.Name + ". If you're using Screens you may have forgotten to remove a Sprite that was " + "added in the Screen."); } mTexture = sprite.Texture; ColorOperation = sprite.ColorOperation; BlendOperation = sprite.BlendOperation; TextureFilter = sprite.TextureFilter.HasValue ? sprite.TextureFilter.Value : FlatRedBallServices.GraphicsOptions.TextureFilter; if (sprite.Texture == null) { // requirement for reach profile - this shouldn't impact anything TextureAddressMode = Microsoft.Xna.Framework.Graphics.TextureAddressMode.Clamp; } else { TextureAddressMode = sprite.TextureAddressMode; } Red = sprite.Red; Green = sprite.Green; Blue = sprite.Blue; } else { Red = 0; Green = 0; Blue = 0; mTexture = null; ColorOperation = ColorOperation.Texture; BlendOperation = BlendOperation.Regular; TextureAddressMode = TextureAddressMode.Clamp; TextureFilter = FlatRedBallServices.GraphicsOptions.TextureFilter; } } public RenderBreak(int itemNumber, Text text, int textureIndex) { #if DEBUG ObjectCausingBreak = text; #endif LayerName = Renderer.CurrentLayerName ; Red = 1; Green = 1; Blue = 1; #if !USE_CUSTOM_SHADER if (text.ColorOperation != Graphics.ColorOperation.Texture) { Red = text.Red; Green = text.Green; Blue = text.Blue; } #endif ItemNumber = itemNumber; PrimitiveType = PrimitiveType.TriangleList; TextureFilter = FlatRedBallServices.GraphicsOptions.TextureFilter; _originalTextureFilter = TextureFilter.Linear; if (text != null) { if (text.Font.Texture != null && text.Font.Texture.IsDisposed) { throw new ObjectDisposedException("Cannot create render break with disposed Texture2D"); } mTexture = text.Font.Textures[textureIndex]; ColorOperation = text.ColorOperation; BlendOperation = text.BlendOperation; TextureAddressMode = TextureAddressMode.Clamp; } else { mTexture = null; ColorOperation = ColorOperation.Texture; BlendOperation = BlendOperation.Regular; TextureAddressMode = TextureAddressMode.Clamp; } } public RenderBreak(int itemNumber, Texture2D texture, ColorOperation colorOperation, BlendOperation blendOperation, TextureAddressMode textureAddressMode) { #if DEBUG ObjectCausingBreak = null; #endif LayerName = Renderer.CurrentLayerName; PrimitiveType = PrimitiveType.TriangleList; ItemNumber = itemNumber; if (texture != null && texture.IsDisposed) { throw new ObjectDisposedException("Cannot create render break with disposed Texture2D"); } mTexture = texture; ColorOperation = colorOperation; BlendOperation = blendOperation; TextureAddressMode = textureAddressMode; TextureFilter = FlatRedBallServices.GraphicsOptions.TextureFilter; _originalTextureFilter = TextureFilter.Linear; Red = 0; Green = 0; Blue = 0; } #endregion #region Public Methods public bool DiffersFrom(Sprite sprite) { // Some explanation on why we are doing this: // ColorTextureAlpha is implemented using a custom // shader on FRB XNA. FRB MonoGame doesn't (yet) use // custom shaders, so it has to rely on fixed function- // equivalent code (technically it is using shaders, just // not ones we wrote for FRB). Therefore, when using this color // operation, we have to change states on any color change. But to // make this more efficient we'll only do this if in ColorTExtureAlpha. // Even though FlatRedBall XNA doesn't require a state change here, we want // all engines to beave the same if the user uses FRB XNA for performance measurements. // Therefore, we'll inject a render break here on PC and eat the performance penalty to // get identical behavior across platforms. bool isColorChangingOnColorTextureAlpha = sprite.mColorOperation == ColorOperation.ColorTextureAlpha && (sprite.mRed != Red || sprite.mGreen != Green || sprite.mBlue != Blue); return sprite.mTexture != Texture || sprite.mColorOperation != ColorOperation || sprite.BlendOperation != BlendOperation || sprite.TextureAddressMode != TextureAddressMode || (sprite.TextureFilter != null && sprite.TextureFilter != TextureFilter) || isColorChangingOnColorTextureAlpha; } public bool DiffersFrom(Text text) { return text.Font.Texture != Texture || text.ColorOperation != ColorOperation || text.BlendOperation != BlendOperation || TextureAddressMode != TextureAddressMode.Clamp #if !USE_CUSTOM_SHADER || text.Red != Red || text.Green != Green || text.Blue != Blue #endif ; } public void SetStates() { //if (Renderer.RendererDiagnosticSettings.RenderBreaksPerformStateChanges) { if (ColorOperation != Graphics.ColorOperation.Color) { Renderer.Texture = Texture; } if (Texture == null && ColorOperation == ColorOperation.Texture) { ColorOperation = ColorOperation.Color; } Renderer.ColorOperation = ColorOperation; Renderer.BlendOperation = BlendOperation; Renderer.TextureAddressMode = TextureAddressMode; _originalTextureFilter = FlatRedBallServices.GraphicsOptions.TextureFilter; //if (TextureFilter != FlatRedBallServices.GraphicsOptions.TextureFilter) FlatRedBallServices.GraphicsOptions.TextureFilter = TextureFilter; #if !USE_CUSTOM_SHADER if (ColorOperation == Graphics.ColorOperation.ColorTextureAlpha) { Renderer.SetFogForColorOperation(Red, Green, Blue); } #endif } } public void SetStates(Effect effect) { //if (Renderer.RendererDiagnosticSettings.RenderBreaksPerformStateChanges) { effect.Parameters["CurrentTexture"].SetValue(Texture); EffectParameter address = effect.Parameters["Address"]; if (address != null) { address.SetValue((int)TextureAddressMode); } Renderer.ForceSetColorOperation(this.ColorOperation); Renderer.BlendOperation = BlendOperation; _originalTextureFilter = FlatRedBallServices.GraphicsOptions.TextureFilter; if (TextureFilter != FlatRedBallServices.GraphicsOptions.TextureFilter) FlatRedBallServices.GraphicsOptions.TextureFilter = TextureFilter; } } public override string ToString() { string textureName = "<null texture>"; if (this.Texture != null) { textureName = this.Texture.Name; } return textureName; } #endregion #endregion public void Cleanup() { if (_originalTextureFilter != FlatRedBallServices.GraphicsOptions.TextureFilter) FlatRedBallServices.GraphicsOptions.TextureFilter = _originalTextureFilter; } } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // 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.IO; using log4net.Util; using log4net.Layout; using log4net.Core; namespace log4net.Appender { /// <summary> /// Sends logging events to a <see cref="TextWriter"/>. /// </summary> /// <remarks> /// <para> /// An Appender that writes to a <see cref="TextWriter"/>. /// </para> /// <para> /// This appender may be used stand alone if initialized with an appropriate /// writer, however it is typically used as a base class for an appender that /// can open a <see cref="TextWriter"/> to write to. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Douglas de la Torre</author> public class TextWriterAppender : AppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="TextWriterAppender" /> class. /// </summary> /// <remarks> /// <para> /// Default constructor. /// </para> /// </remarks> public TextWriterAppender() { } /// <summary> /// Initializes a new instance of the <see cref="TextWriterAppender" /> class and /// sets the output destination to a new <see cref="StreamWriter"/> initialized /// with the specified <see cref="Stream"/>. /// </summary> /// <param name="layout">The layout to use with this appender.</param> /// <param name="os">The <see cref="Stream"/> to output to.</param> /// <remarks> /// <para> /// Obsolete constructor. /// </para> /// </remarks> [Obsolete("Instead use the default constructor and set the Layout & Writer properties")] public TextWriterAppender(ILayout layout, Stream os) : this(layout, new StreamWriter(os)) { } /// <summary> /// Initializes a new instance of the <see cref="TextWriterAppender" /> class and sets /// the output destination to the specified <see cref="StreamWriter" />. /// </summary> /// <param name="layout">The layout to use with this appender</param> /// <param name="writer">The <see cref="TextWriter" /> to output to</param> /// <remarks> /// The <see cref="TextWriter" /> must have been previously opened. /// </remarks> /// <remarks> /// <para> /// Obsolete constructor. /// </para> /// </remarks> [Obsolete("Instead use the default constructor and set the Layout & Writer properties")] public TextWriterAppender(ILayout layout, TextWriter writer) { Layout = layout; Writer = writer; } #endregion #region Public Instance Properties /// <summary> /// Gets or set whether the appender will flush at the end /// of each append operation. /// </summary> /// <value> /// <para> /// The default behavior is to flush at the end of each /// append operation. /// </para> /// <para> /// If this option is set to <c>false</c>, then the underlying /// stream can defer persisting the logging event to a later /// time. /// </para> /// </value> /// <remarks> /// Avoiding the flush operation at the end of each append results in /// a performance gain of 10 to 20 percent. However, there is safety /// trade-off involved in skipping flushing. Indeed, when flushing is /// skipped, then it is likely that the last few log events will not /// be recorded on disk when the application exits. This is a high /// price to pay even for a 20% performance gain. /// </remarks> public bool ImmediateFlush { get { return m_immediateFlush; } set { m_immediateFlush = value; } } /// <summary> /// Sets the <see cref="TextWriter"/> where the log output will go. /// </summary> /// <remarks> /// <para> /// The specified <see cref="TextWriter"/> must be open and writable. /// </para> /// <para> /// The <see cref="TextWriter"/> will be closed when the appender /// instance is closed. /// </para> /// <para> /// <b>Note:</b> Logging to an unopened <see cref="TextWriter"/> will fail. /// </para> /// </remarks> virtual public TextWriter Writer { get { return m_qtw; } set { lock(this) { Reset(); if (value != null) { m_qtw = new QuietTextWriter(value, ErrorHandler); WriteHeader(); } } } } #endregion Public Instance Properties #region Override implementation of AppenderSkeleton /// <summary> /// This method determines if there is a sense in attempting to append. /// </summary> /// <remarks> /// <para> /// This method checked if an output target has been set and if a /// layout has been set. /// </para> /// </remarks> /// <returns><c>false</c> if any of the preconditions fail.</returns> override protected bool PreAppendCheck() { if (!base.PreAppendCheck()) { return false; } if (m_qtw == null) { // Allow subclass to lazily create the writer PrepareWriter(); if (m_qtw == null) { ErrorHandler.Error("No output stream or file set for the appender named ["+ Name +"]."); return false; } } if (m_qtw.Closed) { ErrorHandler.Error("Output stream for appender named ["+ Name +"] has been closed."); return false; } return true; } /// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> /// method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes a log statement to the output stream if the output stream exists /// and is writable. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { RenderLoggingEvent(m_qtw, loggingEvent); if (m_immediateFlush) { m_qtw.Flush(); } } /// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent[])"/> /// method. /// </summary> /// <param name="loggingEvents">The array of events to log.</param> /// <remarks> /// <para> /// This method writes all the bulk logged events to the output writer /// before flushing the stream. /// </para> /// </remarks> override protected void Append(LoggingEvent[] loggingEvents) { foreach(LoggingEvent loggingEvent in loggingEvents) { RenderLoggingEvent(m_qtw, loggingEvent); } if (m_immediateFlush) { m_qtw.Flush(); } } /// <summary> /// Close this appender instance. The underlying stream or writer is also closed. /// </summary> /// <remarks> /// Closed appenders cannot be reused. /// </remarks> override protected void OnClose() { lock(this) { Reset(); } } /// <summary> /// Gets or set the <see cref="IErrorHandler"/> and the underlying /// <see cref="QuietTextWriter"/>, if any, for this appender. /// </summary> /// <value> /// The <see cref="IErrorHandler"/> for this appender. /// </value> override public IErrorHandler ErrorHandler { get { return base.ErrorHandler; } set { lock(this) { if (value == null) { LogLog.Warn("TextWriterAppender: You have tried to set a null error-handler."); } else { base.ErrorHandler = value; if (m_qtw != null) { m_qtw.ErrorHandler = value; } } } } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion Override implementation of AppenderSkeleton #region Protected Instance Methods /// <summary> /// Writes the footer and closes the underlying <see cref="TextWriter"/>. /// </summary> /// <remarks> /// <para> /// Writes the footer and closes the underlying <see cref="TextWriter"/>. /// </para> /// </remarks> virtual protected void WriteFooterAndCloseWriter() { WriteFooter(); CloseWriter(); } /// <summary> /// Closes the underlying <see cref="TextWriter"/>. /// </summary> /// <remarks> /// <para> /// Closes the underlying <see cref="TextWriter"/>. /// </para> /// </remarks> virtual protected void CloseWriter() { if (m_qtw != null) { try { m_qtw.Close(); } catch(Exception e) { ErrorHandler.Error("Could not close writer ["+m_qtw+"]", e); // do need to invoke an error handler // at this late stage } } } /// <summary> /// Clears internal references to the underlying <see cref="TextWriter" /> /// and other variables. /// </summary> /// <remarks> /// <para> /// Subclasses can override this method for an alternate closing behavior. /// </para> /// </remarks> virtual protected void Reset() { WriteFooterAndCloseWriter(); m_qtw = null; } /// <summary> /// Writes a footer as produced by the embedded layout's <see cref="ILayout.Footer"/> property. /// </summary> /// <remarks> /// <para> /// Writes a footer as produced by the embedded layout's <see cref="ILayout.Footer"/> property. /// </para> /// </remarks> virtual protected void WriteFooter() { if (Layout != null && m_qtw != null && !m_qtw.Closed) { string f = Layout.Footer; if (f != null) { m_qtw.Write(f); } } } /// <summary> /// Writes a header produced by the embedded layout's <see cref="ILayout.Header"/> property. /// </summary> /// <remarks> /// <para> /// Writes a header produced by the embedded layout's <see cref="ILayout.Header"/> property. /// </para> /// </remarks> virtual protected void WriteHeader() { if (Layout != null && m_qtw != null && !m_qtw.Closed) { string h = Layout.Header; if (h != null) { m_qtw.Write(h); } } } /// <summary> /// Called to allow a subclass to lazily initialize the writer /// </summary> /// <remarks> /// <para> /// This method is called when an event is logged and the <see cref="Writer"/> or /// <see cref="QuietWriter"/> have not been set. This allows a subclass to /// attempt to initialize the writer multiple times. /// </para> /// </remarks> virtual protected void PrepareWriter() { } #endregion Protected Instance Methods /// <summary> /// Gets or sets the <see cref="log4net.Util.QuietTextWriter"/> where logging events /// will be written to. /// </summary> /// <value> /// The <see cref="log4net.Util.QuietTextWriter"/> where logging events are written. /// </value> /// <remarks> /// <para> /// This is the <see cref="log4net.Util.QuietTextWriter"/> where logging events /// will be written to. /// </para> /// </remarks> protected QuietTextWriter QuietWriter { get { return m_qtw; } set { m_qtw = value; } } #region Private Instance Fields /// <summary> /// This is the <see cref="log4net.Util.QuietTextWriter"/> where logging events /// will be written to. /// </summary> private QuietTextWriter m_qtw; /// <summary> /// Immediate flush means that the underlying <see cref="TextWriter" /> /// or output stream will be flushed at the end of each append operation. /// </summary> /// <remarks> /// <para> /// Immediate flush is slower but ensures that each append request is /// actually written. If <see cref="ImmediateFlush"/> is set to /// <c>false</c>, then there is a good chance that the last few /// logging events are not actually persisted if and when the application /// crashes. /// </para> /// <para> /// The default value is <c>true</c>. /// </para> /// </remarks> private bool m_immediateFlush = true; #endregion Private Instance Fields } }
// 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.Runtime; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Reflection.Runtime.General; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; namespace Internal.Runtime.TypeLoader { /// <summary> /// Helper structure describing all info needed to construct dynamic field accessors. /// </summary> public struct FieldAccessMetadata { /// <summary> /// Module containing the relevant metadata, null when not found /// </summary> public TypeManagerHandle MappingTableModule; /// <summary> /// Cookie for field access. This field is set to IntPtr.Zero when the value is not available. /// </summary> public IntPtr Cookie; /// <summary> /// Field access and characteristics bitmask. /// </summary> public FieldTableFlags Flags; /// <summary> /// Field offset, address or cookie based on field access type. /// </summary> public int Offset; } [StructLayout(LayoutKind.Sequential)] struct ThreadStaticFieldOffsets { public uint StartingOffsetInTlsBlock; // Offset in the TLS block containing the thread static fields of a given type public uint FieldOffset; // Offset of a thread static field from the start of its containing type's TLS fields block // (in other words, the address of a field is 'TLS block + StartingOffsetInTlsBlock + FieldOffset') } public sealed partial class TypeLoaderEnvironment { /// <summary> /// Try to look up field access info for given canon in metadata blobs for all available modules. /// </summary> /// <param name="metadataReader">Metadata reader for the declaring type</param> /// <param name="declaringTypeHandle">Declaring type for the method</param> /// <param name="fieldHandle">Field handle</param> /// <param name="canonFormKind">Canonical form to use</param> /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param> /// <returns>true when found, false otherwise</returns> public static bool TryGetFieldAccessMetadata( MetadataReader metadataReader, RuntimeTypeHandle runtimeTypeHandle, FieldHandle fieldHandle, out FieldAccessMetadata fieldAccessMetadata) { fieldAccessMetadata = default(FieldAccessMetadata); if (TryGetFieldAccessMetadataFromFieldAccessMap( metadataReader, runtimeTypeHandle, fieldHandle, CanonicalFormKind.Specific, ref fieldAccessMetadata)) { return true; } if (TryGetFieldAccessMetadataFromFieldAccessMap( metadataReader, runtimeTypeHandle, fieldHandle, CanonicalFormKind.Universal, ref fieldAccessMetadata)) { return true; } TypeSystemContext context = TypeSystemContextFactory.Create(); bool success = TryGetFieldAccessMetadataFromNativeFormatMetadata( metadataReader, runtimeTypeHandle, fieldHandle, context, ref fieldAccessMetadata); TypeSystemContextFactory.Recycle(context); return success; } /// <summary> /// Try to look up field access info for given canon in metadata blobs for all available modules. /// </summary> /// <param name="metadataReader">Metadata reader for the declaring type</param> /// <param name="declaringTypeHandle">Declaring type for the method</param> /// <param name="fieldHandle">Field handle</param> /// <param name="canonFormKind">Canonical form to use</param> /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param> /// <returns>true when found, false otherwise</returns> private unsafe static bool TryGetFieldAccessMetadataFromFieldAccessMap( MetadataReader metadataReader, RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle, CanonicalFormKind canonFormKind, ref FieldAccessMetadata fieldAccessMetadata) { CanonicallyEquivalentEntryLocator canonWrapper = new CanonicallyEquivalentEntryLocator(declaringTypeHandle, canonFormKind); TypeManagerHandle fieldHandleModule = ModuleList.Instance.GetModuleForMetadataReader(metadataReader); bool isDynamicType = RuntimeAugments.IsDynamicType(declaringTypeHandle); string fieldName = null; RuntimeTypeHandle declaringTypeHandleDefinition = Instance.GetTypeDefinition(declaringTypeHandle); foreach (NativeFormatModuleInfo mappingTableModule in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(declaringTypeHandle))) { NativeReader fieldMapReader; if (!TryGetNativeReaderForBlob(mappingTableModule, ReflectionMapBlob.FieldAccessMap, out fieldMapReader)) continue; NativeParser fieldMapParser = new NativeParser(fieldMapReader, 0); NativeHashtable fieldHashtable = new NativeHashtable(fieldMapParser); ExternalReferencesTable externalReferences = default(ExternalReferencesTable); if (!externalReferences.InitializeCommonFixupsTable(mappingTableModule)) { continue; } var lookup = fieldHashtable.Lookup(canonWrapper.LookupHashCode); NativeParser entryParser; while (!(entryParser = lookup.GetNext()).IsNull) { // Grammar of a hash table entry: // Flags + DeclaringType + MdHandle or Name + Cookie or Ordinal or Offset FieldTableFlags entryFlags = (FieldTableFlags)entryParser.GetUnsigned(); if ((canonFormKind == CanonicalFormKind.Universal) != ((entryFlags & FieldTableFlags.IsUniversalCanonicalEntry) != 0)) continue; RuntimeTypeHandle entryDeclaringTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned()); if (!entryDeclaringTypeHandle.Equals(declaringTypeHandle) && !canonWrapper.IsCanonicallyEquivalent(entryDeclaringTypeHandle)) continue; if ((entryFlags & FieldTableFlags.HasMetadataHandle) != 0) { Handle entryFieldHandle = (((int)HandleType.Field << 24) | (int)entryParser.GetUnsigned()).AsHandle(); if (!fieldHandle.Equals(entryFieldHandle)) continue; } else { if (fieldName == null) { QTypeDefinition qTypeDefinition; bool success = Instance.TryGetMetadataForNamedType( declaringTypeHandleDefinition, out qTypeDefinition); Debug.Assert(success); MetadataReader nativeFormatMetadataReader = qTypeDefinition.NativeFormatReader; fieldName = nativeFormatMetadataReader.GetString(fieldHandle.GetField(nativeFormatMetadataReader).Name); } string entryFieldName = entryParser.GetString(); if (fieldName != entryFieldName) continue; } int fieldOffset = -1; int threadStaticsStartOffset = -1; IntPtr fieldAddressCookie = IntPtr.Zero; if (canonFormKind == CanonicalFormKind.Universal) { if (!TypeLoaderEnvironment.Instance.TryGetFieldOffset(declaringTypeHandle, entryParser.GetUnsigned() /* field ordinal */, out fieldOffset)) { Debug.Assert(false); return false; } } else { if ((entryFlags & FieldTableFlags.StorageClass) == FieldTableFlags.ThreadStatic) { if ((entryFlags & FieldTableFlags.FieldOffsetEncodedDirectly) != 0) { if ((entryFlags & FieldTableFlags.IsAnyCanonicalEntry) == 0) { int rvaToThreadStaticFieldOffsets = (int)externalReferences.GetRvaFromIndex(entryParser.GetUnsigned()); fieldAddressCookie = RvaToNonGenericStaticFieldAddress(mappingTableModule.Handle, rvaToThreadStaticFieldOffsets); threadStaticsStartOffset = *(int*)fieldAddressCookie.ToPointer(); } fieldOffset = (int)entryParser.GetUnsigned(); } else { int rvaToThreadStaticFieldOffsets = (int)externalReferences.GetRvaFromIndex(entryParser.GetUnsigned()); fieldAddressCookie = RvaToNonGenericStaticFieldAddress(mappingTableModule.Handle, rvaToThreadStaticFieldOffsets); ThreadStaticFieldOffsets* pThreadStaticFieldOffsets = (ThreadStaticFieldOffsets*)fieldAddressCookie.ToPointer(); threadStaticsStartOffset = (int)pThreadStaticFieldOffsets->StartingOffsetInTlsBlock; fieldOffset = (int)pThreadStaticFieldOffsets->FieldOffset; } } else { if ((entryFlags & FieldTableFlags.FieldOffsetEncodedDirectly) != 0) { fieldOffset = (int)entryParser.GetUnsigned(); } else { #if PROJECTN fieldOffset = (int)externalReferences.GetRvaFromIndex(entryParser.GetUnsigned()); #else fieldOffset = 0; fieldAddressCookie = externalReferences.GetFieldAddressFromIndex(entryParser.GetUnsigned()); if((entryFlags & FieldTableFlags.IsGcSection) != 0) fieldOffset = (int)entryParser.GetUnsigned(); #endif } } } if ((entryFlags & FieldTableFlags.StorageClass) == FieldTableFlags.ThreadStatic) { // TODO: CoreRT support if (!entryDeclaringTypeHandle.Equals(declaringTypeHandle)) { if (!TypeLoaderEnvironment.Instance.TryGetThreadStaticStartOffset(declaringTypeHandle, out threadStaticsStartOffset)) return false; } fieldAddressCookie = new IntPtr(threadStaticsStartOffset); } fieldAccessMetadata.MappingTableModule = mappingTableModule.Handle; fieldAccessMetadata.Cookie = fieldAddressCookie; fieldAccessMetadata.Flags = entryFlags; fieldAccessMetadata.Offset = fieldOffset; return true; } } return false; } private enum FieldAccessStaticDataKind { NonGC, GC, TLS } private static class FieldAccessFlags { public const int RemoteStaticFieldRVA = unchecked((int)0x80000000); } /// <summary> /// This structure describes one static field in an external module. It is represented /// by an indirection cell pointer and an offset within the cell - the final address /// of the static field is essentially *IndirectionCell + Offset. /// </summary> [StructLayout(LayoutKind.Sequential)] private struct RemoteStaticFieldDescriptor { public unsafe IntPtr* IndirectionCell; public int Offset; } /// <summary> /// Resolve a given 32-bit integer (staticFieldRVA) representing a static field address. /// For "local" static fields residing in the module given by moduleHandle, staticFieldRVA /// directly contains the RVA of the static field. For remote static fields residing in other /// modules, staticFieldRVA has the highest bit set (FieldAccessFlags.RemoteStaticFieldRVA) /// and it contains the RVA of a RemoteStaticFieldDescriptor structure residing in the module /// given by moduleHandle that holds a pointer to the indirection cell /// of the remote static field and its offset within the cell. /// </summary> /// <param name="moduleHandle">Reference module handle used for static field lookup</param> /// <param name="staticFieldRVA"> /// RVA of static field for local fields; for remote fields, RVA of a RemoteStaticFieldDescriptor /// structure for the field or-ed with the FieldAccessFlags.RemoteStaticFieldRVA bit /// </param> public static unsafe IntPtr RvaToNonGenericStaticFieldAddress(TypeManagerHandle moduleHandle, int staticFieldRVA) { IntPtr staticFieldAddress; if ((staticFieldRVA & FieldAccessFlags.RemoteStaticFieldRVA) != 0) { RemoteStaticFieldDescriptor* descriptor = (RemoteStaticFieldDescriptor*)(moduleHandle.ConvertRVAToPointer (staticFieldRVA & ~FieldAccessFlags.RemoteStaticFieldRVA)); staticFieldAddress = *descriptor->IndirectionCell + descriptor->Offset; } else staticFieldAddress = (IntPtr)(moduleHandle.ConvertRVAToPointer(staticFieldRVA)); return staticFieldAddress; } /// <summary> /// Try to look up non-gc/gc static effective field bases for a non-generic non-dynamic type. /// </summary> /// <param name="declaringTypeHandle">Declaring type for the method</param> /// <param name="fieldAccessKind">type of static base to find</param> /// <param name="staticsRegionAddress">Output - statics region address info</param> /// <returns>true when found, false otherwise</returns> private static unsafe bool TryGetStaticFieldBaseFromFieldAccessMap( RuntimeTypeHandle declaringTypeHandle, FieldAccessStaticDataKind fieldAccessKind, out IntPtr staticsRegionAddress) { staticsRegionAddress = IntPtr.Zero; byte* comparableStaticRegionAddress = null; CanonicallyEquivalentEntryLocator canonWrapper = new CanonicallyEquivalentEntryLocator(declaringTypeHandle, CanonicalFormKind.Specific); // This function only finds results for non-dynamic, non-generic types if (RuntimeAugments.IsDynamicType(declaringTypeHandle) || RuntimeAugments.IsGenericType(declaringTypeHandle)) return false; foreach (NativeFormatModuleInfo mappingTableModule in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(declaringTypeHandle))) { NativeReader fieldMapReader; if (!TryGetNativeReaderForBlob(mappingTableModule, ReflectionMapBlob.FieldAccessMap, out fieldMapReader)) continue; NativeParser fieldMapParser = new NativeParser(fieldMapReader, 0); NativeHashtable fieldHashtable = new NativeHashtable(fieldMapParser); ExternalReferencesTable externalReferences = default(ExternalReferencesTable); if (!externalReferences.InitializeCommonFixupsTable(mappingTableModule)) { continue; } var lookup = fieldHashtable.Lookup(canonWrapper.LookupHashCode); NativeParser entryParser; while (!(entryParser = lookup.GetNext()).IsNull) { // Grammar of a hash table entry: // Flags + DeclaringType + MdHandle or Name + Cookie or Ordinal or Offset FieldTableFlags entryFlags = (FieldTableFlags)entryParser.GetUnsigned(); Debug.Assert((entryFlags & FieldTableFlags.IsUniversalCanonicalEntry) == 0); if ((entryFlags & FieldTableFlags.Static) == 0) continue; switch (fieldAccessKind) { case FieldAccessStaticDataKind.NonGC: if ((entryFlags & FieldTableFlags.IsGcSection) != 0) continue; if ((entryFlags & FieldTableFlags.ThreadStatic) != 0) continue; break; case FieldAccessStaticDataKind.GC: if ((entryFlags & FieldTableFlags.IsGcSection) != 0) continue; if ((entryFlags & FieldTableFlags.ThreadStatic) != 0) continue; break; case FieldAccessStaticDataKind.TLS: default: // TODO! TLS statics Environment.FailFast("TLS static field access not yet supported"); return false; } RuntimeTypeHandle entryDeclaringTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned()); if (!entryDeclaringTypeHandle.Equals(declaringTypeHandle)) continue; if ((entryFlags & FieldTableFlags.HasMetadataHandle) != 0) { // skip metadata handle entryParser.GetUnsigned(); } else { // skip field name entryParser.SkipString(); } int cookieOrOffsetOrOrdinal = (int)entryParser.GetUnsigned(); int fieldOffset = (int)externalReferences.GetRvaFromIndex((uint)cookieOrOffsetOrOrdinal); IntPtr fieldAddress = RvaToNonGenericStaticFieldAddress( mappingTableModule.Handle, fieldOffset); if ((comparableStaticRegionAddress == null) || (comparableStaticRegionAddress > fieldAddress.ToPointer())) { comparableStaticRegionAddress = (byte*)fieldAddress.ToPointer(); } } // Static fields for a type can only be found in at most one module if (comparableStaticRegionAddress != null) break; } if (comparableStaticRegionAddress != null) { staticsRegionAddress = new IntPtr(comparableStaticRegionAddress); return true; } else { return false; } } /// <summary> /// Try to figure out field access information based on type metadata for native format types. /// </summary> /// <param name="metadataReader">Metadata reader for the declaring type</param> /// <param name="declaringTypeHandle">Declaring type for the method</param> /// <param name="fieldHandle">Field handle</param> /// <param name="canonFormKind">Canonical form to use</param> /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param> /// <returns>true when found, false otherwise</returns> private static bool TryGetFieldAccessMetadataFromNativeFormatMetadata( MetadataReader metadataReader, RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle, TypeSystemContext context, ref FieldAccessMetadata fieldAccessMetadata) { Field field = metadataReader.GetField(fieldHandle); string fieldName = metadataReader.GetString(field.Name); TypeDesc declaringType = context.ResolveRuntimeTypeHandle(declaringTypeHandle); #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING if (declaringType is MetadataType) { return TryGetFieldAccessMetadataForNativeFormatType(declaringType, fieldName, ref fieldAccessMetadata); } #endif return false; } /// <summary> /// Locate field on native format type and fill in the field access flags and offset. /// </summary> /// <param name="type">Metadata reader for the declaring type</param> /// <param name="fieldName">Field name</param> /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param> /// <returns>true when found, false otherwise</returns> private static bool TryGetFieldAccessMetadataForNativeFormatType( TypeDesc type, string fieldName, ref FieldAccessMetadata fieldAccessMetadata) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING FieldDesc fieldDesc = type.GetField(fieldName); if (fieldDesc == null) { return false; } fieldAccessMetadata.MappingTableModule = default(TypeManagerHandle); #if SUPPORTS_R2R_LOADING fieldAccessMetadata.MappingTableModule = ModuleList.Instance.GetModuleForMetadataReader(((NativeFormatType)type.GetTypeDefinition()).MetadataReader); #endif fieldAccessMetadata.Offset = fieldDesc.Offset.AsInt; fieldAccessMetadata.Flags = FieldTableFlags.HasMetadataHandle; if (fieldDesc.IsThreadStatic) { // Specify that the data is thread local fieldAccessMetadata.Flags |= FieldTableFlags.ThreadStatic; // Specify that the general purpose field access routine that only relies on offset should be used. fieldAccessMetadata.Flags |= FieldTableFlags.IsUniversalCanonicalEntry; } else if (fieldDesc.IsStatic) { uint nonGcStaticsRVA = 0; uint gcStaticsRVA = 0; bool nonGenericCase = false; if (type is MetadataType) { // Static fields on Non-Generic types are contained within the module, and their offsets // are adjusted by their static rva base. nonGenericCase = true; #if SUPPORTS_R2R_LOADING if (!TryGetStaticsTableEntry((MetadataType)type, nonGcStaticsRVA: out nonGcStaticsRVA, gcStaticsRVA: out gcStaticsRVA)) #endif { Environment.FailFast( "Failed to locate statics table entry for for field '" + fieldName + "' on type " + type.ToString()); } } if (fieldDesc.HasGCStaticBase) { if ((gcStaticsRVA == 0) && nonGenericCase) { Environment.FailFast( "GC statics region was not found for field '" + fieldName + "' on type " + type.ToString()); } fieldAccessMetadata.Offset += (int)gcStaticsRVA; fieldAccessMetadata.Flags |= FieldTableFlags.IsGcSection; } else { if ((nonGcStaticsRVA == 0) && nonGenericCase) { Environment.FailFast( "Non-GC statics region was not found for field '" + fieldName + "' on type " + type.ToString()); } fieldAccessMetadata.Offset += (int)nonGcStaticsRVA; } fieldAccessMetadata.Flags |= FieldTableFlags.Static; return true; } else { // Instance field fieldAccessMetadata.Flags |= FieldTableFlags.Instance; } return true; #else return false; #endif } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// JobOperations operations. /// </summary> public partial interface IJobOperations { /// <summary> /// Gets statistics of the specified job. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// Job Information ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobStatistics>> GetStatisticsWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the job debug data information specified by the job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobDataPath>> GetDebugDataPathWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Builds (compiles) the specified job in the specified Data Lake /// Analytics account for job correctness and validation. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='parameters'> /// The parameters to build a job. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobInformation>> BuildWithHttpMessagesAsync(string accountName, JobInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Cancels the running job specified by the job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID to cancel. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the job information for the specified job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobInformation>> GetWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Submits a job to the specified Data Lake Analytics account. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// The job ID (a GUID) for the job being submitted. /// </param> /// <param name='parameters'> /// The parameters to submit a job. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobInformation>> CreateWithHttpMessagesAsync(string accountName, Guid jobIdentity, JobInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the jobs, if any, associated with the specified Data Lake /// Analytics account. The response includes a link to the next page /// of results, if any. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to /// just those requested, e.g. /// Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the /// matching resources included with the resources in the response, /// e.g. Categories?$count=true. Optional. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<JobInformation>>> ListWithHttpMessagesAsync(string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the jobs, if any, associated with the specified Data Lake /// Analytics account. The response includes a link to the next page /// of results, if any. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<JobInformation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Media; /*using Microsoft.DirectX; // DirectSound stuff not working :( using Microsoft.DirectX.DirectSound;*/ namespace DotNET_Tests { public partial class AudioTest : Form { SoundPlayer player = new SoundPlayer(); // DirectSound stuff /*private Device ApplicationDevice = null; private DevicesCollection DevicesCollection = null; private SecondaryBuffer ApplicationBuffer = null;*/ private string original; // DLL Imports [System.Runtime.InteropServices.DllImport("winmm.DLL", EntryPoint = "PlaySound", SetLastError = true)] private static extern bool PlaySound(string szSound, System.IntPtr hMod, PlaySoundFlags flags); [System.Flags] public enum PlaySoundFlags : int { SND_SYNC = 0x0000, SND_ASYNC = 0x0001, SND_NODEFAULT = 0x0002, SND_LOOP = 0x0008, SND_NOSTOP = 0x0010, SND_NOWAIT = 0x00002000, SND_FILENAME = 0x00020000, SND_RESOURCE = 0x00040004 } // DirectSound device description /*private struct DeviceDescription { public DeviceInformation info; public override string ToString() { return info.Description; } public DeviceDescription(DeviceInformation d) { info = d; } }*/ // Loading public AudioTest() { InitializeComponent(); } private void AudioTest_Load(object sender, EventArgs e) { CenterToScreen(); labelWMPVersion.Text = "Windows Media Player Version: " + axWindowsMediaPlayer.versionInfo; labelWMPStatus.Text = "WMP Status: " + axWindowsMediaPlayer.status; // Retrieve the DirectSound Devices first. /*DevicesCollection = new DevicesCollection(); foreach (DeviceInformation dev in DevicesCollection) { DeviceDescription dd = new DeviceDescription(dev); comboBoxDXDevice.Items.Add(dd); } // Select the first item in the combobox if (0 < comboBoxDXDevice.Items.Count) comboBoxDXDevice.SelectedIndex = 0;*/ } // Basic tab private void buttonBasicBrowse_Click(object sender, EventArgs e) { if (openFileDialogWave.ShowDialog() == DialogResult.OK) textBoxBasicFileName.Text = openFileDialogWave.FileName; } private void buttonPlaySoundSync_Click(object sender, EventArgs e) { if (!PlaySound(textBoxBasicFileName.Text, new IntPtr(), PlaySoundFlags.SND_SYNC)) Tools.Error("Could not play sound"); } private void buttonPlaySoundAsync_Click(object sender, EventArgs e) { if (!PlaySound(textBoxBasicFileName.Text, new IntPtr(), PlaySoundFlags.SND_ASYNC | (checkBoxLoopAsync.Checked ? PlaySoundFlags.SND_LOOP : 0))) Tools.Error("Could not play sound"); } private void buttonStopAsync_Click(object sender, EventArgs e) { PlaySound(null, new IntPtr(), 0); } private void buttonSoundPlayerSync_Click(object sender, EventArgs e) { player.SoundLocation = textBoxBasicFileName.Text; player.PlaySync(); } private void buttonSoundPlayerAsync_Click(object sender, EventArgs e) { player.SoundLocation = textBoxBasicFileName.Text; if (checkBoxLoopAsync.Checked) player.PlayLooping(); else player.Play(); } private void buttonSoundPlayerStopAsync_Click(object sender, EventArgs e) { player.Stop(); } private void buttonSoundPlayerPlayResource_Click(object sender, EventArgs e) { player.Stream = DotNET_Tests.Properties.Resources.winAquariumSysStart; if (checkBoxLoopAsync.Checked) player.PlayLooping(); else player.Play(); } // WMP tab private void buttonWMPBrowse_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() != DialogResult.OK) return; textBoxWMPFileName.Text = openFileDialog.FileName; axWindowsMediaPlayer.URL = textBoxWMPFileName.Text; } private void buttonPlaylist_Click(object sender, EventArgs e) { WMPLib.IWMPPlaylistArray array = axWindowsMediaPlayer.playlistCollection.getAll(); contextMenuStripPlaylist.Items.Clear(); for (int x = 0; x < array.count; x++) { WMPLib.IWMPPlaylist playlist = array.Item(x); contextMenuStripPlaylist.Items.Add(playlist.name, null, contextMenuStripPlaylist_Click); } contextMenuStripPlaylist.Show(PointToScreen(new Point(buttonPlaylist.Left, buttonPlaylist.Bottom))); } private void contextMenuStripPlaylist_Click(object sender, EventArgs e) { WMPLib.IWMPPlaylistArray array = axWindowsMediaPlayer.playlistCollection.getAll(); for (int x = 0; x < array.count; x++) { WMPLib.IWMPPlaylist playlist = array.Item(x); if (sender.ToString() == playlist.name) axWindowsMediaPlayer.currentPlaylist = playlist; } } private void axWindowsMediaPlayer_StatusChange(object sender, EventArgs e) { labelWMPStatus.Text = "WMP Status: " + axWindowsMediaPlayer.status; } // DXAudio tab private void buttonDXBrowse_Click(object sender, EventArgs e) { if (openFileDialogWave.ShowDialog() == DialogResult.OK) textBoxDXFileName.Text = openFileDialogWave.FileName; } private void buttonDXPlay_Click(object sender, EventArgs e) { // Check to see if there is a device /*if (comboBoxDXDevice.Items.Count == 0) { Tools.Error("No devices are available"); return; } // Stop the sound if it's already playing before you open the the dialog if (ApplicationBuffer != null) { ApplicationBuffer.Stop(); } try { DeviceDescription itemSelect = (DeviceDescription)comboBoxDXDevice.Items[comboBoxDXDevice.SelectedIndex]; if (Guid.Empty == itemSelect.info.DriverGuid) ApplicationDevice = new Device(); else ApplicationDevice = new Device(itemSelect.info.DriverGuid); ApplicationDevice.SetCooperativeLevel(this, CooperativeLevel.Priority); } catch (Exception) { Tools.Error("Unable to create device"); return; } try { ApplicationBuffer = new SecondaryBuffer(textBoxDXFileName.Text, ApplicationDevice); } catch (Exception) { Tools.Error("Unable to create buffer"); return; } if (ApplicationBuffer != null) ApplicationBuffer.Play(0, BufferPlayFlags.Default);*/ } private void AudioTest_Deactivate(object sender, EventArgs e) { if (tabControl1.SelectedIndex == 1) { tabControl1.SelectedIndex = 0; original = textBoxWMPFileName.Text; axWindowsMediaPlayer.URL = ""; axWindowsMediaPlayer.Visible = false; textBoxWMPFileName.Text = ""; } } private void labelWMPStatus_Click(object sender, EventArgs e) { axWindowsMediaPlayer.Visible = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { //Only contains static methods. Does not require serialization using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Security; using System.Runtime; #if BIT64 using nuint = System.UInt64; #else // BIT64 using nuint = System.UInt32; #endif // BIT64 [System.Runtime.InteropServices.ComVisible(true)] public static class Buffer { // Copies from one primitive array to another primitive array without // respecting types. This calls memmove internally. The count and // offset parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); // A very simple and efficient memmove that assumes all of the // parameter validation has already been done. The count and offset // parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalBlockCopy(Array src, int srcOffsetBytes, Array dst, int dstOffsetBytes, int byteCount); // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates // pretty good code here and this ends up being within a couple % of the CRT asm. // It is however cross platform as the CRT hasn't ported their fast version to 64-bit // platforms. // [System.Security.SecurityCritical] // auto-generated internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count) { Contract.Assert(src != null, "src should not be null"); byte* pByte = src + index; // Align up the pointer to sizeof(int). while (((int)pByte & 3) != 0) { if (count == 0) return -1; else if (*pByte == value) return (int) (pByte - src); count--; pByte++; } // Fill comparer with value byte for comparisons // // comparer = 0/0/value/value uint comparer = (((uint)value << 8) + (uint)value); // comparer = value/value/value/value comparer = (comparer << 16) + comparer; // Run through buffer until we hit a 4-byte section which contains // the byte we're looking for or until we exhaust the buffer. while (count > 3) { // Test the buffer for presence of value. comparer contains the byte // replicated 4 times. uint t1 = *(uint*)pByte; t1 = t1 ^ comparer; uint t2 = 0x7efefeff + t1; t1 = t1 ^ 0xffffffff; t1 = t1 ^ t2; t1 = t1 & 0x81010100; // if t1 is zero then these 4-bytes don't contain a match if (t1 != 0) { // We've found a match for value, figure out which position it's in. int foundIndex = (int) (pByte - src); if (pByte[0] == value) return foundIndex; else if (pByte[1] == value) return foundIndex + 1; else if (pByte[2] == value) return foundIndex + 2; else if (pByte[3] == value) return foundIndex + 3; } count -= 4; pByte += 4; } // Catch any bytes that might be left at the tail of the buffer while (count > 0) { if (*pByte == value) return (int) (pByte - src); count--; pByte++; } // If we don't have a match return -1; return -1; } // Returns a bool to indicate if the array is of primitive data types // or not. [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsPrimitiveTypeArray(Array array); // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return ((byte*)array) + index. // [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern byte _GetByte(Array array, int index); [System.Security.SecuritySafeCritical] // auto-generated public static byte GetByte(Array array, int index) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException(nameof(index)); return _GetByte(array, index); } // Sets a particular byte in an the array. The array must be an // array of primitives. // // This essentially does the following: // *(((byte*)array) + index) = value. // [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _SetByte(Array array, int index, byte value); [System.Security.SecuritySafeCritical] // auto-generated public static void SetByte(Array array, int index, byte value) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException(nameof(index)); // Make the FCall to do the work _SetByte(array, index, value); } // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return array.length * sizeof(array.UnderlyingElementType). // [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int _ByteLength(Array array); [System.Security.SecuritySafeCritical] // auto-generated public static int ByteLength(Array array) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); return _ByteLength(array); } [System.Security.SecurityCritical] // auto-generated internal unsafe static void ZeroMemory(byte* src, long len) { while(len-- > 0) *(src + len) = 0; } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) { Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Contract.Assert(dest.Length - destIndex >= len, "not enough bytes in dest"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) return; fixed(byte* pDest = dest) { Memcpy(pDest + destIndex, src + srcIndex, len); } } [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len) { Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Contract.Assert(src.Length - srcIndex >= len, "not enough bytes in src"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) return; fixed(byte* pSrc = src) { Memcpy(pDest + destIndex, pSrc + srcIndex, len); } } // This is tricky to get right AND fast, so lets make it useful for the whole Fx. // E.g. System.Runtime.WindowsRuntime!WindowsRuntimeBufferExtensions.MemCopy uses it. // This method has a slightly different behavior on arm and other platforms. // On arm this method behaves like memcpy and does not handle overlapping buffers. // While on other platforms it behaves like memmove and handles overlapping buffers. // This behavioral difference is unfortunate but intentional because // 1. This method is given access to other internal dlls and this close to release we do not want to change it. // 2. It is difficult to get this right for arm and again due to release dates we would like to visit it later. [FriendAccessAllowed] [System.Security.SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if ARM [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe static extern void Memcpy(byte* dest, byte* src, int len); #else // ARM [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] internal unsafe static void Memcpy(byte* dest, byte* src, int len) { Contract.Assert(len >= 0, "Negative length in memcopy!"); Memmove(dest, src, (uint)len); } #endif // ARM // This method has different signature for x64 and other platforms and is done for performance reasons. [System.Security.SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memmove(byte* dest, byte* src, nuint len) { // P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards // This check can produce false positives for lengths greater than Int32.MaxInt. It is fine because we want to use PInvoke path for the large lengths anyway. if ((nuint)dest - (nuint)src < len) goto PInvoke; // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do. // // Ideally, we would just use the cpblk IL instruction here. Unfortunately, cpblk IL instruction is not as efficient as // possible yet and so we have this implementation here for now. // Note: It's important that this switch handles lengths at least up to 22. // See notes below near the main loop for why. // The switch will be very fast since it can be implemented using a jump // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info. switch (len) { case 0: return; case 1: *dest = *src; return; case 2: *(short*)dest = *(short*)src; return; case 3: *(short*)dest = *(short*)src; *(dest + 2) = *(src + 2); return; case 4: *(int*)dest = *(int*)src; return; case 5: *(int*)dest = *(int*)src; *(dest + 4) = *(src + 4); return; case 6: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); return; case 7: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); *(dest + 6) = *(src + 6); return; case 8: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif return; case 9: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(dest + 8) = *(src + 8); return; case 10: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); return; case 11: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); *(dest + 10) = *(src + 10); return; case 12: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); return; case 13: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(dest + 12) = *(src + 12); return; case 14: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); return; case 15: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); *(dest + 14) = *(src + 14); return; case 16: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif return; case 17: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(dest + 16) = *(src + 16); return; case 18: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(short*)(dest + 16) = *(short*)(src + 16); return; case 19: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(short*)(dest + 16) = *(short*)(src + 16); *(dest + 18) = *(src + 18); return; case 20: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); return; case 21: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); *(dest + 20) = *(src + 20); return; case 22: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); *(short*)(dest + 20) = *(short*)(src + 20); return; } // P/Invoke into the native version for large lengths if (len >= 512) goto PInvoke; nuint i = 0; // byte offset at which we're copying if (((int)dest & 3) != 0) { if (((int)dest & 1) != 0) { *(dest + i) = *(src + i); i += 1; if (((int)dest & 2) != 0) goto IntAligned; } *(short*)(dest + i) = *(short*)(src + i); i += 2; } IntAligned: #if BIT64 // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If // (int)dest % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1 // bytes to the next aligned address (respectively), so do nothing. On the other hand, // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until // we're aligned. // The thing 1, 2, 3, and 4 have in common that the others don't is that if you // subtract one from them, their 3rd lsb will not be set. Hence, the below check. if ((((int)dest - 1) & 4) == 0) { *(int*)(dest + i) = *(int*)(src + i); i += 4; } #endif // BIT64 nuint end = len - 16; len -= i; // lower 4 bits of len represent how many bytes are left *after* the unrolled loop // We know due to the above switch-case that this loop will always run 1 iteration; max // bytes we copy before checking is 23 (7 to align the pointers, 16 for 1 iteration) so // the switch handles lengths 0-22. Contract.Assert(end >= 7 && i <= end); // This is separated out into a different variable, so the i + 16 addition can be // performed at the start of the pipeline and the loop condition does not have // a dependency on the writes. nuint counter; do { counter = i + 16; // This loop looks very costly since there appear to be a bunch of temporary values // being created with the adds, but the jit (for x86 anyways) will convert each of // these to use memory addressing operands. // So the only cost is a bit of code size, which is made up for by the fact that // we save on writes to dest/src. #if BIT64 *(long*)(dest + i) = *(long*)(src + i); *(long*)(dest + i + 8) = *(long*)(src + i + 8); #else *(int*)(dest + i) = *(int*)(src + i); *(int*)(dest + i + 4) = *(int*)(src + i + 4); *(int*)(dest + i + 8) = *(int*)(src + i + 8); *(int*)(dest + i + 12) = *(int*)(src + i + 12); #endif i = counter; // See notes above for why this wasn't used instead // i += 16; } while (counter <= end); if ((len & 8) != 0) { #if BIT64 *(long*)(dest + i) = *(long*)(src + i); #else *(int*)(dest + i) = *(int*)(src + i); *(int*)(dest + i + 4) = *(int*)(src + i + 4); #endif i += 8; } if ((len & 4) != 0) { *(int*)(dest + i) = *(int*)(src + i); i += 4; } if ((len & 2) != 0) { *(short*)(dest + i) = *(short*)(src + i); i += 2; } if ((len & 1) != 0) { *(dest + i) = *(src + i); // We're not using i after this, so not needed // i += 1; } return; PInvoke: _Memmove(dest, src, len); } // Non-inlinable wrapper around the QCall that avoids poluting the fast path // with P/Invoke prolog/epilog. [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.NoInlining)] private unsafe static void _Memmove(byte* dest, byte* src, nuint len) { __Memmove(dest, src, len); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] extern private unsafe static void __Memmove(byte* dest, byte* src, nuint len); // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } Memmove((byte*)destination, (byte*)source, checked((nuint)sourceBytesToCopy)); } // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } #if BIT64 Memmove((byte*)destination, (byte*)source, sourceBytesToCopy); #else // BIT64 Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy)); #endif // BIT64 } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // 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.Collections.Generic; using System.Data; using System.Linq; using FluentMigrator.Builders.Execute; using FluentMigrator.Model; using FluentMigrator.Runner; using FluentMigrator.Runner.Processors.SqlServer; namespace FluentMigrator.SchemaDump.SchemaDumpers { public class SqlServerSchemaDumper : ISchemaDumper { public virtual IAnnouncer Announcer { get; set; } public SqlServerProcessor Processor { get; set; } public bool WasCommitted { get; private set; } public SqlServerSchemaDumper(SqlServerProcessor processor, IAnnouncer announcer) { this.Announcer = announcer; this.Processor = processor; } public virtual void Execute(string template, params object[] args) { Processor.Execute(template, args); } public virtual bool Exists(string template, params object[] args) { return Processor.Exists(template, args); } public virtual DataSet ReadTableData(string tableName) { return Processor.Read("SELECT * FROM [{0}]", tableName); } public virtual DataSet Read(string template, params object[] args) { return Processor.Read(template, args); } public virtual void Process(PerformDBOperationExpression expression) { Processor.Process(expression); } protected string FormatSqlEscape(string sql) { return sql.Replace("'", "''"); } public virtual IList<TableDefinition> ReadDbSchema() { IList<TableDefinition> tables = ReadTables(); foreach (TableDefinition table in tables) { table.Indexes = ReadIndexes(table.SchemaName, table.Name); table.ForeignKeys = ReadForeignKeys(table.SchemaName, table.Name); } return tables as IList<TableDefinition>; } protected virtual IList<FluentMigrator.Model.TableDefinition> ReadTables() { string query = @"SELECT OBJECT_SCHEMA_NAME(t.[object_id],DB_ID()) AS [Schema], t.name AS [Table], c.[Name] AS ColumnName, t.object_id AS [TableID], c.column_id AS [ColumnID], def.definition AS [DefaultValue], c.[system_type_id] AS [TypeID], c.[user_type_id] AS [UserTypeID], c.[max_length] AS [Length], c.[precision] AS [Precision], c.[scale] AS [Scale], c.[is_identity] AS [IsIdentity], c.[is_nullable] AS [IsNullable], CASE WHEN EXISTS(SELECT 1 FROM sys.foreign_key_columns fkc WHERE t.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id) THEN 1 ELSE 0 END AS IsForeignKey, CASE WHEN EXISTS(select 1 from sys.index_columns ic WHERE t.object_id = ic.object_id AND c.column_id = ic.column_id) THEN 1 ELSE 0 END AS IsIndexed ,CASE WHEN kcu.CONSTRAINT_NAME IS NOT NULL THEN 1 ELSE 0 END AS IsPrimaryKey , CASE WHEN EXISTS(select stc.CONSTRAINT_NAME, skcu.TABLE_NAME, skcu.COLUMN_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS stc JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE skcu ON skcu.CONSTRAINT_NAME = stc.CONSTRAINT_NAME WHERE stc.CONSTRAINT_TYPE = 'UNIQUE' AND skcu.TABLE_NAME = t.name AND skcu.COLUMN_NAME = c.name) THEN 1 ELSE 0 END AS IsUnique ,pk.name AS PrimaryKeyName FROM sys.all_columns c JOIN sys.tables t ON c.object_id = t.object_id AND t.type = 'u' LEFT JOIN sys.default_constraints def ON c.default_object_id = def.object_id LEFT JOIN sys.key_constraints pk ON t.object_id = pk.parent_object_id AND pk.type = 'PK' LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON t.name = kcu.TABLE_NAME AND c.name = kcu.COLUMN_NAME AND pk.name = kcu.CONSTRAINT_NAME ORDER BY t.name, c.name"; DataSet ds = Read(query); DataTable dt = ds.Tables[0]; IList<TableDefinition> tables = new List<TableDefinition>(); foreach (DataRow dr in dt.Rows) { List<TableDefinition> matches = (from t in tables where t.Name == dr["Table"].ToString() && t.SchemaName == dr["Schema"].ToString() select t).ToList(); TableDefinition tableDef = null; if (matches.Count > 0) tableDef = matches[0]; // create the table if not found if (tableDef == null) { tableDef = new TableDefinition() { Name = dr["Table"].ToString(), SchemaName = dr["Schema"].ToString() }; tables.Add(tableDef); } //find the column List<ColumnDefinition> cmatches = (from c in tableDef.Columns where c.Name == dr["ColumnName"].ToString() select c).ToList(); ColumnDefinition colDef = null; if (cmatches.Count > 0) colDef = cmatches[0]; if (colDef == null) { //need to create and add the column tableDef.Columns.Add(new ColumnDefinition() { Name = dr["ColumnName"].ToString(), CustomType = "", //TODO: set this property DefaultValue = dr.IsNull("DefaultValue") ? "" : dr["DefaultValue"].ToString(), IsForeignKey = dr["IsForeignKey"].ToString() == "1", IsIdentity = dr["IsIdentity"].ToString() == "1", IsIndexed = dr["IsIndexed"].ToString() == "1", IsNullable = dr["IsNullable"].ToString() == "1", IsPrimaryKey = dr["IsPrimaryKey"].ToString() == "1", IsUnique = dr["IsUnique"].ToString() == "1", Precision = int.Parse(dr["Precision"].ToString()), PrimaryKeyName = dr.IsNull("PrimaryKeyName") ? "" : dr["PrimaryKeyName"].ToString(), Size = int.Parse(dr["Length"].ToString()), TableName = dr["Table"].ToString(), Type = GetDbType(int.Parse(dr["TypeID"].ToString())), //TODO: set this property ModificationType = ColumnModificationType.Create }); } } return tables; } protected virtual DbType GetDbType(int typeNum) { switch (typeNum) { case 34: //'byte[]' return DbType.Byte; case 35: //'string' return DbType.String; case 36: //'System.Guid' return DbType.Guid; case 48: //'byte' return DbType.Byte; case 52: //'short' return DbType.Int16; case 56: //'int' return DbType.Int32; case 58: //'System.DateTime' return DbType.DateTime; case 59: //'float' return DbType.Int64; case 60: //'decimal' return DbType.Decimal; case 61: //'System.DateTime' return DbType.DateTime; case 62: //'double' return DbType.Double; case 98: //'object' return DbType.Object; case 99: //'string' return DbType.String; case 104: //'bool' return DbType.Boolean; case 106: //'decimal' return DbType.Decimal; case 108: //'decimal' return DbType.Decimal; case 122: //'decimal' return DbType.Decimal; case 127: //'long' return DbType.Int64; case 165: //'byte[]' return DbType.Byte; case 167: //'string' return DbType.String; case 173: //'byte[]' return DbType.Byte; case 175: //'string' return DbType.String; case 189: //'long' return DbType.Int64; case 231: //'string' case 239: //'string' case 241: //'string' default: return DbType.String; } } protected virtual IList<IndexDefinition> ReadIndexes(string schemaName, string tableName) { string query = @"SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema], T.[name] AS [table_name], I.[name] AS [index_name], AC.[name] AS [column_name], I.[type_desc], I.[is_unique], I.[data_space_id], I.[ignore_dup_key], I.[is_primary_key], I.[is_unique_constraint], I.[fill_factor], I.[is_padded], I.[is_disabled], I.[is_hypothetical], I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column] FROM sys.[tables] AS T INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id] INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' AND T.object_id = OBJECT_ID('[{0}].[{1}]') ORDER BY T.[name], I.[index_id], IC.[key_ordinal]"; DataSet ds = Read(query, schemaName, tableName); DataTable dt = ds.Tables[0]; IList<IndexDefinition> indexes = new List<IndexDefinition>(); foreach (DataRow dr in dt.Rows) { List<IndexDefinition> matches = (from i in indexes where i.Name == dr["index_name"].ToString() && i.SchemaName == dr["Schema"].ToString() select i).ToList(); IndexDefinition iDef = null; if (matches.Count > 0) iDef = matches[0]; // create the table if not found if (iDef == null) { iDef = new IndexDefinition() { Name = dr["index_name"].ToString(), SchemaName = dr["Schema"].ToString(), IsClustered = dr["type_desc"].ToString() == "CLUSTERED", IsUnique = dr["is_unique"].ToString() == "1", TableName = dr["table_name"].ToString() }; indexes.Add(iDef); } ICollection<IndexColumnDefinition> ms; // columns ms = (from m in iDef.Columns where m.Name == dr["column_name"].ToString() select m).ToList(); if (ms.Count == 0) { iDef.Columns.Add(new IndexColumnDefinition() { Name = dr["column_name"].ToString(), Direction = dr["is_descending_key"].ToString() == "1" ? Direction.Descending : Direction.Ascending }); } } return indexes; } protected virtual IList<ForeignKeyDefinition> ReadForeignKeys(string schemaName, string tableName) { string query = @"SELECT C.CONSTRAINT_SCHEMA AS Contraint_Schema, C.CONSTRAINT_NAME AS Constraint_Name, FK.CONSTRAINT_SCHEMA AS ForeignTableSchema, FK.TABLE_NAME AS FK_Table, CU.COLUMN_NAME AS FK_Column, PK.CONSTRAINT_SCHEMA as PrimaryTableSchema, PK.TABLE_NAME AS PK_Table, PT.COLUMN_NAME AS PK_Column FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE PK.TABLE_NAME = '{1}' AND PK.CONSTRAINT_SCHEMA = '{0}' ORDER BY Constraint_Name"; DataSet ds = Read(query, schemaName, tableName); DataTable dt = ds.Tables[0]; IList<ForeignKeyDefinition> keys = new List<ForeignKeyDefinition>(); foreach (DataRow dr in dt.Rows) { List<ForeignKeyDefinition> matches = (from i in keys where i.Name == dr["Constraint_Name"].ToString() select i).ToList(); ForeignKeyDefinition d = null; if (matches.Count > 0) d = matches[0]; // create the table if not found if (d == null) { d = new ForeignKeyDefinition() { Name = dr["Constraint_Name"].ToString(), ForeignTableSchema = dr["ForeignTableSchema"].ToString(), ForeignTable = dr["FK_Table"].ToString(), PrimaryTable = dr["PK_Table"].ToString(), PrimaryTableSchema = dr["PrimaryTableSchema"].ToString() }; keys.Add(d); } ICollection<string> ms; // Foreign Columns ms = (from m in d.ForeignColumns where m == dr["FK_Table"].ToString() select m).ToList(); if (ms.Count == 0) d.ForeignColumns.Add(dr["FK_Table"].ToString()); // Primary Columns ms = (from m in d.PrimaryColumns where m == dr["PK_Table"].ToString() select m).ToList(); if (ms.Count == 0) d.PrimaryColumns.Add(dr["PK_Table"].ToString()); } return keys; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // #if FEATURE_UTF32 namespace System.Text { using System; using System.Diagnostics.Contracts; using System.Globalization; // Encodes text into and out of UTF-32. UTF-32 is a way of writing // Unicode characters with a single storage unit (32 bits) per character, // // The UTF-32 byte order mark is simply the Unicode byte order mark // (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order // mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't // switch the byte orderings. [Serializable] public sealed class UTF32Encoding : Encoding { /* words bits UTF-32 representation ----- ---- ----------------------------------- 1 16 00000000 00000000 xxxxxxxx xxxxxxxx 2 21 00000000 000xxxxx hhhhhhll llllllll ----- ---- ----------------------------------- Surrogate: Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000 */ // private bool emitUTF32ByteOrderMark = false; private bool isThrowException = false; private bool bigEndian = false; public UTF32Encoding(): this(false, true, false) { } public UTF32Encoding(bool bigEndian, bool byteOrderMark): this(bigEndian, byteOrderMark, false) { } public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters): base(bigEndian ? 12001 : 12000) { this.bigEndian = bigEndian; this.emitUTF32ByteOrderMark = byteOrderMark; this.isThrowException = throwOnInvalidCharacters; // Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions if (this.isThrowException) SetDefaultFallbacks(); } internal override void SetDefaultFallbacks() { // For UTF-X encodings, we use a replacement fallback with an empty string if (this.isThrowException) { this.encoderFallback = EncoderFallback.ExceptionFallback; this.decoderFallback = DecoderFallback.ExceptionFallback; } else { this.encoderFallback = new EncoderReplacementFallback("\xFFFD"); this.decoderFallback = new DecoderReplacementFallback("\xFFFD"); } } // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (chars.Length == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetByteCount(String s) { // Validate input if (s==null) throw new ArgumentNullException("s"); Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", Environment.GetResourceString("ArgumentOutOfRange_IndexCount")); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fix our input array if 0 length because fixed doesn't like 0 length arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed ( byte* pBytes = bytes) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (chars.Length == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fix our input array if 0 length because fixed doesn't like 0 length arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = bytes) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays. if (bytes.Length == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (bytes.Length == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fix our input array if 0 length because fixed doesn't like 0 length arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = chars) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // auto-generated public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (bytes.Length == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } // // End of standard methods copied from EncodingNLS.cs // [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder) { Contract.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null"); Contract.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0"); char* end = chars + count; char* charStart = chars; int byteCount = 0; char highSurrogate = '\0'; // For fallback we may need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; if (encoder != null) { highSurrogate = encoder.charLeftOver; fallbackBuffer = encoder.FallbackBuffer; // We mustn't have left over fallback data when counting if (fallbackBuffer.Remaining > 0) throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType())); } else { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, end, encoder, false); char ch; TryAgain: while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Do we need a low surrogate? if (highSurrogate != '\0') { // // In previous char, we encounter a high surrogate, so we are expecting a low surrogate here. // if (Char.IsLowSurrogate(ch)) { // They're all legal highSurrogate = '\0'; // // One surrogate pair will be translated into 4 bytes UTF32. // byteCount += 4; continue; } // We are missing our low surrogate, decrement chars and fallback the high surrogate // The high surrogate may have come from the encoder, but nothing else did. Contract.Assert(chars > charStart, "[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate"); chars--; // Do the fallback fallbackBuffer.InternalFallback(highSurrogate, ref chars); // We're going to fallback the old high surrogate. highSurrogate = '\0'; continue; } // Do we have another high surrogate? if (Char.IsHighSurrogate(ch)) { // // We'll have a high surrogate to check next time. // highSurrogate = ch; continue; } // Check for illegal characters if (Char.IsLowSurrogate(ch)) { // We have a leading low surrogate, do the fallback fallbackBuffer.InternalFallback(ch, ref chars); // Try again with fallback buffer continue; } // We get to add the character (4 bytes UTF32) byteCount += 4; } // May have to do our last surrogate if ((encoder == null || encoder.MustFlush) && highSurrogate > 0) { // We have to do the fallback for the lonely high surrogate fallbackBuffer.InternalFallback(highSurrogate, ref chars); highSurrogate = (char)0; goto TryAgain; } // Check for overflows. if (byteCount < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString( "ArgumentOutOfRange_GetByteCountOverflow")); // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check m_throwOnOverflow for count) Contract.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end"); // Return our count return byteCount; } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char *chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { Contract.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null"); Contract.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null"); Contract.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0"); Contract.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0"); char* charStart = chars; char* charEnd = chars + charCount; byte* byteStart = bytes; byte* byteEnd = bytes + byteCount; char highSurrogate = '\0'; // For fallback we may need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; if (encoder != null) { highSurrogate = encoder.charLeftOver; fallbackBuffer = encoder.FallbackBuffer; // We mustn't have left over fallback data when not converting if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0) throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType())); } else { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); char ch; TryAgain: while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Do we need a low surrogate? if (highSurrogate != '\0') { // // In previous char, we encountered a high surrogate, so we are expecting a low surrogate here. // if (Char.IsLowSurrogate(ch)) { // Is it a legal one? uint iTemp = GetSurrogate(highSurrogate, ch); highSurrogate = '\0'; // // One surrogate pair will be translated into 4 bytes UTF32. // if (bytes+3 >= byteEnd) { // Don't have 4 bytes if (fallbackBuffer.bFallingBack) { fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars fallbackBuffer.MovePrevious(); } else { // If we don't have enough room, then either we should've advanced a while // or we should have bytes==byteStart and throw below Contract.Assert(chars > charStart + 1 || bytes == byteStart, "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair"); chars-=2; // Aren't using those 2 chars } ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written) highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary) break; } if (bigEndian) { *(bytes++) = (byte)(0x00); *(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0 *(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF *(bytes++) = (byte)(iTemp); // Implies & 0xFF } else { *(bytes++) = (byte)(iTemp); // Implies & 0xFF *(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF *(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0 *(bytes++) = (byte)(0x00); } continue; } // We are missing our low surrogate, decrement chars and fallback the high surrogate // The high surrogate may have come from the encoder, but nothing else did. Contract.Assert(chars > charStart, "[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate"); chars--; // Do the fallback fallbackBuffer.InternalFallback(highSurrogate, ref chars); // We're going to fallback the old high surrogate. highSurrogate = '\0'; continue; } // Do we have another high surrogate?, if so remember it if (Char.IsHighSurrogate(ch)) { // // We'll have a high surrogate to check next time. // highSurrogate = ch; continue; } // Check for illegal characters (low surrogate) if (Char.IsLowSurrogate(ch)) { // We have a leading low surrogate, do the fallback fallbackBuffer.InternalFallback(ch, ref chars); // Try again with fallback buffer continue; } // We get to add the character, yippee. if (bytes+3 >= byteEnd) { // Don't have 4 bytes if (fallbackBuffer.bFallingBack) fallbackBuffer.MovePrevious(); // Aren't using this fallback char else { // Must've advanced already Contract.Assert(chars > charStart, "[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character"); chars--; // Aren't using this char } ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written) break; // Didn't throw, stop } if (bigEndian) { *(bytes++) = (byte)(0x00); *(bytes++) = (byte)(0x00); *(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF *(bytes++) = (byte)(ch); // Implies & 0xFF } else { *(bytes++) = (byte)(ch); // Implies & 0xFF *(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF *(bytes++) = (byte)(0x00); *(bytes++) = (byte)(0x00); } } // May have to do our last surrogate if ((encoder == null || encoder.MustFlush) && highSurrogate > 0) { // We have to do the fallback for the lonely high surrogate fallbackBuffer.InternalFallback(highSurrogate, ref chars); highSurrogate = (char)0; goto TryAgain; } // Fix our encoder if we have one Contract.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush), "[UTF32Encoding.GetBytes]Expected encoder to be flushed."); if (encoder != null) { // Remember our left over surrogate (or 0 if flushing) encoder.charLeftOver = highSurrogate; // Need # chars used encoder.m_charsUsed = (int)(chars-charStart); } // return the new length return (int)(bytes - byteStart); } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Contract.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null"); Contract.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0"); UTF32Decoder decoder = (UTF32Decoder)baseDecoder; // None so far! int charCount = 0; byte* end = bytes + count; byte* byteStart = bytes; // Set up decoder int readCount = 0; uint iChar = 0; // For fallback we may need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; // See if there's anything in our decoder if (decoder != null) { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; fallbackBuffer = decoder.FallbackBuffer; // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for chars or count) Contract.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start"); } else { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, null); // Loop through our input, 4 characters at a time! while (bytes < end && charCount >= 0) { // Get our next character if(bigEndian) { // Scoot left and add it to the bottom iChar <<= 8; iChar += *(bytes++); } else { // Scoot right and add it to the top iChar >>= 8; iChar += (uint)(*(bytes++)) << 24; } readCount++; // See if we have all the bytes yet if (readCount < 4) continue; // Have the bytes readCount = 0; // See if its valid to encode if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF)) { // Need to fall back these 4 bytes byte[] fallbackBytes; if (this.bigEndian) { fallbackBytes = new byte[] { unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) }; } else { fallbackBytes = new byte[] { unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)), unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) }; } charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes); // Ignore the illegal character iChar = 0; continue; } // Ok, we have something we can add to our output if (iChar >= 0x10000) { // Surrogates take 2 charCount++; } // Add the rest of the surrogate or our normal character charCount++; // iChar is back to 0 iChar = 0; } // See if we have something left over that has to be decoded if (readCount > 0 && (decoder == null || decoder.MustFlush)) { // Oops, there's something left over with no place to go. byte[] fallbackBytes = new byte[readCount]; if (this.bigEndian) { while(readCount > 0) { fallbackBytes[--readCount] = unchecked((byte)iChar); iChar >>= 8; } } else { while (readCount > 0) { fallbackBytes[--readCount] = unchecked((byte)(iChar>>24)); iChar <<= 8; } } charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes); } // Check for overflows. if (charCount < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for chars or count) Contract.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end"); // Return our count return charCount; } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Contract.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null"); Contract.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null"); Contract.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0"); Contract.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0"); UTF32Decoder decoder = (UTF32Decoder)baseDecoder; // None so far! char* charStart = chars; char* charEnd = chars + charCount; byte* byteStart = bytes; byte* byteEnd = bytes + byteCount; // See if there's anything in our decoder (but don't clear it yet) int readCount = 0; uint iChar = 0; // For fallback we may need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; // See if there's anything in our decoder if (decoder != null) { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; fallbackBuffer = baseDecoder.FallbackBuffer; // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) Contract.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetChars]Expected empty fallback buffer at start"); } else { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(bytes, chars + charCount); // Loop through our input, 4 characters at a time! while (bytes < byteEnd) { // Get our next character if(bigEndian) { // Scoot left and add it to the bottom iChar <<= 8; iChar += *(bytes++); } else { // Scoot right and add it to the top iChar >>= 8; iChar += (uint)(*(bytes++)) << 24; } readCount++; // See if we have all the bytes yet if (readCount < 4) continue; // Have the bytes readCount = 0; // See if its valid to encode if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF)) { // Need to fall back these 4 bytes byte[] fallbackBytes; if (this.bigEndian) { fallbackBytes = new byte[] { unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) }; } else { fallbackBytes = new byte[] { unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)), unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) }; } // Chars won't be updated unless this works. if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars)) { // Couldn't fallback, throw or wait til next time // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart Contract.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing fallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output break; // Stop here, didn't throw } // Ignore the illegal character iChar = 0; continue; } // Ok, we have something we can add to our output if (iChar >= 0x10000) { // Surrogates take 2 if (chars >= charEnd - 1) { // Throwing or stopping // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart Contract.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output break; // Stop here, didn't throw } *(chars++) = GetHighSurrogate(iChar); iChar = GetLowSurrogate(iChar); } // Bounds check for normal character else if (chars >= charEnd) { // Throwing or stopping // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart Contract.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)"); bytes-=4; // get back to where we were iChar=0; // Remembering nothing ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output break; // Stop here, didn't throw } // Add the rest of the surrogate or our normal character *(chars++) = (char)iChar; // iChar is back to 0 iChar = 0; } // See if we have something left over that has to be decoded if (readCount > 0 && (decoder == null || decoder.MustFlush)) { // Oops, there's something left over with no place to go. byte[] fallbackBytes = new byte[readCount]; int tempCount = readCount; if (this.bigEndian) { while(tempCount > 0) { fallbackBytes[--tempCount] = unchecked((byte)iChar); iChar >>= 8; } } else { while (tempCount > 0) { fallbackBytes[--tempCount] = unchecked((byte)(iChar>>24)); iChar <<= 8; } } if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars)) { // Couldn't fallback. fallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output // Stop here, didn't throw, backed up, so still nothing in buffer } else { // Don't clear our decoder unless we could fall it back. // If we caught the if above, then we're a convert() and will catch this next time. readCount = 0; iChar = 0; } } // Remember any left over stuff, clearing buffer as well for MustFlush if (decoder != null) { decoder.iChar = (int)iChar; decoder.readByteCount = readCount; decoder.m_bytesUsed = (int)(bytes - byteStart); } // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) Contract.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetChars]Expected empty fallback buffer at end"); // Return our count return (int)(chars - charStart); } private uint GetSurrogate(char cHigh, char cLow) { return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000; } private char GetHighSurrogate(uint iChar) { return (char)((iChar - 0x10000) / 0x400 + 0xD800); } private char GetLowSurrogate(uint iChar) { return (char)((iChar - 0x10000) % 0x400 + 0xDC00); } public override Decoder GetDecoder() { return new UTF32Decoder(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 4 bytes per char byteCount *= 4; if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars, // plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char. // Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair int charCount = (byteCount / 2) + 2; // Also consider fallback because our input bytes could be out of range of unicode. // Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount. if (DecoderFallback.MaxCharCount > 2) { // Multiply time fallback size charCount *= DecoderFallback.MaxCharCount; // We were already figuring 2 chars per 4 bytes, but fallback will be different # charCount /= 2; } if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } public override byte[] GetPreamble() { if (emitUTF32ByteOrderMark) { // Allocate new array to prevent users from modifying it. if (bigEndian) { return new byte[4] { 0x00, 0x00, 0xFE, 0xFF }; } else { return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF } } else return EmptyArray<Byte>.Value; } public override bool Equals(Object value) { UTF32Encoding that = value as UTF32Encoding; if (that != null) { return (emitUTF32ByteOrderMark == that.emitUTF32ByteOrderMark) && (bigEndian == that.bigEndian) && // (isThrowException == that.isThrowException) && // same as encoder/decoderfallback being exceptions (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } return (false); } public override int GetHashCode() { //Not great distribution, but this is relatively unlikely to be used as the key in a hashtable. return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() + CodePage + (emitUTF32ByteOrderMark?4:0) + (bigEndian?8:0); } [Serializable] internal class UTF32Decoder : DecoderNLS { // Need a place to store any extra bytes we may have picked up internal int iChar = 0; internal int readByteCount = 0; public UTF32Decoder(UTF32Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.iChar = 0; this.readByteCount = 0; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Anything left in our decoder? internal override bool HasState { get { // ReadByteCount is our flag. (iChar==0 doesn't mean much). return (this.readByteCount != 0); } } } } } #endif // FEATURE_UTF32
namespace XenAdmin.Dialogs { partial class AddServerDialog { /// <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(AddServerDialog)); this.AddButton = new System.Windows.Forms.Button(); this.CancelButton2 = new System.Windows.Forms.Button(); this.ServerNameLabel = new System.Windows.Forms.Label(); this.UsernameLabel = new System.Windows.Forms.Label(); this.PasswordLabel = new System.Windows.Forms.Label(); this.UsernameTextBox = new System.Windows.Forms.TextBox(); this.PasswordTextBox = new System.Windows.Forms.TextBox(); this.ServerNameComboBox = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tableLayoutPanelCreds = new System.Windows.Forms.TableLayoutPanel(); this.labelError = new System.Windows.Forms.Label(); this.pictureBoxError = new System.Windows.Forms.PictureBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.comboBoxClouds = new System.Windows.Forms.ComboBox(); this.labelInstructions = new System.Windows.Forms.Label(); this.tableLayoutPanelType = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.groupBox1.SuspendLayout(); this.tableLayoutPanelCreds.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).BeginInit(); this.flowLayoutPanel1.SuspendLayout(); this.tableLayoutPanelType.SuspendLayout(); this.SuspendLayout(); // // AddButton // resources.ApplyResources(this.AddButton, "AddButton"); this.AddButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.AddButton.Name = "AddButton"; this.AddButton.UseVisualStyleBackColor = true; this.AddButton.Click += new System.EventHandler(this.AddButton_Click); // // CancelButton2 // resources.ApplyResources(this.CancelButton2, "CancelButton2"); this.CancelButton2.CausesValidation = false; this.CancelButton2.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.CancelButton2.Name = "CancelButton2"; this.CancelButton2.UseVisualStyleBackColor = true; this.CancelButton2.Click += new System.EventHandler(this.CancelButton2_Click); this.CancelButton2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.CancelButton2_KeyDown); // // ServerNameLabel // resources.ApplyResources(this.ServerNameLabel, "ServerNameLabel"); this.ServerNameLabel.Name = "ServerNameLabel"; // // UsernameLabel // resources.ApplyResources(this.UsernameLabel, "UsernameLabel"); this.UsernameLabel.Name = "UsernameLabel"; // // PasswordLabel // resources.ApplyResources(this.PasswordLabel, "PasswordLabel"); this.PasswordLabel.Name = "PasswordLabel"; // // UsernameTextBox // resources.ApplyResources(this.UsernameTextBox, "UsernameTextBox"); this.UsernameTextBox.Name = "UsernameTextBox"; this.UsernameTextBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged); // // PasswordTextBox // resources.ApplyResources(this.PasswordTextBox, "PasswordTextBox"); this.PasswordTextBox.Name = "PasswordTextBox"; this.PasswordTextBox.UseSystemPasswordChar = true; this.PasswordTextBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged); // // ServerNameComboBox // resources.ApplyResources(this.ServerNameComboBox, "ServerNameComboBox"); this.ServerNameComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.ServerNameComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource; this.tableLayoutPanelType.SetColumnSpan(this.ServerNameComboBox, 2); this.ServerNameComboBox.Name = "ServerNameComboBox"; this.ServerNameComboBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged); // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.tableLayoutPanelType.SetColumnSpan(this.groupBox1, 3); this.groupBox1.Controls.Add(this.tableLayoutPanelCreds); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // tableLayoutPanelCreds // resources.ApplyResources(this.tableLayoutPanelCreds, "tableLayoutPanelCreds"); this.tableLayoutPanelCreds.Controls.Add(this.UsernameLabel, 0, 0); this.tableLayoutPanelCreds.Controls.Add(this.PasswordLabel, 0, 1); this.tableLayoutPanelCreds.Controls.Add(this.PasswordTextBox, 1, 1); this.tableLayoutPanelCreds.Controls.Add(this.UsernameTextBox, 1, 0); this.tableLayoutPanelCreds.Controls.Add(this.labelError, 1, 2); this.tableLayoutPanelCreds.Controls.Add(this.pictureBoxError, 0, 2); this.tableLayoutPanelCreds.Name = "tableLayoutPanelCreds"; // // labelError // resources.ApplyResources(this.labelError, "labelError"); this.labelError.Name = "labelError"; this.labelError.TextChanged += new System.EventHandler(this.labelError_TextChanged); // // pictureBoxError // resources.ApplyResources(this.pictureBoxError, "pictureBoxError"); this.pictureBoxError.Image = global::XenAdmin.Properties.Resources._000_error_h32bit_16; this.pictureBoxError.Name = "pictureBoxError"; this.pictureBoxError.TabStop = false; // // flowLayoutPanel1 // resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.tableLayoutPanelType.SetColumnSpan(this.flowLayoutPanel1, 3); this.flowLayoutPanel1.Controls.Add(this.CancelButton2); this.flowLayoutPanel1.Controls.Add(this.AddButton); this.flowLayoutPanel1.Controls.Add(this.comboBoxClouds); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // comboBoxClouds // this.comboBoxClouds.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.comboBoxClouds, "comboBoxClouds"); this.comboBoxClouds.FormattingEnabled = true; this.comboBoxClouds.Name = "comboBoxClouds"; // // labelInstructions // resources.ApplyResources(this.labelInstructions, "labelInstructions"); this.tableLayoutPanelType.SetColumnSpan(this.labelInstructions, 3); this.labelInstructions.MaximumSize = new System.Drawing.Size(355, 100); this.labelInstructions.Name = "labelInstructions"; // // tableLayoutPanelType // resources.ApplyResources(this.tableLayoutPanelType, "tableLayoutPanelType"); this.tableLayoutPanelType.Controls.Add(this.ServerNameComboBox, 1, 2); this.tableLayoutPanelType.Controls.Add(this.groupBox1, 0, 3); this.tableLayoutPanelType.Controls.Add(this.ServerNameLabel, 0, 2); this.tableLayoutPanelType.Controls.Add(this.labelInstructions, 0, 0); this.tableLayoutPanelType.Controls.Add(this.flowLayoutPanel1, 0, 4); this.tableLayoutPanelType.Name = "tableLayoutPanelType"; // // tableLayoutPanel2 // resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2"); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; // // AddServerDialog // this.AcceptButton = this.AddButton; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.CancelButton2; this.Controls.Add(this.tableLayoutPanelType); this.Name = "AddServerDialog"; this.Load += new System.EventHandler(this.AddServerDialog_Load); this.Shown += new System.EventHandler(this.AddServerDialog_Shown); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.tableLayoutPanelCreds.ResumeLayout(false); this.tableLayoutPanelCreds.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).EndInit(); this.flowLayoutPanel1.ResumeLayout(false); this.tableLayoutPanelType.ResumeLayout(false); this.tableLayoutPanelType.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion protected System.Windows.Forms.Label ServerNameLabel; protected System.Windows.Forms.Label UsernameLabel; protected System.Windows.Forms.Label PasswordLabel; protected System.Windows.Forms.TextBox UsernameTextBox; protected System.Windows.Forms.TextBox PasswordTextBox; protected System.Windows.Forms.ComboBox ServerNameComboBox; protected System.Windows.Forms.Button CancelButton2; protected System.Windows.Forms.Button AddButton; protected System.Windows.Forms.GroupBox groupBox1; protected System.Windows.Forms.TableLayoutPanel tableLayoutPanelCreds; protected System.Windows.Forms.PictureBox pictureBoxError; protected System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; protected System.Windows.Forms.Label labelError; protected System.Windows.Forms.Label labelInstructions; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; protected System.Windows.Forms.RadioButton XenServerRadioButton; protected System.Windows.Forms.TableLayoutPanel tableLayoutPanelType; private System.Windows.Forms.ComboBox comboBoxClouds; } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERLevel; namespace SelfLoad.Business.ERLevel { /// <summary> /// C11_CityRoadColl (editable child list).<br/> /// This is a generated base class of <see cref="C11_CityRoadColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="C10_City"/> editable child object.<br/> /// The items of the collection are <see cref="C12_CityRoad"/> objects. /// </remarks> [Serializable] public partial class C11_CityRoadColl : BusinessListBase<C11_CityRoadColl, C12_CityRoad> { #region Collection Business Methods /// <summary> /// Removes a <see cref="C12_CityRoad"/> item from the collection. /// </summary> /// <param name="cityRoad_ID">The CityRoad_ID of the item to be removed.</param> public void Remove(int cityRoad_ID) { foreach (var c12_CityRoad in this) { if (c12_CityRoad.CityRoad_ID == cityRoad_ID) { Remove(c12_CityRoad); break; } } } /// <summary> /// Determines whether a <see cref="C12_CityRoad"/> item is in the collection. /// </summary> /// <param name="cityRoad_ID">The CityRoad_ID of the item to search for.</param> /// <returns><c>true</c> if the C12_CityRoad is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int cityRoad_ID) { foreach (var c12_CityRoad in this) { if (c12_CityRoad.CityRoad_ID == cityRoad_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="C12_CityRoad"/> item is in the collection's DeletedList. /// </summary> /// <param name="cityRoad_ID">The CityRoad_ID of the item to search for.</param> /// <returns><c>true</c> if the C12_CityRoad is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int cityRoad_ID) { foreach (var c12_CityRoad in DeletedList) { if (c12_CityRoad.CityRoad_ID == cityRoad_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="C12_CityRoad"/> item of the <see cref="C11_CityRoadColl"/> collection, based on a given CityRoad_ID. /// </summary> /// <param name="cityRoad_ID">The CityRoad_ID.</param> /// <returns>A <see cref="C12_CityRoad"/> object.</returns> public C12_CityRoad FindC12_CityRoadByCityRoad_ID(int cityRoad_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].CityRoad_ID.Equals(cityRoad_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C11_CityRoadColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="C11_CityRoadColl"/> collection.</returns> internal static C11_CityRoadColl NewC11_CityRoadColl() { return DataPortal.CreateChild<C11_CityRoadColl>(); } /// <summary> /// Factory method. Loads a <see cref="C11_CityRoadColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_City_ID">The Parent_City_ID parameter of the C11_CityRoadColl to fetch.</param> /// <returns>A reference to the fetched <see cref="C11_CityRoadColl"/> collection.</returns> internal static C11_CityRoadColl GetC11_CityRoadColl(int parent_City_ID) { return DataPortal.FetchChild<C11_CityRoadColl>(parent_City_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C11_CityRoadColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C11_CityRoadColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="C11_CityRoadColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_City_ID">The Parent City ID.</param> protected void Child_Fetch(int parent_City_ID) { var args = new DataPortalHookArgs(parent_City_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<IC11_CityRoadCollDal>(); var data = dal.Fetch(parent_City_ID); LoadCollection(data); } OnFetchPost(args); } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="C11_CityRoadColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(C12_CityRoad.GetC12_CityRoad(dr)); } RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Diagnostics; using System.Xml; namespace Microsoft.SharePointIntegration { /// <summary> /// Static class with general utilities for manipulating strings. /// </summary> public static partial class TextUtilities { public static byte[] GetBytesFromString(String str) { return Encoding.UTF8.GetBytes(str); } public static char CharAt(this String str, int index) { return str[index]; } public static String GetSimplifiedString(String name) { String result = String.Empty; foreach (char c in name) { if (Char.IsDigit(c) || Char.IsLetter(c)) { result += c; } } return result; } public static String Normalize(String name) { String normalizedName= String.Empty; foreach (Char c in name) { if (Char.IsLetterOrDigit(c)) { normalizedName += c; } } return normalizedName; } public static IEnumerable<int> GetWordInstances(String source, String word, StringComparison comparisonType) { List<int> instances = null; int i = source.IndexOf(word, comparisonType); while (i >= 0) { bool isWord = true; if (i > 0) { isWord = TextUtilities.IsBreakerChar(source[i - 1]); } if (isWord && i + word.Length < source.Length - 1) { isWord = TextUtilities.IsBreakerChar(source[i + word.Length]); } if (isWord) { if (instances == null) { instances = new List<int>(); } instances.Add(i); } i = source.IndexOf(word, i + 1, comparisonType); } return instances; } public static bool ContainsWord(String source, String word, StringComparison comparisonType) { int i = source.IndexOf(word, comparisonType); while (i >= 0) { bool isWord = true; if (i > 0) { isWord = TextUtilities.IsBreakerChar(source[i - 1]); } if (isWord && i + word.Length < source.Length - 1) { isWord = TextUtilities.IsBreakerChar(source[i + word.Length]); } if (isWord) { return true; } i = source.IndexOf(word, i + 1, comparisonType); } return false; } public static bool IsInteger(String text) { int result = 0; return Int32.TryParse(text, out result); } public static bool IsBreakerChar(char cand) { return Char.IsControl(cand) || Char.IsPunctuation(cand) || Char.IsSeparator(cand); } public static String RemoveTextToLeftOfNewLine(String text, int index) { if (index > text.Length) { index = text.Length; } int left = -1; int nextChar = text.LastIndexOf("\r", index); if (nextChar > left) { left = nextChar; } nextChar = text.LastIndexOf("\n", index); if (nextChar > left) { left = nextChar; } nextChar = text.LastIndexOf("\t", index); if (nextChar > left) { left = nextChar; } if (left > 0) { text = text.Substring(left +1, text.Length - (left + 1)); } return text; } public static String RemoveTextToRightOfNewLine(String text, int index) { if (index < 0) { index = 0; } int right = text.Length + 1; int nextChar = text.IndexOf("\r", index); if (nextChar < right && nextChar >= 0) { right = nextChar; } nextChar = text.IndexOf("\n", index); if (nextChar < right && nextChar >= 0) { right = nextChar; } nextChar = text.IndexOf("\t", index); if (nextChar < right && nextChar >= 0) { right = nextChar; } if (right < text.Length) { text = text.Substring(0, right); } return text; } public static void ConvertAllTagsToSingleton(ref String source, String tagName) { Regex regexSpecificTagStart = new Regex("<" + tagName + "(\\s|>)"); Match matchSpecificTagStart = regexSpecificTagStart.Match(source); while (matchSpecificTagStart.Success) { int i = matchSpecificTagStart.Index; int nextTagStart= source.IndexOf("<", i + 1); int nextStartTagEnd= source.IndexOf(">", i + 1); int nextSingletonTagEnd = source.IndexOf("/>", i + 1); if ( nextSingletonTagEnd < 0 || // make sure this tag is not a singleton (nextTagStart > i && nextSingletonTagEnd > nextTagStart) ) { source = source.Substring(0, nextStartTagEnd) + "/" + source.Substring(nextStartTagEnd, source.Length - nextStartTagEnd); } else matchSpecificTagStart = regexSpecificTagStart.Match(source, nextSingletonTagEnd); } source = source.Replace("</" + tagName + ">", ""); } public static void EnsureExplicitEndTag(ref String source, String tagName, String[] pseudoEndTags) { Regex regexSpecificTagStart = new Regex("<" + tagName + "(\\s|>)"); Match matchSpecificTagStart = regexSpecificTagStart.Match(source); while (matchSpecificTagStart.Success) { int i = matchSpecificTagStart.Index; int iNextTagStart= source.IndexOf("<", i + 1); int iNextStartTagEnd= source.IndexOf(">", i + 1); int iNextSingletonTagEnd = source.IndexOf("/>", i + 1); if ( iNextSingletonTagEnd < 0 || // make sure this tag is not a singleton (iNextTagStart > i && iNextSingletonTagEnd > iNextTagStart) ) { int iEndTag = source.IndexOf("</" + tagName + ">", i + 1); int iNextPseudoEnd = -1; foreach (String sPseudoEnd in pseudoEndTags) { int iPseudoEnd = source.IndexOf("<" + sPseudoEnd, i + 1); if (iPseudoEnd > 0 && (iNextPseudoEnd < 0 || iPseudoEnd < iNextPseudoEnd)) { iNextPseudoEnd = iPseudoEnd; } } if ( (iEndTag < 0 && iNextPseudoEnd > 0) || (iEndTag > 0 && iNextPseudoEnd > 0 && iEndTag > iNextPseudoEnd) ) { source = source.Substring(0, iNextPseudoEnd) + "</" + tagName + ">" + source.Substring(iNextPseudoEnd, source.Length - iNextPseudoEnd); } matchSpecificTagStart = regexSpecificTagStart.Match(source, i + 1); } else matchSpecificTagStart = regexSpecificTagStart.Match(source, iNextSingletonTagEnd); } } public static void MakeTagNameUnderneathTagFirst(ref String source, String underneathTagName, String tagName) { Regex regexSpecificTagStart = new Regex("<" + underneathTagName + "(\\s|>)"); Match matchSpecificTagStart = regexSpecificTagStart.Match(source); while (matchSpecificTagStart.Success) { int i = matchSpecificTagStart.Index; int iNextTagStart= source.IndexOf("<", i + 1); int iNextStartTagEnd= source.IndexOf(">", i + 1); int iNextSingletonTagEnd = source.IndexOf("/>", i + 1); int iNextComplexTagEnd = GetEndOfTag(source, underneathTagName, i); if ( iNextSingletonTagEnd < 0 || // make sure this tag is not a singleton (iNextTagStart > i && iNextSingletonTagEnd > iNextTagStart) ) { iNextStartTagEnd++; int iLast = source.LastIndexOf("</", iNextComplexTagEnd); String sTag = source.Substring(iNextStartTagEnd, iLast - iNextStartTagEnd ); String sDiscard= StripTagsOfTypeAndTheirContents(ref sTag, tagName, true); MakeTagNameUnderneathTagFirst(ref sTag, underneathTagName, tagName); sTag = sDiscard + sTag; source = source.Substring(0, iNextStartTagEnd) + sTag + source.Substring(iLast, source.Length - iLast); matchSpecificTagStart = regexSpecificTagStart.Match(source, iNextComplexTagEnd); } else matchSpecificTagStart = regexSpecificTagStart.Match(source, iNextSingletonTagEnd); } } public static int GetMatchingEndCharacter(String source, String starterTags, String endTags, int startIndex) { Regex regexEnd = new Regex(endTags); Regex regexStart = new Regex(starterTags); // really find the start of the tag (should match startIndex) Match matchStart = regexStart.Match(source, startIndex); Match matchEnd = regexEnd.Match(source, startIndex); int iStartTags = 1; while (iStartTags > 0 && matchEnd.Success) { if ( matchEnd.Index < matchStart.Index || !matchStart.Success) { iStartTags--; if (iStartTags > 0) matchEnd = regexEnd.Match(source, matchEnd.Index + 1); } // is the next thing a tag start? else if ( matchStart.Success && matchStart.Index < matchEnd.Index) { iStartTags++; matchStart = regexStart.Match(source, matchStart.Index + 2); } else { Debug.Assert(false, "Warning: malformed tags detected in source '" + source + "' (mismatched tree)"); return -1; } } if (matchEnd.Success) { return matchEnd.Index + matchEnd.Length; } // Console.WriteLine("Warning: malformed tags detected in source '" + source + "' (no end tag)"); return -1; } public static String GetTagInnerXml(String source, String tagName) { return GetTagInnerXml(source, tagName, 0); } public static String GetTagInnerXml(String source, String tagName, int startIndex) { Regex regexSpecificTagStart = new Regex("<" + tagName + "(\\s|/|>)"); // really find the start of the tag (should match startIndex) Match matchStart = regexSpecificTagStart.Match(source, startIndex); if (!matchStart.Success) { //Console.WriteLine("Warning: could not find start tag '" + tagName + "'."); return null; } int endOfStartTag = source.IndexOf(">", matchStart.Index) + 1; if (endOfStartTag <= 1) { //Console.WriteLine("Warning: could not find start tag '" + tagName + "'."); return null; } int endOfEndTag = GetEndOfTag(source, tagName, matchStart.Index); if (endOfStartTag == endOfEndTag) { return String.Empty; } int startOfEndTag = source.LastIndexOf("<", endOfEndTag - 1); return source.Substring(endOfStartTag, startOfEndTag - endOfStartTag); } public static int GetStartOfTag(String source, String tagName, int startIndex) { tagName = tagName.Replace("?", "\\?"); Regex regexSpecificTagStart = new Regex("<" + tagName + "(\\s|/|>)"); Match matchNextTagStart = regexSpecificTagStart.Match(source, startIndex); if (matchNextTagStart.Success) { return matchNextTagStart.Index; } return -1; } /// <summary> /// /// </summary> /// <param name="source"> /// </param> /// <param name="tagName"> /// </param> /// <param name="startIndex"> /// </param> /// <returns> /// The index of the first character after the end of this tag, or -1 if this is a /// malformed source. /// </returns> public static int GetEndOfTag(String source, String tagName, int startIndex) { Regex regexSpecificTagStart; Regex regexSingleTagEnd = new Regex("/>"); Regex regexComplexTagEnd; Regex regexTagStart = new Regex("<[\\w|?]"); bool findComplexEndAndLeave = false; if (tagName == "?xml") { regexSpecificTagStart = new Regex("<\\?xml(\\s|/|>)"); regexComplexTagEnd = new Regex(">"); findComplexEndAndLeave = true; } else if (tagName == "![CDATA[") { regexSpecificTagStart = new Regex("<!\\[CDATA\\["); regexComplexTagEnd = new Regex("]]>"); findComplexEndAndLeave = true; } else if (tagName.Length > 8 && tagName.Substring(0, 8) == "![CDATA[") { regexSpecificTagStart = new Regex("<!\\[CDATA\\["); regexComplexTagEnd = new Regex("]]>"); findComplexEndAndLeave = true; } else { regexSpecificTagStart = new Regex("<" + tagName + "(\\s|/|>)"); if (tagName == "!--") { regexComplexTagEnd = new Regex("-->"); findComplexEndAndLeave = true; } else { regexComplexTagEnd = new Regex("</" + tagName + ">"); } } // really find the start of the tag (should match startIndex) Match matchStart = regexSpecificTagStart.Match(source, startIndex); if (!matchStart.Success) { throw new MalformedXmlException("Warning: Could not find and end to the tag '" + tagName + "'.", source); } // find the end of the start tag int iEndOfStartTagInitial = matchStart.Index + matchStart.Length - 1; // find next </Foo> Match matchNextComplexCloser = regexComplexTagEnd.Match(source, iEndOfStartTagInitial); while (!findComplexEndAndLeave && matchNextComplexCloser.Success && IsInsideOfIgnoredArea(ref source, matchNextComplexCloser.Index)) { matchNextComplexCloser = regexComplexTagEnd.Match(source, matchNextComplexCloser.Index + 1); } if (findComplexEndAndLeave && matchNextComplexCloser.Success) { return matchNextComplexCloser.Index + matchNextComplexCloser.Length; } Debug.Assert(!findComplexEndAndLeave); // find next <Foo Match matchNextSpecificSingleStart = regexSpecificTagStart.Match(source, iEndOfStartTagInitial); while (matchNextSpecificSingleStart.Success && IsInsideOfIgnoredArea(ref source, matchNextSpecificSingleStart.Index)) { matchNextSpecificSingleStart = regexSpecificTagStart.Match(source, matchNextSpecificSingleStart.Index + 1); } // find next /> Match matchNextSingleCloser = regexSingleTagEnd.Match(source, iEndOfStartTagInitial); while (matchNextSingleCloser.Success && IsInsideOfIgnoredArea(ref source, matchNextSingleCloser.Index)) { matchNextSingleCloser = regexSingleTagEnd.Match(source, matchNextSingleCloser.Index + 1); } // find next < Match matchNextSingleStart = regexTagStart.Match(source, iEndOfStartTagInitial); while (matchNextSingleStart.Success && IsInsideOfIgnoredArea(ref source, matchNextSingleStart.Index)) { matchNextSingleStart = regexTagStart.Match(source, matchNextSingleStart.Index + 1); } // are we dealing with a singleton (<Foo/>) tag? if so, just kill it. if ( matchNextSingleCloser.Success && ( !matchNextSingleStart.Success || matchNextSingleCloser.Index < matchNextSingleStart.Index) && ( !matchNextComplexCloser.Success || matchNextSingleCloser.Index < matchNextComplexCloser.Index) ) { return matchNextSingleCloser.Index + 2; } // ok, it's a complex tag. We need to maintain a count of the number of start tags // we have seen, and subtract out the number of closer tags we have seen // when starttags == 0, we know we are done. int iStartTags = 1; while (iStartTags > 0 && matchNextComplexCloser.Success) { if ( matchNextComplexCloser.Index < matchNextSpecificSingleStart.Index || !matchNextSpecificSingleStart.Success) { iStartTags--; if (iStartTags > 0) { matchNextComplexCloser = regexComplexTagEnd.Match(source, matchNextComplexCloser.Index + 1); while (matchNextComplexCloser.Success && IsInsideOfIgnoredArea(ref source, matchNextComplexCloser.Index)) { matchNextComplexCloser = regexComplexTagEnd.Match(source, matchNextComplexCloser.Index + 1); } } } // is the next thing a tag start? else if ( matchNextSpecificSingleStart.Success && matchNextSpecificSingleStart.Index < matchNextComplexCloser.Index) { iStartTags++; // see if this is a singleton tag... if so, subtract the count back out. matchNextSingleCloser = regexSingleTagEnd.Match(source, matchNextSpecificSingleStart.Index + 1); matchNextSingleStart = regexTagStart.Match(source, matchNextSpecificSingleStart.Index + 1); if ( matchNextSingleCloser.Success && // we've found a /> matchNextSingleCloser.Index < matchNextComplexCloser.Index && // it comes before the next </Foo> ( matchNextSingleCloser.Index < matchNextSingleStart.Index || // it comes before the next <Bar> or <Foo> or whatever. !matchNextSingleStart.Success)) { iStartTags--; } matchNextSpecificSingleStart = regexSpecificTagStart.Match(source, matchNextSpecificSingleStart.Index + 2); while (matchNextSpecificSingleStart.Success && IsInsideOfIgnoredArea(ref source, matchNextSpecificSingleStart.Index)) { matchNextSpecificSingleStart = regexSpecificTagStart.Match(source, matchNextSpecificSingleStart.Index + 1); } } else { throw new MalformedXmlException("Warning: malformed tags detected in source (mismatched tree)", source); } } if (matchNextComplexCloser.Success) { int iComplexEnd = source.IndexOf(">", matchNextComplexCloser.Index); // for any complex tag ender </, there should be a > that follows it. if not, bail. if (iComplexEnd >= 0) { iComplexEnd++; return iComplexEnd; } } throw new MalformedXmlException("Warning: malformed tags detected in source (no end tag)", source); } /// <summary> /// This derivation of GetEndOfTag accepts markup more tolerant than strict XML rules, and will accept things like <div><img src="fa"></div> /// </summary> /// <param name="source"></param> /// <param name="tagName"></param> /// <param name="startIndex"></param> /// <returns></returns> public static int GetEndOfTagTolerant(String source, String tagName, int startIndex) { Regex regexSpecificTagStart = new Regex("<" + tagName + "(\\s|>)"); Regex regexSingleTagEnd = new Regex("/>"); Regex regexComplexTagEnd = new Regex("</" + tagName + ">"); Regex regexTagStart = new Regex("<[\\w|?]"); // really find the start of the tag (should match startIndex) Match matchStart = regexSpecificTagStart.Match(source, startIndex); if (!matchStart.Success) { // Console.WriteLine("Warning: could not refind start tag '" + tagName + "'."); return -1; } // find the end of the start tag int iEndOfStartTagInitial = matchStart.Index + matchStart.Length; // find next </Foo> Match matchNextComplexCloser = regexComplexTagEnd.Match(source, iEndOfStartTagInitial); // find next <Foo Match matchNextSpecificSingleStart = regexSpecificTagStart.Match(source, iEndOfStartTagInitial); // find next /> Match matchNextSingleCloser = regexSingleTagEnd.Match(source, iEndOfStartTagInitial); // find next < Match matchNextSingleStart = regexTagStart.Match(source, iEndOfStartTagInitial); // are we dealing with a singleton (<Foo/>) tag? if so, just kill it. if (matchNextSingleCloser.Success && (!matchNextSingleStart.Success || matchNextSingleCloser.Index < matchNextSingleStart.Index) && (!matchNextComplexCloser.Success || matchNextSingleCloser.Index < matchNextComplexCloser.Index) ) { return matchNextSingleCloser.Index + 2; } // ok, it's a complex tag. We need to maintain a count of the number of start tags // we have seen, and subtract out the number of closer tags we have seen // when starttags == 0, we know we are done. int iStartTags = 1; while (iStartTags > 0 && matchNextComplexCloser.Success) { if (matchNextComplexCloser.Index < matchNextSpecificSingleStart.Index || !matchNextSpecificSingleStart.Success) { iStartTags--; if (iStartTags > 0) matchNextComplexCloser = regexComplexTagEnd.Match(source, matchNextComplexCloser.Index + 1); } // is the next thing a tag start? else if (matchNextSpecificSingleStart.Success && matchNextSpecificSingleStart.Index < matchNextComplexCloser.Index) { iStartTags++; // see if this is a singleton tag... if so, subtract the count back out. matchNextSingleCloser = regexSingleTagEnd.Match(source, matchNextSpecificSingleStart.Index + 1); matchNextSingleStart = regexTagStart.Match(source, matchNextSpecificSingleStart.Index + 1); if (matchNextSingleCloser.Success && // we've found a /> matchNextSingleCloser.Index < matchNextComplexCloser.Index && // it comes before the next </Foo> (matchNextSingleCloser.Index < matchNextSingleStart.Index || // it comes before the next <Bar> or <Foo> or whatever. !matchNextSingleStart.Success)) { iStartTags--; } matchNextSpecificSingleStart = regexSpecificTagStart.Match(source, matchNextSpecificSingleStart.Index + 2); } else { // Console.WriteLine("Warning: malformed tags detected in source '" + source + "' (mismatched tree)"); return -1; } } if (matchNextComplexCloser.Success) { int iComplexEnd = source.IndexOf(">", matchNextComplexCloser.Index); // for any complex tag ender </, there should be a > that follows it. if not, bail. if (iComplexEnd >= 0) { iComplexEnd++; return iComplexEnd; } } // Console.WriteLine("Warning: malformed tags detected in source '" + source + "' (no end tag)"); return -1; } private static bool IsInsideOfIgnoredArea(ref String content, int index) { int lastTag = content.LastIndexOf("<![CDATA[", index + 1); if (lastTag >= 0) { int lastEnd = content.LastIndexOf("]]>", index + 1); if (lastEnd < lastTag) { return true; } } return false; } public static int CountCharsInBetween(ref String source, String token, int start, int end) { int count = 0; int next = source.IndexOf(token, start); while (next >= 0 && next < end) { count++; next = source.IndexOf(token, next + token.Length); } return count; } public static bool IsInQuote(ref String source, int index) { if (index < 0) { return false; } return ((TextUtilities.CountCharsInBetween(ref source, "\"", 0, index) % 2) == 1); } public static bool IsInComment(String source, int index) { int lastStart = source.LastIndexOf("/*", index); if (lastStart >= 0) { int lastEnd = source.LastIndexOf("*/", index); if (lastEnd < lastStart) { return true; } } lastStart = source.LastIndexOf("//", index); if (lastStart >= 0) { int lastEnd = source.LastIndexOf("\n", index); if (lastEnd < lastStart) { return true; } } return false; } public static int GetStartOfComment(String source, int index) { return GetStartOfComment(source, index, "/*", "//", "<!--"); } private static int GetStartOfComment(String source, int index, String slashStar, String slashSlash, String lessThanQuestionMark) { int previousSlashStar = source.LastIndexOf(slashStar, index); int previousSlashSlash = source.LastIndexOf(slashSlash, index); int previousLessThanQuestionMark = source.LastIndexOf(lessThanQuestionMark, index); if (previousSlashStar >= 0 && previousSlashSlash < previousSlashStar && previousLessThanQuestionMark < previousSlashStar) { return previousSlashStar; } if (previousSlashSlash >= 0 && previousLessThanQuestionMark < previousSlashSlash) { previousSlashSlash = source.LastIndexOf('\n', previousSlashSlash) + 1; return previousSlashSlash; } return previousLessThanQuestionMark; } public static int GetEndOfComment(String source, int index) { int start = GetStartOfComment(source, index); Debug.Assert(start >= 0); String end; if (source.Substring(start, 2) == "/*") { end = "*/"; } else if (source.Substring(start, 4) == "<!--") { end = "-->"; } else { end = "\n"; } return source.IndexOf(end, index) + end.Length; } public static int GetTagDepth(String source, int tagStartIndex) { int iTagDepth = 0; String sPrior = source.Substring(0, tagStartIndex); Regex regexSingleTagEnd = new Regex("/>"); Regex regexComplexTagEnd = new Regex("</"); Regex regexTagStart = new Regex("<[\\w|?]"); Match matchNextTagStart = regexTagStart.Match(sPrior); Match matchNextTagEnd = regexComplexTagEnd.Match(sPrior); while (matchNextTagStart.Success || matchNextTagEnd.Success) { if ( (matchNextTagEnd.Index < matchNextTagStart.Index && matchNextTagEnd.Success) || !matchNextTagStart.Success) { iTagDepth --; matchNextTagEnd = regexComplexTagEnd.Match(sPrior, matchNextTagEnd.Index + 1); } // is the next thing a tag start? else if ( (matchNextTagStart.Index < matchNextTagEnd.Index && matchNextTagStart.Success) || !matchNextTagEnd.Success) { iTagDepth++; Match matchNextSingleTagEnd = regexSingleTagEnd.Match(sPrior, matchNextTagStart.Index + 2); matchNextTagStart = regexTagStart.Match(sPrior, matchNextTagStart.Index + 1); // see if this is a singleton tag... if so, subtract the count back out. if (matchNextSingleTagEnd.Success) { if ( (!matchNextTagStart.Success || matchNextSingleTagEnd.Index < matchNextTagStart.Index) && (!matchNextTagEnd.Success || matchNextSingleTagEnd.Index < matchNextTagEnd.Index)) { iTagDepth--; } } } else { Console.WriteLine("Warning: malformed tags detected in sPrior '" + sPrior + "' (mismatched tree)"); return -1; } } return iTagDepth; } public static void ConvertTagNameUnderneathTag(ref String source, String underneathTagName, String oldTagName, String newTagName) { Regex regexSpecificTagStart = new Regex("<" +underneathTagName + "(\\s|>)"); Match matchStart = regexSpecificTagStart.Match(source); while (matchStart.Success) { int iEndOfTag= GetEndOfTag(source, underneathTagName, matchStart.Index); if ( iEndOfTag >= 0 ) { String sTag = source.Substring(matchStart.Index, iEndOfTag - matchStart.Index); ConvertTagName(ref sTag, oldTagName, newTagName); source = source.Substring(0, matchStart.Index) + sTag + source.Substring(iEndOfTag, source.Length - iEndOfTag); } matchStart = regexSpecificTagStart.Match(source, matchStart.Index + 1); } } public static void ConvertTagName(ref String source, String oldTagName, String newTagName) { // stupid but effective... source = source.Replace("<" + oldTagName + "\t", "<" + newTagName + "\t"); source = source.Replace("<" + oldTagName + " ", "<" + newTagName + " "); source = source.Replace("<" + oldTagName + ">", "<" + newTagName + ">"); source = source.Replace("<" + oldTagName + "/>", "<" + newTagName + "/>"); source = source.Replace("</" + oldTagName + ">", "</" + newTagName + ">"); } public static String GetAttribute(ref String source, String attributeName) { return GetAttribute(ref source, attributeName, 0); } public static int GetAttributeStart(ref String source, String attributeName, int startIndex) { // Regex attributeInitial = new Regex(attributeName + "=(\"|\')"); Regex attributeInitial = new Regex(attributeName + "="); Match attributeStartMatch = attributeInitial.Match(source, startIndex); if (!attributeStartMatch.Success) { return -1; } return attributeStartMatch.Index + attributeStartMatch.Length; } public static int GetAttributeEnd(ref String source, String attributeName, int startIndex) { char sep = source[startIndex]; Match attributeEndMatch = null; if (sep == '\'' || sep == '\"') { Regex attributeEnd = new Regex("(\"|\')"); attributeEndMatch = attributeEnd.Match(source, startIndex + 1); if (!attributeEndMatch.Success) { return -1; } } else { Regex attributeEnd = new Regex("(/|\\s|>)"); attributeEndMatch = attributeEnd.Match(source, startIndex); if (!attributeEndMatch.Success) { return -1; } } return attributeEndMatch.Index; } public static String GetAttribute(ref String source, String attributeName, int startIndex) { int startOfAttributeContent = GetAttributeStart(ref source, attributeName, startIndex); if (startOfAttributeContent < 0) { return null; } int endOfAttributeContent = GetAttributeEnd(ref source, attributeName, startOfAttributeContent); if (endOfAttributeContent < 0) { return null; } return source.Substring(startOfAttributeContent + 1, endOfAttributeContent - (startOfAttributeContent + 1)); } public static void StripAttributeFromTags(ref String source, String[] tagNames, String attributeName) { foreach (String tagName in tagNames) StripAttributeFromTag(ref source, tagName, attributeName); } public static void StripAttributeFromTag(ref String source, String tagName, String attributeName) { // find tag starts int i = source.IndexOf("<" + tagName); while (i >= 0) { // find the end of the tag int iEnd = source.IndexOf(">", i); // if there is no closer for this tag, then things are bad. bail. if (iEnd < i) { Console.WriteLine("Incomplete tag detected in source '" + source + "'. Parts of this file could not be processed."); return; } // now find the attribute within the tag. int iAttributeStart = source.IndexOf(attributeName + "=", i); if (iAttributeStart > i && iAttributeStart < iEnd) { // get the quote char in use... is it ' or " ? char chQuote = source[iAttributeStart + attributeName.Length + 1]; // find the closing quote char int iAttributeEnd = source.IndexOf(chQuote, iAttributeStart + attributeName.Length + 2); if (iAttributeEnd > iAttributeStart && iAttributeEnd < iEnd) { iEnd -= (iAttributeEnd - iAttributeStart); source = source.Substring(0, iAttributeStart) + source.Substring(iAttributeEnd + 1, source.Length - (iAttributeEnd + 1)); } } i = source.IndexOf("<" + tagName, iEnd); } } public static void ChangeAttributeNameForTags(ref String source, String[] tagNames, String oldAttributeName, String newAttributeName) { foreach (String tagName in tagNames) { ChangeAttributeNameForTag(ref source, tagName, oldAttributeName, newAttributeName); } } public static void ChangeAttributeNameForTag(ref String source, String tagName, String oldAttributeName, String newAttributeName) { int i = source.IndexOf("<" + tagName); while (i >= 0) { int iEnd = source.IndexOf(">", i); if (iEnd < i) return; int iOldAttribute = source.IndexOf(oldAttributeName, i); if (iOldAttribute > i && iOldAttribute < iEnd) { source = source.Substring(0, iOldAttribute) + newAttributeName + source.Substring(iOldAttribute + oldAttributeName.Length, source.Length - (iOldAttribute + oldAttributeName.Length)); } i = source.IndexOf("<" + tagName, iEnd); } } public static void StripTagsOfType(ref String source, String tagName) { int iLeft = source.IndexOf("<" + tagName); while (iLeft >= 0) { int iRight = source.IndexOf(">", iLeft); if (iRight < iLeft) { Console.WriteLine("Warning: source string '" + source + "' looks malformed."); return; } source = source.Substring(0, iLeft) + source.Substring(iRight + 1, source.Length - (iRight + 1)); iLeft = source.IndexOf("<" + tagName); } source = source.Replace("</" + tagName + ">", ""); } public static void StripTags(ref String source) { StripChunks(ref source, "<", ">"); } public static void StripChunks(ref String source, String chunkStart, String chunkEnd) { int iChunkStart = source.IndexOf(chunkStart); int iChunkEnd; while (iChunkStart >= 0) { iChunkEnd = source.IndexOf(chunkEnd, iChunkStart); if (iChunkEnd >= iChunkStart) source = source.Substring(0, iChunkStart) + source.Substring(iChunkEnd + chunkEnd.Length, source.Length - (iChunkEnd + chunkEnd.Length)); else { Console.WriteLine("Warning: malformed chunk found. There is no chunk end '" + chunkEnd + "' for the start."); return; } iChunkStart = source.IndexOf(chunkStart); } } public static void StripTagsAndTheirContents(ref String source) { // deal with meta tags StripChunks(ref source, "<?", "?>"); // deal with comments StripChunks(ref source, "<!--", "-->"); // now deal with normal tags. Regex regexTagStart = new Regex("<[\\w|?]"); Regex regexSingleTagEnd = new Regex("/>"); Regex regexComplexTagEnd = new Regex("</"); Match matchStart = regexTagStart.Match(source); while (matchStart.Success) { int iEndOfStartTagInitial = matchStart.Index + matchStart.Length; Match matchNextSingleCloser = regexSingleTagEnd.Match(source, iEndOfStartTagInitial); Match matchNextComplexCloser = regexComplexTagEnd.Match(source, iEndOfStartTagInitial); Match matchNextSingleStart = regexTagStart.Match(source, iEndOfStartTagInitial); // are we dealing with a singleton (<Foo/>) tag? if so, just kill it. if ( matchNextSingleCloser.Success && ( !matchNextSingleStart.Success || matchNextSingleCloser.Index < matchNextSingleStart.Index) && ( !matchNextComplexCloser.Success || matchNextSingleCloser.Index < matchNextComplexCloser.Index) ) { source = source.Substring(0, matchStart.Index) + source.Substring(matchNextSingleCloser.Index + 2, source.Length - (matchNextSingleCloser.Index + 2)); } else { int iStartTags = 1; while (iStartTags > 0 && matchNextComplexCloser.Success) { // is the next thing a />? if ( matchNextSingleCloser.Success && // we've found a single closer ( matchNextSingleCloser.Index < matchNextSingleStart.Index || // it comes before the next <foo.. tag (or there is no more <foo.. tags) !matchNextSingleStart.Success) && matchNextSingleCloser.Index < matchNextComplexCloser.Index) // it comes before the next </foo { iStartTags--; matchNextSingleCloser = regexSingleTagEnd.Match(source, matchNextSingleCloser.Index + 2); } // is the next thing a </ ?) // note we always assume there must be a future complex closer... else if ( ( matchNextComplexCloser.Index < matchNextSingleStart.Index || !matchNextSingleStart.Success) && ( matchNextComplexCloser.Index < matchNextSingleCloser.Index || !matchNextSingleCloser.Success)) { iStartTags--; if (iStartTags > 0) matchNextComplexCloser = regexComplexTagEnd.Match(source, matchNextComplexCloser.Index + 2); } // is the next thing a tag start? else if ( matchNextSingleStart.Success && matchNextSingleStart.Index < matchNextComplexCloser.Index && ( matchNextSingleStart.Index < matchNextSingleCloser.Index || !matchNextSingleCloser.Success)) { iStartTags++; matchNextSingleStart = regexTagStart.Match(source, matchNextSingleStart.Index + 2); } } if (matchNextComplexCloser.Success) { int iComplexEnd = source.IndexOf(">", matchNextComplexCloser.Index); // for any complex tag ender </, there should be a > that follows it. if not, bail. if (iComplexEnd < 0) { Console.WriteLine("Warning: malformed tags detected in source '" + source + "'"); return; } iComplexEnd++; source = source.Substring(0, matchStart.Index) + source.Substring(iComplexEnd, source.Length - iComplexEnd); } else { //Console.WriteLine("Warning: could not find a proper end tag in source '" + source + "'"); return; } } matchStart = regexTagStart.Match(source); } } /// <summary> /// Given, say, a list of files on a path, returh /// </summary> public static String[] GetFileList(String source) { source = source.Trim(); List<String> files = new List<string>(); int last = 0; int nextSpace = source.IndexOf(" "); while (TextUtilities.IsInQuote(ref source, nextSpace)) { nextSpace = source.IndexOf(" ", nextSpace + 1); } while (nextSpace >= 0) { files.Add(source.Substring(last, nextSpace - last)); nextSpace++; last = nextSpace; nextSpace = source.IndexOf(" ", nextSpace); while (TextUtilities.IsInQuote(ref source, nextSpace)) { nextSpace = source.IndexOf(" ", nextSpace + 1); } } String lastPart = source.Substring(last, source.Length - last); files.Add(lastPart); String[] fileList = new String[files.Count]; files.CopyTo(fileList); return fileList; } public static String StripTagsOfTypeAndTheirContents(ref String source, String tagName, bool topLevelTagsOnly) { String sDiscardedContent = ""; Regex regexSpecificTagStart = new Regex("<" + tagName + "(\\s|>)"); Match matchStart = regexSpecificTagStart.Match(source); while (matchStart.Success) { if (!topLevelTagsOnly || GetTagDepth(source, matchStart.Index) < 1) { int iEndOfTag = GetEndOfTag(source, tagName, matchStart.Index); int iTagBeginning = matchStart.Index - 1; // back the count up and get the whitespace before the tag start. while (iTagBeginning >= 0 && (source[iTagBeginning] == ' ' || source[iTagBeginning] == '\r' || source[iTagBeginning] == '\n' || source[iTagBeginning] == '\t')) iTagBeginning--; // we iterated until we found the first non whitespace char, so add one back in // to take us to a whitespace char. iTagBeginning++; if (iEndOfTag < 0) return null; sDiscardedContent += source.Substring(iTagBeginning, iEndOfTag - iTagBeginning); source = source.Substring(0, iTagBeginning) + source.Substring(iEndOfTag, source.Length - iEndOfTag); matchStart = regexSpecificTagStart.Match(source, iTagBeginning); } else { matchStart = regexSpecificTagStart.Match(source, matchStart.Index + 1); } } return sDiscardedContent; } public static String GetUtf8StringFromBytes(byte[] bytes) { if (bytes == null) { return null; } return UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length); } public static String EncodeForParam(String str) { String copy = str; XmlUtilities.Entitize(ref copy); copy = copy.Replace(",", "&comma;"); return copy; } public static String GetAsciiStringFromBytes(byte[] bytes) { if (bytes == null) { return null; } if (bytes.Length >= 3 && bytes[0] == 239 && bytes[1] == 187 && bytes[2] == 191) { String resultStr = Encoding.UTF8.GetString(bytes); if (resultStr[0] == 65279) // TODO: find out what this thing is, and handle appropriately { resultStr = resultStr.Substring(1, resultStr.Length - 1); } return resultStr; } return Encoding.UTF8.GetString(bytes); } public static String PostPadText(String content, String postPendText, int targetLength) { Debug.Assert(postPendText.Length > 0); if (content == null) { content = String.Empty; } while (content.Length < targetLength) { content = content + postPendText; } return content; } public static String PrePadText(String content, String prePendText, int targetLength) { Debug.Assert(prePendText.Length > 0); if (content == null) { content = String.Empty; } while (content.Length < targetLength) { content = prePendText + content; } return content; } public static String DecodeFromParam(String str) { String copy = str; copy = copy.Replace("&comma;", ","); XmlUtilities.DeEntitize(ref copy); return copy; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using Palaso.UI.WindowsForms.Keyboarding; using Palaso.WritingSystems; namespace Palaso.UI.WindowsForms.WritingSystems { public partial class WSSortControl : UserControl { private WritingSystemSetupModel _model; private readonly Hashtable _sortUsingValueMap; private Hashtable _languageOptionMap; private bool _changingModel; private IKeyboardDefinition _defaultKeyboard; private string _defaultFontName; private float _defaultFontSize; public event EventHandler UserWantsHelpWithCustomSorting; public WSSortControl() { InitializeComponent(); _sortUsingValueMap = new Hashtable(); foreach (KeyValuePair<string, string> sortUsingOption in WritingSystemSetupModel.SortUsingOptions) { int index = _sortUsingComboBox.Items.Add(sortUsingOption.Value); _sortUsingValueMap[sortUsingOption.Key] = index; _sortUsingValueMap[index] = sortUsingOption.Key; } _defaultFontName = _sortRulesTextBox.Font.Name; _defaultFontSize = _sortRulesTextBox.Font.SizeInPoints; // default text for testing the sort rules // default text for testing the sort rules; bug fix for WS-55 so all platforms have the right line ending _testSortText.Text = String.Join(Environment.NewLine, new string[] { "pear", "apple", "orange", "mango", "peach" }); } public void BindToModel(WritingSystemSetupModel model) { if (_model != null) { _model.SelectionChanged -= ModelSelectionChanged; _model.CurrentItemUpdated -= ModelCurrentItemUpdated; } _model = model; if (_model != null) { UpdateFromModel(); _model.SelectionChanged += ModelSelectionChanged; _model.CurrentItemUpdated += ModelCurrentItemUpdated; } this.Disposed += OnDisposed; } void OnDisposed(object sender, EventArgs e) { if (_model != null) { _model.SelectionChanged -= ModelSelectionChanged; _model.CurrentItemUpdated -= ModelCurrentItemUpdated; } } private void ModelSelectionChanged(object sender, EventArgs e) { UpdateFromModel(); } private void ModelCurrentItemUpdated(object sender, EventArgs e) { if (_changingModel) { return; } UpdateFromModel(); } private void UpdateFromModel() { _rulesValidationTimer.Enabled = false; if (!_model.HasCurrentSelection) { _sortrules_panel.Visible = false; _languagecombo_panel.Visible = false; Enabled = false; return; } Enabled = true; LoadLanguageChoicesFromModel(); if (_sortUsingValueMap.ContainsKey(_model.CurrentSortUsing)) { _sortUsingComboBox.SelectedIndex = (int)_sortUsingValueMap[_model.CurrentSortUsing]; } else { _sortUsingComboBox.SelectedIndex = -1; } SetControlFonts(); } private void LoadLanguageChoicesFromModel() { _languageComboBox.Items.Clear(); _languageOptionMap = new Hashtable(); foreach (KeyValuePair<string, string> languageOption in _model.SortLanguageOptions) { int index = _languageComboBox.Items.Add(languageOption.Value); _languageOptionMap[index] = languageOption.Key; _languageOptionMap[languageOption.Key] = index; } _sortUsingComboBox.SelectedIndex = -1; } private void _sortRulesTextBox_TextChanged(object sender, EventArgs e) { _changingModel = true; try { _model.CurrentSortRules = _sortRulesTextBox.Text; _rulesValidationTimer.Stop(); _rulesValidationTimer.Start(); } finally { _changingModel = false; } } private void _sortUsingComboBox_SelectedIndexChanged(object sender, EventArgs e) { _sortrules_panel.Visible = false; _languagecombo_panel.Visible = false; if (_sortUsingComboBox.SelectedIndex == -1) { return; } string newValue = (string)_sortUsingValueMap[_sortUsingComboBox.SelectedIndex]; _changingModel = true; try { _model.CurrentSortUsing = newValue; } finally { _changingModel = false; } if (newValue == "OtherLanguage") { _sortrules_panel.Visible = true; _languagecombo_panel.Visible = true; _rulesValidationTimer.Enabled = false; if (_languageOptionMap.ContainsKey(_model.CurrentSortRules)) { _languageComboBox.SelectedIndex = (int)_languageOptionMap[_model.CurrentSortRules]; } } else if (newValue == "CustomSimple" || newValue == "CustomICU") { _sortrules_panel.Visible = true; _sortRulesTextBox.Text = _model.CurrentSortRules; } } private void _languageComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (_languageComboBox.SelectedIndex == -1) { return; } string newValue = (string) _languageOptionMap[_languageComboBox.SelectedIndex]; _changingModel = true; try { _model.CurrentSortRules = newValue; } finally { _changingModel = false; } } private void _testSortButton_Click(object sender, EventArgs e) { try { if (ValidateSortRules()) { _testSortResult.Text = _model.TestSort(_testSortText.Text); } } catch (ApplicationException ex) { Palaso.Reporting.ErrorReport.NotifyUserOfProblem("Unable to sort test text: {0}", ex.Message); } } private void SetControlFonts() { float fontSize = _model.CurrentDefaultFontSize; if (fontSize <= 0 || float.IsNaN(fontSize) || float.IsInfinity(fontSize)) { fontSize = _defaultFontSize; } string fontName = _model.CurrentDefaultFontName; if (string.IsNullOrEmpty(fontName)) { fontName = _defaultFontName; } Font customFont = new Font(fontName, fontSize); _sortRulesTextBox.Font = customFont; // We are not setting the RightToLeft propert for the sort rules because the ICU syntax is inherently left to right. _testSortText.Font = customFont; _testSortText.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No; _testSortResult.Font = customFont; _testSortResult.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No; } private void TextControl_Enter(object sender, EventArgs e) { if (_model == null) { return; } _defaultKeyboard = Keyboard.Controller.ActiveKeyboard; _model.ActivateCurrentKeyboard(); } private void TextControl_Leave(object sender, EventArgs e) { if (_model == null) { return; } _defaultKeyboard.Activate(); if (_rulesValidationTimer.Enabled) { _rulesValidationTimer.Enabled = false; ValidateSortRules(); } } private void _rulesValidationTimer_Tick(object sender, EventArgs e) { _rulesValidationTimer.Enabled = false; ValidateSortRules(); } private bool ValidateSortRules() { string message; const string prefixToMessage = "SORT RULES WILL NOT BE SAVED\r\n"; if (!_model.ValidateCurrentSortRules(out message)) { _testSortResult.Text = prefixToMessage + (message ?? String.Empty); _testSortResult.ForeColor = Color.Red; return false; } if (_testSortResult.Text.StartsWith(prefixToMessage)) { _testSortResult.Text = String.Empty; _testSortResult.ForeColor = Color.Black; } return true; } private void OnHelpLabelClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (UserWantsHelpWithCustomSorting != null) UserWantsHelpWithCustomSorting(sender, e); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.Owin.Helpers; using Microsoft.Owin.Infrastructure; using Microsoft.Owin.Logging; using Microsoft.Owin.Security.Infrastructure; using Newtonsoft.Json.Linq; namespace Microsoft.Owin.Security.Facebook { internal class FacebookAuthenticationHandler : AuthenticationHandler<FacebookAuthenticationOptions> { private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; private readonly ILogger _logger; private readonly HttpClient _httpClient; public FacebookAuthenticationHandler(HttpClient httpClient, ILogger logger) { _httpClient = httpClient; _logger = logger; } protected override async Task<AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string code = null; string state = null; IReadableStringCollection query = Request.Query; IList<string> values = query.GetValues("code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return null; } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties, _logger)) { return new AuthenticationTicket(null, properties); } string tokenEndpoint = "https://graph.facebook.com/oauth/access_token"; string requestPrefix = Request.Scheme + "://" + Request.Host; string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; string tokenRequest = "grant_type=authorization_code" + "&code=" + Uri.EscapeDataString(code) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&client_id=" + Uri.EscapeDataString(Options.AppId) + "&client_secret=" + Uri.EscapeDataString(Options.AppSecret); HttpResponseMessage tokenResponse = await _httpClient.GetAsync(tokenEndpoint + "?" + tokenRequest, Request.CallCancelled); tokenResponse.EnsureSuccessStatusCode(); string text = await tokenResponse.Content.ReadAsStringAsync(); IFormCollection form = WebHelpers.ParseForm(text); string accessToken = form["access_token"]; string expires = form["expires"]; string graphApiEndpoint = "https://graph.facebook.com/me"; HttpResponseMessage graphResponse = await _httpClient.GetAsync( graphApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled); graphResponse.EnsureSuccessStatusCode(); text = await graphResponse.Content.ReadAsStringAsync(); JObject user = JObject.Parse(text); var context = new FacebookAuthenticatedContext(Context, user, accessToken, expires); context.Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!string.IsNullOrEmpty(context.Id)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Name)) { context.Identity.AddClaim(new Claim("urn:facebook:name", context.Name, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Link)) { context.Identity.AddClaim(new Claim("urn:facebook:link", context.Link, XmlSchemaString, Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return new AuthenticationTicket(context.Identity, context.Properties); } catch (Exception ex) { _logger.WriteError(ex.Message); } return new AuthenticationTicket(null, properties); } protected override Task ApplyResponseChallengeAsync() { if (Response.StatusCode != 401) { return Task.FromResult<object>(null); } AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); if (challenge != null) { string baseUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase; string currentUri = baseUri + Request.Path + Request.QueryString; string redirectUri = baseUri + Options.CallbackPath; AuthenticationProperties properties = challenge.Properties; if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = currentUri; } // OAuth2 10.12 CSRF GenerateCorrelationId(properties); // comma separated string scope = string.Join(",", Options.Scope); string state = Options.StateDataFormat.Protect(properties); string authorizationEndpoint = "https://www.facebook.com/dialog/oauth" + "?response_type=code" + "&client_id=" + Uri.EscapeDataString(Options.AppId) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&scope=" + Uri.EscapeDataString(scope) + "&state=" + Uri.EscapeDataString(state); Response.Redirect(authorizationEndpoint); } return Task.FromResult<object>(null); } public override async Task<bool> InvokeAsync() { return await InvokeReplyPathAsync(); } private async Task<bool> InvokeReplyPathAsync() { if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path) { // TODO: error responses AuthenticationTicket ticket = await AuthenticateAsync(); if (ticket == null) { _logger.WriteWarning("Invalid return state, unable to redirect."); Response.StatusCode = 500; return true; } var context = new FacebookReturnEndpointContext(Context, ticket); context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType; context.RedirectUri = ticket.Properties.RedirectUri; await Options.Provider.ReturnEndpoint(context); if (context.SignInAsAuthenticationType != null && context.Identity != null) { ClaimsIdentity grantIdentity = context.Identity; if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal)) { grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType); } Context.Authentication.SignIn(context.Properties, grantIdentity); } if (!context.IsRequestCompleted && context.RedirectUri != null) { string redirectUri = context.RedirectUri; if (context.Identity == null) { // add a redirect hint that sign-in failed in some way redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied"); } Response.Redirect(redirectUri); context.RequestCompleted(); } return context.IsRequestCompleted; } return false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Excess.Concurrent.Runtime; namespace DiningPhilosophers { [Concurrent(id = "0b0cb53d-54d9-4014-b69e-c337dad28649")] [ConcurrentSingleton(id: "5d1dcbd1-a861-4392-b8e4-0a5f4d300951")] public class __app : ConcurrentObject { protected override void __started() { var __enum = __concurrentmain(default (CancellationToken), null, null); __enter(() => __advance(__enum.GetEnumerator()), null); } private IEnumerable<Expression> __concurrentmain(CancellationToken __cancellation, Action<object> __success, Action<Exception> __failure) { var names = new[]{"Kant", "Archimedes", "Nietzche", "Plato", "Spinoza", }; var meals = 0; if (Arguments.Length != 1 || !int.TryParse(Arguments[0], out meals)) meals = 3; //create chopsticks var chopsticks = names.Select(n => spawn<chopstick>()).ToArray(); //create philosophers var phCount = names.Length; var stopper = new StopCount(phCount); for (int i = 0; i < phCount; i++) { var left = chopsticks[i]; var right = i == phCount - 1 ? chopsticks[0] : chopsticks[i + 1]; spawn<philosopher>(names[i], left, right, meals, stopper); } { __dispatch("main"); if (__success != null) __success(null); yield break; } } private static __app __singleton; public static void Start(IConcurrentApp app) { __singleton = app.Spawn<__app>(); } public readonly Guid __ID = Guid.NewGuid(); public static void Start(string[] args) { Arguments = args; var app = new ThreadedConcurrentApp(threadCount: 4, blockUntilNextEvent: true, priority: ThreadPriority.Normal); app.Start(); app.Spawn(new __app()); Await = () => app.AwaitCompletion(); Stop = () => app.Stop(); } public static string[] Arguments { get; set; } public static Action Stop { get; private set; } public static Action Await { get; private set; } } [Concurrent(id = "8f75b5fa-639c-4862-8912-0126480630c6")] class philosopher : ConcurrentObject { string _name; chopstick _left; chopstick _right; int _meals; StopCount _stop; public philosopher(string name, chopstick left, chopstick right, int meals, StopCount stop) { _name = name; _left = left; _right = right; _meals = meals; _stop = stop; } protected override void __started() { var __enum = __concurrentmain(default (CancellationToken), null, null); __enter(() => __advance(__enum.GetEnumerator()), null); } void think() { throw new InvalidOperationException("Cannot call private signals directly"); } void hungry() { throw new InvalidOperationException("Cannot call private signals directly"); } void eat() { throw new InvalidOperationException("Cannot call private signals directly"); } private IEnumerable<Expression> __concurrentmain(CancellationToken __cancellation, Action<object> __success, Action<Exception> __failure) { for (int i = 0; i < _meals; i++) { { var __expr1_var = new __expr1{Start = (___expr) => { var __expr = (__expr1)___expr; __advance((__concurrentthink(__cancellation, (__res) => { __expr.__op1(true, null, null); } , (__ex) => { __expr.__op1(false, null, __ex); } )).GetEnumerator()); __expr.__op1(null, false, null); } , End = (__expr) => { __enter(() => __advance(__expr.Continuator), __failure); } }; yield return __expr1_var; if (__expr1_var.Failure != null) throw __expr1_var.Failure; } } if (_stop.ShouldStop()) { App.Stop(); } { __dispatch("main"); if (__success != null) __success(null); yield break; } } private IEnumerable<Expression> __concurrentthink(CancellationToken __cancellation, Action<object> __success, Action<Exception> __failure) { Console.WriteLine(_name + " is thinking"); var __expr2_var = new __expr2{Start = (___expr) => { var __expr = (__expr2)___expr; Task.Delay((int)((rand(1.0, 2.0)) * 1000)).ContinueWith(__task => { __enter(() => __expr.__op2(true, null, null), (__ex) => __expr.__op2(false, null, __ex)); } ); } , End = (__expr) => { __enter(() => __advance(__expr.Continuator), __failure); } , __start1 = (___expr) => { var __expr = (__expr2)___expr; __enter(() => { __advance((__concurrenthungry(__cancellation, (__res) => { __expr.__op2(null, true, null); } , (__ex) => { __expr.__op2(null, false, __ex); } )).GetEnumerator()); } , __failure); } }; yield return __expr2_var; if (__expr2_var.Failure != null) throw __expr2_var.Failure; { __dispatch("think"); if (__success != null) __success(null); yield break; } } private IEnumerable<Expression> __concurrenthungry(CancellationToken __cancellation, Action<object> __success, Action<Exception> __failure) { Console.WriteLine(_name + " is hungry"); var __expr3_var = new __expr3{Start = (___expr) => { var __expr = (__expr3)___expr; _left.acquire(this, __cancellation, (__res) => __expr.__op4(true, null, null), (__ex) => __expr.__op4(false, null, __ex)); _right.acquire(this, __cancellation, (__res) => __expr.__op4(null, true, null), (__ex) => __expr.__op4(null, false, __ex)); } , End = (__expr) => { __enter(() => __advance(__expr.Continuator), __failure); } , __start2 = (___expr) => { var __expr = (__expr3)___expr; __enter(() => { __advance((__concurrenteat(__cancellation, (__res) => { __expr.__op3(null, true, null); } , (__ex) => { __expr.__op3(null, false, __ex); } )).GetEnumerator()); } , __failure); } }; yield return __expr3_var; if (__expr3_var.Failure != null) throw __expr3_var.Failure; { __dispatch("hungry"); if (__success != null) __success(null); yield break; } } private IEnumerable<Expression> __concurrenteat(CancellationToken __cancellation, Action<object> __success, Action<Exception> __failure) { Console.WriteLine(_name + " is eating"); { var __expr4_var = new __expr4{Start = (___expr) => { var __expr = (__expr4)___expr; Task.Delay((int)((rand(1.0, 2.0)) * 1000)).ContinueWith(__task => { __enter(() => __expr.__op5(true, null, null), (__ex) => __expr.__op5(false, null, __ex)); } ); __expr.__op5(null, false, null); } , End = (__expr) => { __enter(() => __advance(__expr.Continuator), __failure); } }; yield return __expr4_var; if (__expr4_var.Failure != null) throw __expr4_var.Failure; } _left.release(this); _right.release(this); { __dispatch("eat"); if (__success != null) __success(null); yield break; } } private class __expr1 : Expression { public void __op1(bool ? v1, bool ? v2, Exception __ex) { if (!tryUpdate(v1, v2, ref __op1_Left, ref __op1_Right, __ex)) return; if (v1.HasValue) { if (__op1_Left.Value) __complete(true, null); else if (__op1_Right.HasValue) __complete(false, __ex); } else { if (__op1_Right.Value) __complete(true, null); else if (__op1_Left.HasValue) __complete(false, __ex); } } private bool ? __op1_Left; private bool ? __op1_Right; } private class __expr2 : Expression { public void __op2(bool ? v1, bool ? v2, Exception __ex) { if (!tryUpdate(v1, v2, ref __op2_Left, ref __op2_Right, __ex)) return; if (v1.HasValue) { if (__op2_Left.Value) __start1(this); else __complete(false, __ex); } else { if (__op2_Right.Value) __complete(true, null); else __complete(false, __ex); } } private bool ? __op2_Left; private bool ? __op2_Right; public Action<__expr2> __start1; } private class __expr3 : Expression { public void __op3(bool ? v1, bool ? v2, Exception __ex) { if (!tryUpdate(v1, v2, ref __op3_Left, ref __op3_Right, __ex)) return; if (v1.HasValue) { if (__op3_Left.Value) __start2(this); else __complete(false, __ex); } else { if (__op3_Right.Value) __complete(true, null); else __complete(false, __ex); } } private bool ? __op3_Left; private bool ? __op3_Right; public Action<__expr3> __start2; public void __op4(bool ? v1, bool ? v2, Exception __ex) { if (!tryUpdate(v1, v2, ref __op4_Left, ref __op4_Right, __ex)) return; if (v1.HasValue) { if (!__op4_Left.Value) __op3(false, null, __ex); else if (__op4_Right.HasValue) __op3(true, null, null); } else { if (!__op4_Right.Value) __op3(false, null, __ex); else if (__op4_Left.HasValue) __op3(true, null, null); } } private bool ? __op4_Left; private bool ? __op4_Right; } private class __expr4 : Expression { public void __op5(bool ? v1, bool ? v2, Exception __ex) { if (!tryUpdate(v1, v2, ref __op5_Left, ref __op5_Right, __ex)) return; if (v1.HasValue) { if (__op5_Left.Value) __complete(true, null); else if (__op5_Right.HasValue) __complete(false, __ex); } else { if (__op5_Right.Value) __complete(true, null); else if (__op5_Left.HasValue) __complete(false, __ex); } } private bool ? __op5_Left; private bool ? __op5_Right; } public readonly Guid __ID = Guid.NewGuid(); } [Concurrent(id = "18e234d9-d4b3-49b6-80a5-19a21d9362be")] class chopstick : ConcurrentObject { philosopher _owner; [Concurrent] public void acquire(philosopher owner) { acquire(owner, default (CancellationToken), null, null); } [Concurrent] public void release(philosopher owner) { release(owner, default (CancellationToken), null, null); } private IEnumerable<Expression> __concurrentacquire(philosopher owner, CancellationToken __cancellation, Action<object> __success, Action<Exception> __failure) { if (_owner != null) { { var __expr5_var = new __expr5{Start = (___expr) => { var __expr = (__expr5)___expr; __listen("release", () => { __expr.__op6(true, null, null); } ); __expr.__op6(null, false, null); } , End = (__expr) => { __enter(() => __advance(__expr.Continuator), __failure); } }; yield return __expr5_var; if (__expr5_var.Failure != null) throw __expr5_var.Failure; } } _owner = owner; { __dispatch("acquire"); if (__success != null) __success(null); yield break; } } public Task<object> acquire(philosopher owner, CancellationToken cancellation) { var completion = new TaskCompletionSource<object>(); Action<object> __success = (__res) => completion.SetResult((object)__res); Action<Exception> __failure = (__ex) => completion.SetException(__ex); var __cancellation = cancellation; __enter(() => __advance(__concurrentacquire(owner, __cancellation, __success, __failure).GetEnumerator()), __failure); return completion.Task; } public void acquire(philosopher owner, CancellationToken cancellation, Action<object> success, Action<Exception> failure) { var __success = success; var __failure = failure; var __cancellation = cancellation; __enter(() => __advance(__concurrentacquire(owner, __cancellation, __success, __failure).GetEnumerator()), failure); } private IEnumerable<Expression> __concurrentrelease(philosopher owner, CancellationToken __cancellation, Action<object> __success, Action<Exception> __failure) { if (_owner != owner) throw new ArgumentException(); _owner = null; { __dispatch("release"); if (__success != null) __success(null); yield break; } } public Task<object> release(philosopher owner, CancellationToken cancellation) { var completion = new TaskCompletionSource<object>(); Action<object> __success = (__res) => completion.SetResult((object)__res); Action<Exception> __failure = (__ex) => completion.SetException(__ex); var __cancellation = cancellation; __enter(() => __advance(__concurrentrelease(owner, __cancellation, __success, __failure).GetEnumerator()), __failure); return completion.Task; } public void release(philosopher owner, CancellationToken cancellation, Action<object> success, Action<Exception> failure) { var __success = success; var __failure = failure; var __cancellation = cancellation; __enter(() => __advance(__concurrentrelease(owner, __cancellation, __success, __failure).GetEnumerator()), failure); } private class __expr5 : Expression { public void __op6(bool ? v1, bool ? v2, Exception __ex) { if (!tryUpdate(v1, v2, ref __op6_Left, ref __op6_Right, __ex)) return; if (v1.HasValue) { if (__op6_Left.Value) __complete(true, null); else if (__op6_Right.HasValue) __complete(false, __ex); } else { if (__op6_Right.Value) __complete(true, null); else if (__op6_Left.HasValue) __complete(false, __ex); } } private bool ? __op6_Left; private bool ? __op6_Right; } public readonly Guid __ID = Guid.NewGuid(); } //temporary class to abort the app when all meals has been served //will dissapear soon. class StopCount { int _count; public StopCount(int count) { _count = count; } public bool ShouldStop() => --_count == 0; } class Program { static void Main(string[] args) { __app.Start(args); { } __app.Await(); } } }
/* * The MIT License (MIT) * * Copyright (c) 2014 Youcef Lemsafer * * 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. */ /** * Creator: Youcef Lemsafer * Creation date: 2013.07.11 **/ namespace dcs.Tests { /// <summary> /// Summary description for ParserTest. /// </summary> [TestClass] public class ParserTests { public ParserTests() { } [TestMethod] void parseNumberTest() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("127"); Assert.isTrue(exprAST.GetType() == typeof(NumberNode)); Assert.areEq(new Number("127"), (exprAST as NumberNode).Value); } [TestMethod] void parseAddExpr() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("2+3"); Assert.isTrue(exprAST.GetType() == typeof(AddExprNode)); AddExprNode addExpr = exprAST as AddExprNode; Assert.isTrue(addExpr.LeftOperand as NumberNode != null); Assert.areEq(new Number("2"), (addExpr.LeftOperand as NumberNode).Value); Assert.isTrue(addExpr.RightOperand as NumberNode != null); Assert.areEq(new Number("3"), (addExpr.RightOperand as NumberNode).Value); } [TestMethod] void parseAddExprWithThreeTerms() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("1 + 3 + 7"); Assert.isOfType(exprAST, typeof(AddExprNode)); AddExprNode add_7 = exprAST as AddExprNode; Assert.isOfType(add_7.LeftOperand, typeof(AddExprNode)); Assert.isOfType(add_7.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("7"), (add_7.RightOperand as NumberNode).Value); AddExprNode add_3 = add_7.LeftOperand as AddExprNode; Assert.isOfType(add_3.LeftOperand, typeof(NumberNode)); Assert.isOfType(add_3.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("1"), (add_3.LeftOperand as NumberNode).Value); Assert.areEq(new Number("3"), (add_3.RightOperand as NumberNode).Value); } [TestMethod] void parseSubExprWithThreeTerms() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("1 - 3 - 7"); Assert.isOfType(exprAST, typeof(SubExprNode)); SubExprNode add_7 = exprAST as SubExprNode; Assert.isOfType(add_7.LeftOperand, typeof(SubExprNode)); Assert.isOfType(add_7.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("7"), (add_7.RightOperand as NumberNode).Value); SubExprNode add_3 = add_7.LeftOperand as SubExprNode; Assert.isOfType(add_3.LeftOperand, typeof(NumberNode)); Assert.isOfType(add_3.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("1"), (add_3.LeftOperand as NumberNode).Value); Assert.areEq(new Number("3"), (add_3.RightOperand as NumberNode).Value); } [TestMethod] void parseMulExpr() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("2 * 3"); Assert.isOfType(exprAST, typeof(MulExprNode)); MulExprNode mulExpr = exprAST as MulExprNode; Assert.isTrue(mulExpr.LeftOperand as NumberNode != null); Assert.areEq(new Number("2"), (mulExpr.LeftOperand as NumberNode).Value); Assert.isTrue(mulExpr.RightOperand as NumberNode != null); Assert.areEq(new Number("3"), (mulExpr.RightOperand as NumberNode).Value); } [TestMethod] void parseDivExpr() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("4 / 2"); Assert.isOfType(exprAST, typeof(DivExprNode)); DivExprNode divExpr = exprAST as DivExprNode; Assert.isTrue(divExpr.LeftOperand as NumberNode != null); Assert.areEq(new Number("4"), (divExpr.LeftOperand as NumberNode).Value); Assert.isTrue(divExpr.RightOperand as NumberNode != null); Assert.areEq(new Number("2"), (divExpr.RightOperand as NumberNode).Value); } [TestMethod] void parseAddExprWithThreeFactors() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("3 * 5 * 7"); Assert.isOfType(exprAST, typeof(MulExprNode)); MulExprNode mul_7 = exprAST as MulExprNode; Assert.isOfType(mul_7.LeftOperand, typeof(MulExprNode)); Assert.isOfType(mul_7.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("7"), (mul_7.RightOperand as NumberNode).Value); MulExprNode mul_5 = mul_7.LeftOperand as MulExprNode; Assert.isOfType(mul_5.LeftOperand, typeof(NumberNode)); Assert.isOfType(mul_5.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("3"), (mul_5.LeftOperand as NumberNode).Value); Assert.areEq(new Number("5"), (mul_5.RightOperand as NumberNode).Value); } [TestMethod] void parseDivExprWithThreeFactors() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("1024 / 256 / 2"); Assert.isOfType(exprAST, typeof(DivExprNode)); DivExprNode div_2 = exprAST as DivExprNode; Assert.isOfType(div_2.LeftOperand, typeof(DivExprNode)); Assert.isOfType(div_2.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("2"), (div_2.RightOperand as NumberNode).Value); DivExprNode div_256 = div_2.LeftOperand as DivExprNode; Assert.isOfType(div_256.LeftOperand, typeof(NumberNode)); Assert.isOfType(div_256.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("1024"), (div_256.LeftOperand as NumberNode).Value); Assert.areEq(new Number( "256"), (div_256.RightOperand as NumberNode).Value); } [TestMethod] void parseMulExprDivExpr() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("6 * 8 / 2"); Assert.isOfType(exprAST, typeof(DivExprNode)); DivExprNode div_2 = exprAST as DivExprNode; Assert.isOfType(div_2.LeftOperand, typeof(MulExprNode)); Assert.isOfType(div_2.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("2"), (div_2.RightOperand as NumberNode).Value); MulExprNode mul_8 = div_2.LeftOperand as MulExprNode; Assert.isOfType(mul_8.LeftOperand, typeof(NumberNode)); Assert.isOfType(mul_8.RightOperand, typeof(NumberNode)); Assert.areEq(new Number("6"), (mul_8.LeftOperand as NumberNode).Value); Assert.areEq(new Number("8"), (mul_8.RightOperand as NumberNode).Value); } [TestMethod] void parseAddAndMulExpr() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("1 + 2 * 3"); Assert.isOfType(exprAST, typeof(AddExprNode)); AddExprNode addExpr = exprAST as AddExprNode; Assert.isOfType(addExpr.LeftOperand, typeof(NumberNode)); Assert.isOfType(addExpr.RightOperand, typeof(MulExprNode)); MulExprNode mulExpr = addExpr.RightOperand as MulExprNode; Assert.isTrue(mulExpr.LeftOperand as NumberNode != null); Assert.areEq(new Number("2"), (mulExpr.LeftOperand as NumberNode).Value); Assert.isTrue(mulExpr.RightOperand as NumberNode != null); Assert.areEq(new Number("3"), (mulExpr.RightOperand as NumberNode).Value); } [TestMethod] void parseAddAndParenthesizedExpr() { ExprParser parser = new ExprParser(); ExprNode exprAST = parser.parseExpr("(1+2)*6"); Assert.isOfType(exprAST, typeof(MulExprNode)); MulExprNode mulExpr = exprAST as MulExprNode; Assert.isOfType(mulExpr.LeftOperand, typeof(AddExprNode)); Assert.isOfType(mulExpr.RightOperand, typeof(NumberNode)); } void parseInvalidExprMethod() { ExprParser parser = new ExprParser(); parser.parseExpr("1+2("); } [TestMethod] void parseInvalidExpr() { Assert.throws(new TestMethod(parseInvalidExprMethod), typeof(ParseException)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Razor.Language.Components; using Microsoft.AspNetCore.Razor.Language.Syntax; namespace Microsoft.AspNetCore.Razor.Language.Legacy { internal static class TagHelperBlockRewriter { public static TagMode GetTagMode( MarkupStartTagSyntax startTag, MarkupEndTagSyntax endTag, TagHelperBinding bindingResult) { var childSpan = startTag.GetLastToken()?.Parent; // Self-closing tags are always valid despite descriptors[X].TagStructure. if (childSpan?.GetContent().EndsWith("/>", StringComparison.Ordinal) ?? false) { return TagMode.SelfClosing; } var hasDirectiveAttribute = false; foreach (var descriptor in bindingResult.Descriptors) { var boundRules = bindingResult.Mappings[descriptor]; var nonDefaultRule = boundRules.FirstOrDefault(rule => rule.TagStructure != TagStructure.Unspecified); if (nonDefaultRule?.TagStructure == TagStructure.WithoutEndTag) { return TagMode.StartTagOnly; } // Directive attribute will tolerate forms that don't work for tag helpers. For instance: // // <input @onclick="..."> vs <input onclick="..." /> // // We don't want this to become an error just because you added a directive attribute. if (descriptor.IsAnyComponentDocumentTagHelper() && !descriptor.IsComponentOrChildContentTagHelper()) { hasDirectiveAttribute = true; } } if (hasDirectiveAttribute && startTag.IsVoidElement() && endTag == null) { return TagMode.StartTagOnly; } return TagMode.StartTagAndEndTag; } public static MarkupTagHelperStartTagSyntax Rewrite( string tagName, RazorParserFeatureFlags featureFlags, MarkupStartTagSyntax startTag, TagHelperBinding bindingResult, ErrorSink errorSink, RazorSourceDocument source) { var processedBoundAttributeNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var attributes = startTag.Attributes; var attributeBuilder = SyntaxListBuilder<RazorSyntaxNode>.Create(); for (var i = 0; i < startTag.Attributes.Count; i++) { var isMinimized = false; var attributeNameLocation = SourceLocation.Undefined; var child = startTag.Attributes[i]; TryParseResult result; if (child is MarkupAttributeBlockSyntax attributeBlock) { attributeNameLocation = attributeBlock.Name.GetSourceLocation(source); result = TryParseAttribute( tagName, attributeBlock, bindingResult.Descriptors, errorSink, processedBoundAttributeNames); attributeBuilder.Add(result.RewrittenAttribute); } else if (child is MarkupMinimizedAttributeBlockSyntax minimizedAttributeBlock) { isMinimized = true; attributeNameLocation = minimizedAttributeBlock.Name.GetSourceLocation(source); result = TryParseMinimizedAttribute( tagName, minimizedAttributeBlock, bindingResult.Descriptors, errorSink, processedBoundAttributeNames); attributeBuilder.Add(result.RewrittenAttribute); } else if (child is MarkupMiscAttributeContentSyntax miscContent) { foreach (var contentChild in miscContent.Children) { if (contentChild is CSharpCodeBlockSyntax codeBlock) { // TODO: Accept more than just Markup attributes: https://github.com/aspnet/Razor/issues/96. // Something like: // <input @checked /> var location = new SourceSpan(codeBlock.GetSourceLocation(source), codeBlock.FullWidth); var diagnostic = RazorDiagnosticFactory.CreateParsing_TagHelpersCannotHaveCSharpInTagDeclaration(location, tagName); errorSink.OnError(diagnostic); break; } else { // If the original span content was whitespace it ultimately means the tag // that owns this "attribute" is malformed and is expecting a user to type a new attribute. // ex: <myTH class="btn"| | var literalContent = contentChild.GetContent(); if (!string.IsNullOrWhiteSpace(literalContent)) { var location = contentChild.GetSourceSpan(source); var diagnostic = RazorDiagnosticFactory.CreateParsing_TagHelperAttributeListMustBeWellFormed(location); errorSink.OnError(diagnostic); break; } } } result = null; } else { result = null; } // Only want to track the attribute if we succeeded in parsing its corresponding Block/Span. if (result == null) { // Error occurred while parsing the attribute. Don't try parsing the rest to avoid misleading errors. for (var j = i; j < startTag.Attributes.Count; j++) { attributeBuilder.Add(startTag.Attributes[j]); } break; } // Check if it's a non-boolean bound attribute that is minimized or if it's a bound // non-string attribute that has null or whitespace content. var isValidMinimizedAttribute = featureFlags.AllowMinimizedBooleanTagHelperAttributes && result.IsBoundBooleanAttribute; if ((isMinimized && result.IsBoundAttribute && !isValidMinimizedAttribute) || (!isMinimized && result.IsBoundNonStringAttribute && string.IsNullOrWhiteSpace(GetAttributeValueContent(result.RewrittenAttribute)))) { var errorLocation = new SourceSpan(attributeNameLocation, result.AttributeName.Length); var propertyTypeName = GetPropertyType(result.AttributeName, bindingResult.Descriptors); var diagnostic = RazorDiagnosticFactory.CreateTagHelper_EmptyBoundAttribute(errorLocation, result.AttributeName, tagName, propertyTypeName); errorSink.OnError(diagnostic); } // Check if the attribute was a prefix match for a tag helper dictionary property but the // dictionary key would be the empty string. if (result.IsMissingDictionaryKey) { var errorLocation = new SourceSpan(attributeNameLocation, result.AttributeName.Length); var diagnostic = RazorDiagnosticFactory.CreateParsing_TagHelperIndexerAttributeNameMustIncludeKey(errorLocation, result.AttributeName, tagName); errorSink.OnError(diagnostic); } } if (attributeBuilder.Count > 0) { // This means we rewrote something. Use the new set of attributes. attributes = attributeBuilder.ToList(); } var tagHelperStartTag = SyntaxFactory.MarkupTagHelperStartTag( startTag.OpenAngle, startTag.Bang, startTag.Name, attributes, startTag.ForwardSlash, startTag.CloseAngle); return tagHelperStartTag.WithSpanContext(startTag.GetSpanContext()); } private static TryParseResult TryParseMinimizedAttribute( string tagName, MarkupMinimizedAttributeBlockSyntax attributeBlock, IEnumerable<TagHelperDescriptor> descriptors, ErrorSink errorSink, HashSet<string> processedBoundAttributeNames) { // Have a name now. Able to determine correct isBoundNonStringAttribute value. var result = CreateTryParseResult(attributeBlock.Name.GetContent(), descriptors, processedBoundAttributeNames); result.AttributeStructure = AttributeStructure.Minimized; if (result.IsDirectiveAttribute) { // Directive attributes have a different syntax. result.RewrittenAttribute = RewriteToMinimizedDirectiveAttribute(attributeBlock, result); return result; } else { var rewritten = SyntaxFactory.MarkupMinimizedTagHelperAttribute( attributeBlock.NamePrefix, attributeBlock.Name); rewritten = rewritten.WithTagHelperAttributeInfo( new TagHelperAttributeInfo(result.AttributeName, parameterName: null, result.AttributeStructure, result.IsBoundAttribute, isDirectiveAttribute: false)); result.RewrittenAttribute = rewritten; return result; } } private static TryParseResult TryParseAttribute( string tagName, MarkupAttributeBlockSyntax attributeBlock, IEnumerable<TagHelperDescriptor> descriptors, ErrorSink errorSink, HashSet<string> processedBoundAttributeNames) { // Have a name now. Able to determine correct isBoundNonStringAttribute value. var result = CreateTryParseResult(attributeBlock.Name.GetContent(), descriptors, processedBoundAttributeNames); if (attributeBlock.ValuePrefix == null) { // We are purposefully not persisting NoQuotes even for unbound attributes because it is still possible to // rewrite the values that introduces a space like in UrlResolutionTagHelper. // The other case is it could be an expression, treat NoQuotes and DoubleQuotes equivalently. We purposefully do not persist NoQuotes // ValueStyles at code generation time to protect users from rendering dynamic content with spaces // that can break attributes. // Ex: <tag my-attribute=@value /> where @value results in the test "hello world". // This way, the above code would render <tag my-attribute="hello world" />. result.AttributeStructure = AttributeStructure.DoubleQuotes; } else { var lastToken = attributeBlock.ValuePrefix.GetLastToken(); switch (lastToken.Kind) { case SyntaxKind.DoubleQuote: result.AttributeStructure = AttributeStructure.DoubleQuotes; break; case SyntaxKind.SingleQuote: result.AttributeStructure = AttributeStructure.SingleQuotes; break; default: result.AttributeStructure = AttributeStructure.Minimized; break; } } var attributeValue = attributeBlock.Value; if (attributeValue == null) { var builder = SyntaxListBuilder<RazorSyntaxNode>.Create(); // Add a marker for attribute value when there are no quotes like, <p class= > builder.Add(SyntaxFactory.MarkupTextLiteral(new SyntaxList<SyntaxToken>())); attributeValue = SyntaxFactory.GenericBlock(builder.ToList()); } var rewrittenValue = RewriteAttributeValue(result, attributeValue); if (result.IsDirectiveAttribute) { // Directive attributes have a different syntax. result.RewrittenAttribute = RewriteToDirectiveAttribute(attributeBlock, result, rewrittenValue); return result; } else { var rewritten = SyntaxFactory.MarkupTagHelperAttribute( attributeBlock.NamePrefix, attributeBlock.Name, attributeBlock.NameSuffix, attributeBlock.EqualsToken, attributeBlock.ValuePrefix, rewrittenValue, attributeBlock.ValueSuffix); rewritten = rewritten.WithTagHelperAttributeInfo( new TagHelperAttributeInfo(result.AttributeName, parameterName: null, result.AttributeStructure, result.IsBoundAttribute, isDirectiveAttribute: false)); result.RewrittenAttribute = rewritten; return result; } } private static MarkupTagHelperDirectiveAttributeSyntax RewriteToDirectiveAttribute( MarkupAttributeBlockSyntax attributeBlock, TryParseResult result, MarkupTagHelperAttributeValueSyntax rewrittenValue) { // // Consider, <Foo @bind:param="..." /> // We're now going to rewrite @bind:param from a regular MarkupAttributeBlock to a MarkupTagHelperDirectiveAttribute. // We need to split the name "@bind:param" into four parts, // @ - Transition (MetaCode) // bind - Name (Text) // : - Colon (MetaCode) // param - ParameterName (Text) // var attributeName = result.AttributeName; var attributeNameSyntax = attributeBlock.Name; var transition = SyntaxFactory.RazorMetaCode( new SyntaxList<SyntaxToken>(SyntaxFactory.MissingToken(SyntaxKind.Transition))); RazorMetaCodeSyntax colon = null; MarkupTextLiteralSyntax parameterName = null; if (attributeName.StartsWith("@", StringComparison.Ordinal)) { attributeName = attributeName.Substring(1); var attributeNameToken = SyntaxFactory.Token(SyntaxKind.Text, attributeName); attributeNameSyntax = SyntaxFactory.MarkupTextLiteral().AddLiteralTokens(attributeNameToken); var transitionToken = SyntaxFactory.Token(SyntaxKind.Transition, "@"); transition = SyntaxFactory.RazorMetaCode(new SyntaxList<SyntaxToken>(transitionToken)); } if (attributeName.IndexOf(':') != -1) { var segments = attributeName.Split(new[] { ':' }, 2); var attributeNameToken = SyntaxFactory.Token(SyntaxKind.Text, segments[0]); attributeNameSyntax = SyntaxFactory.MarkupTextLiteral().AddLiteralTokens(attributeNameToken); var colonToken = SyntaxFactory.Token(SyntaxKind.Colon, ":"); colon = SyntaxFactory.RazorMetaCode(new SyntaxList<SyntaxToken>(colonToken)); var parameterNameToken = SyntaxFactory.Token(SyntaxKind.Text, segments[1]); parameterName = SyntaxFactory.MarkupTextLiteral().AddLiteralTokens(parameterNameToken); } var rewritten = SyntaxFactory.MarkupTagHelperDirectiveAttribute( attributeBlock.NamePrefix, transition, attributeNameSyntax, colon, parameterName, attributeBlock.NameSuffix, attributeBlock.EqualsToken, attributeBlock.ValuePrefix, rewrittenValue, attributeBlock.ValueSuffix); rewritten = rewritten.WithTagHelperAttributeInfo( new TagHelperAttributeInfo(result.AttributeName, parameterName?.GetContent(), result.AttributeStructure, result.IsBoundAttribute, isDirectiveAttribute: true)); return rewritten; } private static MarkupMinimizedTagHelperDirectiveAttributeSyntax RewriteToMinimizedDirectiveAttribute( MarkupMinimizedAttributeBlockSyntax attributeBlock, TryParseResult result) { // // Consider, <Foo @bind:param /> // We're now going to rewrite @bind:param from a regular MarkupAttributeBlock to a MarkupTagHelperDirectiveAttribute. // We need to split the name "@bind:param" into four parts, // @ - Transition (MetaCode) // bind - Name (Text) // : - Colon (MetaCode) // param - ParameterName (Text) // var attributeName = result.AttributeName; var attributeNameSyntax = attributeBlock.Name; var transition = SyntaxFactory.RazorMetaCode( new SyntaxList<SyntaxToken>(SyntaxFactory.MissingToken(SyntaxKind.Transition))); RazorMetaCodeSyntax colon = null; MarkupTextLiteralSyntax parameterName = null; if (attributeName.StartsWith("@", StringComparison.Ordinal)) { attributeName = attributeName.Substring(1); var attributeNameToken = SyntaxFactory.Token(SyntaxKind.Text, attributeName); attributeNameSyntax = SyntaxFactory.MarkupTextLiteral().AddLiteralTokens(attributeNameToken); var transitionToken = SyntaxFactory.Token(SyntaxKind.Transition, "@"); transition = SyntaxFactory.RazorMetaCode(new SyntaxList<SyntaxToken>(transitionToken)); } if (attributeName.IndexOf(':') != -1) { var segments = attributeName.Split(new[] { ':' }, 2); var attributeNameToken = SyntaxFactory.Token(SyntaxKind.Text, segments[0]); attributeNameSyntax = SyntaxFactory.MarkupTextLiteral().AddLiteralTokens(attributeNameToken); var colonToken = SyntaxFactory.Token(SyntaxKind.Colon, ":"); colon = SyntaxFactory.RazorMetaCode(new SyntaxList<SyntaxToken>(colonToken)); var parameterNameToken = SyntaxFactory.Token(SyntaxKind.Text, segments[1]); parameterName = SyntaxFactory.MarkupTextLiteral().AddLiteralTokens(parameterNameToken); } var rewritten = SyntaxFactory.MarkupMinimizedTagHelperDirectiveAttribute( attributeBlock.NamePrefix, transition, attributeNameSyntax, colon, parameterName); rewritten = rewritten.WithTagHelperAttributeInfo( new TagHelperAttributeInfo(result.AttributeName, parameterName?.GetContent(), result.AttributeStructure, result.IsBoundAttribute, isDirectiveAttribute: true)); return rewritten; } private static MarkupTagHelperAttributeValueSyntax RewriteAttributeValue(TryParseResult result, RazorBlockSyntax attributeValue) { var rewriter = new AttributeValueRewriter(result); var rewrittenValue = attributeValue; if (result.IsBoundAttribute) { // If the attribute was requested by a tag helper but the corresponding property was not a // string, then treat its value as code. A non-string value can be any C# value so we need // to ensure the tree reflects that. rewrittenValue = (RazorBlockSyntax)rewriter.Visit(attributeValue); } return SyntaxFactory.MarkupTagHelperAttributeValue(rewrittenValue.Children); } // Determines the full name of the Type of the property corresponding to an attribute with the given name. private static string GetPropertyType(string name, IEnumerable<TagHelperDescriptor> descriptors) { foreach (var descriptor in descriptors) { if (TagHelperMatchingConventions.TryGetFirstBoundAttributeMatch(name, descriptor, out var firstBoundAttribute, out var indexerMatch, out var _, out var _)) { if (indexerMatch) { return firstBoundAttribute.IndexerTypeName; } else { return firstBoundAttribute.TypeName; } } } return null; } // Create a TryParseResult for given name, filling in binding details. private static TryParseResult CreateTryParseResult( string name, IEnumerable<TagHelperDescriptor> descriptors, HashSet<string> processedBoundAttributeNames) { var isBoundAttribute = false; var isBoundNonStringAttribute = false; var isBoundBooleanAttribute = false; var isMissingDictionaryKey = false; var isDirectiveAttribute = false; foreach (var descriptor in descriptors) { if (TagHelperMatchingConventions.TryGetFirstBoundAttributeMatch( name, descriptor, out var firstBoundAttribute, out var indexerMatch, out var parameterMatch, out var boundAttributeParameter)) { isBoundAttribute = true; if (parameterMatch) { isBoundNonStringAttribute = !boundAttributeParameter.IsStringProperty; isBoundBooleanAttribute = boundAttributeParameter.IsBooleanProperty; isMissingDictionaryKey = false; } else { isBoundNonStringAttribute = !firstBoundAttribute.ExpectsStringValue(name); isBoundBooleanAttribute = firstBoundAttribute.ExpectsBooleanValue(name); isMissingDictionaryKey = firstBoundAttribute.IndexerNamePrefix != null && name.Length == firstBoundAttribute.IndexerNamePrefix.Length; } isDirectiveAttribute = firstBoundAttribute.IsDirectiveAttribute(); break; } } var isDuplicateAttribute = false; if (isBoundAttribute && !processedBoundAttributeNames.Add(name)) { // A bound attribute with the same name has already been processed. isDuplicateAttribute = true; } return new TryParseResult { AttributeName = name, IsBoundAttribute = isBoundAttribute, IsBoundNonStringAttribute = isBoundNonStringAttribute, IsBoundBooleanAttribute = isBoundBooleanAttribute, IsMissingDictionaryKey = isMissingDictionaryKey, IsDuplicateAttribute = isDuplicateAttribute, IsDirectiveAttribute = isDirectiveAttribute }; } private static string GetAttributeValueContent(RazorSyntaxNode attributeBlock) { if (attributeBlock is MarkupTagHelperAttributeSyntax tagHelperAttribute) { return tagHelperAttribute.Value?.GetContent(); } else if (attributeBlock is MarkupTagHelperDirectiveAttributeSyntax directiveAttribute) { return directiveAttribute.Value?.GetContent(); } else if (attributeBlock is MarkupAttributeBlockSyntax attribute) { return attribute.Value?.GetContent(); } return null; } private class AttributeValueRewriter : SyntaxRewriter { private readonly TryParseResult _tryParseResult; private bool _rewriteAsMarkup; public AttributeValueRewriter(TryParseResult result) { _tryParseResult = result; } public override SyntaxNode VisitGenericBlock(GenericBlockSyntax node) { if (_tryParseResult.IsBoundNonStringAttribute && CanBeCollapsed(node)) { var tokens = node.GetTokens(); var expression = SyntaxFactory.CSharpExpressionLiteral(tokens); var rewrittenExpression = (CSharpExpressionLiteralSyntax)VisitCSharpExpressionLiteral(expression); var newChildren = SyntaxListBuilder<RazorSyntaxNode>.Create(); newChildren.Add(rewrittenExpression); return node.Update(newChildren); } return base.VisitGenericBlock(node); } public override SyntaxNode VisitCSharpTransition(CSharpTransitionSyntax node) { if (!_tryParseResult.IsBoundNonStringAttribute) { return base.VisitCSharpTransition(node); } // For bound non-string attributes, we'll only allow a transition span to appear at the very // beginning of the attribute expression. All later transitions would appear as code so that // they are part of the generated output. E.g. // key="@value" -> MyTagHelper.key = value // key=" @value" -> MyTagHelper.key = @value // key="1 + @case" -> MyTagHelper.key = 1 + @case // key="@int + @case" -> MyTagHelper.key = int + @case // key="@(a + b) -> MyTagHelper.key = a + b // key="4 + @(a + b)" -> MyTagHelper.key = 4 + @(a + b) if (_rewriteAsMarkup) { // Change to a MarkupChunkGenerator so that the '@' \ parenthesis is generated as part of the output. var context = node.GetSpanContext(); var newContext = new SpanContext(new MarkupChunkGenerator(), context.EditHandler); var expression = SyntaxFactory.CSharpExpressionLiteral(new SyntaxList<SyntaxToken>(node.Transition)).WithSpanContext(newContext); return base.VisitCSharpExpressionLiteral(expression); } _rewriteAsMarkup = true; return base.VisitCSharpTransition(node); } public override SyntaxNode VisitCSharpImplicitExpression(CSharpImplicitExpressionSyntax node) { if (_rewriteAsMarkup) { var builder = SyntaxListBuilder<RazorSyntaxNode>.Create(); // Convert transition. // Change to a MarkupChunkGenerator so that the '@' \ parenthesis is generated as part of the output. var context = node.GetSpanContext(); var newContext = new SpanContext(new MarkupChunkGenerator(), context?.EditHandler ?? SpanEditHandler.CreateDefault((content) => Enumerable.Empty<Syntax.InternalSyntax.SyntaxToken>())); var expression = SyntaxFactory.CSharpExpressionLiteral(new SyntaxList<SyntaxToken>(node.Transition.Transition)).WithSpanContext(newContext); expression = (CSharpExpressionLiteralSyntax)VisitCSharpExpressionLiteral(expression); builder.Add(expression); var rewrittenBody = (CSharpCodeBlockSyntax)VisitCSharpCodeBlock(((CSharpImplicitExpressionBodySyntax)node.Body).CSharpCode); builder.AddRange(rewrittenBody.Children); // Since the original transition is part of the body, we need something to take it's place. var transition = SyntaxFactory.CSharpTransition(SyntaxFactory.MissingToken(SyntaxKind.Transition)); var rewrittenCodeBlock = SyntaxFactory.CSharpCodeBlock(builder.ToList()); return SyntaxFactory.CSharpImplicitExpression(transition, SyntaxFactory.CSharpImplicitExpressionBody(rewrittenCodeBlock)); } return base.VisitCSharpImplicitExpression(node); } public override SyntaxNode VisitCSharpExplicitExpression(CSharpExplicitExpressionSyntax node) { CSharpTransitionSyntax transition = null; var builder = SyntaxListBuilder<RazorSyntaxNode>.Create(); if (_rewriteAsMarkup) { // Convert transition. // Change to a MarkupChunkGenerator so that the '@' \ parenthesis is generated as part of the output. var context = node.GetSpanContext(); var newContext = new SpanContext(new MarkupChunkGenerator(), context?.EditHandler ?? SpanEditHandler.CreateDefault((content) => Enumerable.Empty<Syntax.InternalSyntax.SyntaxToken>())); var expression = SyntaxFactory.CSharpExpressionLiteral(new SyntaxList<SyntaxToken>(node.Transition.Transition)).WithSpanContext(newContext); expression = (CSharpExpressionLiteralSyntax)VisitCSharpExpressionLiteral(expression); builder.Add(expression); // Since the original transition is part of the body, we need something to take it's place. transition = SyntaxFactory.CSharpTransition(SyntaxFactory.MissingToken(SyntaxKind.Transition)); var body = (CSharpExplicitExpressionBodySyntax)node.Body; var rewrittenOpenParen = (RazorSyntaxNode)VisitRazorMetaCode(body.OpenParen); var rewrittenBody = (CSharpCodeBlockSyntax)VisitCSharpCodeBlock(body.CSharpCode); var rewrittenCloseParen = (RazorSyntaxNode)VisitRazorMetaCode(body.CloseParen); builder.Add(rewrittenOpenParen); builder.AddRange(rewrittenBody.Children); builder.Add(rewrittenCloseParen); } else { // This is the first expression of a non-string attribute like attr=@(a + b) // Below code converts this to an implicit expression to make the parens // part of the expression so that it is rendered. transition = (CSharpTransitionSyntax)Visit(node.Transition); var body = (CSharpExplicitExpressionBodySyntax)node.Body; var rewrittenOpenParen = (RazorSyntaxNode)VisitRazorMetaCode(body.OpenParen); var rewrittenBody = (CSharpCodeBlockSyntax)VisitCSharpCodeBlock(body.CSharpCode); var rewrittenCloseParen = (RazorSyntaxNode)VisitRazorMetaCode(body.CloseParen); builder.Add(rewrittenOpenParen); builder.AddRange(rewrittenBody.Children); builder.Add(rewrittenCloseParen); } var rewrittenCodeBlock = SyntaxFactory.CSharpCodeBlock(builder.ToList()); return SyntaxFactory.CSharpImplicitExpression(transition, SyntaxFactory.CSharpImplicitExpressionBody(rewrittenCodeBlock)); } public override SyntaxNode VisitRazorMetaCode(RazorMetaCodeSyntax node) { if (!_tryParseResult.IsBoundNonStringAttribute) { return base.VisitRazorMetaCode(node); } if (_rewriteAsMarkup) { // Change to a MarkupChunkGenerator so that the '@' \ parenthesis is generated as part of the output. var context = node.GetSpanContext(); var newContext = new SpanContext(new MarkupChunkGenerator(), context.EditHandler); var expression = SyntaxFactory.CSharpExpressionLiteral(new SyntaxList<SyntaxToken>(node.MetaCode)).WithSpanContext(newContext); return VisitCSharpExpressionLiteral(expression); } _rewriteAsMarkup = true; return base.VisitRazorMetaCode(node); } public override SyntaxNode VisitCSharpStatement(CSharpStatementSyntax node) { // We don't support code blocks inside tag helper attributes. Don't rewrite anything inside a code block. // E.g, <p age="@{1 + 2}"> is not supported. return node; } public override SyntaxNode VisitRazorDirective(RazorDirectiveSyntax node) { // We don't support directives inside tag helper attributes. Don't rewrite anything inside a directive. // E.g, <p age="@functions { }"> is not supported. return node; } public override SyntaxNode VisitMarkupElement(MarkupElementSyntax node) { // We're visiting an attribute value. If we encounter a MarkupElement this means the attribute value is invalid. // We don't want to rewrite anything here. // E.g, <my age="@if (true) { <my4 age=... }"></my4> return node; } public override SyntaxNode VisitCSharpExpressionLiteral(CSharpExpressionLiteralSyntax node) { if (!_tryParseResult.IsBoundNonStringAttribute) { return base.VisitCSharpExpressionLiteral(node); } node = (CSharpExpressionLiteralSyntax)ConfigureNonStringAttribute(node); _rewriteAsMarkup = true; return base.VisitCSharpExpressionLiteral(node); } public override SyntaxNode VisitMarkupLiteralAttributeValue(MarkupLiteralAttributeValueSyntax node) { var builder = SyntaxListBuilder<SyntaxToken>.Create(); if (node.Prefix != null) { builder.AddRange(node.Prefix.LiteralTokens); } if (node.Value != null) { builder.AddRange(node.Value.LiteralTokens); } if (_tryParseResult.IsBoundNonStringAttribute) { _rewriteAsMarkup = true; // Since this is a bound non-string attribute, we want to convert LiteralAttributeValue to just be a CSharp Expression literal. var expression = SyntaxFactory.CSharpExpressionLiteral(builder.ToList()); return VisitCSharpExpressionLiteral(expression); } else { var literal = SyntaxFactory.MarkupTextLiteral(builder.ToList()); var context = node.Value?.GetSpanContext(); literal = context != null ? literal.WithSpanContext(context) : literal; return Visit(literal); } } public override SyntaxNode VisitMarkupDynamicAttributeValue(MarkupDynamicAttributeValueSyntax node) { // Move the prefix to be part of the actual value. var builder = SyntaxListBuilder<RazorSyntaxNode>.Create(); if (node.Prefix != null) { builder.Add(node.Prefix); } if (node.Value?.Children != null) { builder.AddRange(node.Value.Children); } var rewrittenValue = SyntaxFactory.MarkupBlock(builder.ToList()); return base.VisitMarkupBlock(rewrittenValue); } public override SyntaxNode VisitCSharpStatementLiteral(CSharpStatementLiteralSyntax node) { if (!_tryParseResult.IsBoundNonStringAttribute) { return base.VisitCSharpStatementLiteral(node); } _rewriteAsMarkup = true; return base.VisitCSharpStatementLiteral(node); } public override SyntaxNode VisitMarkupTextLiteral(MarkupTextLiteralSyntax node) { if (!_tryParseResult.IsBoundNonStringAttribute) { return base.VisitMarkupTextLiteral(node); } _rewriteAsMarkup = true; node = (MarkupTextLiteralSyntax)ConfigureNonStringAttribute(node); var tokens = new SyntaxList<SyntaxToken>(node.LiteralTokens); var value = SyntaxFactory.CSharpExpressionLiteral(tokens); return value.WithSpanContext(node.GetSpanContext()); } public override SyntaxNode VisitMarkupEphemeralTextLiteral(MarkupEphemeralTextLiteralSyntax node) { if (!_tryParseResult.IsBoundNonStringAttribute) { return base.VisitMarkupEphemeralTextLiteral(node); } // Since this is a non-string attribute we need to rewrite this as code. // Rewriting it to CSharpEphemeralTextLiteral so that it is not rendered to output. _rewriteAsMarkup = true; node = (MarkupEphemeralTextLiteralSyntax)ConfigureNonStringAttribute(node); var tokens = new SyntaxList<SyntaxToken>(node.LiteralTokens); var value = SyntaxFactory.CSharpEphemeralTextLiteral(tokens); return value.WithSpanContext(node.GetSpanContext()); } // Being collapsed represents that a block contains several identical looking markup literal attribute values. This can be the case // when a user has written something like: @onclick="() => SomeMethod()" // In that case there would be 3 children: // - () // - => // - SomeMethod() // There are 3 children because the Razor parser separates attribute values based on whitespace. private static bool CanBeCollapsed(GenericBlockSyntax node) { if (node.Children.Count <= 1) { // The node is either already collapsed or has no children. return false; } for (var i = 0; i < node.Children.Count; i++) { if (node.Children[i].Kind != SyntaxKind.MarkupLiteralAttributeValue) { return false; } } return true; } private SyntaxNode ConfigureNonStringAttribute(SyntaxNode node) { var context = node.GetSpanContext(); var builder = context != null ? new SpanContextBuilder(context) : new SpanContextBuilder(); builder.EditHandler = new ImplicitExpressionEditHandler( builder.EditHandler.Tokenizer, CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) { AcceptedCharacters = AcceptedCharactersInternal.AnyExceptNewline }; if (!_tryParseResult.IsDuplicateAttribute && builder.ChunkGenerator != SpanChunkGenerator.Null) { // We want to mark the value of non-string bound attributes to be CSharp. // Except in two cases, // 1. Cases when we don't want to render the span. Eg: Transition span '@'. // 2. Cases when it is a duplicate of a bound attribute. This should just be rendered as html. builder.ChunkGenerator = new ExpressionChunkGenerator(); } context = builder.Build(); return node.WithSpanContext(context); } } private class TryParseResult { public string AttributeName { get; set; } public RazorSyntaxNode RewrittenAttribute { get; set; } public AttributeStructure AttributeStructure { get; set; } public bool IsBoundAttribute { get; set; } public bool IsBoundNonStringAttribute { get; set; } public bool IsBoundBooleanAttribute { get; set; } public bool IsMissingDictionaryKey { get; set; } public bool IsDuplicateAttribute { get; set; } public bool IsDirectiveAttribute { get; set; } } } }
//----------------------------------------------------------------------- // <copyright file="Buffer.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace Stratus.OdinSerializer { using System; using System.Collections.Generic; /// <summary> /// Provides a way of claiming and releasing cached array buffers. /// </summary> /// <typeparam name="T">The element type of the array to buffer.</typeparam> /// <seealso cref="System.IDisposable" /> public sealed class Buffer<T> : IDisposable { private static readonly object LOCK = new object(); private static readonly List<Buffer<T>> FreeBuffers = new List<Buffer<T>>(); private int count; private T[] array; private volatile bool isFree; private Buffer(int count) { this.array = new T[count]; this.count = count; this.isFree = false; // Always start as non-free } /// <summary> /// Gets the total element count of the buffered array. This will always be a power of two. /// </summary> /// <value> /// The total element count of the buffered array. /// </value> /// <exception cref="System.InvalidOperationException">Cannot access a buffer while it is freed.</exception> public int Count { get { if (this.isFree) { throw new InvalidOperationException("Cannot access a buffer while it is freed."); } return this.count; } } /// <summary> /// Gets the buffered array. /// </summary> /// <value> /// The buffered array. /// </value> /// <exception cref="System.InvalidOperationException">Cannot access a buffer while it is freed.</exception> public T[] Array { get { if (this.isFree) { throw new InvalidOperationException("Cannot access a buffer while it is freed."); } return this.array; } } /// <summary> /// Gets a value indicating whether this buffer is free. /// </summary> /// <value> /// <c>true</c> if this buffer is free; otherwise, <c>false</c>. /// </value> public bool IsFree { get { return this.isFree; } } /// <summary> /// Claims a buffer with the specified minimum capacity. Note: buffers always have a capacity equal to or larger than 256. /// </summary> /// <param name="minimumCapacity">The minimum capacity.</param> /// <returns>A buffer which has a capacity equal to or larger than the specified minimum capacity.</returns> /// <exception cref="System.ArgumentException">Requested size of buffer must be larger than 0.</exception> public static Buffer<T> Claim(int minimumCapacity) { if (minimumCapacity < 0) { throw new ArgumentException("Requested size of buffer must be larger than or equal to 0."); } if (minimumCapacity < 256) { minimumCapacity = 256; // Minimum buffer size } Buffer<T> result = null; lock (LOCK) { // Search for a free buffer of sufficient size for (int i = 0; i < Buffer<T>.FreeBuffers.Count; i++) { var buffer = Buffer<T>.FreeBuffers[i]; if (buffer != null && buffer.count >= minimumCapacity) { result = buffer; result.isFree = false; Buffer<T>.FreeBuffers[i] = null; break; } } } if (result == null) { // Allocate new buffer result = new Buffer<T>(Buffer<T>.NextPowerOfTwo(minimumCapacity)); } return result; } /// <summary> /// Frees the specified buffer. /// </summary> /// <param name="buffer">The buffer to free.</param> /// <exception cref="System.ArgumentNullException">The buffer argument is null.</exception> public static void Free(Buffer<T> buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (buffer.isFree == false) { lock (LOCK) { if (buffer.isFree == false) { buffer.isFree = true; bool added = false; for (int i = 0; i < Buffer<T>.FreeBuffers.Count; i++) { if (Buffer<T>.FreeBuffers[i] == null) { Buffer<T>.FreeBuffers[i] = buffer; added = true; break; } } if (!added) { Buffer<T>.FreeBuffers.Add(buffer); } } } } } /// <summary> /// Frees this buffer. /// </summary> public void Free() { Buffer<T>.Free(this); } /// <summary> /// Frees this buffer. /// </summary> public void Dispose() { Buffer<T>.Free(this); } private static int NextPowerOfTwo(int v) { // Engage bit hax // http://stackoverflow.com/questions/466204/rounding-up-to-nearest-power-of-2 v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Windows.Forms; using System.Collections; using Axiom.Core; using Axiom.Graphics; namespace Axiom.RenderSystems.DirectX9 { public class DefaultForm : System.Windows.Forms.Form { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(DefaultForm)); public static IDictionary WndOverrides = new Hashtable(); public static void AddWndOverride(int wm_msg, IWindowTarget target) { lock (WndOverrides) { if (!WndOverrides.Contains(wm_msg)) { WndOverrides.Add(wm_msg, target); } } } public static bool HasWndOverride(int wm_msg) { lock (WndOverrides) { return WndOverrides.Contains(wm_msg); } } public static void RemoveWndOverride(int wm_msg) { lock (WndOverrides) { if (WndOverrides.Contains(wm_msg)) { WndOverrides.Remove(wm_msg); } } } public static bool WndOverride(ref Message m) { lock (WndOverrides) { if (WndOverrides.Contains(m.Msg)) { // do we need to handle multiple overrides, or overrides // that choose not to do anything? IWindowTarget iw = (IWindowTarget)WndOverrides[m.Msg]; iw.OnMessage(ref m); return true; } else { return false; } } } private RenderWindow renderWindow; // This is the picture box we will use if we are not full screen private AxiomRenderBox pictureBox; // This variable just keeps track of where we are rendering. private Control renderBox = null; public DefaultForm(bool useRenderBox, string initialLoadBitmap) { InitializeComponent(); if (initialLoadBitmap != "") this.BackgroundImage = new System.Drawing.Bitmap(initialLoadBitmap); if (useRenderBox) { // In this case, we will render into the picture box // instead of into the top level form. This is generally // the case if we are not full screen. renderBox = pictureBox; } else { // In this case, we are rendering into the top level form. // I want to hide the pictureBox, since I don't want the // events to get intercepted. I could always just render // into the top level form, but this would cause us to use // the wrong cursor for the top bar (move) and the edges // (resize) pictureBox.Hide(); } this.Deactivate += new System.EventHandler(this.DefaultForm_Deactivate); this.Activated += new System.EventHandler(this.DefaultForm_Activated); this.Closing += new System.ComponentModel.CancelEventHandler(this.DefaultForm_Close); this.Resize += new System.EventHandler(this.DefaultForm_Resize); } protected override void WndProc(ref Message m) { if (!WndOverride(ref m)) { log.DebugFormat("Pre Message m = {0}", m); switch (m.Msg) { case 0x00000005: // WM_SIZE if (renderWindow != null && renderWindow.IsFullScreen) { log.InfoFormat("Ignoring size message, since we are full screen"); break; } base.WndProc(ref m); break; default: base.WndProc(ref m); break; } log.DebugFormat("Post Message m = {0}", m); } } /// <summary> /// /// </summary> /// <param name="source"></param> /// <param name="e"></param> public void DefaultForm_Deactivate(object source, System.EventArgs e) { if (renderWindow != null) { renderWindow.IsActive = false; } } /// <summary> /// /// </summary> /// <param name="source"></param> /// <param name="e"></param> public void DefaultForm_Activated(object source, System.EventArgs e) { if (renderWindow != null) { renderWindow.IsActive = true; } } private void InitializeComponent() { this.pictureBox = new Axiom.RenderSystems.DirectX9.AxiomRenderBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); this.SuspendLayout(); // // pictureBox // this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox.Location = new System.Drawing.Point(0, 0); this.pictureBox.Name = "pictureBox"; this.pictureBox.Size = new System.Drawing.Size(640, 480); this.pictureBox.TabIndex = 1; this.pictureBox.TabStop = false; this.pictureBox.UseWaitCursor = true; this.pictureBox.Visible = false; // // DefaultForm // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.AutoValidate = System.Windows.Forms.AutoValidate.Disable; this.BackColor = System.Drawing.Color.Black; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.CausesValidation = false; this.ClientSize = new System.Drawing.Size(640, 480); this.Controls.Add(this.pictureBox); this.Name = "DefaultForm"; this.UseWaitCursor = true; this.Load += new System.EventHandler(this.DefaultForm_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); this.ResumeLayout(false); } /// <summary> /// /// </summary> /// <param name="source"></param> /// <param name="e"></param> public void DefaultForm_Close(object source, System.ComponentModel.CancelEventArgs e) { // set the window to inactive renderWindow.IsActive = false; // remove it from the list of render windows, which will halt the rendering loop // since there should now be 0 windows left Root.Instance.RenderSystem.DetachRenderTarget(renderWindow); } private void DefaultForm_Load(object sender, System.EventArgs e) { // this.Icon = new System.Drawing.Icon(Axiom.Core.ResourceManager.FindCommonResourceData("AxiomIcon.ico")); } // Not currently used, but there should be some code to trap resize events // when I am fullscreen. private void DefaultForm_Resizing(object sender, System.ComponentModel.CancelEventArgs ce) { object device = renderWindow.GetCustomAttribute("D3DDEVICE"); if (device != null) { Microsoft.DirectX.Direct3D.Device d3dDevice = device as Microsoft.DirectX.Direct3D.Device; if (d3dDevice.PresentationParameters.Windowed == false) ce.Cancel = true; log.InfoFormat("Canceled resize event for full screen window"); return; } } private void DefaultForm_Resize(object sender, System.EventArgs e) { Root.Instance.SuspendRendering = this.WindowState == FormWindowState.Minimized; } /// <summary> /// Get/Set the RenderWindow associated with this form. /// </summary> public RenderWindow RenderWindow { get { return renderWindow; } set { renderWindow = value; } } public Control PictureBox { get { return pictureBox; } } public Control Target { get { if (renderBox != null) return renderBox; return this; } } } }