context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* Copyright 2015-2018 Daniel Adrian Redondo Suarez 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.Linq; using System.Threading.Tasks; using TWCore.Collections; using TWCore.Messaging.Configuration; using TWCore.Messaging.RabbitMQ; using TWCore.Serialization; using TWCore.Services; // ReSharper disable ConvertToConstant.Local // ReSharper disable UnusedMember.Global // ReSharper disable InconsistentNaming // ReSharper disable UnusedVariable // ReSharper disable AccessToDisposedClosure namespace TWCore.Tests { /// <inheritdoc /> public class RabbitMQTest : ContainerParameterServiceAsync { public RabbitMQTest() : base("rabbitmqtest", "RabbitMQ Test") { } protected override async Task OnHandlerAsync(ParameterHandlerInfo info) { Core.Log.Warning("Starting RabbitMQ Test"); #region Set Config var mqConfig = new MQPairConfig { Name = "QueueTest", Types = new MQObjectTypes { ClientType = typeof(RabbitMQueueClient), ServerType = typeof(RabbitMQueueServer), AdminType = typeof(RabbitMQueueAdmin) }, RawTypes = new MQObjectTypes { ClientType = typeof(RabbitMQueueRawClient), ServerType = typeof(RabbitMQueueRawServer), AdminType = typeof(RabbitMQueueAdmin) }, ClientQueues = new List<MQClientQueues> { new MQClientQueues { EnvironmentName = "", MachineName = "", SendQueues = new List<MQConnection> { new MQConnection("amqp://agsw:agsw@127.0.0.1:5672/", "TEST_RQ", null) }, RecvQueue = new MQConnection("amqp://agsw:agsw@127.0.0.1:5672/", "TEST_RS", null) } }, ServerQueues = new List<MQServerQueues> { new MQServerQueues { EnvironmentName = "", MachineName = "", RecvQueues = new List<MQConnection> { new MQConnection("amqp://agsw:agsw@127.0.0.1:5672/", "TEST_RQ", null) }, //ClientQueuesRoutesRebindings = new KeyValueCollection //{ // new KeyValue<string, string> { Key = "amqp://agsw:agsw@127.0.0.1:5672/", Value = "amqp://agsw:agsw@127.0.0.2:5672/" } //} } }, RequestOptions = new MQRequestOptions { SerializerMimeType = SerializerManager.DefaultBinarySerializer.MimeTypes[0], //CompressorEncodingType = "gzip", ClientSenderOptions = new MQClientSenderOptions { Label = "TEST REQUEST", MessageExpirationInSec = 30, MessagePriority = MQMessagePriority.Normal, Recoverable = false }, ServerReceiverOptions = new MQServerReceiverOptions { MaxSimultaneousMessagesPerQueue = 20000, ProcessingWaitOnFinalizeInSec = 10, SleepOnExceptionInSec = 1000 } }, ResponseOptions = new MQResponseOptions { SerializerMimeType = SerializerManager.DefaultBinarySerializer.MimeTypes[0], //CompressorEncodingType = "gzip", ClientReceiverOptions = new MQClientReceiverOptions(60, new KeyValue<string, string>("SingleResponseQueue", "true") ), ServerSenderOptions = new MQServerSenderOptions { Label = "TEST RESPONSE", MessageExpirationInSec = 30, MessagePriority = MQMessagePriority.Normal, Recoverable = false } } }; #endregion JsonTextSerializerExtensions.Serializer.Indent = true; mqConfig.SerializeToXmlFile("mqConfig.xml"); mqConfig.SerializeToJsonFile("mqConfig.json"); var manager = mqConfig.GetQueueManager(); manager.CreateClientQueues(); //Core.DebugMode = true; //Core.Log.MaxLogLevel = Diagnostics.Log.LogLevel.InfoDetail; Core.Log.Warning("Starting with Normal Listener and Client"); await NormalTestAsync(mqConfig).ConfigureAwait(false); mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "true"; Core.Log.Warning("Starting with RAW Listener and Client"); await RawTestAsync(mqConfig).ConfigureAwait(false); } private static async Task NormalTestAsync(MQPairConfig mqConfig) { using (var mqServer = mqConfig.GetServer()) { mqServer.RequestReceived += (s, e) => { e.SetResponseBody("Bienvenido!!!"); //e.Request.Body.Dispose(); return Task.CompletedTask; }; mqServer.StartListeners(); using (var mqClient = mqConfig.GetClient()) { var totalQ = 50000; #region Sync Mode Core.Log.Warning("Sync Mode Test, using Unique Response Queue"); using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times")) { for (var i = 0; i < totalQ; i++) { var response = await mqClient.SendAndReceiveAsync<string>("Hola mundo").ConfigureAwait(false); } Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion #region Parallel Mode Core.Log.Warning("Parallel Mode Test, using Unique Response Queue"); using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times")) { await Task.WhenAll( Enumerable.Range(0, totalQ).Select((i, mc) => (Task)mc.SendAndReceiveAsync<string>("Hola mundo"), mqClient).ToArray() ).ConfigureAwait(false); //Parallel.For(0, totalQ, i => //{ // var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults(); //}); Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion } mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "false"; using (var mqClient = mqConfig.GetClient()) { var totalQ = 1000; #region Sync Mode Core.Log.Warning("Sync Mode Test, using Multiple Response Queue"); using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times")) { for (var i = 0; i < totalQ; i++) { var response = await mqClient.SendAndReceiveAsync<string>("Hola mundo").ConfigureAwait(false); } Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion #region Parallel Mode Core.Log.Warning("Parallel Mode Test, using Multiple Response Queue"); using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times")) { await Task.WhenAll( Enumerable.Range(0, totalQ).Select((i, mc) => (Task)mc.SendAndReceiveAsync<string>("Hola mundo"), mqClient).ToArray() ).ConfigureAwait(false); //Parallel.For(0, totalQ, i => //{ // var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults(); //}); Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion } } } private static async Task RawTestAsync(MQPairConfig mqConfig) { using (var mqServer = mqConfig.GetRawServer()) { var byteRequest = new byte[] { 0x21, 0x22, 0x23, 0x24, 0x25, 0x30, 0x31, 0x32, 0x33, 0x34 }; var byteResponse = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x10, 0x11, 0x12, 0x13, 0x14 }; mqServer.RequestReceived += (s, e) => { e.Response = byteResponse; return Task.CompletedTask; }; mqServer.StartListeners(); using (var mqClient = mqConfig.GetRawClient()) { var totalQ = 50000; #region Sync Mode Core.Log.Warning("RAW Sync Mode Test, using Unique Response Queue"); using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times")) { for (var i = 0; i < totalQ; i++) { var response = await mqClient.SendAndReceiveAsync(byteRequest).ConfigureAwait(false); } Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion #region Parallel Mode Core.Log.Warning("RAW Parallel Mode Test, using Unique Response Queue"); using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times")) { await Task.WhenAll( Enumerable.Range(0, totalQ).Select((i, vTuple) => (Task)vTuple.mqClient.SendAndReceiveAsync(vTuple.byteRequest), (mqClient, byteRequest)).ToArray() ).ConfigureAwait(false); //Parallel.For(0, totalQ, i => //{ // var response = mqClient.SendAndReceive(byteRequest); //}); Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion } mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "false"; using (var mqClient = mqConfig.GetRawClient()) { var totalQ = 1000; #region Sync Mode Core.Log.Warning("RAW Sync Mode Test, using Multiple Response Queue"); using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times")) { for (var i = 0; i < totalQ; i++) { var response = await mqClient.SendAndReceiveAsync(byteRequest).ConfigureAwait(false); } Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion #region Parallel Mode Core.Log.Warning("RAW Parallel Mode Test, using Multiple Response Queue"); using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times")) { await Task.WhenAll( Enumerable.Range(0, totalQ).Select((i, vTuple) => (Task)vTuple.mqClient.SendAndReceiveAsync(vTuple.byteRequest), (mqClient, byteRequest)).ToArray() ).ConfigureAwait(false); //Parallel.For(0, totalQ, i => //{ // var response = mqClient.SendAndReceive(byteRequest); //}); Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using DiffMatchPatch; using EQSpellParser; namespace winparser { //[ComVisible(true)] // for SearchBrowser.ObjectForScripting public partial class MainForm : Form { private const int MAX_RESULTS = 2500; private SpellCache Cache; public string SpellPath; public List<Spell> Results; public HashSet<int> VisibleResults; public SpellSearchFilter DefaultFilter; public List<SpellSearchFilter> SearchHistory = new List<SpellSearchFilter>(); public MainForm() { InitializeComponent(); Width = Math.Min(Screen.PrimaryScreen.WorkingArea.Width - 100, 1800); Height = Screen.PrimaryScreen.WorkingArea.Height - 100; SearchClass.Items.AddRange(Enum.GetNames(typeof(SpellClassesLong))); SearchClass.Sorted = true; SearchClass.Sorted = false; SearchClass.Items.Add("Non PC"); SearchClass.Items.Add("Any PC"); SearchClass.Items.Add(""); SearchEffect1.Items.AddRange(SpellSearchFilter.CommonEffects.Keys.ToArray()); SearchEffect1.Items.Add(""); SearchEffect1.Text = ""; SearchEffect2.Items.AddRange(SpellSearchFilter.CommonEffects.Keys.ToArray()); SearchEffect2.Items.Add(""); SearchEffect3.Items.AddRange(SpellSearchFilter.CommonEffects.Keys.ToArray()); SearchEffect3.Items.Add(""); SearchEffectSlot1.Items.Add(""); SearchEffectSlot1.Items.AddRange(Enumerable.Range(1, 20).Select(x => x.ToString()).ToArray()); SearchEffectSlot2.Items.Add(""); SearchEffectSlot2.Items.AddRange(Enumerable.Range(1, 20).Select(x => x.ToString()).ToArray()); SearchEffectSlot3.Items.Add(""); SearchEffectSlot3.Items.AddRange(Enumerable.Range(1, 20).Select(x => x.ToString()).ToArray()); //SearchBrowser.ObjectForScripting = this; DefaultFilter = GetFilter(); } private void MainForm_Shown(object sender, EventArgs e) { // a winforms bug will trigger TextChanged() the first time a combobox with a "" value loses focus (even if no text has changed) // this hack will quickly cycle all controls and disable the auto search that would be triggered for (int i = 0; i < SearchFilters.Controls.Count; i++) { var combo = SearchFilters.Controls[i] as ComboBox; if (combo != null) combo.Focus(); } SearchText.Focus(); AutoSearch.Enabled = false; } private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { // save current filter //var config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); //var filter = GetFilter(); //var props = filter.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); //foreach (var p in props) // config.AppSettings.Settings.Add(p.Name, p.GetValue(filter, null).ToString()); //config.Save(ConfigurationSaveMode.Modified); // quit if no other windows are open (+1 for FileOpenForm which is hidden) if (Application.OpenForms.Count <= 2) Application.Exit(); } public new void Load(string spellPath) { SpellPath = spellPath; Text = spellPath; Cursor.Current = Cursors.WaitCursor; Cache = new SpellCache(); Cache.LoadSpells(spellPath); SearchCategory.Items.AddRange(Cache.SpellList.SelectMany(x => x.Categories).Distinct().ToArray()); SearchClass_TextChanged(this, null); AutoSearch.Enabled = false; Cursor.Current = Cursors.Default; var html = HtmlBuilder.InitTemplate(); html.AppendFormat("<p>Loaded <strong>{0}</strong> spells from {1}.</p></html>", Cache.SpellList.Count(), SpellPath); html.Append("<p>Use the search button to perform a search on this spell file based on the filters on the left."); html.Append("<p>Use the compare button to compare two different spell files and show the differences. e.g. test server vs live server spells."); html.AppendFormat("<p>This parser is an open source application. Visit <a href='{0}' class='ext' target='_top'>{0}</a> to download updates.", "https://github.com/rumstil/eqspellparser"); //html.Append("<p>Nov 8 2017 - Some spells will now show as 'Mostly Unresistable'. This means they are unresistable by standard resists and can only be resisted by Sanctification/Mystical Shielding AA or SPA 180 spells."); ShowHtml(html.ToString()); } /// <summary> /// Save current filter settings into filter object. This is useful when comparing spell lists on a second form. /// </summary> public SpellSearchFilter GetFilter() { var filter = new SpellSearchFilter(); filter.Text = SearchText.Text.Trim(); filter.Effect[0] = SearchEffect1.Text.Trim(); filter.Effect[1] = SearchEffect2.Text.Trim(); filter.Effect[2] = SearchEffect3.Text.Trim(); int slot; if (Int32.TryParse(SearchEffectSlot1.Text.Trim(), out slot)) filter.EffectSlot[0] = slot; if (Int32.TryParse(SearchEffectSlot2.Text.Trim(), out slot)) filter.EffectSlot[1] = slot; if (Int32.TryParse(SearchEffectSlot3.Text.Trim(), out slot)) filter.EffectSlot[2] = slot; filter.Category = SearchCategory.Text.Trim(); filter.Class = SearchClass.Text.Trim(); int min; int max; ParseRange(SearchLevel.Text, out min, out max); filter.ClassMinLevel = min; filter.ClassMaxLevel = max; //filter.AppendForwardRefs = true; filter.Ranks = SearchRanks.Text.Trim(); filter.AddBackRefs = IncludeRelated.Checked; return filter; } /// <summary> /// Load filter from another form when doing a comparison. /// </summary> public void SetFilter(SpellSearchFilter filter) { SearchText.Text = filter.Text; SearchEffect1.Text = filter.Effect[0]; SearchEffect2.Text = filter.Effect[1]; SearchEffect3.Text = filter.Effect[2]; SearchEffectSlot1.Text = filter.EffectSlot[0].HasValue ? filter.EffectSlot[0].ToString() : ""; SearchEffectSlot2.Text = filter.EffectSlot[1].HasValue ? filter.EffectSlot[1].ToString() : ""; SearchEffectSlot3.Text = filter.EffectSlot[2].HasValue ? filter.EffectSlot[2].ToString() : ""; SearchCategory.Text = filter.Category; SearchClass.Text = filter.Class; if (filter.ClassMinLevel > 0 && filter.ClassMaxLevel > 0) SearchLevel.Text = filter.ClassMinLevel + "-" + filter.ClassMaxLevel; else if (filter.ClassMinLevel > 0) SearchLevel.Text = filter.ClassMinLevel.ToString(); else if (filter.ClassMaxLevel > 0) SearchLevel.Text = filter.ClassMaxLevel.ToString(); IncludeRelated.Checked = filter.AddBackRefs; SearchRanks.Text = filter.Ranks; } private void SearchBtn_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; Search(); ShowResults(); Cursor.Current = Cursors.Default; } /// <summary> /// Search spells and save to [Results] /// </summary> public void Search() { AutoSearch.Enabled = false; var filter = GetFilter(); Results = Cache.Search(filter); // an empty search filter will return all spells and lag out the UI if (Results.Count > 50000) Results.Clear(); // optionally add back refs if (filter.AddBackRefs) Cache.AddBackRefs(Results); else { //removes references to spells with level 0 which are effects of other spells. int cls = SpellParser.ParseClass(SearchClass.Text) - 1; if (cls >= 0) Results.RemoveAll(x => x.Levels[cls] == 0); } // remove excluded ranks (this should be done after back refs are added) if (filter.Ranks == "Unranked") Results.RemoveAll(x => x.Rank != 0); if (filter.Ranks == "Rank 1") Results.RemoveAll(x => x.Rank != 1); if (filter.Ranks == "Rank 2") Results.RemoveAll(x => x.Rank != 2); if (filter.Ranks == "Rank 3") Results.RemoveAll(x => x.Rank != 3); if (filter.Ranks == "Unranked + Rank 1") Results.RemoveAll(x => x.Rank != 0 && x.Rank != 1); if (filter.Ranks == "Unranked + Rank 2") Results.RemoveAll(x => x.Rank != 0 && x.Rank != 2); if (filter.Ranks == "Unranked + Rank 3") Results.RemoveAll(x => x.Rank != 0 && x.Rank != 3); // hide anything that isn't in the results yet. additional spells will only be shown when a link is clicked VisibleResults = new HashSet<int>(Results.Select(x => x.ID)); // if we are filtering by class then auto hide all spells that aren't castable by that class //int i = SpellParser.ParseClass(filter.Class) - 1; //VisibleResults = new HashSet<int>(i >= 0 ? Results.Where(x => x.Levels[i] != 0).Select(x => x.ID) : Results.Select(x => x.ID)); // always add forward refs so that links can be clicked Cache.AddForwardRefs(Results); Cache.Sort(Results, filter); } /// <summary> /// Display the current search results /// </summary> private void ShowResults() { SearchNotes.Text = String.Format("{0} results", VisibleResults.Count); var html = new HtmlBuilder(Cache); if (Results.Count == 0) { html.Html.Append("<p><strong>Sorry, no matching spells were found.</strong></p><p>You may have made the filters too restrictive (including levels), accidentally defined conflicting filters, or left one of the filters filled in from a previous search. Try filtering by just one or two filters.</p>"); } else { if (Results.Count > MAX_RESULTS) { html.Html.Append(String.Format("<p>Too many results -- only the first {0} will be shown.</p>", MAX_RESULTS)); Results.RemoveRange(MAX_RESULTS, Results.Count - MAX_RESULTS); } Func<Spell, bool> visible = spell => VisibleResults.Contains(spell.ID); if (DisplayText.Checked) html.ShowAsText(Results, visible); else html.ShowAsTable(Results, visible); } ShowHtml(html.ToString()); } private void ShowHtml(string html) { SearchBrowser.DocumentText = html; //SearchBrowser.DocumentText = ""; //SearchBrowser.Document.Write(html.ToString()); //SearchBrowser.Refresh(); //var path = Directory.GetCurrentDirectory() + "\\results.htm"; //File.WriteAllText(path, html.ToString()); //SearchBrowser.Navigate("file:///" + path); } private void ParseRange(string text, out int min, out int max) { min = 1; max = 254; if (String.IsNullOrEmpty(text)) return; var parts = text.Replace(" ", "").Split('-'); if (parts.Length == 2) { if (!Int32.TryParse(parts[0], out min)) min = 1; if (min == 0) min = 1; // zero would include spells the class can't cast if (!Int32.TryParse(parts[1], out max)) max = 254; } else if (parts.Length == 1 && parts[0].Length > 0) { if (!Int32.TryParse(parts[0], out min)) min = 1; max = min; } } private void SearchBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e) { // start external links in an external window // internal links will all be "about:blank" // using a target other than target=_top seems to force IE rather than the default browser on one of my computers if (e.Url.Scheme.StartsWith("http") || !String.IsNullOrEmpty(e.TargetFrameName)) { e.Cancel = true; System.Diagnostics.Process.Start(e.Url.ToString()); } } private void CompareBtn_Click(object sender, EventArgs e) { FileOpenForm open = null; MainForm other = null; foreach (var f in Application.OpenForms) { if (f is MainForm && f != this) other = (MainForm)f; if (f is FileOpenForm) open = (FileOpenForm)f; } if (other == null) { open.Show(); open.WindowState = FormWindowState.Normal; open.SetStatus("Please open another spell file to compare with " + SpellPath); return; } Cursor.Current = Cursors.WaitCursor; Compare(other); Cursor.Current = Cursors.Default; } public void Compare(MainForm other) { // perform the same search on both spell files var filter = GetFilter(); Results = Cache.Search(filter); other.Results = other.Cache.Search(filter); MainForm oldVer = this; MainForm newVer = other; if (File.GetLastWriteTime(other.SpellPath) < File.GetLastWriteTime(SpellPath)) { oldVer = other; newVer = this; } // these functions generates the comparison text for each spell Func<Spell, string> getOldText = x => x.ToString() + "\n" + oldVer.Cache.InsertRefNames(String.Join("\n", x.Details())) + "\n\n"; Func<Spell, string> getNewText = x => x.ToString() + "\n" + newVer.Cache.InsertRefNames(String.Join("\n", x.Details())) + "\n\n"; var diffs = Compare(oldVer.Results, newVer.Results, getOldText, getNewText); var html = HtmlBuilder.InitTemplate(); if (diffs.Count == 0) html.AppendFormat("<p>No differences were found between {0} and {1} based on the search filters.</p>", oldVer.SpellPath, newVer.SpellPath); else { html.AppendFormat("<p>Found {0} differences between <del>{1}</del> and <ins>{2}</ins>.</p>", diffs.Count(x => x.operation != Operation.EQUAL), oldVer.SpellPath, newVer.SpellPath); html.Append(diff_match_patch.diff_prettyHtml(diffs)); } ShowHtml(html.ToString()); } private static List<Diff> Compare(IEnumerable<Spell> setA, IEnumerable<Spell> setB, Func<Spell, string> getTextA, Func<Spell, string> getTextB) { var dmp = new DiffMatchPatch.diff_match_patch(); var diffs = new List<Diff>(); // compare the same spell ID in each list one by one, then each line by line var A = setA.Where(x => x.ID > 0).OrderBy(x => x.ID).ToList(); var B = setB.Where(x => x.ID > 0).OrderBy(x => x.ID).ToList(); int a = 0; // current index in list A int b = 0; // current index in list B int count = 0; int id = 0; while (true) { id++; if (a >= A.Count && b >= B.Count) break; // reached end of list A, treat remainder of list B as inserts if (a >= A.Count) { while (b < B.Count) diffs.Add(new Diff(Operation.INSERT, getTextB(B[b++]))); break; } // reached end of list B, treat remainder of list A as deletes if (b >= B.Count) { while (a < A.Count) diffs.Add(new Diff(Operation.DELETE, getTextA(A[a++]))); break; } // id doesn't exist in either list if (A[a].ID > id && B[b].ID > id) continue; // id exists in both lists if (A[a].ID == id && B[b].ID == id) { var textA = getTextA(A[a++]); var textB = getTextB(B[b++]); // ignore equal spells if (textA == textB) continue; diffs.AddRange(dmp.diff_lineMode(textA, textB)); count++; continue; } // id exist only in list A if (A[a].ID == id) { diffs.Add(new Diff(Operation.DELETE, getTextA(A[a++]))); count++; continue; } // id exists only in list B if (B[b].ID == id) { diffs.Add(new Diff(Operation.INSERT, getTextB(B[b++]))); count++; continue; } throw new NotImplementedException(); // should never get here } return diffs; } private void SearchClass_TextChanged(object sender, EventArgs e) { // cancel if spells haven't been loaded yet if (Cache == null) return; // only show level filter when a class is selected int cls = SpellParser.ParseClass(SearchClass.Text) - 1; SearchLevel.Enabled = (cls >= 0); SearchText_TextChanged(sender, e); } private void SearchText_TextChanged(object sender, EventArgs e) { // reset timer every time the user presses a key //var combo = sender as ComboBox; AutoSearch.Interval = (sender is TextBox) ? 800 : 400; AutoSearch.Enabled = false; AutoSearch.Enabled = true; } private void ResetBtn_Click(object sender, EventArgs e) { SetFilter(DefaultFilter); AutoSearch.Enabled = false; } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Provides access to all native methods provided by <c>NativeExtension</c>. /// An extra level of indirection is added to P/Invoke calls to allow intelligent loading /// of the right configuration of the native extension based on current platform, architecture etc. /// </summary> internal class NativeMethods { #region Native methods public readonly Delegates.grpcsharp_init_delegate grpcsharp_init; public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown; public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string; public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create; public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata; public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length; public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata; public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled; public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy; public readonly Delegates.grpcsharp_request_call_context_create_delegate grpcsharp_request_call_context_create; public readonly Delegates.grpcsharp_request_call_context_call_delegate grpcsharp_request_call_context_call; public readonly Delegates.grpcsharp_request_call_context_method_delegate grpcsharp_request_call_context_method; public readonly Delegates.grpcsharp_request_call_context_host_delegate grpcsharp_request_call_context_host; public readonly Delegates.grpcsharp_request_call_context_deadline_delegate grpcsharp_request_call_context_deadline; public readonly Delegates.grpcsharp_request_call_context_request_metadata_delegate grpcsharp_request_call_context_request_metadata; public readonly Delegates.grpcsharp_request_call_context_destroy_delegate grpcsharp_request_call_context_destroy; public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create; public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release; public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel; public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status; public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary; public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming; public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming; public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming; public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message; public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client; public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server; public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message; public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata; public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside; public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata; public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials; public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer; public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy; public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create; public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string; public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer; public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy; public readonly Delegates.grpcsharp_override_default_ssl_roots grpcsharp_override_default_ssl_roots; public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create; public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create; public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release; public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create; public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create; public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call; public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state; public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state; public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target; public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy; public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event; public readonly Delegates.grpcsharp_completion_queue_create_async_delegate grpcsharp_completion_queue_create_async; public readonly Delegates.grpcsharp_completion_queue_create_sync_delegate grpcsharp_completion_queue_create_sync; public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown; public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next; public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck; public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy; public readonly Delegates.gprsharp_free_delegate gprsharp_free; public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create; public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add; public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count; public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key; public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value; public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full; public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log; public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin; public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin; public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create; public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release; public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create; public readonly Delegates.grpcsharp_server_register_completion_queue_delegate grpcsharp_server_register_completion_queue; public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port; public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port; public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start; public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call; public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls; public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback; public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy; public readonly Delegates.grpcsharp_call_auth_context_delegate grpcsharp_call_auth_context; public readonly Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate grpcsharp_auth_context_peer_identity_property_name; public readonly Delegates.grpcsharp_auth_context_property_iterator_delegate grpcsharp_auth_context_property_iterator; public readonly Delegates.grpcsharp_auth_property_iterator_next_delegate grpcsharp_auth_property_iterator_next; public readonly Delegates.grpcsharp_auth_context_release_delegate grpcsharp_auth_context_release; public readonly Delegates.gprsharp_now_delegate gprsharp_now; public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future; public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past; public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type; public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec; public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback; public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop; public readonly Delegates.grpcsharp_test_override_method_delegate grpcsharp_test_override_method; #endregion public NativeMethods(UnmanagedLibrary library) { this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library); this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library); this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library); this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library); this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library); this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library); this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library); this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library); this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library); this.grpcsharp_request_call_context_create = GetMethodDelegate<Delegates.grpcsharp_request_call_context_create_delegate>(library); this.grpcsharp_request_call_context_call = GetMethodDelegate<Delegates.grpcsharp_request_call_context_call_delegate>(library); this.grpcsharp_request_call_context_method = GetMethodDelegate<Delegates.grpcsharp_request_call_context_method_delegate>(library); this.grpcsharp_request_call_context_host = GetMethodDelegate<Delegates.grpcsharp_request_call_context_host_delegate>(library); this.grpcsharp_request_call_context_deadline = GetMethodDelegate<Delegates.grpcsharp_request_call_context_deadline_delegate>(library); this.grpcsharp_request_call_context_request_metadata = GetMethodDelegate<Delegates.grpcsharp_request_call_context_request_metadata_delegate>(library); this.grpcsharp_request_call_context_destroy = GetMethodDelegate<Delegates.grpcsharp_request_call_context_destroy_delegate>(library); this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library); this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library); this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library); this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library); this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library); this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library); this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library); this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library); this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library); this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library); this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library); this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library); this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library); this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library); this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library); this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library); this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library); this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library); this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library); this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library); this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library); this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library); this.grpcsharp_override_default_ssl_roots = GetMethodDelegate<Delegates.grpcsharp_override_default_ssl_roots>(library); this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library); this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library); this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library); this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library); this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library); this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library); this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library); this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library); this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library); this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library); this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library); this.grpcsharp_completion_queue_create_async = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_async_delegate>(library); this.grpcsharp_completion_queue_create_sync = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_sync_delegate>(library); this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library); this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library); this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library); this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library); this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library); this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library); this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library); this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library); this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library); this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library); this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library); this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library); this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library); this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library); this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library); this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library); this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library); this.grpcsharp_server_register_completion_queue = GetMethodDelegate<Delegates.grpcsharp_server_register_completion_queue_delegate>(library); this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library); this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library); this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library); this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library); this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library); this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library); this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library); this.grpcsharp_call_auth_context = GetMethodDelegate<Delegates.grpcsharp_call_auth_context_delegate>(library); this.grpcsharp_auth_context_peer_identity_property_name = GetMethodDelegate<Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate>(library); this.grpcsharp_auth_context_property_iterator = GetMethodDelegate<Delegates.grpcsharp_auth_context_property_iterator_delegate>(library); this.grpcsharp_auth_property_iterator_next = GetMethodDelegate<Delegates.grpcsharp_auth_property_iterator_next_delegate>(library); this.grpcsharp_auth_context_release = GetMethodDelegate<Delegates.grpcsharp_auth_context_release_delegate>(library); this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library); this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library); this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library); this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library); this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library); this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library); this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library); this.grpcsharp_test_override_method = GetMethodDelegate<Delegates.grpcsharp_test_override_method_delegate>(library); } /// <summary> /// Gets singleton instance of this class. /// </summary> public static NativeMethods Get() { return NativeExtension.Get().NativeMethods; } static T GetMethodDelegate<T>(UnmanagedLibrary library) where T : class { var methodName = RemoveStringSuffix(typeof(T).Name, "_delegate"); return library.GetNativeMethodDelegate<T>(methodName); } static string RemoveStringSuffix(string str, string toRemove) { if (!str.EndsWith(toRemove)) { return str; } return str.Substring(0, str.Length - toRemove.Length); } /// <summary> /// Delegate types for all published native methods. Declared under inner class to prevent scope pollution. /// </summary> public class Delegates { public delegate void grpcsharp_init_delegate(); public delegate void grpcsharp_shutdown_delegate(); public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char* public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate(); public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx); public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx); public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen); public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx); public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx, out UIntPtr detailsLength); public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx); public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx); public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx); public delegate RequestCallContextSafeHandle grpcsharp_request_call_context_create_delegate(); public delegate CallSafeHandle grpcsharp_request_call_context_call_delegate(RequestCallContextSafeHandle ctx); public delegate IntPtr grpcsharp_request_call_context_method_delegate(RequestCallContextSafeHandle ctx, out UIntPtr methodLength); public delegate IntPtr grpcsharp_request_call_context_host_delegate(RequestCallContextSafeHandle ctx, out UIntPtr hostLength); public delegate Timespec grpcsharp_request_call_context_deadline_delegate(RequestCallContextSafeHandle ctx); public delegate IntPtr grpcsharp_request_call_context_request_metadata_delegate(RequestCallContextSafeHandle ctx); public delegate void grpcsharp_request_call_context_destroy_delegate(IntPtr ctx); public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2); public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials); public delegate CallError grpcsharp_call_cancel_delegate(CallSafeHandle call); public delegate CallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description); public delegate CallError grpcsharp_call_start_unary_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_send_message_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, int sendEmptyInitialMetadata); public delegate CallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, byte[] statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, int sendEmptyInitialMetadata, byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags); public delegate CallError grpcsharp_call_recv_message_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); public delegate CallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials); public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call); public delegate void grpcsharp_call_destroy_delegate(IntPtr call); public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs); public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value); public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value); public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args); public delegate void grpcsharp_override_default_ssl_roots(string pemRootCerts); public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey); public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds); public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials); public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs); public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs); public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline); public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect); public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState, Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx); public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call); public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel); public delegate int grpcsharp_sizeof_grpc_event_delegate(); public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_async_delegate(); public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_sync_delegate(); public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq); public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq); public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag); public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq); public delegate void gprsharp_free_delegate(IntPtr ptr); public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity); public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength); public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray); public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr keyLength); public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr valueLength); public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array); public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback); public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor); public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails); public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, int forceClientAuth); public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials); public delegate ServerSafeHandle grpcsharp_server_create_delegate(ChannelArgsSafeHandle args); public delegate void grpcsharp_server_register_completion_queue_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq); public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr); public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds); public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server); public delegate CallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, RequestCallContextSafeHandle ctx); public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server); public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx); public delegate void grpcsharp_server_destroy_delegate(IntPtr server); public delegate AuthContextSafeHandle grpcsharp_call_auth_context_delegate(CallSafeHandle call); public delegate IntPtr grpcsharp_auth_context_peer_identity_property_name_delegate(AuthContextSafeHandle authContext); // returns const char* public delegate AuthContextSafeHandle.NativeAuthPropertyIterator grpcsharp_auth_context_property_iterator_delegate(AuthContextSafeHandle authContext); public delegate IntPtr grpcsharp_auth_property_iterator_next_delegate(ref AuthContextSafeHandle.NativeAuthPropertyIterator iterator); // returns const auth_property* public delegate void grpcsharp_auth_context_release_delegate(IntPtr authContext); public delegate Timespec gprsharp_now_delegate(ClockType clockType); public delegate Timespec gprsharp_inf_future_delegate(ClockType clockType); public delegate Timespec gprsharp_inf_past_delegate(ClockType clockType); public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, ClockType targetClock); public delegate int gprsharp_sizeof_timespec_delegate(); public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback); public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr); public delegate void grpcsharp_test_override_method_delegate(string methodName, string variant); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace WebAPI2AuthenticationExample.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // This code was created by Jeff Molofee '99 // // If you've found this code useful, please let me know. // // Visit me at www.demonews.com/hosted/nehe // //===================================================================== // Converted to C# and MonoMac by Kenneth J. Pouncey // http://www.cocoa-mono.org // // Copyright (c) 2011 Kenneth J. Pouncey // // // 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.Linq; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.CoreVideo; using MonoMac.CoreGraphics; using MonoMac.OpenGL; namespace NeHeLesson17 { public partial class MyOpenGLView : MonoMac.AppKit.NSView { NSOpenGLContext openGLContext; NSOpenGLPixelFormat pixelFormat; MainWindowController controller; CVDisplayLink displayLink; NSObject notificationProxy; [Export("initWithFrame:")] public MyOpenGLView (RectangleF frame) : this(frame, null) { } public MyOpenGLView (RectangleF frame,NSOpenGLContext context) : base(frame) { var attribs = new object [] { NSOpenGLPixelFormatAttribute.Accelerated, NSOpenGLPixelFormatAttribute.NoRecovery, NSOpenGLPixelFormatAttribute.DoubleBuffer, NSOpenGLPixelFormatAttribute.ColorSize, 24, NSOpenGLPixelFormatAttribute.DepthSize, 16 }; pixelFormat = new NSOpenGLPixelFormat (attribs); if (pixelFormat == null) Console.WriteLine ("No OpenGL pixel format"); // NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead openGLContext = new NSOpenGLContext (pixelFormat, context); openGLContext.MakeCurrentContext (); // Synchronize buffer swaps with vertical refresh rate openGLContext.SwapInterval = true; // Initialize our newly created view. InitGL (); SetupDisplayLink (); // Look for changes in view size // Note, -reshape will not be called automatically on size changes because NSView does not export it to override notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.GlobalFrameChangedNotification, HandleReshape); } public override void DrawRect (RectangleF dirtyRect) { // Ignore if the display link is still running if (!displayLink.IsRunning && controller != null) DrawView (); } public override bool AcceptsFirstResponder () { // We want this view to be able to receive key events return true; } public override void LockFocus () { base.LockFocus (); if (openGLContext.View != this) openGLContext.View = this; } public override void KeyDown (NSEvent theEvent) { controller.KeyDown (theEvent); } public override void MouseDown (NSEvent theEvent) { controller.MouseDown (theEvent); } // All Setup For OpenGL Goes Here public bool InitGL () { // Enables Smooth Shading GL.ShadeModel (ShadingModel.Smooth); // Set background color to black GL.ClearColor(Color.Black); // Setup Depth Testing // Depth Buffer setup GL.ClearDepth (1.0); // Enables Depth testing GL.Enable (EnableCap.DepthTest); // The type of depth testing to do GL.DepthFunc (DepthFunction.Lequal); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One); // Really Nice Perspective Calculations GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); GL.Enable (EnableCap.Texture2D); return true; } private void DrawView () { var previous = NSApplication.CheckForIllegalCrossThreadCalls; NSApplication.CheckForIllegalCrossThreadCalls = false; // This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop) // Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Make sure we draw to the right context openGLContext.MakeCurrentContext (); // Delegate to the scene object for rendering controller.Scene.DrawGLScene (); openGLContext.FlushBuffer (); openGLContext.CGLContext.Unlock (); NSApplication.CheckForIllegalCrossThreadCalls = previous; } private void SetupDisplayLink () { // Create a display link capable of being used with all active displays displayLink = new CVDisplayLink (); // Set the renderer output callback function displayLink.SetOutputCallback (MyDisplayLinkOutputCallback); // Set the display link for the current renderer CGLContext cglContext = openGLContext.CGLContext; CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat; displayLink.SetCurrentDisplay (cglContext, cglPixelFormat); } public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut) { CVReturn result = GetFrameForTime (inOutputTime); return result; } private CVReturn GetFrameForTime (CVTimeStamp outputTime) { // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool ()) { // Update the animation DrawView (); } return CVReturn.Success; } public NSOpenGLContext OpenGLContext { get { return openGLContext; } } public NSOpenGLPixelFormat PixelFormat { get { return pixelFormat; } } public MainWindowController MainController { set { controller = value; } } public void UpdateView () { // This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Delegate to the scene object to update for a change in the view size controller.Scene.ResizeGLScene (Bounds); openGLContext.Update (); openGLContext.CGLContext.Unlock (); } private void HandleReshape (NSNotification note) { UpdateView (); } public void StartAnimation () { if (displayLink != null && !displayLink.IsRunning) displayLink.Start (); } public void StopAnimation () { if (displayLink != null && displayLink.IsRunning) displayLink.Stop (); } // Clean up the notifications public void DeAllocate () { displayLink.Stop (); displayLink.SetOutputCallback (null); NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy); } [Export("toggleFullScreen:")] public void toggleFullScreen (NSObject sender) { controller.toggleFullScreen (sender); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Web; using System.Web.Mvc; namespace Orchard.UI.Resources { public class ResourceDefinition { private static readonly Dictionary<string, string> _resourceTypeTagNames = new Dictionary<string, string> { { "script", "script" }, { "stylesheet", "link" } }; private static readonly Dictionary<string, string> _filePathAttributes = new Dictionary<string, string> { { "script", "src" }, { "link", "href" } }; private static readonly Dictionary<string, Dictionary<string,string>> _resourceAttributes = new Dictionary<string, Dictionary<string,string>> { { "script", new Dictionary<string, string> { {"type", "text/javascript"} } }, { "stylesheet", new Dictionary<string, string> { {"type", "text/css"}, {"rel", "stylesheet"} } } }; private static readonly Dictionary<string, TagRenderMode> _fileTagRenderModes = new Dictionary<string, TagRenderMode> { { "script", TagRenderMode.Normal }, { "link", TagRenderMode.SelfClosing } }; private static readonly Dictionary<string, string> _resourceTypeDirectories = new Dictionary<string, string> { {"script", "scripts/"}, {"stylesheet", "styles/"} }; private string _basePath; private readonly Dictionary<RequireSettings, string> _urlResolveCache = new Dictionary<RequireSettings, string>(); public ResourceDefinition(ResourceManifest manifest, string type, string name) { Manifest = manifest; Type = type; Name = name; TagBuilder = new TagBuilder(_resourceTypeTagNames.ContainsKey(type) ? _resourceTypeTagNames[type] : "meta"); TagRenderMode = _fileTagRenderModes.ContainsKey(TagBuilder.TagName) ? _fileTagRenderModes[TagBuilder.TagName] : TagRenderMode.Normal; Dictionary<string, string> attributes; if (_resourceAttributes.TryGetValue(type, out attributes)) { foreach(var pair in attributes) { TagBuilder.Attributes[pair.Key] = pair.Value; } } FilePathAttributeName = _filePathAttributes.ContainsKey(TagBuilder.TagName) ? _filePathAttributes[TagBuilder.TagName] : null; } internal static string GetBasePathFromViewPath(string resourceType, string viewPath) { if (String.IsNullOrEmpty(viewPath)) { return null; } string basePath = null; var viewsPartIndex = viewPath.IndexOf("/Views", StringComparison.OrdinalIgnoreCase); if (viewsPartIndex >= 0) { basePath = viewPath.Substring(0, viewsPartIndex + 1) + GetResourcePath(resourceType); } return basePath; } internal static string GetResourcePath(string resourceType) { string path; _resourceTypeDirectories.TryGetValue(resourceType, out path); return path ?? ""; } private static string Coalesce(params string[] strings) { foreach (var str in strings) { if (!String.IsNullOrEmpty(str)) { return str; } } return null; } public IResourceManifest Manifest { get; private set; } public string TagName { get { return TagBuilder.TagName; } } public TagRenderMode TagRenderMode { get; private set; } public string Name { get; private set; } public string Type { get; private set; } public string Version { get; private set; } public string BasePath { get { if (!String.IsNullOrEmpty(_basePath)) { return _basePath; } var basePath = Manifest.BasePath; if (!String.IsNullOrEmpty(basePath)) { basePath += GetResourcePath(Type); } return basePath ?? ""; } } public string Url { get; private set; } public string UrlDebug { get; private set; } public string UrlCdn { get; private set; } public string UrlCdnDebug { get; private set; } public string[] Cultures { get; private set; } public bool CdnSupportsSsl { get; private set; } public IEnumerable<string> Dependencies { get; private set; } public string FilePathAttributeName { get; private set; } public TagBuilder TagBuilder { get; private set; } public ResourceDefinition AddAttribute(string name, string value) { TagBuilder.MergeAttribute(name, value); return this; } public ResourceDefinition SetAttribute(string name, string value) { TagBuilder.MergeAttribute(name, value, true); return this; } public ResourceDefinition SetBasePath(string virtualPath) { _basePath = virtualPath; return this; } public ResourceDefinition SetUrl(string url) { return SetUrl(url, null); } public ResourceDefinition SetUrl(string url, string urlDebug) { if (String.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } Url = url; if (urlDebug != null) { UrlDebug = urlDebug; } return this; } public ResourceDefinition SetCdn(string cdnUrl) { return SetCdn(cdnUrl, null, null); } public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug) { return SetCdn(cdnUrl, cdnUrlDebug, null); } public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug, bool? cdnSupportsSsl) { if (String.IsNullOrEmpty(cdnUrl)) { throw new ArgumentNullException("cdnUrl"); } UrlCdn = cdnUrl; if (cdnUrlDebug != null) { UrlCdnDebug = cdnUrlDebug; } if (cdnSupportsSsl.HasValue) { CdnSupportsSsl = cdnSupportsSsl.Value; } return this; } /// <summary> /// Sets the version of the resource. /// </summary> /// <param name="version">The version to set, in the form of <code>major.minor[.build[.revision]]</code></param> public ResourceDefinition SetVersion(string version) { Version = version; return this; } public ResourceDefinition SetCultures(params string[] cultures) { Cultures = cultures; return this; } public ResourceDefinition SetDependencies(params string[] dependencies) { Dependencies = dependencies; return this; } public string ResolveUrl(RequireSettings settings, string applicationPath) { string url; if (_urlResolveCache.TryGetValue(settings, out url)) { return url; } // Url priority: if (settings.DebugMode) { url = settings.CdnMode ? Coalesce(UrlCdnDebug, UrlDebug, UrlCdn, Url) : Coalesce(UrlDebug, Url, UrlCdnDebug, UrlCdn); } else { url = settings.CdnMode ? Coalesce(UrlCdn, Url, UrlCdnDebug, UrlDebug) : Coalesce(Url, UrlDebug, UrlCdn, UrlCdnDebug); } if (String.IsNullOrEmpty(url)) { return null; } if (!String.IsNullOrEmpty(settings.Culture)) { string nearestCulture = FindNearestCulture(settings.Culture); if (!String.IsNullOrEmpty(nearestCulture)) { url = Path.ChangeExtension(url, nearestCulture + Path.GetExtension(url)); } } if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) && !VirtualPathUtility.IsAbsolute(url) && !VirtualPathUtility.IsAppRelative(url) && !String.IsNullOrEmpty(BasePath)) { // relative urls are relative to the base path of the module that defined the manifest url = VirtualPathUtility.Combine(BasePath, url); } if (VirtualPathUtility.IsAppRelative(url)) { url = VirtualPathUtility.ToAbsolute(url, applicationPath); } _urlResolveCache[settings] = url; return url; } public string FindNearestCulture(string culture) { // go for an exact match if (Cultures == null) { return null; } int selectedIndex = Array.IndexOf(Cultures, culture); if (selectedIndex != -1) { return Cultures[selectedIndex]; } // try parent culture if any var cultureInfo = CultureInfo.GetCultureInfo(culture); if (cultureInfo.Parent.Name != culture) { var selectedCulture = FindNearestCulture(cultureInfo.Parent.Name); if (selectedCulture != null) { return selectedCulture; } } return null; } public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) { return false; } var that = (ResourceDefinition)obj; return string.Equals(that.Name, Name, StringComparison.Ordinal) && string.Equals(that.Type, Type, StringComparison.Ordinal) && string.Equals(that.Version, Version, StringComparison.Ordinal); } public override int GetHashCode() { return (Name ?? "").GetHashCode() ^ (Type ?? "").GetHashCode(); } } }
using ExitGames.Client.Photon; using ExitGames.Client.Photon.Lite; using System.Collections.Generic; using Photon; using Photon.Enums; // ReSharper disable once CheckNamespace internal class LoadbalancingPeer : PhotonPeer { public LoadbalancingPeer(IPhotonPeerListener listener, ConnectionProtocol protocolType) : base(listener, protocolType) { } public virtual bool OpAuthenticate(string appId, string appVersion, string userId, AuthenticationValues authValues, string regionCode) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object>(); if (authValues?.Secret != null) { customOpParameters[ParameterCode.Secret] = authValues.Secret; return this.OpCustom(OperationCode.Authenticate, customOpParameters, true, 0, false); } customOpParameters[ParameterCode.AppVersion] = appVersion; customOpParameters[ParameterCode.ApplicationId] = appId; if (!string.IsNullOrEmpty(regionCode)) customOpParameters[ParameterCode.Region] = regionCode; if (!string.IsNullOrEmpty(userId)) customOpParameters[ParameterCode.UserId] = userId; if (authValues != null && authValues.AuthType != CustomAuthenticationType.None) { if (!IsEncryptionAvailable) { Listener.DebugReturn(DebugLevel.ERROR, "OpAuthenticate() failed. When you want Custom Authentication encryption is mandatory."); return false; } customOpParameters[ParameterCode.ClientAuthenticationType] = (byte) authValues.AuthType; if (!string.IsNullOrEmpty(authValues.Secret)) customOpParameters[ParameterCode.Secret] = authValues.Secret; if (!string.IsNullOrEmpty(authValues.AuthParameters)) customOpParameters[ParameterCode.ClientAuthenticationParams] = authValues.AuthParameters; if (authValues.AuthPostData != null) customOpParameters[ParameterCode.ClientAuthenticationData] = authValues.AuthPostData; } return this.OpCustom(OperationCode.Authenticate, customOpParameters, true, 0, IsEncryptionAvailable); } public virtual bool OpChangeGroups(byte[] groupsToRemove, byte[] groupsToAdd) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object>(2); if (groupsToRemove != null) customOpParameters[ParameterCode.Remove] = groupsToRemove; if (groupsToAdd != null) customOpParameters[ParameterCode.Add] = groupsToAdd; return this.OpCustom(OperationCode.ChangeGroups, customOpParameters, true, 0); } public virtual bool OpCreateRoom(string roomName, RoomOptions roomOptions, TypedLobby lobby, Hashtable playerProperties, bool onGameServer) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object>(); if (!string.IsNullOrEmpty(roomName)) { customOpParameters[ParameterCode.RoomName] = roomName; } if (lobby != null) { customOpParameters[ParameterCode.LobbyName] = lobby.Name; customOpParameters[ParameterCode.LobbyType] = (byte) lobby.Type; } if (onGameServer) { if (playerProperties != null && playerProperties.Count > 0) { customOpParameters[ParameterCode.PlayerProperties] = playerProperties; customOpParameters[ParameterCode.Broadcast] = true; } if (roomOptions == null) roomOptions = new RoomOptions(); Hashtable target = new Hashtable(); customOpParameters[ParameterCode.GameProperties] = target; target.MergeStringKeys(roomOptions); target[GamePropertyKey.IsOpen] = roomOptions.IsOpen; target[GamePropertyKey.IsVisible] = roomOptions.IsVisible; target[GamePropertyKey.PropsListedInLobby] = new string[0]; if (roomOptions.MaxPlayers > 0) target[GamePropertyKey.MaxPlayers] = roomOptions.MaxPlayers; if (roomOptions.DoAutoCleanup == true) { customOpParameters[ParameterCode.CleanupCacheOnLeave] = true; target[GamePropertyKey.CleanupCacheOnLeave] = true; } } return this.OpCustom(OperationCode.CreateGame, customOpParameters, true); } public virtual bool OpFindFriends(string[] friendsToFind) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object>(); if (friendsToFind != null && friendsToFind.Length > 0) customOpParameters[1] = friendsToFind; return this.OpCustom(OperationCode.FindFriends, customOpParameters, true); } public virtual bool OpGetRegions(string appId) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object> { [ParameterCode.ApplicationId] = appId }; return this.OpCustom(OperationCode.GetRegions, customOpParameters, true, 0, true); } public virtual bool OpJoinLobby(TypedLobby lobby) { if (DebugOut >= DebugLevel.INFO) { Listener.DebugReturn(DebugLevel.INFO, "OpJoinLobby()"); } Dictionary<byte, object> customOpParameters = null; if (lobby != null && !lobby.IsDefault) { customOpParameters = new Dictionary<byte, object> { [ParameterCode.LobbyName] = lobby.Name, [ParameterCode.LobbyType] = (byte)lobby.Type }; } return this.OpCustom(OperationCode.JoinLobby, customOpParameters, true); } public virtual bool OpJoinRandomRoom(Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers, Hashtable playerProperties, MatchmakingMode matchingType, TypedLobby typedLobby, string sqlLobbyFilter) { Hashtable target = new Hashtable(); target.MergeStringKeys(expectedCustomRoomProperties); if (expectedMaxPlayers > 0) target[GamePropertyKey.MaxPlayers] = expectedMaxPlayers; Dictionary<byte, object> customOpParameters = new Dictionary<byte, object>(); if (target.Count > 0) customOpParameters[ParameterCode.GameProperties] = target; if (playerProperties != null && playerProperties.Count > 0) customOpParameters[ParameterCode.PlayerProperties] = playerProperties; if (matchingType != MatchmakingMode.FillRoom) customOpParameters[ParameterCode.MatchMakingType] = (byte) matchingType; if (typedLobby != null) { customOpParameters[ParameterCode.LobbyName] = typedLobby.Name; customOpParameters[ParameterCode.LobbyType] = (byte) typedLobby.Type; } if (!string.IsNullOrEmpty(sqlLobbyFilter)) customOpParameters[245] = sqlLobbyFilter; return this.OpCustom(OperationCode.JoinRandomGame, customOpParameters, true); } public virtual bool OpJoinRoom(string roomName, RoomOptions roomOptions, TypedLobby lobby, bool createIfNotExists, Hashtable playerProperties, bool onGameServer) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object>(); if (!string.IsNullOrEmpty(roomName)) { customOpParameters[ParameterCode.RoomName] = roomName; } if (createIfNotExists) { customOpParameters[ParameterCode.CreateIfNotExists] = true; if (lobby != null) { customOpParameters[ParameterCode.LobbyName] = lobby.Name; customOpParameters[ParameterCode.LobbyType] = (byte) lobby.Type; } } if (onGameServer) { if (playerProperties != null && playerProperties.Count > 0) { customOpParameters[ParameterCode.PlayerProperties] = playerProperties; customOpParameters[ParameterCode.Broadcast] = true; } if (createIfNotExists) { if (roomOptions == null) { roomOptions = new RoomOptions(); } Hashtable target = new Hashtable(); customOpParameters[248] = target; target.MergeStringKeys(roomOptions); target[GamePropertyKey.IsOpen] = roomOptions.IsOpen; target[GamePropertyKey.IsVisible] = roomOptions.IsVisible; target[GamePropertyKey.PropsListedInLobby] = new string[0]; if (roomOptions.MaxPlayers > 0) { target[GamePropertyKey.MaxPlayers] = roomOptions.MaxPlayers; } if (roomOptions.DoAutoCleanup == true) { customOpParameters[ParameterCode.CleanupCacheOnLeave] = true; target[GamePropertyKey.CleanupCacheOnLeave] = true; } } } return this.OpCustom(OperationCode.JoinGame, customOpParameters, true); } public virtual bool OpLeaveLobby() { if (DebugOut >= DebugLevel.INFO) { Listener.DebugReturn(DebugLevel.INFO, "OpLeaveLobby()"); } return this.OpCustom(OperationCode.LeaveLobby, null, true); } public virtual bool OpRaiseEvent(byte eventCode, object customEventContent, bool sendReliable, RaiseEventOptions raiseEventOptions) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object> { [ParameterCode.Code] = eventCode }; if (customEventContent != null) customOpParameters[ParameterCode.Data] = customEventContent; if (raiseEventOptions == null) { raiseEventOptions = RaiseEventOptions.Default; } else { if (raiseEventOptions.CachingOption != EventCaching.DoNotCache) customOpParameters[ParameterCode.Cache] = (byte) raiseEventOptions.CachingOption; if (raiseEventOptions.Receivers != ReceiverGroup.Others) customOpParameters[ParameterCode.ReceiverGroup] = (byte) raiseEventOptions.Receivers; if (raiseEventOptions.InterestGroup != 0) customOpParameters[ParameterCode.Group] = raiseEventOptions.InterestGroup; if (raiseEventOptions.TargetActors != null) customOpParameters[ParameterCode.ActorList] = raiseEventOptions.TargetActors; if (raiseEventOptions.ForwardToWebhook) customOpParameters[ParameterCode.EventForward] = true; } return this.OpCustom(OperationCode.RaiseEvent, customOpParameters, sendReliable, raiseEventOptions.SequenceChannel, false); } public bool OpSetCustomPropertiesOfActor(int actorNr, Hashtable actorProperties, bool broadcast, byte channelId) { return this.OpSetPropertiesOfActor(actorNr, actorProperties.StripToStringKeys(), broadcast, channelId); } public bool OpSetCustomPropertiesOfRoom(Hashtable gameProperties, bool broadcast, byte channelId) { return this.OpSetPropertiesOfRoom(gameProperties.StripToStringKeys(), broadcast, channelId); } protected bool OpSetPropertiesOfActor(int actorNr, Hashtable actorProperties, bool broadcast, byte channelId) { if (DebugOut >= DebugLevel.INFO) { Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfActor()"); } if (actorNr > 0 && actorProperties != null) { Dictionary<byte, object> customOpParameters = new Dictionary<byte, object> { { ParameterCode.Properties, actorProperties }, { ParameterCode.ActorNr, actorNr } }; if (broadcast) customOpParameters.Add(250, true); return this.OpCustom(OperationCode.SetProperties, customOpParameters, broadcast, channelId); } if (DebugOut >= DebugLevel.INFO) Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfActor not sent. ActorNr must be > 0 and actorProperties != null."); return false; } public bool OpSetPropertiesOfRoom(Hashtable gameProperties, bool broadcast, byte channelId) { if (DebugOut >= DebugLevel.INFO) { Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfRoom()"); } Dictionary<byte, object> customOpParameters = new Dictionary<byte, object> { { ParameterCode.Properties, gameProperties } }; if (broadcast) customOpParameters.Add(ParameterCode.Broadcast, true); return this.OpCustom(OperationCode.SetProperties, customOpParameters, broadcast, channelId); } protected void OpSetPropertyOfRoom(byte propCode, object value) { Hashtable gameProperties = new Hashtable { [propCode] = value }; this.OpSetPropertiesOfRoom(gameProperties, true, 0); } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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.Globalization; using System.IO; using System.Security.AccessControl; using System.Text.RegularExpressions; using DiscUtils.Internal; using DiscUtils.Streams; namespace DiscUtils.Wim { /// <summary> /// Provides access to the file system within a WIM file image. /// </summary> public class WimFileSystem : ReadOnlyDiscFileSystem, IWindowsFileSystem { private readonly ObjectCache<long, List<DirectoryEntry>> _dirCache; private WimFile _file; private Stream _metaDataStream; private long _rootDirPos; private List<RawSecurityDescriptor> _securityDescriptors; internal WimFileSystem(WimFile file, int index) { _file = file; ShortResourceHeader metaDataFileInfo = _file.LocateImage(index); if (metaDataFileInfo == null) { throw new ArgumentException("No such image: " + index, nameof(index)); } _metaDataStream = _file.OpenResourceStream(metaDataFileInfo); ReadSecurityDescriptors(); _dirCache = new ObjectCache<long, List<DirectoryEntry>>(); } /// <summary> /// Provides a friendly description of the file system type. /// </summary> public override string FriendlyName { get { return "Microsoft WIM"; } } /// <summary> /// Gets the security descriptor associated with the file or directory. /// </summary> /// <param name="path">The file or directory to inspect.</param> /// <returns>The security descriptor.</returns> public RawSecurityDescriptor GetSecurity(string path) { uint id = GetEntry(path).SecurityId; if (id == uint.MaxValue) { return null; } if (id >= 0 && id < _securityDescriptors.Count) { return _securityDescriptors[(int)id]; } // What if there is no descriptor? throw new NotImplementedException(); } /// <summary> /// Sets the security descriptor associated with the file or directory. /// </summary> /// <param name="path">The file or directory to change.</param> /// <param name="securityDescriptor">The new security descriptor.</param> public void SetSecurity(string path, RawSecurityDescriptor securityDescriptor) { throw new NotSupportedException(); } /// <summary> /// Gets the reparse point data associated with a file or directory. /// </summary> /// <param name="path">The file to query.</param> /// <returns>The reparse point information.</returns> public ReparsePoint GetReparsePoint(string path) { DirectoryEntry dirEntry = GetEntry(path); ShortResourceHeader hdr = _file.LocateResource(dirEntry.Hash); if (hdr == null) { throw new IOException("No reparse point"); } using (Stream s = _file.OpenResourceStream(hdr)) { byte[] buffer = new byte[s.Length]; s.Read(buffer, 0, buffer.Length); return new ReparsePoint((int)dirEntry.ReparseTag, buffer); } } /// <summary> /// Sets the reparse point data on a file or directory. /// </summary> /// <param name="path">The file to set the reparse point on.</param> /// <param name="reparsePoint">The new reparse point.</param> public void SetReparsePoint(string path, ReparsePoint reparsePoint) { throw new NotSupportedException(); } /// <summary> /// Removes a reparse point from a file or directory, without deleting the file or directory. /// </summary> /// <param name="path">The path to the file or directory to remove the reparse point from.</param> public void RemoveReparsePoint(string path) { throw new NotSupportedException(); } /// <summary> /// Gets the short name for a given path. /// </summary> /// <param name="path">The path to convert.</param> /// <returns>The short name.</returns> /// <remarks> /// This method only gets the short name for the final part of the path, to /// convert a complete path, call this method repeatedly, once for each path /// segment. If there is no short name for the given path,<c>null</c> is /// returned. /// </remarks> public string GetShortName(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry.ShortName; } /// <summary> /// Sets the short name for a given file or directory. /// </summary> /// <param name="path">The full path to the file or directory to change.</param> /// <param name="shortName">The shortName, which should not include a path.</param> public void SetShortName(string path, string shortName) { throw new NotSupportedException(); } /// <summary> /// Gets the standard file information for a file. /// </summary> /// <param name="path">The full path to the file or directory to query.</param> /// <returns>The standard file information.</returns> public WindowsFileInformation GetFileStandardInformation(string path) { DirectoryEntry dirEntry = GetEntry(path); return new WindowsFileInformation { CreationTime = DateTime.FromFileTimeUtc(dirEntry.CreationTime), LastAccessTime = DateTime.FromFileTimeUtc(dirEntry.LastAccessTime), ChangeTime = DateTime.FromFileTimeUtc(Math.Max(dirEntry.LastWriteTime, Math.Max(dirEntry.CreationTime, dirEntry.LastAccessTime))), LastWriteTime = DateTime.FromFileTimeUtc(dirEntry.LastWriteTime), FileAttributes = dirEntry.Attributes }; } /// <summary> /// Sets the standard file information for a file. /// </summary> /// <param name="path">The full path to the file or directory to query.</param> /// <param name="info">The standard file information.</param> public void SetFileStandardInformation(string path, WindowsFileInformation info) { throw new NotSupportedException(); } /// <summary> /// Gets the names of the alternate data streams for a file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns> /// The list of alternate data streams (or empty, if none). To access the contents /// of the alternate streams, use OpenFile(path + ":" + name, ...). /// </returns> public string[] GetAlternateDataStreams(string path) { DirectoryEntry dirEntry = GetEntry(path); List<string> names = new List<string>(); if (dirEntry.AlternateStreams != null) { foreach (KeyValuePair<string, AlternateStreamEntry> altStream in dirEntry.AlternateStreams) { if (!string.IsNullOrEmpty(altStream.Key)) { names.Add(altStream.Key); } } } return names.ToArray(); } /// <summary> /// Gets the file id for a given path. /// </summary> /// <param name="path">The path to get the id of.</param> /// <returns>The file id, or -1.</returns> /// <remarks> /// The returned file id uniquely identifies the file, and is shared by all hard /// links to the same file. The value -1 indicates no unique identifier is /// available, and so it can be assumed the file has no hard links. /// </remarks> public long GetFileId(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry.HardLink == 0 ? -1 : (long)dirEntry.HardLink; } /// <summary> /// Indicates whether the file is known by other names. /// </summary> /// <param name="path">The file to inspect.</param> /// <returns><c>true</c> if the file has other names, else <c>false</c>.</returns> public bool HasHardLinks(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry.HardLink != 0; } /// <summary> /// Indicates if a directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the directory exists.</returns> public override bool DirectoryExists(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry != null && (dirEntry.Attributes & FileAttributes.Directory) != 0; } /// <summary> /// Indicates if a file exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file exists.</returns> public override bool FileExists(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry != null && (dirEntry.Attributes & FileAttributes.Directory) == 0; } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of directories matching the search pattern.</returns> public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern); List<string> dirs = new List<string>(); DoSearch(dirs, path, re, searchOption == SearchOption.AllDirectories, true, false); return dirs.ToArray(); } /// <summary> /// Gets the names of files in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of files matching the search pattern.</returns> public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern); List<string> results = new List<string>(); DoSearch(results, path, re, searchOption == SearchOption.AllDirectories, false, true); return results.ToArray(); } /// <summary> /// Gets the names of all files and subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path) { DirectoryEntry parentDirEntry = GetEntry(path); if (parentDirEntry == null) { throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "The directory '{0}' does not exist", path)); } List<DirectoryEntry> parentDir = GetDirectory(parentDirEntry.SubdirOffset); return Utilities.Map(parentDir, m => Utilities.CombinePaths(path, m.FileName)); } /// <summary> /// Gets the names of files and subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path, string searchPattern) { Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern); DirectoryEntry parentDirEntry = GetEntry(path); if (parentDirEntry == null) { throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "The directory '{0}' does not exist", path)); } List<DirectoryEntry> parentDir = GetDirectory(parentDirEntry.SubdirOffset); List<string> result = new List<string>(); foreach (DirectoryEntry dirEntry in parentDir) { if (re.IsMatch(dirEntry.FileName)) { result.Add(Utilities.CombinePaths(path, dirEntry.FileName)); } } return result.ToArray(); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <param name="access">The access permissions for the created stream.</param> /// <returns>The new stream.</returns> public override SparseStream OpenFile(string path, FileMode mode, FileAccess access) { if (mode != FileMode.Open && mode != FileMode.OpenOrCreate) { throw new NotSupportedException("No write support for WIM files"); } if (access != FileAccess.Read) { throw new NotSupportedException("No write support for WIM files"); } byte[] streamHash = GetFileHash(path); ShortResourceHeader hdr = _file.LocateResource(streamHash); if (hdr == null) { if (Utilities.IsAllZeros(streamHash, 0, streamHash.Length)) { return new ZeroStream(0); } throw new IOException("Unable to locate file contents"); } return _file.OpenResourceStream(hdr); } /// <summary> /// Gets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to inspect.</param> /// <returns>The attributes of the file or directory.</returns> public override FileAttributes GetAttributes(string path) { DirectoryEntry dirEntry = GetEntry(path); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return dirEntry.Attributes; } /// <summary> /// Gets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public override DateTime GetCreationTimeUtc(string path) { DirectoryEntry dirEntry = GetEntry(path); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return DateTime.FromFileTimeUtc(dirEntry.CreationTime); } /// <summary> /// Gets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> public override DateTime GetLastAccessTimeUtc(string path) { DirectoryEntry dirEntry = GetEntry(path); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return DateTime.FromFileTimeUtc(dirEntry.LastAccessTime); } /// <summary> /// Gets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> public override DateTime GetLastWriteTimeUtc(string path) { DirectoryEntry dirEntry = GetEntry(path); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return DateTime.FromFileTimeUtc(dirEntry.LastWriteTime); } /// <summary> /// Gets the length of a file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>The length in bytes.</returns> public override long GetFileLength(string path) { string filePart; string altStreamPart; SplitFileName(path, out filePart, out altStreamPart); DirectoryEntry dirEntry = GetEntry(filePart); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return dirEntry.GetLength(altStreamPart); } /// <summary> /// Gets the SHA-1 hash of a file's contents. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>The 160-bit hash.</returns> /// <remarks>The WIM file format internally stores the SHA-1 hash of files. /// This method provides access to the stored hash. Callers can use this /// value to compare against the actual hash of the byte stream to validate /// the integrity of the file contents.</remarks> public byte[] GetFileHash(string path) { string filePart; string altStreamPart; SplitFileName(path, out filePart, out altStreamPart); DirectoryEntry dirEntry = GetEntry(filePart); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return dirEntry.GetStreamHash(altStreamPart); } /// <summary> /// Size of the Filesystem in bytes /// </summary> public override long Size { get { throw new NotSupportedException("Filesystem size is not (yet) supported"); } } /// <summary> /// Used space of the Filesystem in bytes /// </summary> public override long UsedSpace { get { throw new NotSupportedException("Filesystem size is not (yet) supported"); } } /// <summary> /// Available space of the Filesystem in bytes /// </summary> public override long AvailableSpace { get { throw new NotSupportedException("Filesystem size is not (yet) supported"); } } /// <summary> /// Disposes of this instance. /// </summary> /// <param name="disposing"><c>true</c> if disposing, else <c>false</c>.</param> protected override void Dispose(bool disposing) { try { _metaDataStream.Dispose(); _metaDataStream = null; _file = null; } finally { base.Dispose(disposing); } } private static void SplitFileName(string path, out string filePart, out string altStreamPart) { int streamSepPos = path.IndexOf(":", StringComparison.Ordinal); if (streamSepPos >= 0) { filePart = path.Substring(0, streamSepPos); altStreamPart = path.Substring(streamSepPos + 1); } else { filePart = path; altStreamPart = string.Empty; } } private List<DirectoryEntry> GetDirectory(long id) { List<DirectoryEntry> dir = _dirCache[id]; if (dir == null) { _metaDataStream.Position = id == 0 ? _rootDirPos : id; LittleEndianDataReader reader = new LittleEndianDataReader(_metaDataStream); dir = new List<DirectoryEntry>(); DirectoryEntry entry = DirectoryEntry.ReadFrom(reader); while (entry != null) { dir.Add(entry); entry = DirectoryEntry.ReadFrom(reader); } _dirCache[id] = dir; } return dir; } private void ReadSecurityDescriptors() { LittleEndianDataReader reader = new LittleEndianDataReader(_metaDataStream); long startPos = reader.Position; uint totalLength = reader.ReadUInt32(); uint numEntries = reader.ReadUInt32(); ulong[] sdLengths = new ulong[numEntries]; for (uint i = 0; i < numEntries; ++i) { sdLengths[i] = reader.ReadUInt64(); } _securityDescriptors = new List<RawSecurityDescriptor>((int)numEntries); for (uint i = 0; i < numEntries; ++i) { _securityDescriptors.Add(new RawSecurityDescriptor(reader.ReadBytes((int)sdLengths[i]), 0)); } if (reader.Position < startPos + totalLength) { reader.Skip((int)(startPos + totalLength - reader.Position)); } _rootDirPos = MathUtilities.RoundUp(startPos + totalLength, 8); } private DirectoryEntry GetEntry(string path) { if (path.EndsWith(@"\", StringComparison.Ordinal)) { path = path.Substring(0, path.Length - 1); } if (!string.IsNullOrEmpty(path) && !path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = @"\" + path; } return GetEntry(GetDirectory(0), path.Split('\\')); } private DirectoryEntry GetEntry(List<DirectoryEntry> dir, string[] path) { List<DirectoryEntry> currentDir = dir; DirectoryEntry nextEntry = null; for (int i = 0; i < path.Length; ++i) { nextEntry = null; foreach (DirectoryEntry entry in currentDir) { if (path[i].Equals(entry.FileName, StringComparison.OrdinalIgnoreCase) || (!string.IsNullOrEmpty(entry.ShortName) && path[i].Equals(entry.ShortName, StringComparison.OrdinalIgnoreCase))) { nextEntry = entry; break; } } if (nextEntry == null) { return null; } if (nextEntry.SubdirOffset != 0) { currentDir = GetDirectory(nextEntry.SubdirOffset); } } return nextEntry; } private void DoSearch(List<string> results, string path, Regex regex, bool subFolders, bool dirs, bool files) { DirectoryEntry parentDirEntry = GetEntry(path); if (parentDirEntry.SubdirOffset == 0) { return; } List<DirectoryEntry> parentDir = GetDirectory(parentDirEntry.SubdirOffset); foreach (DirectoryEntry de in parentDir) { bool isDir = (de.Attributes & FileAttributes.Directory) != 0; if ((isDir && dirs) || (!isDir && files)) { if (regex.IsMatch(de.SearchName)) { results.Add(Utilities.CombinePaths(path, de.FileName)); } } if (subFolders && isDir) { DoSearch(results, Utilities.CombinePaths(path, de.FileName), regex, subFolders, dirs, files); } } } } }
// 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.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Factories; using System.IO; using System.Linq; using System.Linq.Expressions; using System.UnitTesting; using System.ComponentModel.Composition.Primitives; using System.Reflection; using Xunit; namespace System.ComponentModel.Composition { // This is a glorious do nothing ReflectionContext public class DirectoryCatalogTestsReflectionContext : ReflectionContext { public override Assembly MapAssembly(Assembly assembly) { return assembly; } #if FEATURE_INTERNAL_REFLECTIONCONTEXT public override Type MapType(Type type) #else public override TypeInfo MapType(TypeInfo type) #endif { return type; } } public class DirectoryCatalogTests { internal const string NonExistentSearchPattern = "*.NonExistentSearchPattern"; public static void Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull(Func<ReflectionContext, DirectoryCatalog> catalogCreator) { Assert.Throws<ArgumentNullException>("reflectionContext", () => { var catalog = catalogCreator(null); }); } public static void Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull(Func<ICompositionElement, DirectoryCatalog> catalogCreator) { Assert.Throws<ArgumentNullException>("definitionOrigin", () => { var catalog = catalogCreator(null); }); } [Fact] public void Constructor2_NullReflectionContextArgument_ShouldThrowArgumentNull() { DirectoryCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) => { return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), rc); }); } [Fact] public void Constructor3_NullDefinitionOriginArgument_ShouldThrowArgumentNull() { DirectoryCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) => { return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), dO); }); } [Fact] public void Constructor4_NullReflectionContextArgument_ShouldThrowArgumentNull() { DirectoryCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) => { return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), rc, CreateDirectoryCatalog()); }); } [Fact] public void Constructor4_NullDefinitionOriginArgument_ShouldThrowArgumentNull() { DirectoryCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) => { return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), new DirectoryCatalogTestsReflectionContext(), dO); }); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'. public void ICompositionElementDisplayName_ShouldIncludeCatalogTypeNameAndDirectoryPath() { var paths = GetPathExpectations(); foreach (var path in paths) { var catalog = (ICompositionElement)CreateDirectoryCatalog(path, NonExistentSearchPattern); string expected = string.Format("DirectoryCatalog (Path=\"{0}\")", path); Assert.Equal(expected, catalog.DisplayName); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'. public void ICompositionElementDisplayName_ShouldIncludeDerivedCatalogTypeNameAndAssemblyFullName() { var paths = GetPathExpectations(); foreach (var path in paths) { var catalog = (ICompositionElement)new DerivedDirectoryCatalog(path, NonExistentSearchPattern); string expected = string.Format("DerivedDirectoryCatalog (Path=\"{0}\")", path); Assert.Equal(expected, catalog.DisplayName); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'. public void ToString_ShouldReturnICompositionElementDisplayName() { var paths = GetPathExpectations(); foreach (var path in paths) { var catalog = (ICompositionElement)CreateDirectoryCatalog(path, NonExistentSearchPattern); Assert.Equal(catalog.DisplayName, catalog.ToString()); } } [Fact] public void ICompositionElementDisplayName_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); var displayName = ((ICompositionElement)catalog).DisplayName; } [Fact] public void ICompositionElementOrigin_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); var origin = ((ICompositionElement)catalog).Origin; } [Fact] public void Parts_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); ExceptionAssert.ThrowsDisposed(catalog, () => { var parts = catalog.Parts; }); } [Fact] public void GetExports_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); var definition = ImportDefinitionFactory.Create(); ExceptionAssert.ThrowsDisposed(catalog, () => { catalog.GetExports(definition); }); } [Fact] public void Refresh_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); ExceptionAssert.ThrowsDisposed(catalog, () => { catalog.Refresh(); }); } [Fact] public void ToString_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); catalog.ToString(); } [Fact] public void GetExports_NullAsConstraintArgument_ShouldThrowArgumentNull() { var catalog = CreateDirectoryCatalog(); Assert.Throws<ArgumentNullException>("definition", () => { catalog.GetExports((ImportDefinition)null); }); } [Fact] public void Dispose_ShouldNotThrow() { using (var catalog = CreateDirectoryCatalog()) { } } [Fact] public void Dispose_CanBeCalledMultipleTimes() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); catalog.Dispose(); catalog.Dispose(); } [Fact] public void AddAssembly1_NullPathArgument_ShouldThrowArugmentNull() { Assert.Throws<ArgumentNullException>(() => new DirectoryCatalog((string)null)); } [Fact] public void AddAssembly1_EmptyPathArgument_ShouldThrowArugment() { Assert.Throws<ArgumentException>(() => new DirectoryCatalog("")); } [Fact] [ActiveIssue(25498)] public void AddAssembly1_TooLongPathNameArgument_ShouldThrowPathTooLongException() { Assert.Throws<PathTooLongException>(() => { var c1 = new DirectoryCatalog(@"c:\This is a very long path\And Just to make sure\We will continue to make it very long\This is a very long path\And Just to make sure\We will continue to make it very long\This is a very long path\And Just to make sure\We will continue to make it very long\myassembly.dll"); }); } [Fact] [ActiveIssue(25498)] public void Parts() { var catalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.NotNull(catalog.Parts); Assert.True(catalog.Parts.Count() > 0); } [Fact] [ActiveIssue(25498)] public void Parts_ShouldSetDefinitionOriginToCatalogItself() { var catalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.True(catalog.Parts.Count() > 0); foreach (ICompositionElement definition in catalog.Parts) { Assert.Same(catalog, definition.Origin); } } [Fact] [ActiveIssue(25498)] public void Path_ValidPath_ShouldBeFine() { var expectations = new ExpectationCollection<string, string>(); expectations.Add(".", "."); expectations.Add(TemporaryFileCopier.RootTemporaryDirectoryName, TemporaryFileCopier.RootTemporaryDirectoryName); expectations.Add(TemporaryFileCopier.GetRootTemporaryDirectory(), TemporaryFileCopier.GetRootTemporaryDirectory()); expectations.Add(TemporaryFileCopier.GetTemporaryDirectory(), TemporaryFileCopier.GetTemporaryDirectory()); foreach (var e in expectations) { var cat = CreateDirectoryCatalog(e.Input, NonExistentSearchPattern); Assert.Equal(e.Output, cat.Path); } } [Fact] [ActiveIssue(25498)] public void FullPath_ValidPath_ShouldBeFine() { var expectations = new ExpectationCollection<string, string>(); // Ensure the path is always normalized properly. string rootTempPath = Path.GetFullPath(TemporaryFileCopier.GetRootTemporaryDirectory()).ToUpperInvariant(); // Note: These relative paths work properly because the unit test temporary directories are always // created as a subfolder off the AppDomain.CurrentDomain.BaseDirectory. expectations.Add(".", Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".")).ToUpperInvariant()); expectations.Add(TemporaryFileCopier.RootTemporaryDirectoryName, rootTempPath); expectations.Add(TemporaryFileCopier.GetRootTemporaryDirectory(), rootTempPath); expectations.Add(TemporaryFileCopier.GetTemporaryDirectory(), Path.GetFullPath(TemporaryFileCopier.GetTemporaryDirectory()).ToUpperInvariant()); foreach (var e in expectations) { var cat = CreateDirectoryCatalog(e.Input, NonExistentSearchPattern); Assert.Equal(e.Output, cat.FullPath); } } [Fact] public void LoadedFiles_EmptyDirectory_ShouldBeFine() { var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.Equal(0, cat.LoadedFiles.Count); } [Fact] public void LoadedFiles_ContainsMultipleDllsAndSomeNonDll_ShouldOnlyContainDlls() { // Add one text file using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt"))) { } // Add two dll's string dll1 = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test1.dll"); string dll2 = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test2.dll"); File.Copy(Assembly.GetExecutingAssembly().Location, dll1); File.Copy(Assembly.GetExecutingAssembly().Location, dll2); var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); EqualityExtensions.CheckEquals(new string[] { dll1.ToUpperInvariant(), dll2.ToUpperInvariant() }, cat.LoadedFiles); } [Fact] public void Constructor_InvalidAssembly_ShouldBeFine() { using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll"))) { } var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); } [Fact] public void Constructor_NonExistentDirectory_ShouldThrow() { Assert.Throws<DirectoryNotFoundException>(() => new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory() + @"\NonexistentDirectoryWithoutEndingSlash")); Assert.Throws<DirectoryNotFoundException>(() => new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory() + @"\NonexistentDirectoryWithEndingSlash\")); } [Fact] [ActiveIssue(25498)] public void Constructor_PassExistingFileName_ShouldThrow() { using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt"))) { } Assert.Throws<IOException>(() => new DirectoryCatalog(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt"))); } [Fact] public void Constructor_PassNonExistingFileName_ShouldThrow() { Assert.Throws<DirectoryNotFoundException>(() => new DirectoryCatalog(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "NonExistingFile.txt"))); } [Fact] [ActiveIssue(25498)] public void Refresh_AssemblyAdded_ShouldFireOnChanged() { bool changedFired = false; bool changingFired = false; var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.Equal(0, cat.Parts.Count()); cat.Changing += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) => { Assert.Equal(0, cat.Parts.Count()); changingFired = true; }); cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) => { Assert.NotEqual(0, cat.Parts.Count()); changedFired = true; }); File.Copy(Assembly.GetExecutingAssembly().Location, Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll")); cat.Refresh(); Assert.True(changingFired); Assert.True(changedFired); } [Fact] [ActiveIssue(25498)] public void Refresh_AssemblyRemoved_ShouldFireOnChanged() { string file = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll"); File.Copy(Assembly.GetExecutingAssembly().Location, file); bool changedFired = false; var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) => changedFired = true); // This assembly can be deleted because it was already loaded by the CLR in another context // in another location so it isn't locked on disk. File.Delete(file); cat.Refresh(); Assert.True(changedFired); } [Fact] public void Refresh_NoChanges_ShouldNotFireOnChanged() { var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) => Assert.False(true)); cat.Refresh(); } [Fact] [ActiveIssue(25498)] public void Refresh_DirectoryRemoved_ShouldThrowDirectoryNotFound() { DirectoryCatalog cat; cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); ExceptionAssert.Throws<DirectoryNotFoundException>(RetryMode.DoNotRetry, () => cat.Refresh()); } [Fact] public void GetExports() { var catalog = new AggregateCatalog(); Expression<Func<ExportDefinition, bool>> constraint = (ExportDefinition exportDefinition) => exportDefinition.ContractName == AttributedModelServices.GetContractName(typeof(MyExport)); IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> matchingExports = null; matchingExports = catalog.GetExports(constraint); Assert.NotNull(matchingExports); Assert.True(matchingExports.Count() == 0); var testsDirectoryCatalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); catalog.Catalogs.Add(testsDirectoryCatalog); matchingExports = catalog.GetExports(constraint); Assert.NotNull(matchingExports); Assert.True(matchingExports.Count() >= 0); IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> expectedMatchingExports = catalog.Parts .SelectMany(part => part.ExportDefinitions, (part, export) => new Tuple<ComposablePartDefinition, ExportDefinition>(part, export)) .Where(partAndExport => partAndExport.Item2.ContractName == AttributedModelServices.GetContractName(typeof(MyExport))); Assert.True(matchingExports.SequenceEqual(expectedMatchingExports)); catalog.Catalogs.Remove(testsDirectoryCatalog); matchingExports = catalog.GetExports(constraint); Assert.NotNull(matchingExports); Assert.True(matchingExports.Count() == 0); } [Fact] [ActiveIssue(25498)] public void AddAndRemoveDirectory() { var cat = new AggregateCatalog(); var container = new CompositionContainer(cat); Assert.False(container.IsPresent<MyExport>()); var dir1 = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); cat.Catalogs.Add(dir1); Assert.True(container.IsPresent<MyExport>()); cat.Catalogs.Remove(dir1); Assert.False(container.IsPresent<MyExport>()); } [Fact] public void AddDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { var cat = new DirectoryCatalog("Directory That Should Never Exist tadfasdfasdfsdf"); }); } [Fact] public void ExecuteOnCreationThread() { // Add a proper test for event notification on caller thread } private DirectoryCatalog CreateDirectoryCatalog() { return CreateDirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory()); } private DirectoryCatalog CreateDirectoryCatalog(string path) { return new DirectoryCatalog(path); } private DirectoryCatalog CreateDirectoryCatalog(string path, string searchPattern) { return new DirectoryCatalog(path, searchPattern); } public IEnumerable<string> GetPathExpectations() { yield return AppDomain.CurrentDomain.BaseDirectory; yield return AppDomain.CurrentDomain.BaseDirectory + @"\"; yield return "."; } private class DerivedDirectoryCatalog : DirectoryCatalog { public DerivedDirectoryCatalog(string path, string searchPattern) : base(path, searchPattern) { } } } }
// Copyright (c) ZeroC, Inc. All rights reserved. using Microsoft.VisualStudio.Shell.Interop; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; using System.Windows.Threading; using MSProject = Microsoft.Build.Evaluation.Project; namespace IceBuilder { class ProjectConverter { public static void TryUpgrade(List<IVsProject> projects) { Dictionary<string, IVsProject> upgradeProjects = new Dictionary<string, IVsProject>(); foreach (IVsProject project in projects) { IceBuilderProjectType projectType = IsIceBuilderEnabled(project); if (projectType != IceBuilderProjectType.None) { upgradeProjects.Add(project.GetDTEProject().UniqueName, project); } } if (upgradeProjects.Count > 0) { UpgradeDialog dialog = new UpgradeDialog { StartPosition = FormStartPosition.CenterParent, Projects = upgradeProjects }; dialog.ShowDialog(); } } public static void Upgrade(Dictionary<string, IVsProject> projects, IUpgradeProgressCallback progressCallback) { Dispatcher dispatcher = Dispatcher.CurrentDispatcher; Thread t = new Thread(() => { try { var NuGet = Package.Instance.NuGet; if (!NuGet.IsUserConsentGranted()) { Package.WriteMessage("Ice Builder cannot download the required NuGet packages because " + "\"Allow NuGet to download missing packages\" is disabled"); dispatcher.Invoke(new Action(() => progressCallback.Finished())); return; } var DTE = Package.Instance.DTE; var builder = Package.Instance; int i = 0; int total = projects.Count; foreach (var entry in projects) { var project = entry.Value; var dteProject = project.GetDTEProject(); var uniqueName = dteProject.UniqueName; var name = entry.Key; i++; if (progressCallback.Canceled) { break; } dispatcher.Invoke( new Action(() => { progressCallback.ReportProgress(name, i); })); try { NuGet.Restore(dteProject); } catch (Exception ex) { Package.WriteMessage( string.Format("\nNuGet package restore failed:\n{0}\n", ex.Message)); dispatcher.Invoke(new Action(() => progressCallback.Finished())); break; } if (!NuGet.IsPackageInstalled(dteProject, Package.NuGetBuilderPackageId)) { try { DTE.StatusBar.Text = string.Format("Installing NuGet package {0} in project {1}", Package.NuGetBuilderPackageId, name); NuGet.InstallLatestPackage(dteProject, Package.NuGetBuilderPackageId); } catch (Exception ex) { Package.WriteMessage( string.Format("\nNuGet package zeroc.icebuilder.msbuild install failed:\n{0}\n", ex.Message)); dispatcher.Invoke(new Action(() => progressCallback.Finished())); break; } } IceBuilderProjectType projectType = IsIceBuilderEnabled(project); if (projectType != IceBuilderProjectType.None) { bool cpp = projectType == IceBuilderProjectType.CppProjectType; DTE.StatusBar.Text = string.Format("Upgrading project {0} Ice Builder settings", project.GetDTEProject().UniqueName); var fullPath = project.GetProjectFullPath(); var assemblyDir = project.GetEvaluatedProperty("IceAssembliesDir"); var outputDir = project.GetEvaluatedProperty("IceBuilderOutputDir"); var outputDirUnevaluated = project.GetPropertyWithDefault("IceBuilderOutputDir", "generated"); var sourceExt = project.GetPropertyWithDefault("IceBuilderSourceExt", "cpp"); var headerOutputDirUnevaluated = project.GetProperty("IceBuilderHeaderOutputDir"); var headerExt = project.GetPropertyWithDefault("IceBuilderHeaderExt", "h"); var cppOutputDir = new List<string>(); var cppHeaderOutputDir = new List<string>(); if (cpp) { var waitEvent = new ManualResetEvent(false); dispatcher.BeginInvoke(new Action(() => { foreach (EnvDTE.Configuration configuration in dteProject.ConfigurationManager) { cppOutputDir.Add(Package.Instance.VCUtil.Evaluate(configuration, outputDirUnevaluated)); if (string.IsNullOrEmpty(headerOutputDirUnevaluated)) { cppHeaderOutputDir.Add( Package.Instance.VCUtil.Evaluate( configuration, outputDirUnevaluated)); } else { cppHeaderOutputDir.Add( Package.Instance.VCUtil.Evaluate( configuration, headerOutputDirUnevaluated)); } } waitEvent.Set(); })); waitEvent.WaitOne(); } else { foreach (VSLangProj80.Reference3 r in dteProject.GetProjectRererences()) { if (Package.AssemblyNames.Contains(r.Name)) { project.UpdateProject((MSProject msproject) => { var item = msproject.AllEvaluatedItems.FirstOrDefault( referenceItem => referenceItem.ItemType.Equals("Reference") && referenceItem.EvaluatedInclude.Split( ",".ToCharArray()).ElementAt(0).Equals(r.Name)); if (item != null && item.HasMetadata("HintPath")) { var hintPath = item.GetMetadata("HintPath").UnevaluatedValue; if (hintPath.Contains("$(IceAssembliesDir)")) { hintPath = hintPath.Replace( "$(IceAssembliesDir)", FileUtil.RelativePath( Path.GetDirectoryName(r.ContainingProject.FullName), assemblyDir)); // If the HintPath points to the NuGet zeroc.ice.net package // we upgrade it to not use IceAssembliesDir otherwise we // remove it if (hintPath.Contains("packages\\zeroc.ice.net")) { item.SetMetadataValue("HintPath", hintPath); } else { item.RemoveMetadata("HintPath"); } } } }); } } } project.UpdateProject((MSProject msproject) => { MSBuildUtils.UpgradeProjectImports(msproject); MSBuildUtils.UpgradeProjectProperties(msproject, cpp); MSBuildUtils.RemoveIceBuilderFromProject(msproject, true); MSBuildUtils.UpgradeProjectItems(msproject); MSBuildUtils.UpgradeCSharpGeneratedItems(msproject, outputDir); foreach (var d in cppOutputDir) { MSBuildUtils.UpgradeGeneratedItems(msproject, d, sourceExt, "ClCompile"); } foreach (var d in cppHeaderOutputDir) { MSBuildUtils.UpgradeGeneratedItems(msproject, d, headerExt, "ClInclude"); } var propertyGroup = msproject.Xml.PropertyGroups.FirstOrDefault( group => group.Label.Equals("IceBuilder")); if (propertyGroup != null) { propertyGroup.Parent.RemoveChild(propertyGroup); } if (cpp) { propertyGroup = msproject.Xml.AddPropertyGroup(); propertyGroup.Label = "IceBuilder"; propertyGroup.AddProperty("IceCppMapping", "cpp98"); } }); dispatcher.BeginInvoke(new Action(() => { builder.ReloadProject(project); })); } } dispatcher.BeginInvoke(new Action(() => progressCallback.Finished())); } catch (Exception ex) { dispatcher.BeginInvoke(new Action(() => { progressCallback.Canceled = true; Package.UnexpectedExceptionWarning(ex); })); } }); t.Start(); } // Check if IceBuilder 4.x is enabled public static IceBuilderProjectType IsIceBuilderEnabled(IVsProject project) { if (project != null) { IceBuilderProjectType type = project.IsCppProject() ? IceBuilderProjectType.CppProjectType : project.IsCSharpProject() ? IceBuilderProjectType.CsharpProjectType : IceBuilderProjectType.None; if (type != IceBuilderProjectType.None) { return project.WithProject((MSProject msproject) => { if (MSBuildUtils.IsIceBuilderEnabled(msproject)) { return type; } return IceBuilderProjectType.None; }); } } return IceBuilderProjectType.None; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using Flurl; using Flurl.Http; using NBitcoin; using Newtonsoft.Json; using Stratis.Bitcoin.Features.Wallet.Models; using Stratis.Bitcoin.IntegrationTests; using Stratis.Bitcoin.IntegrationTests.Common; using Stratis.Bitcoin.IntegrationTests.Common.EnvironmentMockUpHelpers; using Stratis.Bitcoin.Networks; using Stratis.Bitcoin.Tests.Common; using Stratis.Features.Collateral.CounterChain; using Stratis.Features.FederatedPeg.Models; using Stratis.Sidechains.Networks; namespace Stratis.Features.FederatedPeg.IntegrationTests.Utils { public class SidechainTestContext : IDisposable { private const string WalletName = "mywallet"; private const string WalletPassword = "password"; private const string WalletPassphrase = "passphrase"; private const string WalletAccount = "account 0"; private const string ConfigSideChain = "sidechain"; private const string ConfigMainChain = "mainchain"; private const string ConfigAgentPrefix = "agentprefix"; // TODO: Make these private, or move to public immutable properties. Will happen naturally over time. public readonly IList<Mnemonic> mnemonics; public readonly Dictionary<Mnemonic, PubKey> pubKeysByMnemonic; public readonly (Script payToMultiSig, BitcoinAddress sidechainMultisigAddress, BitcoinAddress mainchainMultisigAddress) scriptAndAddresses; public readonly List<string> chains; private readonly SidechainNodeBuilder nodeBuilder; public Network MainChainNetwork { get; } public CirrusRegTest SideChainNetwork { get; } // TODO: HashSets / Readonly public IReadOnlyList<CoreNode> MainChainNodes { get; } public IReadOnlyList<CoreNode> SideChainNodes { get; } public IReadOnlyList<CoreNode> MainChainFedNodes { get; } public IReadOnlyList<CoreNode> SideChainFedNodes { get; } public CoreNode MainUser { get; } public CoreNode FedMain1 { get; } public CoreNode FedMain2 { get; } public CoreNode FedMain3 { get; } public CoreNode SideUser { get; } public CoreNode FedSide1 { get; } public CoreNode FedSide2 { get; } public CoreNode FedSide3 { get; } public SidechainTestContext() { this.MainChainNetwork = Networks.Stratis.Regtest(); this.SideChainNetwork = (CirrusRegTest)CirrusNetwork.NetworksSelector.Regtest(); this.mnemonics = this.SideChainNetwork.FederationMnemonics; this.pubKeysByMnemonic = this.mnemonics.ToDictionary(m => m, m => m.DeriveExtKey().PrivateKey.PubKey); this.scriptAndAddresses = FederatedPegTestHelper.GenerateScriptAndAddresses(this.MainChainNetwork, this.SideChainNetwork, 2, this.pubKeysByMnemonic); this.chains = new[] { "mainchain", "sidechain" }.ToList(); this.nodeBuilder = SidechainNodeBuilder.CreateSidechainNodeBuilder(this); this.MainUser = this.nodeBuilder.CreateStratisPosNode(this.MainChainNetwork, nameof(this.MainUser)).WithWallet(); this.FedMain1 = this.nodeBuilder.CreateMainChainFederationNode(this.MainChainNetwork, this.SideChainNetwork).WithWallet(); this.FedMain2 = this.nodeBuilder.CreateMainChainFederationNode(this.MainChainNetwork, this.SideChainNetwork); this.FedMain3 = this.nodeBuilder.CreateMainChainFederationNode(this.MainChainNetwork, this.SideChainNetwork); this.SideUser = this.nodeBuilder.CreateSidechainNode(this.SideChainNetwork).WithWallet(); this.FedSide1 = this.nodeBuilder.CreateSidechainFederationNode(this.SideChainNetwork, this.MainChainNetwork, this.SideChainNetwork.FederationKeys[0]); this.FedSide2 = this.nodeBuilder.CreateSidechainFederationNode(this.SideChainNetwork, this.MainChainNetwork, this.SideChainNetwork.FederationKeys[1]); this.FedSide3 = this.nodeBuilder.CreateSidechainFederationNode(this.SideChainNetwork, this.MainChainNetwork, this.SideChainNetwork.FederationKeys[2]); this.SideChainNodes = new List<CoreNode>() { this.SideUser, this.FedSide1, this.FedSide2, this.FedSide3 }; this.MainChainNodes = new List<CoreNode>() { this.MainUser, this.FedMain1, this.FedMain2, this.FedMain3, }; this.SideChainFedNodes = new List<CoreNode>() { this.FedSide1, this.FedSide2, this.FedSide3 }; this.MainChainFedNodes = new List<CoreNode>() { this.FedMain1, this.FedMain2, this.FedMain3 }; this.ApplyConfigParametersToNodes(); } public void StartAndConnectNodes() { this.StartMainNodes(); this.StartSideNodes(); TestBase.WaitLoop(() => this.FedMain3.State == CoreNodeState.Running && this.FedSide3.State == CoreNodeState.Running); this.ConnectMainChainNodes(); this.ConnectSideChainNodes(); } public void StartMainNodes() { foreach (CoreNode node in this.MainChainNodes) { node.Start(); } } public void StartSideNodes() { foreach (CoreNode node in this.SideChainNodes) { node.Start(); } } public void ConnectMainChainNodes() { TestHelper.Connect(this.MainUser, this.FedMain1); TestHelper.Connect(this.MainUser, this.FedMain2); TestHelper.Connect(this.MainUser, this.FedMain3); TestHelper.Connect(this.FedMain1, this.MainUser); TestHelper.Connect(this.FedMain1, this.FedMain2); TestHelper.Connect(this.FedMain1, this.FedMain3); TestHelper.Connect(this.FedMain2, this.MainUser); TestHelper.Connect(this.FedMain2, this.FedMain1); TestHelper.Connect(this.FedMain2, this.FedMain3); TestHelper.Connect(this.FedMain3, this.MainUser); TestHelper.Connect(this.FedMain3, this.FedMain1); TestHelper.Connect(this.FedMain3, this.FedMain2); } public void ConnectSideChainNodes() { TestHelper.Connect(this.SideUser, this.FedSide1); TestHelper.Connect(this.SideUser, this.FedSide2); TestHelper.Connect(this.SideUser, this.FedSide3); TestHelper.Connect(this.FedSide1, this.SideUser); TestHelper.Connect(this.FedSide1, this.FedSide2); TestHelper.Connect(this.FedSide1, this.FedSide3); TestHelper.Connect(this.FedSide2, this.SideUser); TestHelper.Connect(this.FedSide2, this.FedSide1); TestHelper.Connect(this.FedSide2, this.FedSide3); TestHelper.Connect(this.FedSide3, this.SideUser); TestHelper.Connect(this.FedSide3, this.FedSide1); TestHelper.Connect(this.FedSide3, this.FedSide2); } public void EnableMainFedWallets() { EnableFederationWallets(this.MainChainFedNodes); } public void EnableSideFedWallets() { EnableFederationWallets(this.SideChainFedNodes); } private void EnableFederationWallets(IReadOnlyList<CoreNode> nodes) { for (int i = 0; i < nodes.Count; i++) { CoreNode node = nodes[i]; $"http://localhost:{node.ApiPort}/api".AppendPathSegment("FederationWallet/enable-federation").PostJsonAsync(new EnableFederationRequest { Password = "password", Mnemonic = this.mnemonics[i].ToString() }).Result.StatusCode.Should().Be(HttpStatusCode.OK); } } /// <summary> /// Helper method to build and send a deposit transaction to the federation on the main chain. /// </summary> public async Task DepositToSideChain(CoreNode node, decimal amount, string sidechainDepositAddress) { HttpResponseMessage depositTransaction = await $"http://localhost:{node.ApiPort}/api" .AppendPathSegment("wallet/build-transaction") .PostJsonAsync(new { walletName = WalletName, accountName = WalletAccount, password = WalletPassword, opReturnData = sidechainDepositAddress, feeAmount = "0.01", allowUnconfirmed = true, recipients = new[] { new { destinationAddress = this.scriptAndAddresses.mainchainMultisigAddress.ToString(), amount = amount } } }); string result = await depositTransaction.Content.ReadAsStringAsync(); WalletBuildTransactionModel walletBuildTxModel = JsonConvert.DeserializeObject<WalletBuildTransactionModel>(result); HttpResponseMessage sendTransactionResponse = await $"http://localhost:{node.ApiPort}/api" .AppendPathSegment("wallet/send-transaction") .PostJsonAsync(new { hex = walletBuildTxModel.Hex }); } public async Task WithdrawToMainChain(CoreNode node, decimal amount, string mainchainWithdrawAddress) { HttpResponseMessage withdrawTransaction = await $"http://localhost:{node.ApiPort}/api" .AppendPathSegment("wallet/build-transaction") .PostJsonAsync(new { walletName = WalletName, accountName = WalletAccount, password = WalletPassword, opReturnData = mainchainWithdrawAddress, feeAmount = "0.01", recipients = new[] { new { destinationAddress = this.scriptAndAddresses.sidechainMultisigAddress.ToString(), amount = amount } } }); string result = await withdrawTransaction.Content.ReadAsStringAsync(); WalletBuildTransactionModel walletBuildTxModel = JsonConvert.DeserializeObject<WalletBuildTransactionModel>(result); HttpResponseMessage sendTransactionResponse = await $"http://localhost:{node.ApiPort}/api" .AppendPathSegment("wallet/send-transaction") .PostJsonAsync(new { hex = walletBuildTxModel.Hex }); } private void ApplyFederationIPs(CoreNode fed1, CoreNode fed2, CoreNode fed3) { string fedIps = $"{fed1.Endpoint},{fed2.Endpoint},{fed3.Endpoint}"; fed1.AppendToConfig($"{FederatedPegSettings.FederationIpsParam}={fedIps}"); fed2.AppendToConfig($"{FederatedPegSettings.FederationIpsParam}={fedIps}"); fed3.AppendToConfig($"{FederatedPegSettings.FederationIpsParam}={fedIps}"); } private void ApplyCounterChainAPIPort(CoreNode fromNode, CoreNode toNode) { fromNode.AppendToConfig($"{CounterChainSettings.CounterChainApiPortParam}={toNode.ApiPort.ToString()}"); toNode.AppendToConfig($"{CounterChainSettings.CounterChainApiPortParam}={fromNode.ApiPort.ToString()}"); } private void ApplyConfigParametersToNodes() { this.FedSide1.AppendToConfig($"{ConfigSideChain}=1"); this.FedSide2.AppendToConfig($"{ConfigSideChain}=1"); this.FedSide3.AppendToConfig($"{ConfigSideChain}=1"); this.FedMain1.AppendToConfig($"{ConfigMainChain}=1"); this.FedMain2.AppendToConfig($"{ConfigMainChain}=1"); this.FedMain3.AppendToConfig($"{ConfigMainChain}=1"); this.FedSide1.AppendToConfig($"mindepositconfirmations=5"); this.FedSide2.AppendToConfig($"mindepositconfirmations=5"); this.FedSide3.AppendToConfig($"mindepositconfirmations=5"); this.FedMain1.AppendToConfig($"mindepositconfirmations=5"); this.FedMain2.AppendToConfig($"mindepositconfirmations=5"); this.FedMain3.AppendToConfig($"mindepositconfirmations=5"); // To look for deposits from the beginning on our sidechain. this.FedSide1.AppendToConfig($"{FederatedPegSettings.CounterChainDepositBlock}=1"); this.FedSide2.AppendToConfig($"{FederatedPegSettings.CounterChainDepositBlock}=1"); this.FedSide3.AppendToConfig($"{FederatedPegSettings.CounterChainDepositBlock}=1"); this.FedSide1.AppendToConfig($"{FederatedPegSettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedSide2.AppendToConfig($"{FederatedPegSettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedSide3.AppendToConfig($"{FederatedPegSettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedMain1.AppendToConfig($"{FederatedPegSettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedMain2.AppendToConfig($"{FederatedPegSettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedMain3.AppendToConfig($"{FederatedPegSettings.RedeemScriptParam}={this.scriptAndAddresses.payToMultiSig.ToString()}"); this.FedSide1.AppendToConfig($"{FederatedPegSettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[0]].ToString()}"); this.FedSide2.AppendToConfig($"{FederatedPegSettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[1]].ToString()}"); this.FedSide3.AppendToConfig($"{FederatedPegSettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[2]].ToString()}"); this.FedMain1.AppendToConfig($"{FederatedPegSettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[0]].ToString()}"); this.FedMain2.AppendToConfig($"{FederatedPegSettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[1]].ToString()}"); this.FedMain3.AppendToConfig($"{FederatedPegSettings.PublicKeyParam}={this.pubKeysByMnemonic[this.mnemonics[2]].ToString()}"); this.ApplyFederationIPs(this.FedMain1, this.FedMain2, this.FedMain3); this.ApplyFederationIPs(this.FedSide1, this.FedSide2, this.FedSide3); this.ApplyCounterChainAPIPort(this.FedMain1, this.FedSide1); this.ApplyCounterChainAPIPort(this.FedMain2, this.FedSide2); this.ApplyCounterChainAPIPort(this.FedMain3, this.FedSide3); this.ApplyAgentPrefixToNodes(); } private void ApplyAgentPrefixToNodes() { // name assigning a little gross here - fix later. string[] names = new string[] { "SideUser", "FedSide1", "FedSide2", "FedSide3", "MainUser", "FedMain1", "FedMain2", "FedMain3" }; int index = 0; foreach (CoreNode n in this.SideChainNodes.Concat(this.MainChainNodes)) { string text = File.ReadAllText(n.Config); text = text.Replace($"{ConfigAgentPrefix}=node{n.Endpoint.Port}", $"{ConfigAgentPrefix}={names[index]}"); File.WriteAllText(n.Config, text); index++; } } public void Dispose() { this.nodeBuilder?.Dispose(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { private partial class WorkCoordinator { private partial class IncrementalAnalyzerProcessor { private static readonly Func<int, object, bool, string> s_enqueueLogger = (t, i, s) => string.Format("[{0}] {1} : {2}", t, i.ToString(), s); private readonly Registration _registration; private readonly IAsynchronousOperationListener _listener; private readonly IDocumentTrackingService _documentTracker; private readonly IProjectCacheService _cacheService; private readonly HighPriorityProcessor _highPriorityProcessor; private readonly NormalPriorityProcessor _normalPriorityProcessor; private readonly LowPriorityProcessor _lowPriorityProcessor; private LogAggregator _logAggregator; public IncrementalAnalyzerProcessor( IAsynchronousOperationListener listener, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, Registration registration, int highBackOffTimeSpanInMs, int normalBackOffTimeSpanInMs, int lowBackOffTimeSpanInMs, CancellationToken shutdownToken) { _logAggregator = new LogAggregator(); _listener = listener; _registration = registration; _cacheService = registration.GetService<IProjectCacheService>(); var lazyActiveFileAnalyzers = new Lazy<ImmutableArray<IIncrementalAnalyzer>>(() => GetActiveFileIncrementalAnalyzers(_registration, analyzerProviders)); var lazyAllAnalyzers = new Lazy<ImmutableArray<IIncrementalAnalyzer>>(() => GetIncrementalAnalyzers(_registration, analyzerProviders)); // event and worker queues _documentTracker = _registration.GetService<IDocumentTrackingService>(); var globalNotificationService = _registration.GetService<IGlobalOperationNotificationService>(); _highPriorityProcessor = new HighPriorityProcessor(listener, this, lazyActiveFileAnalyzers, highBackOffTimeSpanInMs, shutdownToken); _normalPriorityProcessor = new NormalPriorityProcessor(listener, this, lazyAllAnalyzers, globalNotificationService, normalBackOffTimeSpanInMs, shutdownToken); _lowPriorityProcessor = new LowPriorityProcessor(listener, this, lazyAllAnalyzers, globalNotificationService, lowBackOffTimeSpanInMs, shutdownToken); } private static ImmutableArray<IIncrementalAnalyzer> GetActiveFileIncrementalAnalyzers( Registration registration, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> providers) { var analyzers = providers.Where(p => p.Metadata.HighPriorityForActiveFile && p.Metadata.WorkspaceKinds.Contains(registration.Workspace.Kind)) .Select(p => p.Value.CreateIncrementalAnalyzer(registration.Workspace)); var orderedAnalyzers = OrderAnalyzers(analyzers); SolutionCrawlerLogger.LogActiveFileAnalyzers(registration.CorrelationId, registration.Workspace, orderedAnalyzers); return orderedAnalyzers; } private static ImmutableArray<IIncrementalAnalyzer> GetIncrementalAnalyzers( Registration registration, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> providers) { var analyzers = providers.Where(p => p.Metadata.WorkspaceKinds.Contains(registration.Workspace.Kind)) .Select(p => p.Value.CreateIncrementalAnalyzer(registration.Workspace)); var orderedAnalyzers = OrderAnalyzers(analyzers); SolutionCrawlerLogger.LogAnalyzers(registration.CorrelationId, registration.Workspace, orderedAnalyzers); return orderedAnalyzers; } private static ImmutableArray<IIncrementalAnalyzer> OrderAnalyzers(IEnumerable<IIncrementalAnalyzer> analyzers) { return SpecializedCollections.SingletonEnumerable(analyzers.FirstOrDefault(a => a is BaseDiagnosticIncrementalAnalyzer)) .Concat(analyzers.Where(a => !(a is BaseDiagnosticIncrementalAnalyzer))) .WhereNotNull().ToImmutableArray(); } public void Enqueue(WorkItem item) { Contract.ThrowIfNull(item.DocumentId); _highPriorityProcessor.Enqueue(item); _normalPriorityProcessor.Enqueue(item); _lowPriorityProcessor.Enqueue(item); } public void Shutdown() { _highPriorityProcessor.Shutdown(); _normalPriorityProcessor.Shutdown(); _lowPriorityProcessor.Shutdown(); } // TODO: delete this once prototyping is done public void ChangeDiagnosticsEngine(bool useV2Engine) { var diagnosticAnalyzer = Analyzers.FirstOrDefault(a => a is BaseDiagnosticIncrementalAnalyzer) as DiagnosticAnalyzerService.IncrementalAnalyzerDelegatee; if (diagnosticAnalyzer == null) { return; } diagnosticAnalyzer.TurnOff(useV2Engine); } public ImmutableArray<IIncrementalAnalyzer> Analyzers { get { return _normalPriorityProcessor.Analyzers; } } public Task AsyncProcessorTask { get { return Task.WhenAll( _highPriorityProcessor.AsyncProcessorTask, _normalPriorityProcessor.AsyncProcessorTask, _lowPriorityProcessor.AsyncProcessorTask); } } private Solution CurrentSolution { get { return _registration.CurrentSolution; } } private IDisposable EnableCaching(ProjectId projectId) { return _cacheService?.EnableCaching(projectId) ?? NullDisposable.Instance; } private ProjectDependencyGraph DependencyGraph { get { return CurrentSolution.GetProjectDependencyGraph(); } } private IEnumerable<DocumentId> GetOpenDocumentIds() { return _registration.Workspace.GetOpenDocumentIds(); } private void ResetLogAggregator() { _logAggregator = new LogAggregator(); } private static async Task ProcessDocumentAnalyzersAsync( Document document, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationToken cancellationToken) { // process all analyzers for each categories in this order - syntax, body, document if (workItem.MustRefresh || workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged)) { await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeSyntaxAsync(d, c), cancellationToken).ConfigureAwait(false); } if (workItem.MustRefresh || workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false); } else { // if we don't need to re-analyze whole body, see whether we need to at least re-analyze one method. await RunBodyAnalyzersAsync(analyzers, workItem, document, cancellationToken).ConfigureAwait(false); } } private static async Task RunAnalyzersAsync<T>(ImmutableArray<IIncrementalAnalyzer> analyzers, T value, Func<IIncrementalAnalyzer, T, CancellationToken, Task> runnerAsync, CancellationToken cancellationToken) { foreach (var analyzer in analyzers) { if (cancellationToken.IsCancellationRequested) { return; } var local = analyzer; await GetOrDefaultAsync(value, async (v, c) => { await runnerAsync(local, v, c).ConfigureAwait(false); return default(object); }, cancellationToken).ConfigureAwait(false); } } private static async Task RunBodyAnalyzersAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, CancellationToken cancellationToken) { try { var root = await GetOrDefaultAsync(document, (d, c) => d.GetSyntaxRootAsync(c), cancellationToken).ConfigureAwait(false); var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); if (root == null || syntaxFactsService == null) { // as a fallback mechanism, if we can't run one method body due to some missing service, run whole document analyzer. await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false); return; } // check whether we know what body has changed. currently, this is an optimization toward typing case. if there are more than one body changes // it will be considered as semantic change and whole document analyzer will take care of that case. var activeMember = GetMemberNode(syntaxFactsService, root, workItem.ActiveMember); if (activeMember == null) { // no active member means, change is out side of a method body, but it didn't affect semantics (such as change in comment) // in that case, we update whole document (just this document) so that we can have updated locations. await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false); return; } // re-run just the body await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, activeMember, c), cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task<TResult> GetOrDefaultAsync<TData, TResult>(TData value, Func<TData, CancellationToken, Task<TResult>> funcAsync, CancellationToken cancellationToken) { try { return await funcAsync(value, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { return default(TResult); } catch (AggregateException e) when (CrashUnlessCanceled(e)) { return default(TResult); } catch (Exception e) when (FatalError.Report(e)) { // TODO: manage bad workers like what code actions does now throw ExceptionUtilities.Unreachable; } } private static SyntaxNode GetMemberNode(ISyntaxFactsService service, SyntaxNode root, SyntaxPath memberPath) { if (root == null || memberPath == null) { return null; } SyntaxNode memberNode; if (!memberPath.TryResolve(root, out memberNode)) { return null; } return service.IsMethodLevelMember(memberNode) ? memberNode : null; } internal ProjectId GetActiveProject() { ProjectId activeProjectId = null; if (_documentTracker != null) { var activeDocument = _documentTracker.GetActiveDocument(); if (activeDocument != null) { activeProjectId = activeDocument.ProjectId; } } return null; } private static bool CrashUnlessCanceled(AggregateException aggregate) { var flattened = aggregate.Flatten(); if (flattened.InnerExceptions.All(e => e is OperationCanceledException)) { return true; } FatalError.Report(flattened); return false; } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items) { _normalPriorityProcessor.WaitUntilCompletion_ForTestingPurposesOnly(analyzers, items); var projectItems = items.Select(i => i.With(null, i.ProjectId, EmptyAsyncToken.Instance)); _lowPriorityProcessor.WaitUntilCompletion_ForTestingPurposesOnly(analyzers, items); } internal void WaitUntilCompletion_ForTestingPurposesOnly() { _normalPriorityProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); _lowPriorityProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); } private class NullDisposable : IDisposable { public static readonly IDisposable Instance = new NullDisposable(); public void Dispose() { } } } } } }
using UnityEngine; using Cinemachine.Utility; namespace Cinemachine { /// <summary> /// The output of the Cinemachine engine for a specific virtual camera. The information /// in this struct can be blended, and provides what is needed to calculate an /// appropriate camera position, orientation, and lens setting. /// /// Raw values are what the Cinemachine behaviours generate. The correction channel /// holds perturbations to the raw values - e.g. noise or smoothing, or obstacle /// avoidance corrections. Coirrections are not considered when making time-based /// calculations such as damping. /// /// The Final position and orientation is the comination of the raw values and /// their corrections. /// </summary> public struct CameraState { /// <summary> /// Camera Lens Settings. /// </summary> public LensSettings Lens { get; set; } /// <summary> /// Which way is up. World space unit vector. /// </summary> public Vector3 ReferenceUp { get; set; } /// <summary> /// The world space focus point of the camera. What the camera wants to look at. /// There is a special constant define to represent "nothing". Be careful to /// check for that (or check the HasLookAt property). /// </summary> public Vector3 ReferenceLookAt { get; set; } /// <summary> /// Returns true if this state has a valid ReferenceLookAt value. /// </summary> public bool HasLookAt { get { return ReferenceLookAt == ReferenceLookAt; } } // will be false if NaN /// <summary> /// This constant represents "no point in space" or "no direction". /// </summary> public static Vector3 kNoPoint = new Vector3(float.NaN, float.NaN, float.NaN); /// <summary> /// Raw (un-corrected) world space position of this camera /// </summary> public Vector3 RawPosition { get; set; } /// <summary> /// Raw (un-corrected) world space orientation of this camera /// </summary> public Quaternion RawOrientation { get; set; } /// <summary> /// Subjective estimation of how "good" the shot is. /// Larger values mean better quality. Default is 1. /// </summary> public float ShotQuality { get; set; } /// <summary> /// Position correction. This will be added to the raw position. /// This value doesn't get fed back into the system when calculating the next frame. /// Can be noise, or smoothing, or both, or something else. /// </summary> public Vector3 PositionCorrection { get; set; } /// <summary> /// Orientation correction. This will be added to the raw orientation. /// This value doesn't get fed back into the system when calculating the next frame. /// Can be noise, or smoothing, or both, or something else. /// </summary> public Quaternion OrientationCorrection { get; set; } /// <summary> /// Position with correction applied. /// </summary> public Vector3 CorrectedPosition { get { return RawPosition + PositionCorrection; } } /// <summary> /// Orientation with correction applied. /// </summary> public Quaternion CorrectedOrientation { get { return RawOrientation * OrientationCorrection; } } /// <summary> /// Position with correction applied. This is what the final camera gets. /// </summary> public Vector3 FinalPosition { get { return RawPosition + PositionCorrection; } } /// <summary> /// Orientation with correction and dutch applied. This is what the final camera gets. /// </summary> public Quaternion FinalOrientation { get { if (Mathf.Abs(Lens.Dutch) > UnityVectorExtensions.Epsilon) return CorrectedOrientation * Quaternion.AngleAxis(Lens.Dutch, Vector3.forward); return CorrectedOrientation; } } /// <summary> /// State with default values /// </summary> public static CameraState Default { get { CameraState state = new CameraState(); state.Lens = LensSettings.Default; state.ReferenceUp = Vector3.up; state.ReferenceLookAt = kNoPoint; state.RawPosition = Vector3.zero; state.RawOrientation = Quaternion.identity; state.ShotQuality = 1; state.PositionCorrection = Vector3.zero; state.OrientationCorrection = Quaternion.identity; return state; } } /// <summary>Intelligently blend the contents of two states.</summary> /// <param name="stateA">The first state, corresponding to t=0</param> /// <param name="stateB">The second state, corresponding to t=1</param> /// <param name="t">How much to interpolate. Internally clamped to 0..1</param> /// <returns>Linearly interpolated CameraState</returns> public static CameraState Lerp(CameraState stateA, CameraState stateB, float t) { t = Mathf.Clamp01(t); float adjustedT = t; CameraState state = new CameraState(); state.Lens = LensSettings.Lerp(stateA.Lens, stateB.Lens, t); state.ReferenceUp = Vector3.Slerp(stateA.ReferenceUp, stateB.ReferenceUp, t); state.RawPosition = Vector3.Lerp(stateA.RawPosition, stateB.RawPosition, t); state.ShotQuality = Mathf.Lerp(stateA.ShotQuality, stateB.ShotQuality, t); state.PositionCorrection = Vector3.Lerp( stateA.PositionCorrection, stateB.PositionCorrection, t); // GML todo: is this right? Can it introduce a roll? state.OrientationCorrection = Quaternion.Slerp( stateA.OrientationCorrection, stateB.OrientationCorrection, t); Vector3 dirTarget = Vector3.zero; if (!stateA.HasLookAt || !stateB.HasLookAt) state.ReferenceLookAt = kNoPoint; // can't interpolate if undefined else { // Re-interpolate FOV to preserve target composition, if possible float fovA = stateA.Lens.FieldOfView; float fovB = stateB.Lens.FieldOfView; if (!state.Lens.Orthographic && !Mathf.Approximately(fovA, fovB)) { LensSettings lens = state.Lens; lens.FieldOfView = state.InterpolateFOV( fovA, fovB, Mathf.Max((stateA.ReferenceLookAt - stateA.CorrectedPosition).magnitude, stateA.Lens.NearClipPlane), Mathf.Max((stateB.ReferenceLookAt - stateB.CorrectedPosition).magnitude, stateB.Lens.NearClipPlane), t); state.Lens = lens; // Make sure we preserve the screen composition through FOV changes adjustedT = Mathf.Abs((lens.FieldOfView - fovA) / (fovB - fovA)); } // Spherical linear interpolation about CorrectedPosition state.ReferenceLookAt = state.CorrectedPosition + Vector3.Slerp( stateA.ReferenceLookAt - state.CorrectedPosition, stateB.ReferenceLookAt - state.CorrectedPosition, adjustedT); dirTarget = state.ReferenceLookAt - state.CorrectedPosition; } // Clever orientation interpolation if (dirTarget.AlmostZero()) { // Don't know what we're looking at - can only slerp state.RawOrientation = UnityQuaternionExtensions.SlerpWithReferenceUp( stateA.RawOrientation, stateB.RawOrientation, t, state.ReferenceUp); } else { // Rotate while preserving our lookAt target dirTarget = dirTarget.normalized; if ((dirTarget - state.ReferenceUp).AlmostZero() || (dirTarget + state.ReferenceUp).AlmostZero()) { // Looking up or down at the pole state.RawOrientation = UnityQuaternionExtensions.SlerpWithReferenceUp( stateA.RawOrientation, stateB.RawOrientation, t, state.ReferenceUp); } else { // Put the target in the center state.RawOrientation = Quaternion.LookRotation(dirTarget, state.ReferenceUp); // Blend the desired offsets from center Vector2 deltaA = -stateA.RawOrientation.GetCameraRotationToTarget( stateA.ReferenceLookAt - stateA.CorrectedPosition, stateA.ReferenceUp); Vector2 deltaB = -stateB.RawOrientation.GetCameraRotationToTarget( stateB.ReferenceLookAt - stateB.CorrectedPosition, stateB.ReferenceUp); state.RawOrientation = state.RawOrientation.ApplyCameraRotation( Vector2.Lerp(deltaA, deltaB, adjustedT), state.ReferenceUp); } } return state; } float InterpolateFOV(float fovA, float fovB, float dA, float dB, float t) { // We interpolate shot height float hA = dA * 2f * Mathf.Tan(fovA * Mathf.Deg2Rad / 2f); float hB = dB * 2f * Mathf.Tan(fovB * Mathf.Deg2Rad / 2f); float h = Mathf.Lerp(hA, hB, t); float fov = 179f; float d = Mathf.Lerp(dA, dB, t); if (d > UnityVectorExtensions.Epsilon) fov = 2f * Mathf.Atan(h / (2 * d)) * Mathf.Rad2Deg; return Mathf.Clamp(fov, Mathf.Min(fovA, fovB), Mathf.Max(fovA, fovB)); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.RegularExpressions; using log4net; using log4net.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Capabilities.Handlers; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests { [TestFixture] public class FetchInventoryDescendents2HandlerTests : OpenSimTestCase { private UUID m_userID = new UUID("00000000-0000-0000-0000-000000000001"); private Scene m_scene; private UUID m_rootFolderID; private int m_rootDescendents; private UUID m_notecardsFolder; private UUID m_objectsFolder; private void Init() { // Create an inventory that looks like this: // // /My Inventory // <other system folders> // /Objects // Some Object // /Notecards // Notecard 1 // Notecard 2 // /Test Folder // Link to notecard -> /Notecards/Notecard 2 // Link to Objects folder -> /Objects m_scene = new SceneHelpers().SetupScene(); m_scene.InventoryService.CreateUserInventory(m_userID); m_rootFolderID = m_scene.InventoryService.GetRootFolder(m_userID).ID; InventoryFolderBase of = m_scene.InventoryService.GetFolderForType(m_userID, FolderType.Object); m_objectsFolder = of.ID; // Add an object InventoryItemBase item = new InventoryItemBase(new UUID("b0000000-0000-0000-0000-00000000000b"), m_userID); item.AssetID = UUID.Random(); item.AssetType = (int)AssetType.Object; item.Folder = m_objectsFolder; item.Name = "Some Object"; m_scene.InventoryService.AddItem(item); InventoryFolderBase ncf = m_scene.InventoryService.GetFolderForType(m_userID, FolderType.Notecard); m_notecardsFolder = ncf.ID; // Add a notecard item = new InventoryItemBase(new UUID("10000000-0000-0000-0000-000000000001"), m_userID); item.AssetID = UUID.Random(); item.AssetType = (int)AssetType.Notecard; item.Folder = m_notecardsFolder; item.Name = "Test Notecard 1"; m_scene.InventoryService.AddItem(item); // Add another notecard item.ID = new UUID("20000000-0000-0000-0000-000000000002"); item.AssetID = new UUID("a0000000-0000-0000-0000-00000000000a"); item.Name = "Test Notecard 2"; m_scene.InventoryService.AddItem(item); // Add a folder InventoryFolderBase folder = new InventoryFolderBase(new UUID("f0000000-0000-0000-0000-00000000000f"), "Test Folder", m_userID, m_rootFolderID); folder.Type = (short)FolderType.None; m_scene.InventoryService.AddFolder(folder); // Add a link to notecard 2 in Test Folder item.AssetID = item.ID; // use item ID of notecard 2 item.ID = new UUID("40000000-0000-0000-0000-000000000004"); item.AssetType = (int)AssetType.Link; item.Folder = folder.ID; item.Name = "Link to notecard"; m_scene.InventoryService.AddItem(item); // Add a link to the Objects folder in Test Folder item.AssetID = m_scene.InventoryService.GetFolderForType(m_userID, FolderType.Object).ID; // use item ID of Objects folder item.ID = new UUID("50000000-0000-0000-0000-000000000005"); item.AssetType = (int)AssetType.LinkFolder; item.Folder = folder.ID; item.Name = "Link to Objects folder"; m_scene.InventoryService.AddItem(item); InventoryCollection coll = m_scene.InventoryService.GetFolderContent(m_userID, m_rootFolderID); m_rootDescendents = coll.Items.Count + coll.Folders.Count; Console.WriteLine("Number of descendents: " + m_rootDescendents); } [Test] public void Test_001_SimpleFolder() { TestHelpers.InMethod(); Init(); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); TestOSHttpRequest req = new TestOSHttpRequest(); TestOSHttpResponse resp = new TestOSHttpResponse(); string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += m_rootFolderID; request += "</uuid><key>owner_id</key><uuid>"; request += m_userID.ToString(); request += "</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>"; string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp); Assert.That(llsdresponse != null, Is.True, "Incorrect null response"); Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response"); Assert.That(llsdresponse.Contains(m_userID.ToString()), Is.True, "Response should contain userID"); string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>"; Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents"); Console.WriteLine(llsdresponse); } [Test] public void Test_002_MultipleFolders() { TestHelpers.InMethod(); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); TestOSHttpRequest req = new TestOSHttpRequest(); TestOSHttpResponse resp = new TestOSHttpResponse(); string request = "<llsd><map><key>folders</key><array>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += m_rootFolderID; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000001</uuid><key>sort_order</key><integer>1</integer></map>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += m_notecardsFolder; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000001</uuid><key>sort_order</key><integer>1</integer></map>"; request += "</array></map></llsd>"; string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp); Console.WriteLine(llsdresponse); string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>"; Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents for root folder"); descendents = "descendents</key><integer>2</integer>"; Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents for Notecard folder"); Assert.That(llsdresponse.Contains("10000000-0000-0000-0000-000000000001"), Is.True, "Notecard 1 is missing from response"); Assert.That(llsdresponse.Contains("20000000-0000-0000-0000-000000000002"), Is.True, "Notecard 2 is missing from response"); } [Test] public void Test_003_Links() { TestHelpers.InMethod(); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); TestOSHttpRequest req = new TestOSHttpRequest(); TestOSHttpResponse resp = new TestOSHttpResponse(); string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += "f0000000-0000-0000-0000-00000000000f"; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000001</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>"; string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp); Console.WriteLine(llsdresponse); string descendents = "descendents</key><integer>2</integer>"; Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents for Test Folder"); // Make sure that the note card link is included Assert.That(llsdresponse.Contains("Link to notecard"), Is.True, "Link to notecard is missing"); //Make sure the notecard item itself is included Assert.That(llsdresponse.Contains("Test Notecard 2"), Is.True, "Notecard 2 item (the source) is missing"); // Make sure that the source item is before the link item int pos1 = llsdresponse.IndexOf("Test Notecard 2"); int pos2 = llsdresponse.IndexOf("Link to notecard"); Assert.Less(pos1, pos2, "Source of link is after link"); // Make sure the folder link is included Assert.That(llsdresponse.Contains("Link to Objects folder"), Is.True, "Link to Objects folder is missing"); /* contents of link folder are not supposed to be listed // Make sure the objects inside the Objects folder are included // Note: I'm not entirely sure this is needed, but that's what I found in the implementation Assert.That(llsdresponse.Contains("Some Object"), Is.True, "Some Object item (contents of the source) is missing"); */ // Make sure that the source item is before the link item pos1 = llsdresponse.IndexOf("Some Object"); pos2 = llsdresponse.IndexOf("Link to Objects folder"); Assert.Less(pos1, pos2, "Contents of source of folder link is after folder link"); } [Test] public void Test_004_DuplicateFolders() { TestHelpers.InMethod(); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); TestOSHttpRequest req = new TestOSHttpRequest(); TestOSHttpResponse resp = new TestOSHttpResponse(); string request = "<llsd><map><key>folders</key><array>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += m_rootFolderID; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += m_notecardsFolder; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += m_rootFolderID; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>"; request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += m_notecardsFolder; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>"; request += "</array></map></llsd>"; string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp); Console.WriteLine(llsdresponse); string root_folder = "<key>folder_id</key><uuid>" + m_rootFolderID + "</uuid>"; string notecards_folder = "<key>folder_id</key><uuid>" + m_notecardsFolder + "</uuid>"; Assert.That(llsdresponse.Contains(root_folder), "Missing root folder"); Assert.That(llsdresponse.Contains(notecards_folder), "Missing notecards folder"); int count = Regex.Matches(llsdresponse, root_folder).Count; Assert.AreEqual(1, count, "More than 1 root folder in response"); count = Regex.Matches(llsdresponse, notecards_folder).Count; Assert.AreEqual(2, count, "More than 1 notecards folder in response"); // Notecards will also be under root, so 2 } [Test] public void Test_005_FolderZero() { TestHelpers.InMethod(); Init(); FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene); TestOSHttpRequest req = new TestOSHttpRequest(); TestOSHttpResponse resp = new TestOSHttpResponse(); string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>"; request += UUID.Zero; request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>"; string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp); Assert.That(llsdresponse != null, Is.True, "Incorrect null response"); Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response"); // we do return a answer now //Assert.That(llsdresponse.Contains("bad_folders</key><array><uuid>00000000-0000-0000-0000-000000000000"), Is.True, "Folder Zero should be a bad folder"); Console.WriteLine(llsdresponse); } } }
using UnityEngine; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using System; using UnityEditor; public abstract class TestBehaviour : MonoBehaviour { public StepList steps; List<Given> givens; float initialDuration; float timeout; string timeUnits; string stepAfterTimeout; bool failed; void Awake() { givens = new List<Given>(); steps = new StepList(); } // update isn't called in abstract classes so just have the test runner call this public void Monitor() { if (stepAfterTimeout == null) { return; } string prefix = "then"; if ("seconds".StartsWith(timeUnits)) { prefix += " within " + initialDuration + (initialDuration == 1 ? " second" : " seconds"); timeout -= Time.deltaTime; } else if (timeUnits == "ms") { prefix += " within " + initialDuration + " ms"; timeout -= Time.deltaTime * 1000; } else if ("frames".StartsWith(timeUnits)) { if (initialDuration != 1) { prefix += " within " + initialDuration + " frames"; } timeout--; } if (timeout <= 0) { RunStep(prefix, stepAfterTimeout); Destroy(gameObject); } } public Given Given(string step) { Given given = new Given(step); givens.Add(given); return given; } public void Scenario(string scenario) { steps.type = scenario; } public void RunAll(string name) { Spec(); givens.Reverse(); foreach (Given given in givens) { given.when.thens.Reverse(); foreach (Then then in given.when.thens) { TestBehaviour fixture = new GameObject().AddComponent(name) as TestBehaviour; fixture.transform.position = GetRandomIsolatedLocation(); fixture.steps.reason = then.when.reason; if (steps.type == null) { fixture.steps.type = name.EndsWith("Test") ? name.Remove(name.Length - 4) : name; fixture.steps.type = Regex.Replace(fixture.steps.type, "[A-Z]", " $0").Trim(); } else { fixture.steps.type = steps.type; } string prefix = "given"; foreach (string step in given.steps) { fixture.RunStep(prefix, step); prefix = "and"; } prefix = "when"; foreach (string step in given.when.steps) { fixture.RunStep(prefix, step); prefix = "and"; } fixture.RunStepAfterTimeout(then.duration, then.step); } } Destroy(this); } public Vector3 GetRandomIsolatedLocation() { bool fixtureNearby = true; Vector3 randomLocation = Vector3.zero; int i = 0; while (fixtureNearby) { if (i++ > 1000) { throw new Exception("testing space is too crowded"); } randomLocation = UnityEngine.Random.insideUnitSphere * 1000; fixtureNearby = false; foreach (TestBehaviour fixture in Resources.FindObjectsOfTypeAll(typeof(TestBehaviour)) as TestBehaviour[]) { if ((randomLocation - fixture.transform.position).magnitude < 10) { fixtureNearby = true; } } } return randomLocation; } public void RunStep(string prefix, string step) { if (failed) { steps.Add(new Step(Step.yellow, prefix + " " + step)); return; } // replace numbers and strings with ___ and save in object[] args List<object> args = new List<object>(); foreach (Match match in Regex.Matches(Regex.Replace(step, " ", " "), @"(?:^| )(-?[0-9]+(?:\.[0-9]+)?|'[^']*')(?:$| )")) { string value = match.Value.Trim(); if (value.StartsWith("'")) { args.Add(Regex.Replace(value.Trim("'".ToCharArray()), " ", " ")); } else if (value.Contains(".")) { args.Add(float.Parse(value)); } else { args.Add(int.Parse(value)); } } string methodName = Regex.Replace(Regex.Replace(Regex.Replace(step.ToLower(), " ", " "), @"(?:^| )(-?[0-9]+(?:\.[0-9]+)?|'[^']*')(?:$| )", "__"), "[^a-z_]", ""); try { bool methodFound = false; foreach (MethodInfo method in GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public)) { if (method.Name.ToLower() == methodName) { method.Invoke(this, args.ToArray()); methodFound = true; break; } } if (methodFound) { steps.Add(new Step(Step.green, prefix + " " + step)); } else { steps.Add(new Step(Step.yellow, prefix + " " + step)); failed = true; } } catch (Exception e) { Exception error = e.InnerException ?? e; steps.Add(new Step(Step.red, prefix + " " + step + "\n" + error.ToString())); failed = true; } } public void RunStepAfterTimeout(string duration, string step) { stepAfterTimeout = step; timeout = float.Parse(Regex.Match(duration.Trim(), @"[\d.]+").Value); initialDuration = timeout; timeUnits = duration.Replace(timeout.ToString(), "").Trim(); } public abstract void Spec(); }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; #if NETSTANDARD2_0 using System.Runtime.Versioning; #else using Microsoft.Win32; #endif namespace NUnit.Framework.Internal { /// <summary> /// RuntimeFramework represents a particular version /// of a common language runtime implementation. /// </summary> [Serializable] public sealed class RuntimeFramework { // NOTE: This version of RuntimeFramework is for use // within the NUnit framework assembly. It is simpler // than the version in the test engine because it does // not need to know what frameworks are available, // only what framework is currently running. #region Static and Instance Fields /// <summary> /// DefaultVersion is an empty Version, used to indicate that /// NUnit should select the CLR version to use for the test. /// </summary> public static readonly Version DefaultVersion = new Version(0,0); private static readonly Lazy<RuntimeFramework> currentFramework = new Lazy<RuntimeFramework>(() => { Type monoRuntimeType = null; Type monoTouchType = null; try { monoRuntimeType = Type.GetType("Mono.Runtime", false); monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate,monotouch", false); } catch { //If exception thrown, assume no valid installation } bool isMonoTouch = monoTouchType != null; bool isMono = monoRuntimeType != null; bool isNetCore = !isMono && !isMonoTouch && IsNetCore(); RuntimeType runtime = isMonoTouch ? RuntimeType.MonoTouch : isMono ? RuntimeType.Mono : isNetCore ? RuntimeType.NetCore : RuntimeType.NetFramework; int major = Environment.Version.Major; int minor = Environment.Version.Minor; if (isMono) { switch (major) { case 1: minor = 0; break; case 2: major = 3; minor = 5; break; } } else if (isNetCore) { major = 0; minor = 0; } else /* It's windows */ #if NETSTANDARD2_0 { minor = 5; } #else if (major == 2) { // The only assembly we compile that can run on the v2 CLR uses .NET Framework 3.5. major = 3; minor = 5; } else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null) { minor = 5; } #endif var currentFramework = new RuntimeFramework( runtime, new Version (major, minor) ) { ClrVersion = Environment.Version }; if (isMono) { MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod( "GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding); if (getDisplayNameMethod != null) currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]); } return currentFramework; }); #endregion #region Constructor /// <summary> /// Construct from a runtime type and version. If the version has /// two parts, it is taken as a framework version. If it has three /// or more, it is taken as a CLR version. In either case, the other /// version is deduced based on the runtime type and provided version. /// </summary> /// <param name="runtime">The runtime type of the framework</param> /// <param name="version">The version of the framework</param> public RuntimeFramework( RuntimeType runtime, Version version) { Runtime = runtime; if (version.Build < 0) InitFromFrameworkVersion(version); else InitFromClrVersion(version); DisplayName = GetDefaultDisplayName(runtime, version); } private void InitFromFrameworkVersion(Version version) { FrameworkVersion = ClrVersion = version; if (version.Major > 0) // 0 means any version switch (Runtime) { case RuntimeType.NetCore: ClrVersion = new Version(4, 0, 30319); break; case RuntimeType.NetFramework: case RuntimeType.Mono: case RuntimeType.Any: switch (version.Major) { case 1: switch (version.Minor) { case 0: ClrVersion = Runtime == RuntimeType.Mono ? new Version(1, 1, 4322) : new Version(1, 0, 3705); break; case 1: if (Runtime == RuntimeType.Mono) FrameworkVersion = new Version(1, 0); ClrVersion = new Version(1, 1, 4322); break; default: ThrowInvalidFrameworkVersion(version); break; } break; case 2: case 3: ClrVersion = new Version(2, 0, 50727); break; case 4: ClrVersion = new Version(4, 0, 30319); break; default: ThrowInvalidFrameworkVersion(version); break; } break; } } private static void ThrowInvalidFrameworkVersion(Version version) { throw new ArgumentException("Unknown framework version " + version, nameof(version)); } private void InitFromClrVersion(Version version) { FrameworkVersion = new Version(version.Major, version.Minor); ClrVersion = version; if (Runtime == RuntimeType.Mono && version.Major == 1) FrameworkVersion = new Version(1, 0); if (Runtime == RuntimeType.NetFramework && version.Major == 4 && version.Minor == 5) ClrVersion = new Version(4, 0, 30319); if (Runtime == RuntimeType.NetCore) ClrVersion = new Version(4, 0, 30319); } #endregion #region Properties /// <summary> /// Static method to return a RuntimeFramework object /// for the framework that is currently in use. /// </summary> public static RuntimeFramework CurrentFramework { get { return currentFramework.Value; } } /// <summary> /// The type of this runtime framework /// </summary> public RuntimeType Runtime { get; } /// <summary> /// The framework version for this runtime framework /// </summary> public Version FrameworkVersion { get; private set; } /// <summary> /// The CLR version for this runtime framework /// </summary> public Version ClrVersion { get; private set; } /// <summary> /// Return true if any CLR version may be used in /// matching this RuntimeFramework object. /// </summary> public bool AllowAnyVersion { get { return ClrVersion == DefaultVersion; } } /// <summary> /// Returns the Display name for this framework /// </summary> public string DisplayName { get; private set; } #endregion #region Public Methods /// <summary> /// Parses a string representing a RuntimeFramework. /// The string may be just a RuntimeType name or just /// a Version or a hyphenated RuntimeType-Version or /// a Version prefixed by 'versionString'. /// </summary> /// <param name="s"></param> /// <returns></returns> public static RuntimeFramework Parse(string s) { RuntimeType runtime = RuntimeType.Any; Version version = DefaultVersion; string[] parts = s.Split('-'); if (parts.Length == 2) { runtime = ParseRuntimeType(parts[0]); string vstring = parts[1]; if (vstring != "") { version = new Version(vstring); if (runtime == RuntimeType.NetFramework && version.Major >= 5) runtime = RuntimeType.NetCore; } } else if (s.StartsWith("v", StringComparison.OrdinalIgnoreCase)) { version = new Version(s.Substring(1)); } else if (IsRuntimeTypeName(s)) { runtime = ParseRuntimeType(s); } else { version = new Version(s); } return new RuntimeFramework(runtime, version); } /// <summary> /// Overridden to return the short name of the framework /// </summary> /// <returns></returns> public override string ToString() { if (AllowAnyVersion) { return GetShortName(Runtime, FrameworkVersion).ToLowerInvariant(); } else { string vstring = FrameworkVersion.ToString(); if (Runtime == RuntimeType.Any) return "v" + vstring; else return GetShortName(Runtime, FrameworkVersion).ToLowerInvariant() + "-" + vstring; } } /// <summary> /// Returns true if the current framework matches the /// one supplied as an argument. Two frameworks match /// if their runtime types are the same or either one /// is RuntimeType.Any and all specified version components /// are equal. Negative (i.e. unspecified) version /// components are ignored. /// </summary> /// <param name="target">The RuntimeFramework to be matched.</param> /// <returns>True on match, otherwise false</returns> public bool Supports(RuntimeFramework target) { if (Runtime != RuntimeType.Any && target.Runtime != RuntimeType.Any && Runtime != target.Runtime) return false; if (AllowAnyVersion || target.AllowAnyVersion) return true; if (!VersionsMatch(ClrVersion, target.ClrVersion)) return false; if (FrameworkVersion.Major > target.FrameworkVersion.Major) return true; return FrameworkVersion.Major == target.FrameworkVersion.Major && FrameworkVersion.Minor >= target.FrameworkVersion.Minor; } #endregion #region Helper Methods private static bool IsNetCore() { if (Environment.Version.Major >= 5) return true; #if NETSTANDARD2_0 // Mono versions will throw a TypeLoadException when attempting to run the internal method, so we wrap it in a try/catch // block to stop any inlining in release builds and check whether the type exists Type runtimeInfoType = Type.GetType("System.Runtime.InteropServices.RuntimeInformation,System.Runtime.InteropServices.RuntimeInformation", false); if (runtimeInfoType != null) { try { return IsNetCore_Internal(); } catch (TypeLoadException) { } } #endif return false; } #if NETSTANDARD2_0 [MethodImpl(MethodImplOptions.NoInlining)] private static bool IsNetCore_Internal() { // Mono versions will throw a TypeLoadException when attempting to run any method that uses RuntimeInformation // so we wrap it in a try/catch block in IsNetCore to catch it in case it ever gets this far if (System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase)) { return true; } return false; } #endif private static RuntimeType ParseRuntimeType(string s) { if (s.ToLowerInvariant() == "net") s = "NetFramework"; return (RuntimeType)Enum.Parse(typeof(RuntimeType), s, true); } private static bool IsRuntimeTypeName(string name) => name.ToLowerInvariant() == "net" || Enum.GetNames(typeof(RuntimeType)).Contains(name, StringComparer.OrdinalIgnoreCase); private static string GetShortName(RuntimeType runtime, Version version) { return runtime == RuntimeType.NetFramework || (runtime == RuntimeType.NetCore && version.Major >= 5) ? "Net" : runtime.ToString(); } private static string GetDefaultDisplayName(RuntimeType runtime, Version version) { if (version == DefaultVersion) return GetShortName(runtime, version); else if (runtime == RuntimeType.Any) return "v" + version; else return GetShortName(runtime, version) + " " + version; } private static bool VersionsMatch(Version v1, Version v2) { return v1.Major == v2.Major && v1.Minor == v2.Minor && (v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) && (v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision); } #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. /*============================================================ ** ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Security; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct IntPtr : IEquatable<IntPtr>, ISerializable { unsafe private void* _value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior. Do not rename (binary serialization) public static readonly IntPtr Zero; // fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access [Pure] internal unsafe bool IsNull() { return (_value == null); } [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(int value) { #if BIT64 _value = (void*)(long)value; #else // !BIT64 (32) _value = (void *)value; #endif } [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(long value) { #if BIT64 _value = (void*)value; #else // !BIT64 (32) _value = (void *)checked((int)value); #endif } [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(void* value) { _value = value; } private unsafe IntPtr(SerializationInfo info, StreamingContext context) { long l = info.GetInt64("value"); if (Size == 4 && (l > Int32.MaxValue || l < Int32.MinValue)) { throw new ArgumentException(SR.Serialization_InvalidPtrValue); } _value = (void*)l; } unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); #if BIT64 info.AddValue("value", (long)(_value)); #else // !BIT64 (32) info.AddValue("value", (long)((int)_value)); #endif } public unsafe override bool Equals(Object obj) { if (obj is IntPtr) { return (_value == ((IntPtr)obj)._value); } return false; } unsafe bool IEquatable<IntPtr>.Equals(IntPtr other) { return _value == other._value; } public unsafe override int GetHashCode() { #if BIT64 long l = (long)_value; return (unchecked((int)l) ^ (int)(l >> 32)); #else // !BIT64 (32) return unchecked((int)_value); #endif } [System.Runtime.Versioning.NonVersionable] public unsafe int ToInt32() { #if BIT64 long l = (long)_value; return checked((int)l); #else // !BIT64 (32) return (int)_value; #endif } [System.Runtime.Versioning.NonVersionable] public unsafe long ToInt64() { #if BIT64 return (long)_value; #else // !BIT64 (32) return (long)(int)_value; #endif } public unsafe override String ToString() { #if BIT64 return ((long)_value).ToString(CultureInfo.InvariantCulture); #else // !BIT64 (32) return ((int)_value).ToString(CultureInfo.InvariantCulture); #endif } public unsafe String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); #if BIT64 return ((long)_value).ToString(format, CultureInfo.InvariantCulture); #else // !BIT64 (32) return ((int)_value).ToString(format, CultureInfo.InvariantCulture); #endif } [System.Runtime.Versioning.NonVersionable] public static explicit operator IntPtr(int value) { return new IntPtr(value); } [System.Runtime.Versioning.NonVersionable] public static explicit operator IntPtr(long value) { return new IntPtr(value); } [CLSCompliant(false), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator IntPtr(void* value) { return new IntPtr(value); } [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator void* (IntPtr value) { return value._value; } [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator int(IntPtr value) { #if BIT64 long l = (long)value._value; return checked((int)l); #else // !BIT64 (32) return (int)value._value; #endif } [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator long(IntPtr value) { #if BIT64 return (long)value._value; #else // !BIT64 (32) return (long)(int)value._value; #endif } [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator ==(IntPtr value1, IntPtr value2) { return value1._value == value2._value; } [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator !=(IntPtr value1, IntPtr value2) { return value1._value != value2._value; } [System.Runtime.Versioning.NonVersionable] public static IntPtr Add(IntPtr pointer, int offset) { return pointer + offset; } [System.Runtime.Versioning.NonVersionable] public static IntPtr operator +(IntPtr pointer, int offset) { #if BIT64 return new IntPtr(pointer.ToInt64() + offset); #else // !BIT64 (32) return new IntPtr(pointer.ToInt32() + offset); #endif } [System.Runtime.Versioning.NonVersionable] public static IntPtr Subtract(IntPtr pointer, int offset) { return pointer - offset; } [System.Runtime.Versioning.NonVersionable] public static IntPtr operator -(IntPtr pointer, int offset) { #if BIT64 return new IntPtr(pointer.ToInt64() - offset); #else // !BIT64 (32) return new IntPtr(pointer.ToInt32() - offset); #endif } public static int Size { [Pure] [System.Runtime.Versioning.NonVersionable] get { #if BIT64 return 8; #else // !BIT64 (32) return 4; #endif } } [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public unsafe void* ToPointer() { return _value; } } }
/* * Copyright (c) 2009 Jim Radford http://www.jimradford.com * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; using System.Net; using Microsoft.Win32; using WeifenLuo.WinFormsUI.Docking; using log4net; using System.Xml.Serialization; using System.IO; using System.Collections; using System.Reflection; using SuperPutty.Utils; namespace SuperPutty.Data { public enum ConnectionProtocol { SSH, SSH2, Telnet, Rlogin, Raw, Serial, Cygterm, Mintty } /// <summary>The main class containing configuration settings for a session</summary> public class SessionData : IComparable, ICloneable { private static readonly ILog Log = LogManager.GetLogger(typeof(SessionData)); /// <summary>Full session id (includes path for session tree)e.g. FolderName/SessionName</summary> private string _SessionId; [XmlAttribute] public string SessionId { get { return this._SessionId; } set { this.OldSessionId = SessionId; this._SessionId = value; } } internal string OldSessionId { get; set; } private string _OldName; [XmlIgnore] public string OldName { get { return _OldName; } set { _OldName = value; } } private string _SessionName; [XmlAttribute] public string SessionName { get { return _SessionName; } set { OldName = _SessionName; _SessionName = value; if (SessionId == null) { SessionId = value; } } } private string _ImageKey; /// <summary>A string containing the key of the image associated with this session</summary> [XmlAttribute] public string ImageKey { get { return _ImageKey; } set { _ImageKey = value; } } private string _Host; [XmlAttribute] public string Host { get { return _Host; } set { _Host = value; } } private int _Port; [XmlAttribute] public int Port { get { return _Port; } set { _Port = value; } } private ConnectionProtocol _Proto; [XmlAttribute] public ConnectionProtocol Proto { get { return _Proto; } set { _Proto = value; } } private string _PuttySession; [XmlAttribute] public string PuttySession { get { return _PuttySession; } set { _PuttySession = value; } } private string _Username; [XmlAttribute] public string Username { get { return _Username; } set { _Username = value; } } private string _Password; [XmlIgnore] public string Password { get { if (String.IsNullOrEmpty(_Password)){ // search if ExtraArgs contains the password _Password = CommandLineOptions.getcommand(this.ExtraArgs, "-pw"); } return _Password; } set { _Password = value; } } private string _ExtraArgs; [XmlAttribute] public string ExtraArgs { get { return _ExtraArgs; } set { _ExtraArgs = value; } } private string _RemotePath; [XmlAttribute] public string RemotePath { get { return _RemotePath; } set { _RemotePath = value; } } private string _LocalPath; [XmlAttribute] public string LocalPath { get { return _LocalPath; } set { _LocalPath = value; } } private DockState m_LastDockstate = DockState.Document; [XmlIgnore] public DockState LastDockstate { get { return m_LastDockstate; } set { m_LastDockstate = value; } } private bool m_AutoStartSession = false; [XmlIgnore] public bool AutoStartSession { get { return m_AutoStartSession; } set { m_AutoStartSession = value; } } /// <summary>Construct a new session data object</summary> /// <param name="sessionName">A string representing the name of the session</param> /// <param name="hostName">The hostname or ip address of the remote host</param> /// <param name="port">The port on the remote host</param> /// <param name="protocol">The protocol to use when connecting to the remote host</param> /// <param name="sessionConfig">the name of the saved configuration settings from putty to use</param> public SessionData(string sessionName, string hostName, int port, ConnectionProtocol protocol, string sessionConfig) { SessionName = sessionName; Host = hostName; Port = port; Proto = protocol; PuttySession = sessionConfig; } /// <summary>Default constructor, instantiate a new <seealso cref="SessionData"/> object</summary> public SessionData() { } /// <summary>Read any existing saved sessions from the registry, decode and populate a list containing the data</summary> /// <returns>A list containing the configuration entries retrieved from the registry</returns> public static List<SessionData> LoadSessionsFromRegistry() { Log.Info("LoadSessionsFromRegistry..."); List<SessionData> sessionList = new List<SessionData>(); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions"); if (key != null) { string[] sessionKeys = key.GetSubKeyNames(); foreach (string session in sessionKeys) { SessionData sessionData = new SessionData(); RegistryKey itemKey = key.OpenSubKey(session); if (itemKey != null) { sessionData.Host = (string)itemKey.GetValue("Host", ""); sessionData.Port = (int)itemKey.GetValue("Port", 22); sessionData.Proto = (ConnectionProtocol)Enum.Parse(typeof(ConnectionProtocol), (string)itemKey.GetValue("Proto", "SSH")); sessionData.PuttySession = (string)itemKey.GetValue("PuttySession", "Default Session"); sessionData.SessionName = session; sessionData.SessionId = (string)itemKey.GetValue("SessionId", session); sessionData.Username = (string)itemKey.GetValue("Login", ""); sessionData.LastDockstate = (DockState)itemKey.GetValue("Last Dock", DockState.Document); sessionData.AutoStartSession = bool.Parse((string)itemKey.GetValue("Auto Start", "False")); sessionData.RemotePath = (string)itemKey.GetValue("RemotePath", ""); sessionData.LocalPath = (string)itemKey.GetValue("LocalPath", ""); sessionList.Add(sessionData); } } } return sessionList; } /// <summary>Load session configuration data from the specified XML file</summary> /// <param name="fileName">The filename containing the settings</param> /// <returns>A <seealso cref="List"/> containing the session configuration data</returns> public static List<SessionData> LoadSessionsFromFile(string fileName) { List<SessionData> sessions = new List<SessionData>(); if (File.Exists(fileName)) { WorkaroundCygwinBug(); XmlSerializer s = new XmlSerializer(sessions.GetType()); using (TextReader r = new StreamReader(fileName)) { sessions = (List<SessionData>)s.Deserialize(r); } Log.InfoFormat("Loaded {0} sessions from {1}", sessions.Count, fileName); } else { Log.WarnFormat("Could not load sessions, file doesn't exist. file={0}", fileName); } return sessions; } static void WorkaroundCygwinBug() { try { // work around known bug with cygwin Dictionary<string, string> envVars = new Dictionary<string, string>(); foreach (DictionaryEntry de in Environment.GetEnvironmentVariables()) { string envVar = (string) de.Key; if (envVars.ContainsKey(envVar.ToUpper())) { // duplicate found... (e.g. TMP and tmp) Log.DebugFormat("Clearing duplicate envVariable, {0}", envVar); Environment.SetEnvironmentVariable(envVar, null); continue; } envVars.Add(envVar.ToUpper(), envVar); } } catch (Exception ex) { Log.WarnFormat("Error working around cygwin issue: {0}", ex.Message); } } /// <summary>Save session configuration to the specified XML file</summary> /// <param name="sessions">A <seealso cref="List"/> containing the session configuration data</param> /// <param name="fileName">A path to a filename to save the data in</param> public static void SaveSessionsToFile(List<SessionData> sessions, string fileName) { Log.InfoFormat("Saving {0} sessions to {1}", sessions.Count, fileName); BackUpFiles(fileName, 20); // sort and save file sessions.Sort(); XmlSerializer s = new XmlSerializer(sessions.GetType()); using (TextWriter w = new StreamWriter(fileName)) { s.Serialize(w, sessions); } } private static void BackUpFiles(string fileName, int count) { if (File.Exists(fileName) && count > 0) { try { // backup string fileBaseName = Path.GetFileNameWithoutExtension(fileName); string dirName = Path.GetDirectoryName(fileName); string backupName = Path.Combine(dirName, string.Format("{0}.{1:yyyyMMdd_hhmmss}.XML", fileBaseName, DateTime.Now)); File.Copy(fileName, backupName, true); // limit last count saves List<string> oldFiles = new List<string>(Directory.GetFiles(dirName, fileBaseName + ".*.XML")); oldFiles.Sort(); oldFiles.Reverse(); if (oldFiles.Count > count) { for (int i = 20; i < oldFiles.Count; i++) { Log.InfoFormat("Cleaning up old file, {0}", oldFiles[i]); File.Delete(oldFiles[i]); } } } catch (Exception ex) { Log.Error("Error backing up files", ex); } } } public int CompareTo(object obj) { SessionData s = obj as SessionData; return s == null ? 1 : this.SessionId.CompareTo(s.SessionId); } public static string CombineSessionIds(string parent, string child) { if (parent == null && child == null) { return null; } else if (child == null) { return parent; } else if (parent == null) { return child; } else { return parent + "/" + child; } } public static string GetSessionNameFromId(string sessionId) { string[] parts = GetSessionNameParts(sessionId); return parts.Length > 0 ? parts[parts.Length - 1] : sessionId; } /// <summary>Split the SessionID into its parent/child parts</summary> /// <param name="sessionId">The SessionID</param> /// <returns>A string array containing the individual path components</returns> public static string[] GetSessionNameParts(string sessionId) { return sessionId.Split('/'); } /// <summary>Get the parent ID of the specified session</summary> /// <param name="sessionId">the ID of the session</param> /// <returns>A string containing the parent sessions ID</returns> public static string GetSessionParentId(string sessionId) { string parentPath = null; if (sessionId != null) { int idx = sessionId.LastIndexOf('/'); if (idx != -1) { parentPath = sessionId.Substring(0, idx); } } return parentPath; } /// <summary>Create a deep copy of the SessionData object</summary> /// <returns>A clone of the <seealso cref="SessionData"/> object</returns> public object Clone() { SessionData session = new SessionData(); foreach (PropertyInfo pi in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (pi.CanWrite) { pi.SetValue(session, pi.GetValue(this, null), null); } } return session; } /// <summary>Return a string containing a uri to the protocol://host:port of this sesssions defined host</summary> /// <returns>A string in uri format containing connection information to this sessions host</returns> public override string ToString() { if (this.Proto == ConnectionProtocol.Cygterm || this.Proto == ConnectionProtocol.Mintty) { return string.Format("{0}://{1}", this.Proto.ToString().ToLower(), this.Host); } else { return string.Format("{0}://{1}:{2}", this.Proto.ToString().ToLower(), this.Host, this.Port); } } } }
//========================================================================= // Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved. // This product is protected by U.S. and international copyright // and intellectual property laws. Pivotal products are covered by // more patents listed at http://www.pivotal.io/patents. //======================================================================== using System; using System.Collections.Generic; using System.Collections; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; using Region = Apache.Geode.Client.IRegion<Object, Object>; public class MyAppDomainResultCollector<TResult> : IResultCollector<TResult> { #region Private members private bool m_resultReady = false; ICollection<TResult> m_results = null; private int m_addResultCount = 0; private int m_getResultCount = 0; private int m_endResultCount = 0; #endregion public int GetAddResultCount() { return m_addResultCount; } public int GetGetResultCount() { return m_getResultCount; } public int GetEndResultCount() { return m_endResultCount; } public MyAppDomainResultCollector() { m_results = new List<TResult>(); } public void AddResult(TResult result) { Util.Log("MyAppDomainResultCollector " + result + " : " + result.GetType()); m_addResultCount++; m_results.Add(result); } public ICollection<TResult> GetResult() { return GetResult(50); } public ICollection<TResult> GetResult(UInt32 timeout) { m_getResultCount++; if (m_resultReady == true) { return m_results; } else { for (int i = 0; i < timeout; i++) { Thread.Sleep(1000); if (m_resultReady == true) { return m_results; } } throw new FunctionExecutionException( "Result is not ready, endResults callback is called before invoking getResult() method"); } } public void EndResults() { m_endResultCount++; m_resultReady = true; } public void ClearResults(/*bool unused*/) { m_results.Clear(); m_addResultCount = 0; m_getResultCount = 0; m_endResultCount = 0; } } [TestFixture] [Category("group3")] [Category("unicast_only")] [Category("generics")] public class ThinClientAppDomainFunctionExecutionTests : ThinClientRegionSteps { #region Private members private static string[] FunctionExecutionRegionNames = { "partition_region", "partition_region1" }; private static string poolName = "__TEST_POOL1__"; private static string serverGroup = "ServerGroup1"; private static string QERegionName = "partition_region"; private static string OnServerHAExceptionFunction = "OnServerHAExceptionFunction"; private static string OnServerHAShutdownFunction = "OnServerHAShutdownFunction"; #endregion protected override ClientBase[] GetClients() { return new ClientBase[] { }; } [TestFixtureSetUp] public override void InitTests() { Util.Log("InitTests: AppDomain: " + AppDomain.CurrentDomain.Id); Properties<string, string> config = new Properties<string, string>(); config.Insert("appdomain-enabled", "true"); CacheHelper.InitConfig(config); } [TearDown] public override void EndTest() { Util.Log("EndTest: AppDomain: " + AppDomain.CurrentDomain.Id); try { CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } finally { CacheHelper.StopJavaServers(); CacheHelper.StopJavaLocators(); } base.EndTest(); } public void createRegionAndAttachPool(string regionName, string poolName) { CacheHelper.CreateTCRegion_Pool<object, object>(regionName, true, true, null, null, poolName, false, serverGroup); } public void createPool(string name, string locators, string serverGroup, int redundancy, bool subscription, bool prSingleHop, bool threadLocal = false) { CacheHelper.CreatePool<object, object>(name, locators, serverGroup, redundancy, subscription, prSingleHop, threadLocal); } public void OnServerHAStepOne() { Region region = CacheHelper.GetVerifyRegion<object, object>(QERegionName); for (int i = 0; i < 34; i++) { region["KEY--" + i] = "VALUE--" + i; } object[] routingObj = new object[17]; ArrayList args1 = new ArrayList(); int j = 0; for (int i = 0; i < 34; i++) { if (i % 2 == 0) continue; routingObj[j] = "KEY--" + i; j++; } Util.Log("routingObj count= {0}.", routingObj.Length); for (int i = 0; i < routingObj.Length; i++) { Console.WriteLine("routingObj[{0}]={1}.", i, (string)routingObj[i]); args1.Add(routingObj[i]); } Boolean getResult = true; //test data independant function execution with result onServer Pool/*<TKey, TValue>*/ pool = PoolManager/*<TKey, TValue>*/.Find(poolName); Apache.Geode.Client.Execution<object> exc = FunctionService<object>.OnServer(pool); Assert.IsTrue(exc != null, "onServer Returned NULL"); IResultCollector<object> rc = exc.WithArgs<ArrayList>(args1).Execute(OnServerHAExceptionFunction, 15); ICollection<object> executeFunctionResult = rc.GetResult(); List<object> resultList = new List<object>(); Console.WriteLine("executeFunctionResult.Length = {0}", executeFunctionResult.Count); foreach (List<object> item in executeFunctionResult) { foreach (object item2 in item) { resultList.Add(item2); } } Util.Log("on region: result count= {0}.", resultList.Count); Assert.IsTrue(resultList.Count == 17, "result count check failed"); for (int i = 0; i < resultList.Count; i++) { Util.Log("on region:get:result[{0}]={1}.", i, (string)resultList[i]); Assert.IsTrue(((string)resultList[i]) != null, "onServer Returned NULL"); } rc = exc.WithArgs<ArrayList>(args1).Execute(OnServerHAShutdownFunction, 15); ICollection<object> executeFunctionResult1 = rc.GetResult(); List<object> resultList1 = new List<object>(); foreach (List<object> item in executeFunctionResult1) { foreach (object item2 in item) { resultList1.Add(item2); } } Util.Log("on region: result count= {0}.", resultList1.Count); Console.WriteLine("resultList1.Count = {0}", resultList1.Count); Assert.IsTrue(resultList1.Count == 17, "result count check failed"); for (int i = 0; i < resultList1.Count; i++) { Util.Log("on region:get:result[{0}]={1}.", i, (string)resultList1[i]); Assert.IsTrue(((string)resultList1[i]) != null, "onServer Returned NULL"); } // Bring down the region //region.LocalDestroyRegion(); } [Test] public void OnServerHAExecuteFunction() { Util.Log("OnServerHAExecuteFunction: AppDomain: " + AppDomain.CurrentDomain.Id); CacheHelper.SetupJavaServers(true, "func_cacheserver1_pool.xml", "func_cacheserver2_pool.xml", "func_cacheserver3_pool.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1); Util.Log("Cacheserver 2 started."); CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1); Util.Log("Cacheserver 3 started."); createPool(poolName, CacheHelper.Locators, serverGroup, 1, true, true, /*threadLocal*/true); createRegionAndAttachPool(QERegionName, poolName); Util.Log("Client 1 (pool locator) regions created"); OnServerHAStepOne(); Close(); Util.Log("Client 1 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); CacheHelper.StopJavaServer(3); Util.Log("Cacheserver 3 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Pkcs.Tests { public static partial class SignerInfoTests { private const string TokenAttributeOid = "1.2.840.113549.1.9.16.2.14"; [Fact] public static void SignerInfo_AddUnsignedAttribute_Adds() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Equal(0, cms.SignerInfos[0].UnsignedAttributes.Count); AsnEncodedData attribute1 = CreateTimestampToken(1); cms.SignerInfos[0].AddUnsignedAttribute(attribute1); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); VerifyAttributesAreEqual(cms.SignerInfos[0].UnsignedAttributes[0].Values[0], attribute1); ReReadSignedCms(ref cms); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); VerifyAttributesAreEqual(cms.SignerInfos[0].UnsignedAttributes[0].Values[0], attribute1); AsnEncodedData attribute2 = CreateTimestampToken(2); cms.SignerInfos[0].AddUnsignedAttribute(attribute2); var expectedAttributes = new List<AsnEncodedData>(); expectedAttributes.Add(attribute1); expectedAttributes.Add(attribute2); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); VerifyAttributesContainsAll(cms.SignerInfos[0].UnsignedAttributes, expectedAttributes); ReReadSignedCms(ref cms); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); VerifyAttributesContainsAll(cms.SignerInfos[0].UnsignedAttributes, expectedAttributes); } [Fact] public static void SignerInfo_RemoveUnsignedAttribute_RemoveCounterSignature() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(2, cms.SignerInfos[0].CounterSignerInfos.Count); byte[] secondSignerCounterSignature = cms.SignerInfos[0].CounterSignerInfos[1].GetSignature(); cms.SignerInfos[0].RemoveUnsignedAttribute(cms.SignerInfos[0].UnsignedAttributes[0].Values[0]); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(1, cms.SignerInfos[0].CounterSignerInfos.Count); Assert.Equal(secondSignerCounterSignature, cms.SignerInfos[0].CounterSignerInfos[0].GetSignature()); ReReadSignedCms(ref cms); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(1, cms.SignerInfos[0].CounterSignerInfos.Count); Assert.Equal(secondSignerCounterSignature, cms.SignerInfos[0].CounterSignerInfos[0].GetSignature()); } [Theory] [MemberData(nameof(SignedDocumentsWithAttributesTestData))] public static void SignerInfo_RemoveUnsignedAttributes_RemoveAllAttributesFromBeginning(byte[] document) { SignedCms cms = new SignedCms(); cms.Decode(document); List<AsnEncodedData> attributes = GetAllAsnEncodedDataFromAttributes(cms.SignerInfos[0].UnsignedAttributes); Assert.True(attributes.Count > 0); for (int i = 0; i < attributes.Count; i++) { AsnEncodedData attribute = attributes[i]; cms.SignerInfos[0].RemoveUnsignedAttribute(attribute); attributes.RemoveAt(0); VerifyAttributesContainsAll(cms.SignerInfos[0].UnsignedAttributes, attributes); ReReadSignedCms(ref cms); VerifyAttributesContainsAll(cms.SignerInfos[0].UnsignedAttributes, attributes); } } [Theory] [MemberData(nameof(SignedDocumentsWithAttributesTestData))] public static void SignerInfo_RemoveUnsignedAttributes_RemoveAllAttributesFromEnd(byte[] document) { SignedCms cms = new SignedCms(); cms.Decode(document); List<AsnEncodedData> attributes = GetAllAsnEncodedDataFromAttributes(cms.SignerInfos[0].UnsignedAttributes); Assert.True(attributes.Count > 0); for (int i = attributes.Count - 1; i >= 0; i--) { AsnEncodedData attribute = attributes[i]; cms.SignerInfos[0].RemoveUnsignedAttribute(attribute); attributes.RemoveAt(i); VerifyAttributesContainsAll(cms.SignerInfos[0].UnsignedAttributes, attributes); ReReadSignedCms(ref cms); VerifyAttributesContainsAll(cms.SignerInfos[0].UnsignedAttributes, attributes); } } [Fact] public static void SignerInfo_RemoveUnsignedAttributes_RemoveWithNonMatchingOid() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); int numberOfAttributes = cms.SignerInfos[0].UnsignedAttributes.Count; Assert.NotEqual(0, numberOfAttributes); AsnEncodedData fakeAttribute = new AsnEncodedData(new Oid("1.2.3.4", "1.2.3.4"), cms.SignerInfos[0].UnsignedAttributes[0].Values[0].RawData); Assert.Throws<CryptographicException>(() => cms.SignerInfos[0].RemoveUnsignedAttribute(fakeAttribute)); Assert.Equal(numberOfAttributes, cms.SignerInfos[0].UnsignedAttributes.Count); } [Fact] public static void SignerInfo_RemoveUnsignedAttributes_RemoveWithNonMatchingData() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); int numberOfAttributes = cms.SignerInfos[0].UnsignedAttributes.Count; Assert.NotEqual(0, numberOfAttributes); AsnEncodedData fakeAttribute = new AsnEncodedData( cms.SignerInfos[0].UnsignedAttributes[0].Oid, cms.SignerInfos[0].UnsignedAttributes[0].Values[0].RawData.Skip(1).ToArray()); Assert.Throws<CryptographicException>(() => cms.SignerInfos[0].RemoveUnsignedAttribute(fakeAttribute)); Assert.Equal(numberOfAttributes, cms.SignerInfos[0].UnsignedAttributes.Count); } [Fact] public static void SignerInfo_RemoveUnsignedAttributes_MultipleAttributeValues() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Equal(0, cms.SignerInfos[0].UnsignedAttributes.Count); AsnEncodedData attribute1 = CreateTimestampToken(1); AsnEncodedData attribute2 = CreateTimestampToken(2); cms.SignerInfos[0].AddUnsignedAttribute(attribute1); cms.SignerInfos[0].AddUnsignedAttribute(attribute2); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); cms.SignerInfos[0].RemoveUnsignedAttribute(attribute1); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); Assert.True(AsnEncodedDataEqual(attribute2, cms.SignerInfos[0].UnsignedAttributes[0].Values[0])); cms.SignerInfos[0].RemoveUnsignedAttribute(attribute2); Assert.Equal(0, cms.SignerInfos[0].UnsignedAttributes.Count); } [Fact] public static void SignerInfo_AddRemoveUnsignedAttributes_JoinCounterSignaturesAttributesIntoOne() { byte[] message = { 1, 2, 3, 4, 5 }; ContentInfo content = new ContentInfo(message); SignedCms cms = new SignedCms(content); using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert); cms.ComputeSignature(signer); } using (X509Certificate2 counterSigner1cert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey()) { CmsSigner counterSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner1cert); counterSigner.IncludeOption = X509IncludeOption.EndCertOnly; counterSigner.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1); cms.SignerInfos[0].ComputeCounterSignature(counterSigner); } using (X509Certificate2 counterSigner2cert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey()) { CmsSigner counterSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner2cert); cms.SignerInfos[0].ComputeCounterSignature(counterSigner); } Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[1].Values.Count); cms.CheckSignature(true); AsnEncodedData counterSignature = cms.SignerInfos[0].UnsignedAttributes[0].Values[0]; cms.SignerInfos[0].RemoveUnsignedAttribute(counterSignature); cms.SignerInfos[0].AddUnsignedAttribute(counterSignature); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); cms.CheckSignature(true); } private static void VerifyAttributesContainsAll(CryptographicAttributeObjectCollection attributes, List<AsnEncodedData> expectedAttributes) { var indices = new HashSet<int>(); foreach (CryptographicAttributeObject attribute in attributes) { foreach (AsnEncodedData attributeValue in attribute.Values) { int idx = FindAsnEncodedData(expectedAttributes, attributeValue); Assert.NotEqual(-1, idx); indices.Add(idx); } } Assert.Equal(expectedAttributes.Count, indices.Count); } private static int FindAsnEncodedData(List<AsnEncodedData> array, AsnEncodedData data) { for (int i = 0; i < array.Count; i++) { if (AsnEncodedDataEqual(array[i], data)) { return i; } } return -1; } private static List<AsnEncodedData> GetAllAsnEncodedDataFromAttributes(CryptographicAttributeObjectCollection attributes) { var ret = new List<AsnEncodedData>(); foreach (CryptographicAttributeObject attribute in attributes) { foreach (AsnEncodedData attributeValue in attribute.Values) { ret.Add(attributeValue); } } return ret; } private static bool AsnEncodedDataEqual(AsnEncodedData a, AsnEncodedData b) { return a.Oid.Value == b.Oid.Value && a.RawData.SequenceEqual(b.RawData); } private static void ReReadSignedCms(ref SignedCms cms) { byte[] bytes = cms.Encode(); cms = new SignedCms(); cms.Decode(bytes); } private static AsnEncodedData CreateTimestampToken(byte serial) { Oid tokenOid = new Oid(TokenAttributeOid, TokenAttributeOid); Oid policyId = new Oid("0.0", "0.0"); Oid hashAlgorithmId = new Oid(Oids.Sha256); var tokenInfo = new Rfc3161TimestampTokenInfo( policyId, hashAlgorithmId, new byte[256 / 8], new byte[] { (byte)serial }, DateTimeOffset.UtcNow); return new AsnEncodedData(tokenOid, tokenInfo.Encode()); } private static void VerifyAttributesAreEqual(AsnEncodedData actual, AsnEncodedData expected) { Assert.NotSame(expected.Oid, actual.Oid); Assert.Equal(expected.Oid.Value, actual.Oid.Value); // We need to decode bytes because DER and BER may encode the same information slightly differently Rfc3161TimestampTokenInfo expectedToken; Assert.True(Rfc3161TimestampTokenInfo.TryDecode(expected.RawData, out expectedToken, out _)); Rfc3161TimestampTokenInfo actualToken; Assert.True(Rfc3161TimestampTokenInfo.TryDecode(actual.RawData, out actualToken, out _)); Assert.Equal(expectedToken.GetSerialNumber().ByteArrayToHex(), actualToken.GetSerialNumber().ByteArrayToHex()); Assert.Equal(expectedToken.Timestamp, actualToken.Timestamp); Assert.Equal(expectedToken.HashAlgorithmId.Value, Oids.Sha256); Assert.Equal(expectedToken.HashAlgorithmId.Value, actualToken.HashAlgorithmId.Value); } private static IEnumerable<object[]> SignedDocumentsWithAttributesTestData() { yield return new object[] { SignedDocuments.CounterSignedRsaPkcs1OneSigner }; yield return new object[] { SignedDocuments.NoSignatureSignedWithAttributesAndCounterSignature }; yield return new object[] { SignedDocuments.OneRsaSignerTwoRsaCounterSigners }; yield return new object[] { SignedDocuments.RsaPkcs1CounterSignedWithNoSignature }; yield return new object[] { SignedDocuments.UnsortedSignerInfos}; } } }
using System; using System.Collections.Generic; using System.Linq; using Content.Client.Alerts.UI; using Content.Client.Chat.Managers; using Content.Client.Resources; using Content.Client.Stylesheets; using Content.Shared.Chat; using Content.Shared.Input; using Robust.Client.AutoGenerated; using Robust.Client.ResourceManagement; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.XAML; using Robust.Shared.Input; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Utility; namespace Content.Client.Chat.UI { [GenerateTypedNameReferences] [Virtual] public partial class ChatBox : Control { [Dependency] protected readonly IChatManager ChatMgr = default!; // order in which the available channel filters show up when available private static readonly ChatChannel[] ChannelFilterOrder = { ChatChannel.Local, ChatChannel.Whisper, ChatChannel.Emotes, ChatChannel.Radio, ChatChannel.OOC, ChatChannel.Dead, ChatChannel.Admin, ChatChannel.Server }; // order in which the channels show up in the channel selector private static readonly ChatSelectChannel[] ChannelSelectorOrder = { ChatSelectChannel.Local, ChatSelectChannel.Whisper, ChatSelectChannel.Emotes, ChatSelectChannel.Radio, ChatSelectChannel.LOOC, ChatSelectChannel.OOC, ChatSelectChannel.Dead, ChatSelectChannel.Admin // NOTE: Console is not in there and it can never be permanently selected. // You can, however, still submit commands as console by prefixing with /. }; public const char AliasLocal = '.'; public const char AliasConsole = '/'; public const char AliasDead = '\\'; public const char AliasOOC = '['; public const char AliasEmotes = '@'; public const char AliasAdmin = ']'; public const char AliasRadio = ';'; public const char AliasWhisper = ','; private static readonly Dictionary<char, ChatSelectChannel> PrefixToChannel = new() { {AliasLocal, ChatSelectChannel.Local}, {AliasWhisper, ChatSelectChannel.Whisper}, {AliasConsole, ChatSelectChannel.Console}, {AliasOOC, ChatSelectChannel.OOC}, {AliasEmotes, ChatSelectChannel.Emotes}, {AliasAdmin, ChatSelectChannel.Admin}, {AliasRadio, ChatSelectChannel.Radio}, {AliasDead, ChatSelectChannel.Dead} }; private static readonly Dictionary<ChatSelectChannel, char> ChannelPrefixes = PrefixToChannel.ToDictionary(kv => kv.Value, kv => kv.Key); private const float FilterPopupWidth = 110; /// <summary> /// The currently default channel that will be used if no prefix is specified. /// </summary> public ChatSelectChannel SelectedChannel { get; private set; } = ChatSelectChannel.OOC; /// <summary> /// The "preferred" channel. Will be switched to if permissions change and the channel becomes available, /// such as by re-entering body. Gets changed if the user manually selects a channel with the buttons. /// </summary> public ChatSelectChannel PreferredChannel { get; set; } = ChatSelectChannel.OOC; public bool ReleaseFocusOnEnter { get; set; } = true; private readonly Popup _channelSelectorPopup; private readonly BoxContainer _channelSelectorHBox; private readonly Popup _filterPopup; private readonly PanelContainer _filterPopupPanel; private readonly BoxContainer _filterVBox; /// <summary> /// When lobbyMode is false, will position / add to correct location in StateRoot and /// be resizable. /// wWen true, will leave layout up to parent and not be resizable. /// </summary> public ChatBox() { IoCManager.InjectDependencies(this); RobustXamlLoader.Load(this); LayoutContainer.SetMarginLeft(this, 4); LayoutContainer.SetMarginRight(this, 4); _filterPopup = new Popup { Children = { (_filterPopupPanel = new PanelContainer { StyleClasses = {StyleNano.StyleClassBorderedWindowPanel}, Children = { new BoxContainer { Orientation = BoxContainer.LayoutOrientation.Horizontal, Children = { new Control {MinSize = (4, 0)}, (_filterVBox = new BoxContainer { Margin = new Thickness(0, 10), Orientation = BoxContainer.LayoutOrientation.Vertical, SeparationOverride = 4 }) } } } }) } }; _channelSelectorPopup = new Popup { Children = { (_channelSelectorHBox = new BoxContainer { Orientation = BoxContainer.LayoutOrientation.Horizontal, SeparationOverride = 1 }) } }; ChannelSelector.OnToggled += OnChannelSelectorToggled; FilterButton.OnToggled += OnFilterButtonToggled; Input.OnKeyBindDown += InputKeyBindDown; Input.OnTextEntered += Input_OnTextEntered; Input.OnTextChanged += InputOnTextChanged; _channelSelectorPopup.OnPopupHide += OnChannelSelectorPopupHide; _filterPopup.OnPopupHide += OnFilterPopupHide; } protected override void EnteredTree() { base.EnteredTree(); ChatMgr.MessageAdded += WriteChatMessage; ChatMgr.ChatPermissionsUpdated += OnChatPermissionsUpdated; ChatMgr.UnreadMessageCountsUpdated += UpdateUnreadMessageCounts; ChatMgr.FiltersUpdated += Repopulate; // The chat manager may have messages logged from before there was a chat box. // In this case, these messages will be marked as unread despite the filters allowing them through. // Tell chat manager to clear these. ChatMgr.ClearUnfilteredUnreads(); ChatPermissionsUpdated(0); UpdateChannelSelectButton(); Repopulate(); } protected override void ExitedTree() { base.ExitedTree(); ChatMgr.MessageAdded -= WriteChatMessage; ChatMgr.ChatPermissionsUpdated -= OnChatPermissionsUpdated; ChatMgr.UnreadMessageCountsUpdated -= UpdateUnreadMessageCounts; ChatMgr.FiltersUpdated -= Repopulate; } private void OnChatPermissionsUpdated(ChatPermissionsUpdatedEventArgs eventArgs) { ChatPermissionsUpdated(eventArgs.OldSelectableChannels); } private void ChatPermissionsUpdated(ChatSelectChannel oldSelectable) { // update the channel selector _channelSelectorHBox.Children.Clear(); foreach (var selectableChannel in ChannelSelectorOrder) { if ((ChatMgr.SelectableChannels & selectableChannel) == 0) continue; var newButton = new ChannelItemButton(selectableChannel); newButton.OnPressed += OnChannelSelectorItemPressed; _channelSelectorHBox.AddChild(newButton); } // Selected channel no longer available, switch to OOC? if ((ChatMgr.SelectableChannels & SelectedChannel) == 0) { // Handle local -> dead mapping when you e.g. ghost. // Only necessary for admins because they always have deadchat // so the normal preferred check won't see it as newly available and do nothing. var mappedSelect = MapLocalIfGhost(SelectedChannel); if ((ChatMgr.SelectableChannels & mappedSelect) != 0) SafelySelectChannel(mappedSelect); else SafelySelectChannel(ChatSelectChannel.OOC); } // If the preferred channel just became available, switch to it. var pref = MapLocalIfGhost(PreferredChannel); if ((oldSelectable & pref) == 0 && (ChatMgr.SelectableChannels & pref) != 0) SafelySelectChannel(pref); // update the channel filters _filterVBox.Children.Clear(); foreach (var channelFilter in ChannelFilterOrder) { if ((ChatMgr.FilterableChannels & channelFilter) == 0) continue; int? unreadCount = null; if (ChatMgr.UnreadMessages.TryGetValue(channelFilter, out var unread)) unreadCount = unread; var newCheckBox = new ChannelFilterCheckbox(channelFilter, unreadCount) { Pressed = (ChatMgr.ChannelFilters & channelFilter) != 0 }; newCheckBox.OnToggled += OnFilterCheckboxToggled; _filterVBox.AddChild(newCheckBox); } UpdateChannelSelectButton(); } private void UpdateUnreadMessageCounts() { foreach (var channelFilter in _filterVBox.Children) { if (channelFilter is not ChannelFilterCheckbox filterCheckbox) continue; if (ChatMgr.UnreadMessages.TryGetValue(filterCheckbox.Channel, out var unread)) { filterCheckbox.UpdateUnreadCount(unread); } else { filterCheckbox.UpdateUnreadCount(null); } } } private void OnFilterCheckboxToggled(BaseButton.ButtonToggledEventArgs args) { if (args.Button is not ChannelFilterCheckbox checkbox) return; ChatMgr.OnFilterButtonToggled(checkbox.Channel, checkbox.Pressed); } private void OnFilterButtonToggled(BaseButton.ButtonToggledEventArgs args) { if (args.Pressed) { var globalPos = FilterButton.GlobalPosition; var (minX, minY) = _filterPopupPanel.MinSize; var box = UIBox2.FromDimensions(globalPos - (FilterPopupWidth, 0), (Math.Max(minX, FilterPopupWidth), minY)); UserInterfaceManager.ModalRoot.AddChild(_filterPopup); _filterPopup.Open(box); } else { _filterPopup.Close(); } } private void OnChannelSelectorToggled(BaseButton.ButtonToggledEventArgs args) { if (args.Pressed) { var globalLeft = GlobalPosition.X; var globalBot = GlobalPosition.Y + Height; var box = UIBox2.FromDimensions((globalLeft, globalBot), (SizeBox.Width, AlertsUI.ChatSeparation)); UserInterfaceManager.ModalRoot.AddChild(_channelSelectorPopup); _channelSelectorPopup.Open(box); } else { _channelSelectorPopup.Close(); } } private void OnFilterPopupHide() { OnPopupHide(_filterPopup, FilterButton); } private void OnChannelSelectorPopupHide() { OnPopupHide(_channelSelectorPopup, ChannelSelector); } private void OnPopupHide(Control popup, BaseButton button) { UserInterfaceManager.ModalRoot.RemoveChild(popup); // this weird check here is because the hiding of the popup happens prior to the button // receiving the keydown, which would cause it to then become unpressed // and reopen immediately. To avoid this, if the popup was hidden due to clicking on the button, // we will not auto-unpress the button, instead leaving it up to the button toggle logic // (and this requires the button to be set to EnableAllKeybinds = true) if (UserInterfaceManager.CurrentlyHovered != button) { button.Pressed = false; } } private void OnChannelSelectorItemPressed(BaseButton.ButtonEventArgs obj) { if (obj.Button is not ChannelItemButton button) return; PreferredChannel = button.Channel; SafelySelectChannel(button.Channel); _channelSelectorPopup.Close(); } public bool SafelySelectChannel(ChatSelectChannel toSelect) { toSelect = MapLocalIfGhost(toSelect); if ((ChatMgr.SelectableChannels & toSelect) == 0) return false; SelectedChannel = toSelect; UpdateChannelSelectButton(); return true; } private void UpdateChannelSelectButton() { var (prefixChannel, _) = SplitInputContents(); var channel = prefixChannel == 0 ? SelectedChannel : prefixChannel; ChannelSelector.Text = ChannelSelectorName(channel); ChannelSelector.Modulate = ChannelSelectColor(channel); } protected override void KeyBindDown(GUIBoundKeyEventArgs args) { base.KeyBindDown(args); if (args.CanFocus) { Input.GrabKeyboardFocus(); } } public void CycleChatChannel(bool forward) { Input.IgnoreNext = true; var idx = Array.IndexOf(ChannelSelectorOrder, SelectedChannel); do { // go over every channel until we find one we can actually select. idx += forward ? 1 : -1; idx = MathHelper.Mod(idx, ChannelSelectorOrder.Length); } while ((ChatMgr.SelectableChannels & ChannelSelectorOrder[idx]) == 0); SafelySelectChannel(ChannelSelectorOrder[idx]); } private void Repopulate() { Contents.Clear(); foreach (var msg in ChatMgr.History) { WriteChatMessage(msg); } } private void WriteChatMessage(StoredChatMessage message) { var messageText = FormattedMessage.EscapeText(message.Message); if (!string.IsNullOrEmpty(message.MessageWrap)) { messageText = string.Format(message.MessageWrap, messageText); } Logger.DebugS("chat", $"{message.Channel}: {messageText}"); if (IsFilteredOut(message.Channel)) return; // TODO: Can make this "smarter" later by only setting it false when the message has been scrolled to message.Read = true; var color = message.MessageColorOverride != Color.Transparent ? message.MessageColorOverride : ChatHelper.ChatColor(message.Channel); AddLine(messageText, message.Channel, color); } private bool IsFilteredOut(ChatChannel channel) { return (ChatMgr.ChannelFilters & channel) == 0; } private void InputKeyBindDown(GUIBoundKeyEventArgs args) { if (args.Function == EngineKeyFunctions.TextReleaseFocus) { Input.ReleaseKeyboardFocus(); args.Handle(); return; } if (args.Function == ContentKeyFunctions.CycleChatChannelForward) { CycleChatChannel(true); args.Handle(); return; } if (args.Function == ContentKeyFunctions.CycleChatChannelBackward) { CycleChatChannel(false); args.Handle(); } } private (ChatSelectChannel selChannel, ReadOnlyMemory<char> text) SplitInputContents() { var text = Input.Text.AsMemory().Trim(); if (text.Length == 0) return default; var prefixChar = text.Span[0]; var channel = GetChannelFromPrefix(prefixChar); if ((ChatMgr.SelectableChannels & channel) != 0) // Cut off prefix if it's valid and we can use the channel in question. text = text[1..]; else channel = 0; channel = MapLocalIfGhost(channel); // Trim from start again to cut out any whitespace between the prefix and message, if any. return (channel, text.TrimStart()); } private void InputOnTextChanged(LineEdit.LineEditEventArgs obj) { // Update channel select button to correct channel if we have a prefix. UpdateChannelSelectButton(); } private static ChatSelectChannel GetChannelFromPrefix(char prefix) { return PrefixToChannel.GetValueOrDefault(prefix); } public static char GetPrefixFromChannel(ChatSelectChannel channel) { return ChannelPrefixes.GetValueOrDefault(channel); } public static string ChannelSelectorName(ChatSelectChannel channel) { return Loc.GetString($"hud-chatbox-select-channel-{channel}"); } public static Color ChannelSelectColor(ChatSelectChannel channel) { return channel switch { ChatSelectChannel.Radio => Color.LimeGreen, ChatSelectChannel.LOOC => Color.MediumTurquoise, ChatSelectChannel.OOC => Color.LightSkyBlue, ChatSelectChannel.Dead => Color.MediumPurple, ChatSelectChannel.Admin => Color.Red, _ => Color.DarkGray }; } public void AddLine(string message, ChatChannel channel, Color color) { DebugTools.Assert(!Disposed); var formatted = new FormattedMessage(3); formatted.PushColor(color); formatted.AddMarkup(message); formatted.Pop(); Contents.AddMessage(formatted); } private void Input_OnTextEntered(LineEdit.LineEditEventArgs args) { if (!string.IsNullOrWhiteSpace(args.Text)) { var (prefixChannel, text) = SplitInputContents(); // Check if message is longer than the character limit if (text.Length > ChatMgr.MaxMessageLength) { string locWarning = Loc.GetString( "chat-manager-max-message-length", ("maxMessageLength", ChatMgr.MaxMessageLength)); AddLine(locWarning, ChatChannel.Server, Color.Orange); return; } ChatMgr.OnChatBoxTextSubmitted(this, text, prefixChannel == 0 ? SelectedChannel : prefixChannel); } Input.Clear(); UpdateChannelSelectButton(); if (ReleaseFocusOnEnter) Input.ReleaseKeyboardFocus(); } public void Focus(ChatSelectChannel? channel = null) { var selectStart = Index.End; if (channel != null) { channel = MapLocalIfGhost(channel.Value); // Channel not selectable, just do NOTHING (not even focus). if (!((ChatMgr.SelectableChannels & channel.Value) != 0)) return; var (_, text) = SplitInputContents(); var newPrefix = GetPrefixFromChannel(channel.Value); DebugTools.Assert(newPrefix != default, "Focus channel must have prefix!"); if (channel == SelectedChannel) { // New selected channel is just the selected channel, // just remove prefix (if any) and leave text unchanged. Input.Text = text.ToString(); selectStart = Index.Start; } else { // Change prefix to new focused channel prefix and leave text unchanged. Input.Text = string.Concat(newPrefix.ToString(), " ", text.Span); selectStart = Index.FromStart(2); } UpdateChannelSelectButton(); } Input.IgnoreNext = true; Input.GrabKeyboardFocus(); Input.CursorPosition = Input.Text.Length; Input.SelectionStart = selectStart.GetOffset(Input.Text.Length); } private ChatSelectChannel MapLocalIfGhost(ChatSelectChannel channel) { if (channel == ChatSelectChannel.Local && ChatMgr.IsGhost) return ChatSelectChannel.Dead; return channel; } } /// <summary> /// Only needed to avoid the issue where right click on the button closes the popup /// but leaves the button highlighted. /// </summary> public sealed class ChannelSelectorButton : Button { public ChannelSelectorButton() { // needed so the popup is untoggled regardless of which key is pressed when hovering this button. // If we don't have this, then right clicking the button while it's toggled on will hide // the popup but keep the button toggled on Mode = ActionMode.Press; EnableAllKeybinds = true; } protected override void KeyBindDown(GUIBoundKeyEventArgs args) { // needed since we need EnableAllKeybinds - don't double-send both UI click and Use if (args.Function == EngineKeyFunctions.Use) return; base.KeyBindDown(args); } } public sealed class FilterButton : ContainerButton { private static readonly Color ColorNormal = Color.FromHex("#7b7e9e"); private static readonly Color ColorHovered = Color.FromHex("#9699bb"); private static readonly Color ColorPressed = Color.FromHex("#789B8C"); private readonly TextureRect _textureRect; public FilterButton() { var filterTexture = IoCManager.Resolve<IResourceCache>() .GetTexture("/Textures/Interface/Nano/filter.svg.96dpi.png"); // needed for same reason as ChannelSelectorButton Mode = ActionMode.Press; EnableAllKeybinds = true; AddChild( (_textureRect = new TextureRect { Texture = filterTexture, HorizontalAlignment = HAlignment.Center, VerticalAlignment = VAlignment.Center }) ); ToggleMode = true; } protected override void KeyBindDown(GUIBoundKeyEventArgs args) { // needed since we need EnableAllKeybinds - don't double-send both UI click and Use if (args.Function == EngineKeyFunctions.Use) return; base.KeyBindDown(args); } private void UpdateChildColors() { if (_textureRect == null) return; switch (DrawMode) { case DrawModeEnum.Normal: _textureRect.ModulateSelfOverride = ColorNormal; break; case DrawModeEnum.Pressed: _textureRect.ModulateSelfOverride = ColorPressed; break; case DrawModeEnum.Hover: _textureRect.ModulateSelfOverride = ColorHovered; break; case DrawModeEnum.Disabled: break; } } protected override void DrawModeChanged() { base.DrawModeChanged(); UpdateChildColors(); } protected override void StylePropertiesChanged() { base.StylePropertiesChanged(); UpdateChildColors(); } } public sealed class ChannelItemButton : Button { public readonly ChatSelectChannel Channel; public ChannelItemButton(ChatSelectChannel channel) { Channel = channel; AddStyleClass(StyleNano.StyleClassChatChannelSelectorButton); Text = ChatBox.ChannelSelectorName(channel); var prefix = ChatBox.GetPrefixFromChannel(channel); if (prefix != default) Text = Loc.GetString("hud-chatbox-select-name-prefixed", ("name", Text), ("prefix", prefix)); } } public sealed class ChannelFilterCheckbox : CheckBox { public readonly ChatChannel Channel; public ChannelFilterCheckbox(ChatChannel channel, int? unreadCount) { Channel = channel; UpdateText(unreadCount); } private void UpdateText(int? unread) { var name = Loc.GetString($"hud-chatbox-channel-{Channel}"); if (unread > 0) // todo: proper fluent stuff here. name += " (" + (unread > 9 ? "9+" : unread) + ")"; Text = name; } public void UpdateUnreadCount(int? unread) { UpdateText(unread); } } public readonly struct ChatResizedEventArgs { /// new bottom that the chat rect is going to have in virtual pixels /// after the imminent relayout public readonly float NewBottom; public ChatResizedEventArgs(float newBottom) { NewBottom = newBottom; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.Style.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { public partial class Style : System.ComponentModel.Component, System.Web.UI.IStateManager { #region Methods and constructors public virtual new void AddAttributesToRender (System.Web.UI.HtmlTextWriter writer, WebControl owner) { Contract.Requires (writer != null); } public void AddAttributesToRender (System.Web.UI.HtmlTextWriter writer) { } public virtual new void CopyFrom (System.Web.UI.WebControls.Style s) { } protected virtual new void FillStyleAttributes (System.Web.UI.CssStyleCollection attributes, System.Web.UI.IUrlResolutionService urlResolver) { Contract.Requires (attributes != null); } public System.Web.UI.CssStyleCollection GetStyleAttributes (System.Web.UI.IUrlResolutionService urlResolver) { Contract.Ensures (Contract.Result<System.Web.UI.CssStyleCollection>() != null); return default(System.Web.UI.CssStyleCollection); } protected internal void LoadViewState (Object state) { } public virtual new void MergeWith (System.Web.UI.WebControls.Style s) { } public virtual new void Reset () { } protected internal virtual new Object SaveViewState () { return default(Object); } protected internal virtual new void SetBit (int bit) { } public void SetDirty () { } public Style () { } public Style (System.Web.UI.StateBag bag) { } void System.Web.UI.IStateManager.LoadViewState (Object state) { } Object System.Web.UI.IStateManager.SaveViewState () { return default(Object); } void System.Web.UI.IStateManager.TrackViewState () { } protected internal virtual new void TrackViewState () { } #endregion #region Properties and indexers public System.Drawing.Color BackColor { get { return default(System.Drawing.Color); } set { } } public System.Drawing.Color BorderColor { get { return default(System.Drawing.Color); } set { } } public BorderStyle BorderStyle { get { return default(BorderStyle); } set { } } public Unit BorderWidth { get { return default(Unit); } set { } } public string CssClass { get { return default(string); } set { } } public FontInfo Font { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.FontInfo>() != null); return default(FontInfo); } } public System.Drawing.Color ForeColor { get { return default(System.Drawing.Color); } set { } } public Unit Height { get { return default(Unit); } set { } } public virtual new bool IsEmpty { get { return default(bool); } } protected bool IsTrackingViewState { get { return default(bool); } } public string RegisteredCssClass { get { return default(string); } } bool System.Web.UI.IStateManager.IsTrackingViewState { get { return default(bool); } } internal protected System.Web.UI.StateBag ViewState { get { Contract.Ensures (Contract.Result<System.Web.UI.StateBag>() != null); return default(System.Web.UI.StateBag); } } public Unit Width { get { return default(Unit); } set { } } #endregion } }
//--------------------------------------------------------------------- // Authors: jachymko, Oisin Grehan // // Description: Base class for writing archive files. // // Creation Date: Jan 4, 2007 //--------------------------------------------------------------------- using System; using System.Diagnostics; using System.IO; using Wintellect.PowerCollections; using Pscx.IO; namespace Pscx.Commands.IO.Compression.ArchiveWriter { /// <summary> /// /// </summary> /// <typeparam name="TCommand"></typeparam> /// <typeparam name="TStream"></typeparam> abstract class WriterBase<TCommand, TStream> : IArchiveWriter where TCommand : WriteArchiveCommandBase where TStream : Stream { private bool _outputCompleted; private TStream _currentOutputStream; private readonly TCommand _command; private readonly Set<string> _excludedPaths; // although events are not strictly needed here for simple progress reporting, // I like the idea of extensibility for custom events to occur, like emitting // ASCII 7 BEL upon archive completion for notification of a long running task. internal event EventHandler<WriteEventArgs> WriteProgress = delegate { }; internal event EventHandler WriteComplete = delegate { }; /// <summary> /// /// </summary> /// <param name="command"></param> protected WriterBase(TCommand command) { _command = command; _excludedPaths = new Set<string>(); WriteProgress += command.OnWriteProgress; } /// <summary> /// Releases all resources used by the WriterBase. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged resources and performs other /// cleanup operations before the WriterBase is reclaimed /// by garbage collection. /// </summary> ~WriterBase() { Dispose(false); } public abstract string DefaultExtension { get; } /// <summary> /// Set to true if archive was written succesfully. This is checked in StopProcessing (e.g. ctrl+c) /// in determine whether or not to delete the incomplete and most like invalid output archive. /// </summary> protected bool OutputCompleted { get { return _outputCompleted; } set { _outputCompleted = value; } } protected TStream CurrentOutputStream { get { return _currentOutputStream; } set { _currentOutputStream = value; } } /// <summary> /// /// </summary> /// <param name="stream"></param> /// <returns></returns> protected abstract TStream OpenCompressedOutputStream(Stream stream); /// <summary> /// /// </summary> /// <param name="outputStream"></param> /// <param name="path"></param> protected virtual void OpenEntry(TStream outputStream, string path) { } /// <summary> /// /// </summary> /// <param name="outputStream"></param> protected virtual void CloseEntry(TStream outputStream) { } /// <summary> /// /// </summary> /// <param name="outputStream"></param> protected virtual void FinishCompressedOutputStream(TStream outputStream) { } /// <summary> /// /// </summary> /// <param name="bytesTotal"></param> /// <param name="bytesRead"></param> protected virtual void OnWriteProgress(long bytesTotal, long bytesRead) { WriteEventArgs args = new WriteEventArgs( CurrentInputFile, CurrentOutputFile, bytesRead, bytesTotal); WriteProgress(this, args); } /// <summary> /// /// </summary> protected virtual void OnWriteComplete() { Debug.WriteLine("OnWriteComplete", "WriterBase"); WriteComplete(this, EventArgs.Empty); } /// <summary> /// /// </summary> public virtual void BeginProcessing() { Debug.WriteLine("BeginProcessing", "WriterBase"); } /// <summary> /// /// </summary> public virtual void EndProcessing() { Debug.WriteLine("EndProcessing", "WriterBase"); } /// <summary> /// Try to clean up any partially finished archive files, if applicable. /// <remarks>We cannot use Command methods here as they will not return due to the cmdlet's "stopping" state.</remarks> /// </summary> public virtual void StopProcessing() { Debug.WriteLine("Begin", "WriterBase.StopProcessing"); if (_outputCompleted == false) { Debug.WriteLine("Trying to delete partial output...", "WriterBase.StopProcessing"); try { if (_currentOutputStream != null) { // using inner try/catch here as sometimes SharpZipLib // will manage to close the handle, but throw an exception for some // other non-determinate reason, due to invalid state. try { // need to close the file handle as it's locking the output file _currentOutputStream.Close(); Debug.WriteLine("Forcibly closed output stream.", "WriterBase.StopProcessing"); } catch (Exception ex) { Trace.WriteLine(ex, "WriterBase.StopProcessing Stream Close Error"); } File.Delete(CurrentOutputFile); Debug.WriteLine("Deleted partial output.", "WriterBase.StopProcessing"); } else { Debug.WriteLine("CurrentOutputStream is null!", "WriterBase.StopProcessing"); } } catch (IOException ex) { // ok, we tried our best to delete the output file and still failed. Trace.WriteLine(ex, "WriterBase.StopProcessing Error"); } } else { Debug.WriteLine("CurrentOutputStream appears properly completed before breaking, no need to clean up.", "WriterBase.StopProcessing"); } Debug.WriteLine("End", "WriterBase.StopProcessing"); } /// <summary> /// /// </summary> /// <param name="directory"></param> public virtual void ProcessDirectory(DirectoryInfo directory) { if (Command.ParameterSetName != PscxInputObjectPathCommandBase.ParameterSetObject) { foreach (string path in Directory.GetFileSystemEntries(directory.FullName)) { ProcessPath(PscxPathInfo.GetPscxPathInfo(Command.SessionState, path)); } } } /// <summary> /// /// </summary> /// <param name="file"></param> public virtual void ProcessFile(FileInfo file) { } /// <summary> /// /// </summary> /// <param name="pscxPath"></param> public virtual void ProcessPath(PscxPathInfo pscxPath) { DirectoryInfo dir = new DirectoryInfo(pscxPath.ProviderPath); FileInfo file = new FileInfo(pscxPath.ProviderPath); if (dir.Exists) { ProcessDirectory(dir); } if (file.Exists) { ProcessFile(file); } } protected DateTime GetLastWriteTime(string path) { FileSystemInfo info; if (EndsWithDirectorySeparator(path)) { info = new DirectoryInfo(path); } else { info = new FileInfo(path); } return info.LastWriteTime; } protected static bool EndsWithDirectorySeparator(string path) { return (path.EndsWith(Path.DirectorySeparatorChar.ToString()) || path.EndsWith(Path.AltDirectorySeparatorChar.ToString())); } protected bool ShouldClobber(string path) { if (Command.NoClobber.IsPresent) { FileInfo file = new FileInfo(path); Command.WriteWarning(String.Format(Properties.Resources.ArchiveOutputAlreadyExists, file.Name)); return false; } return true; } /// <summary> /// Releases the unmanaged resources used by the /// WriterBase and optionally releases the managed resources. /// </summary> /// <param name="disposing"> /// true to release both managed and unmanaged resources; /// false to release only unmanaged resources. /// </param> protected virtual void Dispose(bool disposing) { } /// <summary> /// /// </summary> /// <param name="input"></param> /// <param name="output"></param> protected void WriteStream(Stream input, Stream output) { Command.WriteVerbose("WriteStream input -> output"); // FIXME: do we risk heap fragmentation on heavy usage? // perhaps a static buffer would be a better choice? byte[] buffer = new byte[WriteArchiveCommandBase.BufferSize]; Copy(input, output, buffer); } /// <summary> /// Copy the contents of one <see cref="Stream"/> to another. /// </summary> /// <param name="source">The stream to source data from.</param> /// <param name="destination">The stream to write data to.</param> /// <param name="buffer">The buffer to use during copying.</param> /// <remarks>This is taken from SharpZipLib.Core.StreamUtils and modified for progress callbacks.</remarks> protected void Copy(Stream source, Stream destination, byte[] buffer) { PscxArgumentException.ThrowIfIsNull(source, "source"); PscxArgumentException.ThrowIfIsNull(destination, "destination"); PscxArgumentException.ThrowIfIsNull(buffer, "buffer"); PscxArgumentException.ThrowIf(buffer.Length < 128, "Buffer is too small"); long sourceLength = source.Length; long bytesWritten = 0; bool copying = true; Debug.WriteLine("StartCopy", "WriterBase.Copy"); while (copying) { int bytesRead = source.Read(buffer, 0, buffer.Length); if (bytesRead > 0) { destination.Write(buffer, 0, bytesRead); bytesWritten += bytesRead; OnWriteProgress(sourceLength, bytesWritten); } else { destination.Flush(); copying = false; } } OnWriteComplete(); Debug.WriteLine("EndCopy", "WriterBase.Copy"); } /// <summary> /// /// </summary> protected abstract string CurrentInputFile { get; } /// <summary> /// /// </summary> protected abstract string CurrentOutputFile { get; } /// <summary> /// Should this item be excluded from the current output archive? /// </summary> /// <param name="fullPath">The full path to the item to be tested for exclusion.</param> /// <returns>True if the item should be excluded, false if not.</returns> /// <remarks> /// Typical items that should be excluded are ones that have already been added to the current archive, or items that are a result of the current pipeline (e.g. an archive itself). /// </remarks> protected virtual bool IsExcludedPath(string fullPath) { if (_excludedPaths.Contains(fullPath)) { Command.WriteVerbose("Excluded; skipping " + fullPath); return true; } Command.WriteVerbose("New input: " + fullPath); return false; } /// <summary> /// Mark an item to be excluded from future processing. /// </summary> /// <param name="fullPath"></param> protected virtual void ExcludePath(string fullPath) { Command.WriteVerbose("Excluding " + fullPath); _excludedPaths.Add(fullPath); } /// <summary> /// /// </summary> protected TCommand Command { get { return _command; } } } /// <summary> /// /// </summary> internal class WriteEventArgs : EventArgs { public int Percent { get { float percent = ((float)BytesRead / TotalBytes) * 100; return (int)percent; } } public readonly long BytesRead; public readonly long TotalBytes; public readonly string InputFile; public readonly string OutputFile; public WriteEventArgs(string inFile, string outFile, long bytesRead, long inputLength) { InputFile = inFile; OutputFile = outFile; BytesRead = bytesRead; TotalBytes = inputLength; } } }
/* * Qa full api * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: all * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HostMe.Sdk.Model { /// <summary> /// CreateReservation /// </summary> [DataContract] public partial class CreateReservation : IEquatable<CreateReservation>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CreateReservation" /> class. /// </summary> /// <param name="ReservationTime">ReservationTime.</param> /// <param name="DoB">DoB.</param> /// <param name="GroupSize">GroupSize.</param> /// <param name="Amount">Amount.</param> /// <param name="ReservationSource">ReservationSource.</param> /// <param name="CustomerName">CustomerName.</param> /// <param name="Phone">Phone.</param> /// <param name="Email">Email.</param> /// <param name="Areas">Areas.</param> /// <param name="Language">Language.</param> /// <param name="InternalNotes">InternalNotes.</param> /// <param name="SpecialRequests">SpecialRequests.</param> /// <param name="AboutGuestNotes">AboutGuestNotes.</param> /// <param name="TableNumber">TableNumber.</param> /// <param name="DepositToken">DepositToken.</param> /// <param name="HighChair">HighChair.</param> /// <param name="Stroller">Stroller.</param> /// <param name="Party">Party.</param> /// <param name="Booth">Booth.</param> /// <param name="HighTop">HighTop.</param> /// <param name="Table">Table.</param> /// <param name="Vip">Vip.</param> /// <param name="PartyTypes">PartyTypes.</param> /// <param name="EstimatedTurnOverTime">EstimatedTurnOverTime.</param> /// <param name="CustomerProfile">CustomerProfile.</param> /// <param name="IsOnline">IsOnline.</param> public CreateReservation(DateTimeOffset? ReservationTime = null, DateTimeOffset? DoB = null, int? GroupSize = null, int? Amount = null, string ReservationSource = null, string CustomerName = null, string Phone = null, string Email = null, string Areas = null, string Language = null, string InternalNotes = null, string SpecialRequests = null, string AboutGuestNotes = null, string TableNumber = null, string DepositToken = null, bool? HighChair = null, bool? Stroller = null, bool? Party = null, bool? Booth = null, bool? HighTop = null, bool? Table = null, bool? Vip = null, List<string> PartyTypes = null, int? EstimatedTurnOverTime = null, ProfileData CustomerProfile = null, bool? IsOnline = null) { this.ReservationTime = ReservationTime; this.DoB = DoB; this.GroupSize = GroupSize; this.Amount = Amount; this.ReservationSource = ReservationSource; this.CustomerName = CustomerName; this.Phone = Phone; this.Email = Email; this.Areas = Areas; this.Language = Language; this.InternalNotes = InternalNotes; this.SpecialRequests = SpecialRequests; this.AboutGuestNotes = AboutGuestNotes; this.TableNumber = TableNumber; this.DepositToken = DepositToken; this.HighChair = HighChair; this.Stroller = Stroller; this.Party = Party; this.Booth = Booth; this.HighTop = HighTop; this.Table = Table; this.Vip = Vip; this.PartyTypes = PartyTypes; this.EstimatedTurnOverTime = EstimatedTurnOverTime; this.CustomerProfile = CustomerProfile; this.IsOnline = IsOnline; } /// <summary> /// Gets or Sets ReservationTime /// </summary> [DataMember(Name="reservationTime", EmitDefaultValue=true)] public DateTimeOffset? ReservationTime { get; set; } /// <summary> /// Gets or Sets DoB /// </summary> [DataMember(Name="doB", EmitDefaultValue=true)] public DateTimeOffset? DoB { get; set; } /// <summary> /// Gets or Sets GroupSize /// </summary> [DataMember(Name="groupSize", EmitDefaultValue=true)] public int? GroupSize { get; set; } /// <summary> /// Gets or Sets Amount /// </summary> [DataMember(Name="amount", EmitDefaultValue=true)] public int? Amount { get; set; } /// <summary> /// Gets or Sets ReservationSource /// </summary> [DataMember(Name="reservationSource", EmitDefaultValue=true)] public string ReservationSource { get; set; } /// <summary> /// Gets or Sets CustomerName /// </summary> [DataMember(Name="customerName", EmitDefaultValue=true)] public string CustomerName { get; set; } /// <summary> /// Gets or Sets Phone /// </summary> [DataMember(Name="phone", EmitDefaultValue=true)] public string Phone { get; set; } /// <summary> /// Gets or Sets Email /// </summary> [DataMember(Name="email", EmitDefaultValue=true)] public string Email { get; set; } /// <summary> /// Gets or Sets Areas /// </summary> [DataMember(Name="areas", EmitDefaultValue=true)] public string Areas { get; set; } /// <summary> /// Gets or Sets Language /// </summary> [DataMember(Name="language", EmitDefaultValue=true)] public string Language { get; set; } /// <summary> /// Gets or Sets InternalNotes /// </summary> [DataMember(Name="internalNotes", EmitDefaultValue=true)] public string InternalNotes { get; set; } /// <summary> /// Gets or Sets SpecialRequests /// </summary> [DataMember(Name="specialRequests", EmitDefaultValue=true)] public string SpecialRequests { get; set; } /// <summary> /// Gets or Sets AboutGuestNotes /// </summary> [DataMember(Name="aboutGuestNotes", EmitDefaultValue=true)] public string AboutGuestNotes { get; set; } /// <summary> /// Gets or Sets TableNumber /// </summary> [DataMember(Name="tableNumber", EmitDefaultValue=true)] public string TableNumber { get; set; } /// <summary> /// Gets or Sets DepositToken /// </summary> [DataMember(Name="depositToken", EmitDefaultValue=true)] public string DepositToken { get; set; } /// <summary> /// Gets or Sets HighChair /// </summary> [DataMember(Name="highChair", EmitDefaultValue=true)] public bool? HighChair { get; set; } /// <summary> /// Gets or Sets Stroller /// </summary> [DataMember(Name="stroller", EmitDefaultValue=true)] public bool? Stroller { get; set; } /// <summary> /// Gets or Sets Party /// </summary> [DataMember(Name="party", EmitDefaultValue=true)] public bool? Party { get; set; } /// <summary> /// Gets or Sets Booth /// </summary> [DataMember(Name="booth", EmitDefaultValue=true)] public bool? Booth { get; set; } /// <summary> /// Gets or Sets HighTop /// </summary> [DataMember(Name="highTop", EmitDefaultValue=true)] public bool? HighTop { get; set; } /// <summary> /// Gets or Sets Table /// </summary> [DataMember(Name="table", EmitDefaultValue=true)] public bool? Table { get; set; } /// <summary> /// Gets or Sets Vip /// </summary> [DataMember(Name="vip", EmitDefaultValue=true)] public bool? Vip { get; set; } /// <summary> /// Gets or Sets PartyTypes /// </summary> [DataMember(Name="partyTypes", EmitDefaultValue=true)] public List<string> PartyTypes { get; set; } /// <summary> /// Gets or Sets EstimatedTurnOverTime /// </summary> [DataMember(Name="estimatedTurnOverTime", EmitDefaultValue=true)] public int? EstimatedTurnOverTime { get; set; } /// <summary> /// Gets or Sets CustomerProfile /// </summary> [DataMember(Name="customerProfile", EmitDefaultValue=true)] public ProfileData CustomerProfile { get; set; } /// <summary> /// Gets or Sets IsOnline /// </summary> [DataMember(Name="isOnline", EmitDefaultValue=true)] public bool? IsOnline { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CreateReservation {\n"); sb.Append(" ReservationTime: ").Append(ReservationTime).Append("\n"); sb.Append(" DoB: ").Append(DoB).Append("\n"); sb.Append(" GroupSize: ").Append(GroupSize).Append("\n"); sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" ReservationSource: ").Append(ReservationSource).Append("\n"); sb.Append(" CustomerName: ").Append(CustomerName).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" Areas: ").Append(Areas).Append("\n"); sb.Append(" Language: ").Append(Language).Append("\n"); sb.Append(" InternalNotes: ").Append(InternalNotes).Append("\n"); sb.Append(" SpecialRequests: ").Append(SpecialRequests).Append("\n"); sb.Append(" AboutGuestNotes: ").Append(AboutGuestNotes).Append("\n"); sb.Append(" TableNumber: ").Append(TableNumber).Append("\n"); sb.Append(" DepositToken: ").Append(DepositToken).Append("\n"); sb.Append(" HighChair: ").Append(HighChair).Append("\n"); sb.Append(" Stroller: ").Append(Stroller).Append("\n"); sb.Append(" Party: ").Append(Party).Append("\n"); sb.Append(" Booth: ").Append(Booth).Append("\n"); sb.Append(" HighTop: ").Append(HighTop).Append("\n"); sb.Append(" Table: ").Append(Table).Append("\n"); sb.Append(" Vip: ").Append(Vip).Append("\n"); sb.Append(" PartyTypes: ").Append(PartyTypes).Append("\n"); sb.Append(" EstimatedTurnOverTime: ").Append(EstimatedTurnOverTime).Append("\n"); sb.Append(" CustomerProfile: ").Append(CustomerProfile).Append("\n"); sb.Append(" IsOnline: ").Append(IsOnline).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as CreateReservation); } /// <summary> /// Returns true if CreateReservation instances are equal /// </summary> /// <param name="other">Instance of CreateReservation to be compared</param> /// <returns>Boolean</returns> public bool Equals(CreateReservation other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.ReservationTime == other.ReservationTime || this.ReservationTime != null && this.ReservationTime.Equals(other.ReservationTime) ) && ( this.DoB == other.DoB || this.DoB != null && this.DoB.Equals(other.DoB) ) && ( this.GroupSize == other.GroupSize || this.GroupSize != null && this.GroupSize.Equals(other.GroupSize) ) && ( this.Amount == other.Amount || this.Amount != null && this.Amount.Equals(other.Amount) ) && ( this.ReservationSource == other.ReservationSource || this.ReservationSource != null && this.ReservationSource.Equals(other.ReservationSource) ) && ( this.CustomerName == other.CustomerName || this.CustomerName != null && this.CustomerName.Equals(other.CustomerName) ) && ( this.Phone == other.Phone || this.Phone != null && this.Phone.Equals(other.Phone) ) && ( this.Email == other.Email || this.Email != null && this.Email.Equals(other.Email) ) && ( this.Areas == other.Areas || this.Areas != null && this.Areas.Equals(other.Areas) ) && ( this.Language == other.Language || this.Language != null && this.Language.Equals(other.Language) ) && ( this.InternalNotes == other.InternalNotes || this.InternalNotes != null && this.InternalNotes.Equals(other.InternalNotes) ) && ( this.SpecialRequests == other.SpecialRequests || this.SpecialRequests != null && this.SpecialRequests.Equals(other.SpecialRequests) ) && ( this.AboutGuestNotes == other.AboutGuestNotes || this.AboutGuestNotes != null && this.AboutGuestNotes.Equals(other.AboutGuestNotes) ) && ( this.TableNumber == other.TableNumber || this.TableNumber != null && this.TableNumber.Equals(other.TableNumber) ) && ( this.DepositToken == other.DepositToken || this.DepositToken != null && this.DepositToken.Equals(other.DepositToken) ) && ( this.HighChair == other.HighChair || this.HighChair != null && this.HighChair.Equals(other.HighChair) ) && ( this.Stroller == other.Stroller || this.Stroller != null && this.Stroller.Equals(other.Stroller) ) && ( this.Party == other.Party || this.Party != null && this.Party.Equals(other.Party) ) && ( this.Booth == other.Booth || this.Booth != null && this.Booth.Equals(other.Booth) ) && ( this.HighTop == other.HighTop || this.HighTop != null && this.HighTop.Equals(other.HighTop) ) && ( this.Table == other.Table || this.Table != null && this.Table.Equals(other.Table) ) && ( this.Vip == other.Vip || this.Vip != null && this.Vip.Equals(other.Vip) ) && ( this.PartyTypes == other.PartyTypes || this.PartyTypes != null && this.PartyTypes.SequenceEqual(other.PartyTypes) ) && ( this.EstimatedTurnOverTime == other.EstimatedTurnOverTime || this.EstimatedTurnOverTime != null && this.EstimatedTurnOverTime.Equals(other.EstimatedTurnOverTime) ) && ( this.CustomerProfile == other.CustomerProfile || this.CustomerProfile != null && this.CustomerProfile.Equals(other.CustomerProfile) ) && ( this.IsOnline == other.IsOnline || this.IsOnline != null && this.IsOnline.Equals(other.IsOnline) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.ReservationTime != null) hash = hash * 59 + this.ReservationTime.GetHashCode(); if (this.DoB != null) hash = hash * 59 + this.DoB.GetHashCode(); if (this.GroupSize != null) hash = hash * 59 + this.GroupSize.GetHashCode(); if (this.Amount != null) hash = hash * 59 + this.Amount.GetHashCode(); if (this.ReservationSource != null) hash = hash * 59 + this.ReservationSource.GetHashCode(); if (this.CustomerName != null) hash = hash * 59 + this.CustomerName.GetHashCode(); if (this.Phone != null) hash = hash * 59 + this.Phone.GetHashCode(); if (this.Email != null) hash = hash * 59 + this.Email.GetHashCode(); if (this.Areas != null) hash = hash * 59 + this.Areas.GetHashCode(); if (this.Language != null) hash = hash * 59 + this.Language.GetHashCode(); if (this.InternalNotes != null) hash = hash * 59 + this.InternalNotes.GetHashCode(); if (this.SpecialRequests != null) hash = hash * 59 + this.SpecialRequests.GetHashCode(); if (this.AboutGuestNotes != null) hash = hash * 59 + this.AboutGuestNotes.GetHashCode(); if (this.TableNumber != null) hash = hash * 59 + this.TableNumber.GetHashCode(); if (this.DepositToken != null) hash = hash * 59 + this.DepositToken.GetHashCode(); if (this.HighChair != null) hash = hash * 59 + this.HighChair.GetHashCode(); if (this.Stroller != null) hash = hash * 59 + this.Stroller.GetHashCode(); if (this.Party != null) hash = hash * 59 + this.Party.GetHashCode(); if (this.Booth != null) hash = hash * 59 + this.Booth.GetHashCode(); if (this.HighTop != null) hash = hash * 59 + this.HighTop.GetHashCode(); if (this.Table != null) hash = hash * 59 + this.Table.GetHashCode(); if (this.Vip != null) hash = hash * 59 + this.Vip.GetHashCode(); if (this.PartyTypes != null) hash = hash * 59 + this.PartyTypes.GetHashCode(); if (this.EstimatedTurnOverTime != null) hash = hash * 59 + this.EstimatedTurnOverTime.GetHashCode(); if (this.CustomerProfile != null) hash = hash * 59 + this.CustomerProfile.GetHashCode(); if (this.IsOnline != null) hash = hash * 59 + this.IsOnline.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using CRP.Core.Domain; using CRP.Tests.Core; using CRP.Tests.Core.Extensions; using CRP.Tests.Core.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using UCDArch.Core.PersistanceSupport; using UCDArch.Data.NHibernate; using UCDArch.Testing.Extensions; namespace CRP.Tests.Repositories { /// <summary> /// Entity Name: Validator /// LookupFieldName: Name /// </summary> [TestClass] public class ValidatorRepositoryTests : AbstractRepositoryTests<Validator, int> { /// <summary> /// Gets or sets the Validator repository. /// </summary> /// <value>The Validator repository.</value> public IRepository<Validator> ValidatorRepository { get; set; } #region Init and Overrides /// <summary> /// Initializes a new instance of the <see cref="ValidatorRepositoryTests"/> class. /// </summary> public ValidatorRepositoryTests() { ValidatorRepository = new Repository<Validator>(); } /// <summary> /// Gets the valid entity of type T /// </summary> /// <param name="counter">The counter.</param> /// <returns>A valid entity of type T</returns> protected override Validator GetValid(int? counter) { return CreateValidEntities.Validator(counter); } /// <summary> /// A Query which will return a single record /// </summary> /// <param name="numberAtEnd"></param> /// <returns></returns> protected override IQueryable<Validator> GetQuery(int numberAtEnd) { return ValidatorRepository.Queryable.Where(a => a.Name.EndsWith(numberAtEnd.ToString())); } /// <summary> /// A way to compare the entities that were read. /// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment); /// </summary> /// <param name="entity"></param> /// <param name="counter"></param> protected override void FoundEntityComparison(Validator entity, int counter) { Assert.AreEqual("Name" + counter, entity.Name); } /// <summary> /// Updates , compares, restores. /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> protected override void UpdateUtility(Validator entity, ARTAction action) { const string updateValue = "Updated"; switch (action) { case ARTAction.Compare: Assert.AreEqual(updateValue, entity.Name); break; case ARTAction.Restore: entity.Name = RestoreValue; break; case ARTAction.Update: RestoreValue = entity.Name; entity.Name = updateValue; break; } } [TestMethod] public override void CanUpdateEntity() { CanUpdateEntity(false); //Mutable is false for this table } [TestMethod] [ExpectedException(typeof(NHibernate.HibernateException))] public override void CanDeleteEntity() { try { base.CanDeleteEntity(); } catch (Exception ex) { Assert.IsNotNull(ex); Assert.AreEqual("Attempted to delete an object of immutable class: [CRP.Core.Domain.Validator]", ex.Message); throw; } } /// <summary> /// Loads the data. /// </summary> protected override void LoadData() { ValidatorRepository.DbContext.BeginTransaction(); LoadRecords(5); ValidatorRepository.DbContext.CommitTransaction(); } #endregion Init and Overrides #region Name Tests #region Invalid Tests /// <summary> /// Tests the Name with null value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestNameWithNullValueDoesNotSave() { Validator validator = null; try { #region Arrange validator = GetValid(9); validator.Name = null; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(validator); var results = validator.ValidationResults().AsMessageList(); results.AssertErrorsAre("Name: may not be null or empty"); Assert.IsTrue(validator.IsTransient()); Assert.IsFalse(validator.IsValid()); throw; } } /// <summary> /// Tests the Name with empty string does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestNameWithEmptyStringDoesNotSave() { Validator validator = null; try { #region Arrange validator = GetValid(9); validator.Name = string.Empty; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(validator); var results = validator.ValidationResults().AsMessageList(); results.AssertErrorsAre("Name: may not be null or empty"); Assert.IsTrue(validator.IsTransient()); Assert.IsFalse(validator.IsValid()); throw; } } /// <summary> /// Tests the Name with spaces only does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestNameWithSpacesOnlyDoesNotSave() { Validator validator = null; try { #region Arrange validator = GetValid(9); validator.Name = " "; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(validator); var results = validator.ValidationResults().AsMessageList(); results.AssertErrorsAre("Name: may not be null or empty"); Assert.IsTrue(validator.IsTransient()); Assert.IsFalse(validator.IsValid()); throw; } } /// <summary> /// Tests the Name with too long value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestNameWithTooLongValueDoesNotSave() { Validator validator = null; try { #region Arrange validator = GetValid(9); validator.Name = "x".RepeatTimes((50 + 1)); #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(validator); Assert.AreEqual(50 + 1, validator.Name.Length); var results = validator.ValidationResults().AsMessageList(); results.AssertErrorsAre("Name: length must be between 0 and 50"); Assert.IsTrue(validator.IsTransient()); Assert.IsFalse(validator.IsValid()); throw; } } #endregion Invalid Tests #region Valid Tests /// <summary> /// Tests the Name with one character saves. /// </summary> [TestMethod] public void TestNameWithOneCharacterSaves() { #region Arrange var validator = GetValid(9); validator.Name = "x"; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the Name with long value saves. /// </summary> [TestMethod] public void TestNameWithLongValueSaves() { #region Arrange var validator = GetValid(9); validator.Name = "x".RepeatTimes(50); #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(50, validator.Name.Length); Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } #endregion Valid Tests #endregion Name Tests #region Class Tests #region Invalid Tests /// <summary> /// Tests the Class with too long value does not save. /// </summary> [TestMethod] [ExpectedException(typeof(ApplicationException))] public void TestClassWithTooLongValueDoesNotSave() { Validator validator = null; try { #region Arrange validator = GetValid(9); validator.Class = "x".RepeatTimes((50 + 1)); #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act } catch (Exception) { Assert.IsNotNull(validator); Assert.AreEqual(50 + 1, validator.Class.Length); var results = validator.ValidationResults().AsMessageList(); results.AssertErrorsAre("Class: length must be between 0 and 50"); Assert.IsTrue(validator.IsTransient()); Assert.IsFalse(validator.IsValid()); throw; } } #endregion Invalid Tests #region Valid Tests /// <summary> /// Tests the class with null value saves. /// </summary> [TestMethod] public void TestClassWithNullValueSaves() { #region Arrange var validator = GetValid(9); validator.Class = null; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the class with empty string saves. /// </summary> [TestMethod] public void TestClassWithEmptyStringSaves() { #region Arrange var validator = GetValid(9); validator.Class = string.Empty; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the class with spaces only saves. /// </summary> [TestMethod] public void TestClassWithSpacesOnlySaves() { #region Arrange var validator = GetValid(9); validator.Class = " "; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the Class with one character saves. /// </summary> [TestMethod] public void TestClassWithOneCharacterSaves() { #region Arrange var validator = GetValid(9); validator.Class = "x"; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the Class with long value saves. /// </summary> [TestMethod] public void TestClassWithLongValueSaves() { #region Arrange var validator = GetValid(9); validator.Class = "x".RepeatTimes(50); #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(50, validator.Class.Length); Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } #endregion Valid Tests #endregion Class Tests #region RegEx Tests #region Valid Tests /// <summary> /// Tests the RegEx with null value saves. /// </summary> [TestMethod] public void TestRegExWithNullValueSaves() { #region Arrange var validator = GetValid(9); validator.RegEx = null; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the RegEx with empty string saves. /// </summary> [TestMethod] public void TestRegExWithEmptyStringSaves() { #region Arrange var validator = GetValid(9); validator.RegEx = string.Empty; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the RegEx with spaces only saves. /// </summary> [TestMethod] public void TestRegExWithSpacesOnlySaves() { #region Arrange var validator = GetValid(9); validator.RegEx = " "; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the RegEx with one character saves. /// </summary> [TestMethod] public void TestRegExWithOneCharacterSaves() { #region Arrange var validator = GetValid(9); validator.RegEx = "x"; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the RegEx with long value saves. /// </summary> [TestMethod] public void TestRegExWithLongValueSaves() { #region Arrange var validator = GetValid(9); validator.RegEx = "x".RepeatTimes(999); #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(999, validator.RegEx.Length); Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } #endregion Valid Tests #endregion RegEx Tests #region ErrorMessage Tests #region Valid Tests /// <summary> /// Tests the ErrorMessage with null value saves. /// </summary> [TestMethod] public void TestErrorMessageWithNullValueSaves() { #region Arrange var validator = GetValid(9); validator.ErrorMessage = null; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the ErrorMessage with empty string saves. /// </summary> [TestMethod] public void TestErrorMessageWithEmptyStringSaves() { #region Arrange var validator = GetValid(9); validator.ErrorMessage = string.Empty; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the ErrorMessage with spaces only saves. /// </summary> [TestMethod] public void TestErrorMessageWithSpacesOnlySaves() { #region Arrange var validator = GetValid(9); validator.ErrorMessage = " "; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the ErrorMessage with one character saves. /// </summary> [TestMethod] public void TestErrorMessageWithOneCharacterSaves() { #region Arrange var validator = GetValid(9); validator.ErrorMessage = "x"; #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } /// <summary> /// Tests the ErrorMessage with long value saves. /// </summary> [TestMethod] public void TestErrorMessageWithLongValueSaves() { #region Arrange var validator = GetValid(9); validator.ErrorMessage = "x".RepeatTimes(999); #endregion Arrange #region Act ValidatorRepository.DbContext.BeginTransaction(); ValidatorRepository.EnsurePersistent(validator); ValidatorRepository.DbContext.CommitTransaction(); #endregion Act #region Assert Assert.AreEqual(999, validator.ErrorMessage.Length); Assert.IsFalse(validator.IsTransient()); Assert.IsTrue(validator.IsValid()); #endregion Assert } #endregion Valid Tests #endregion ErrorMessage Tests #region Reflection of Database /// <summary> /// Tests all fields in the database have been tested. /// If this fails and no other tests, it means that a field has been added which has not been tested above. /// </summary> [TestMethod] public void TestAllFieldsInTheDatabaseHaveBeenTested() { #region Arrange var expectedFields = new List<NameAndType>(); expectedFields.Add(new NameAndType("Class", "System.String", new List<string> { "[NHibernate.Validator.Constraints.LengthAttribute((Int32)50)]" })); expectedFields.Add(new NameAndType("ErrorMessage", "System.String", new List<string>())); expectedFields.Add(new NameAndType("Id", "System.Int32", new List<string> { "[Newtonsoft.Json.JsonPropertyAttribute()]", "[System.Xml.Serialization.XmlIgnoreAttribute()]" })); expectedFields.Add(new NameAndType("Name", "System.String", new List<string> { "[NHibernate.Validator.Constraints.LengthAttribute((Int32)50)]", "[UCDArch.Core.NHibernateValidator.Extensions.RequiredAttribute()]" })); expectedFields.Add(new NameAndType("RegEx", "System.String", new List<string>())); #endregion Arrange AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(Validator)); } #endregion Reflection of Database } }
// ------------------------------------------------------------------------------ // 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. 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 ProfilePhotoRequest. /// </summary> public partial class ProfilePhotoRequest : BaseRequest, IProfilePhotoRequest { /// <summary> /// Constructs a new ProfilePhotoRequest. /// </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 ProfilePhotoRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified ProfilePhoto using POST. /// </summary> /// <param name="profilePhotoToCreate">The ProfilePhoto to create.</param> /// <returns>The created ProfilePhoto.</returns> public System.Threading.Tasks.Task<ProfilePhoto> CreateAsync(ProfilePhoto profilePhotoToCreate) { return this.CreateAsync(profilePhotoToCreate, CancellationToken.None); } /// <summary> /// Creates the specified ProfilePhoto using POST. /// </summary> /// <param name="profilePhotoToCreate">The ProfilePhoto to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ProfilePhoto.</returns> public async System.Threading.Tasks.Task<ProfilePhoto> CreateAsync(ProfilePhoto profilePhotoToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<ProfilePhoto>(profilePhotoToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified ProfilePhoto. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified ProfilePhoto. /// </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<ProfilePhoto>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified ProfilePhoto. /// </summary> /// <returns>The ProfilePhoto.</returns> public System.Threading.Tasks.Task<ProfilePhoto> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified ProfilePhoto. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The ProfilePhoto.</returns> public async System.Threading.Tasks.Task<ProfilePhoto> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<ProfilePhoto>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified ProfilePhoto using PATCH. /// </summary> /// <param name="profilePhotoToUpdate">The ProfilePhoto to update.</param> /// <returns>The updated ProfilePhoto.</returns> public System.Threading.Tasks.Task<ProfilePhoto> UpdateAsync(ProfilePhoto profilePhotoToUpdate) { return this.UpdateAsync(profilePhotoToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified ProfilePhoto using PATCH. /// </summary> /// <param name="profilePhotoToUpdate">The ProfilePhoto to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated ProfilePhoto.</returns> public async System.Threading.Tasks.Task<ProfilePhoto> UpdateAsync(ProfilePhoto profilePhotoToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<ProfilePhoto>(profilePhotoToUpdate, 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 IProfilePhotoRequest 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 IProfilePhotoRequest Expand(Expression<Func<ProfilePhoto, 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 IProfilePhotoRequest 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 IProfilePhotoRequest Select(Expression<Func<ProfilePhoto, 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="profilePhotoToInitialize">The <see cref="ProfilePhoto"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(ProfilePhoto profilePhotoToInitialize) { } } }
// 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.Text; using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // public abstract class Decoder { internal DecoderFallback _fallback = null; internal DecoderFallbackBuffer _fallbackBuffer = null; protected Decoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } public DecoderFallback Fallback { get { return _fallback; } set { if (value == null) throw new ArgumentNullException(nameof(value)); // Can't change fallback if buffer is wrong if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); _fallback = value; _fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. public DecoderFallbackBuffer FallbackBuffer { get { if (_fallbackBuffer == null) { if (_fallback != null) _fallbackBuffer = _fallback.CreateFallbackBuffer(); else _fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return _fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return _fallbackBuffer != null; } } // Reset the Decoder // // Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset(). // // Virtual implementation has to call GetChars with flush and a big enough buffer to clear a 0 byte string // We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big. public virtual void Reset() { byte[] byteTemp = Array.Empty<byte>(); char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)]; GetChars(byteTemp, 0, 0, charTemp, 0, true); _fallbackBuffer?.Reset(); } // Returns the number of characters the next call to GetChars will // produce if presented with the given range of bytes. The returned value // takes into account the state in which the decoder was left following the // last call to GetChars. The state of the decoder is not affected // by a call to this method. // public abstract int GetCharCount(byte[] bytes, int index, int count); public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) { return GetCharCount(bytes, index, count); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) [CLSCompliant(false)] public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate input parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); byte[] arrbyte = new byte[count]; int index; for (index = 0; index < count; index++) arrbyte[index] = bytes[index]; return GetCharCount(arrbyte, 0, count); } public virtual unsafe int GetCharCount(ReadOnlySpan<byte> bytes, bool flush) { fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetCharCount(bytesPtr, bytes.Length, flush); } } // Decodes a range of bytes in a byte array into a range of characters // in a character array. The method decodes byteCount bytes from // bytes starting at index byteIndex, storing the resulting // characters in chars starting at index charIndex. The // decoding takes into account the state in which the decoder was left // following the last call to this method. // // An exception occurs if the character array is not large enough to // hold the complete decoding of the bytes. The GetCharCount method // can be used to determine the exact number of characters that will be // produced for a given range of bytes. Alternatively, the // GetMaxCharCount method of the Encoding that produced this // decoder can be used to determine the maximum number of characters that // will be produced for a given number of bytes, regardless of the actual // byte values. // public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implementation of an // external GetChars() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the char[] to our char* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. [CLSCompliant(false)] public virtual unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // Get the byte array to convert byte[] arrByte = new byte[byteCount]; int index; for (index = 0; index < byteCount; index++) arrByte[index] = bytes[index]; // Get the char array to fill char[] arrChar = new char[charCount]; // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush); Debug.Assert(result <= charCount, "Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't // rely on result because it could be a 3rd party implementation. We need // to make sure we never copy more than charCount chars no matter the value // of result if (result < charCount) charCount = result; // We check both result and charCount so that we don't accidentally overrun // our pointer buffer just because of an issue in GetChars for (index = 0; index < charCount; index++) chars[index] = arrChar[index]; return charCount; } public virtual unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush) { fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, flush); } } // This method is used when the output buffer might not be large enough. // It will decode until it runs out of bytes, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted bytes and output characters used. // It will only throw a buffer overflow exception if the entire lenght of chars[] is // too small to store the next char. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); completed = (bytesUsed == byteCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } // This is the version that uses *. // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant(false)] public virtual unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // Get ready to do it bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); completed = (bytesUsed == byteCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } public virtual unsafe void Convert(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { Convert(bytesPtr, bytes.Length, charsPtr, chars.Length, flush, out bytesUsed, out charsUsed, out completed); } } } }
// <copyright file="BernoulliTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2014 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> namespace MathNet.Numerics.UnitTests.DistributionTests.Discrete { using System; using System.Linq; using Distributions; using NUnit.Framework; /// <summary> /// Bernoulli distribution tests. /// </summary> [TestFixture, Category("Distributions")] public class BernoulliTests { /// <summary> /// Can create Bernoulli. /// </summary> /// <param name="p">Probability of one.</param> [TestCase(0.0)] [TestCase(0.3)] [TestCase(1.0)] public void CanCreateBernoulli(double p) { var bernoulli = new Bernoulli(p); Assert.AreEqual(p, bernoulli.P); } /// <summary> /// Bernoulli create fails with bad parameters. /// </summary> /// <param name="p">Probability of one.</param> [TestCase(Double.NaN)] [TestCase(-1.0)] [TestCase(2.0)] public void BernoulliCreateFailsWithBadParameters(double p) { Assert.That(() => new Bernoulli(p), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var b = new Bernoulli(0.3); Assert.AreEqual("Bernoulli(p = 0.3)", b.ToString()); } /// <summary> /// Validate entropy. /// </summary> /// <param name="p">Probability of one.</param> [TestCase(0.0)] [TestCase(0.3)] [TestCase(1.0)] public void ValidateEntropy(double p) { var b = new Bernoulli(p); AssertHelpers.AlmostEqualRelative(-((1.0 - p) * Math.Log(1.0 - p)) - (p * Math.Log(p)), b.Entropy, 14); } /// <summary> /// Validate skewness. /// </summary> /// <param name="p">Probability of one.</param> [TestCase(0.0)] [TestCase(0.3)] [TestCase(1.0)] public void ValidateSkewness(double p) { var b = new Bernoulli(p); Assert.AreEqual((1.0 - (2.0 * p)) / Math.Sqrt(p * (1.0 - p)), b.Skewness); } /// <summary> /// Validate mode. /// </summary> /// <param name="p">Probability of one.</param> /// <param name="m">Expected value.</param> [TestCase(0.0, 0.0)] [TestCase(0.3, 0.0)] [TestCase(1.0, 1.0)] public void ValidateMode(double p, double m) { var b = new Bernoulli(p); Assert.AreEqual(m, b.Mode); } [TestCase(0.0, 0.0)] [TestCase(0.4, 0.0)] [TestCase(0.5, 0.5)] [TestCase(0.6, 1.0)] [TestCase(1.0, 1.0)] public void ValidateMedian(double p, double expected) { Assert.That(new Bernoulli(p).Median, Is.EqualTo(expected)); } /// <summary> /// Validate minimum. /// </summary> [Test] public void ValidateMinimum() { var b = new Bernoulli(0.3); Assert.AreEqual(0.0, b.Minimum); } /// <summary> /// Validate maximum. /// </summary> [Test] public void ValidateMaximum() { var b = new Bernoulli(0.3); Assert.AreEqual(1.0, b.Maximum); } /// <summary> /// Validate probability. /// </summary> /// <param name="p">Probability of one.</param> /// <param name="x">Input X value.</param> /// <param name="d">Expected value.</param> [TestCase(0.0, -1, 0.0)] [TestCase(0.0, 0, 1.0)] [TestCase(0.0, 1, 0.0)] [TestCase(0.0, 2, 0.0)] [TestCase(0.3, -1, 0.0)] [TestCase(0.3, 0, 0.7)] [TestCase(0.3, 1, 0.3)] [TestCase(0.3, 2, 0.0)] [TestCase(1.0, -1, 0.0)] [TestCase(1.0, 0, 0.0)] [TestCase(1.0, 1, 1.0)] [TestCase(1.0, 2, 0.0)] public void ValidateProbability(double p, int x, double d) { var b = new Bernoulli(p); Assert.AreEqual(d, b.Probability(x)); } /// <summary> /// Validate probability log. /// </summary> /// <param name="p">Probability of one.</param> /// <param name="x">Input X value.</param> /// <param name="dln">Expected value.</param> [TestCase(0.0, -1, Double.NegativeInfinity)] [TestCase(0.0, 0, 0.0)] [TestCase(0.0, 1, Double.NegativeInfinity)] [TestCase(0.0, 2, Double.NegativeInfinity)] [TestCase(0.3, -1, Double.NegativeInfinity)] [TestCase(0.3, 0, -0.35667494393873244235395440410727451457180907089949815)] [TestCase(0.3, 1, -1.2039728043259360296301803719337238685164245381839102)] [TestCase(0.3, 2, Double.NegativeInfinity)] [TestCase(1.0, -1, Double.NegativeInfinity)] [TestCase(1.0, 0, Double.NegativeInfinity)] [TestCase(1.0, 1, 0.0)] [TestCase(1.0, 2, Double.NegativeInfinity)] public void ValidateProbabilityLn(double p, int x, double dln) { var b = new Bernoulli(p); Assert.AreEqual(dln, b.ProbabilityLn(x)); } /// <summary> /// Can sample static. /// </summary> [Test] public void CanSampleStatic() { Bernoulli.Sample(new Random(0), 0.3); } /// <summary> /// Can sample sequence static. /// </summary> [Test] public void CanSampleSequenceStatic() { var ied = Bernoulli.Samples(new Random(0), 0.3); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Fail sample static with bad values. /// </summary> [Test] public void FailSampleStatic() { Assert.That(() => Bernoulli.Sample(new Random(0), -1.0), Throws.ArgumentException); } /// <summary> /// Fail sample sequence static with bad values. /// </summary> [Test] public void FailSampleSequenceStatic() { Assert.That(() => Bernoulli.Samples(new Random(0), -1.0).First(), Throws.ArgumentException); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var n = new Bernoulli(0.3); n.Sample(); } /// <summary> /// Can sample sequence. /// </summary> [Test] public void CanSampleSequence() { var n = new Bernoulli(0.3); var ied = n.Samples(); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Validate cumulative distribution. /// </summary> /// <param name="p">Probability of one.</param> /// <param name="x">Input X value.</param> /// <param name="cdf">Expected value.</param> [TestCase(0.0, -1.0, 0.0)] [TestCase(0.0, 0.0, 1.0)] [TestCase(0.0, 0.5, 1.0)] [TestCase(0.0, 1.0, 1.0)] [TestCase(0.0, 2.0, 1.0)] [TestCase(0.3, -1.0, 0.0)] [TestCase(0.3, 0.0, 0.7)] [TestCase(0.3, 0.5, 0.7)] [TestCase(0.3, 1.0, 1.0)] [TestCase(0.3, 2.0, 1.0)] [TestCase(1.0, -1.0, 0.0)] [TestCase(1.0, 0.0, 0.0)] [TestCase(1.0, 0.5, 0.0)] [TestCase(1.0, 1.0, 1.0)] [TestCase(1.0, 2.0, 1.0)] public void ValidateCumulativeDistribution(double p, double x, double cdf) { var b = new Bernoulli(p); Assert.AreEqual(cdf, b.CumulativeDistribution(x)); } } }
// 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.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// JobOperationResultsOperations operations. /// </summary> internal partial class JobOperationResultsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IJobOperationResultsOperations { /// <summary> /// Initializes a new instance of the JobOperationResultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal JobOperationResultsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Fetches the result of any operation. /// the operation. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='jobName'> /// Job name whose operation result has to be fetched. /// </param> /// <param name='operationId'> /// OperationID which represents the operation whose result has to be fetched. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string jobName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (jobName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "jobName"); } if (operationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/{jobName}/operationResults/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.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 System.Net.Http.HttpRequestMessage _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 (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new Microsoft.Rest.Azure.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 Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.IO; using System.Xml; using System.Text; using System.Collections.Generic; public static class DllMapVerifier { private struct DllImportRef { public DllImportRef (string name, int line, int column) { Name = name; Line = line; Column = column; } public string Name; public int Line; public int Column; } private static Dictionary<string, List<DllImportRef>> dll_imports = new Dictionary<string, List<DllImportRef>> (); private static List<string> ignore_dlls = new List<string> (); private static List<string> config_dlls = null; public static int Main (string [] args) { LoadConfigDlls (args[0]); foreach (string file in args) { LoadDllImports (file); } return VerifyDllImports (args[0]) ? 0 : 1; } private static bool VerifyDllImports (string configFile) { int total_unmapped_count = 0; foreach (KeyValuePair<string, List<DllImportRef>> dll_import in dll_imports) { int file_unmapped_count = 0; foreach (DllImportRef dll_import_ref in dll_import.Value) { if (config_dlls != null && config_dlls.Contains (dll_import_ref.Name)) { continue; } if (file_unmapped_count++ == 0) { Console.Error.WriteLine ("Unmapped DLLs in file: {0}", dll_import.Key); } Console.Error.WriteLine (" + {0} : {1},{2}", dll_import_ref.Name, dll_import_ref.Line, dll_import_ref.Column); } total_unmapped_count += file_unmapped_count; } if (total_unmapped_count > 0 && config_dlls == null) { Console.Error.WriteLine ("No config file for DLL mapping was found ({0})", configFile); } return total_unmapped_count == 0; } private static void LoadDllImports (string csFile) { if (csFile.StartsWith ("-i")) { ignore_dlls.Add (csFile.Substring (2)); return; } if (Path.GetExtension (csFile) == ".cs" && File.Exists (csFile)) { List<DllImportRef> dll_import_refs = null; foreach (DllImportRef dll_import in ParseFileForDllImports (csFile)) { if (ignore_dlls.Contains (dll_import.Name)) { continue; } if (dll_import_refs == null) { dll_import_refs = new List<DllImportRef> (); } dll_import_refs.Add (dll_import); } if (dll_import_refs != null) { dll_imports.Add (csFile, dll_import_refs); } } } private static void LoadConfigDlls (string configFile) { try { XmlTextReader config = new XmlTextReader (configFile); config_dlls = new List<string> (); while (config.Read ()) { if (config.NodeType == XmlNodeType.Element && config.Name == "dllmap") { string dll = config.GetAttribute ("dll"); if (!config_dlls.Contains (dll)) { config_dlls.Add (dll); } } } } catch { } } #region DllImport parser private static StreamReader reader; private static int reader_line; private static int reader_col; private static IEnumerable<DllImportRef> ParseFileForDllImports (string file) { reader_line = 1; reader_col = 1; using (reader = new StreamReader (file)) { char c; bool in_paren = false; bool in_attr = false; bool in_dll_attr = false; bool in_string = false; int dll_line = 1, dll_col = 1; while ((c = (char)reader.Peek ()) != Char.MaxValue) { switch (c) { case ' ': case '\t': Read (); break; case '[': in_attr = true; dll_line = reader_line; dll_col = reader_col; Read (); break; case '(': Read (); in_paren = true; break; case '"': Read (); if (in_dll_attr && in_paren && !in_string) { in_string = true; } break; case ']': in_attr = false; in_dll_attr = false; Read (); break; default: if (!in_dll_attr && in_attr && ReadDllAttribute ()) { in_dll_attr = true; } else if (in_dll_attr && in_string) { yield return new DllImportRef (ReadDllString (), dll_line, dll_col); in_string = false; in_dll_attr = false; in_attr = false; in_paren = false; } else { Read (); } break; } } } } private static bool ReadDllAttribute () { return Read () == 'D' && Read () == 'l' && Read () == 'l' && Read () == 'I' && Read () == 'm' && Read () == 'p' && Read () == 'o' && Read () == 'r' && Read () == 't'; } private static string ReadDllString () { StringBuilder builder = new StringBuilder (32); while (true) { char c = Read (); if (Char.IsLetterOrDigit (c) || c == '.' || c == '-' || c == '_') { builder.Append (c); } else { break; } } return builder.ToString (); } private static char Read () { char c = (char)reader.Read (); if (c == '\n') { reader_line++; reader_col = 1; } else { reader_col++; } return c; } #endregion }
using System; using System.Drawing; using System.Diagnostics; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; namespace Simbiosis { /// <summary> /// One square of terrain, composed of two triangles. /// Vertices are in the order: left triangle - NW, NE, SW; right triangle - SE, SW, NE. /// Note: Triangle strips would take up less space, but I want to batch them and render them all /// at once, so I need to use discrete triangles /// </summary> public class Tile : Renderable { /// <summary> Triangle strip </summary> private CustomVertex.PositionNormalTextured[] mesh = new CustomVertex.PositionNormalTextured[4]; /// <summary> Face normals for the two triangles (1=NW, 2-SE) </summary> private Vector3 faceNormal1 = new Vector3(); public Vector3 FaceNormal1 { get { return faceNormal1; } } private Vector3 faceNormal2 = new Vector3(); public Vector3 FaceNormal2 { get { return faceNormal2; } } /// <summary> ref to the texture </summary> private Texture texture; /// <summary> Overrides of Renderable members - abs centre and radius for culling </summary> private float radius; private Vector3 absCentre; public override float Radius { get { return radius; } } public override Vector3 AbsCentre { get { return absCentre; } } /// <summary> /// Construct a tile. (Normals and textures must be set separately) /// </summary> /// <param name="x">position in the heightfield grid</param> /// <param name="y">position in the heightfield grid</param> /// <param name="tileWidth">width (X) of 1 tile in world coords</param> /// <param name="tileHeight">height (Z) of 1 tile in world coords</param> /// <param name="height">The 2D array of heights</param> public Tile(int x, int y, float tileWidth, float tileHeight, ref float[,] height) { float wx = x*tileWidth; // world xy of top-left vertex float wy = y*tileHeight; // create the two triangles for this square mesh[0].X = wx; mesh[0].Y = height[x,y+1]; mesh[0].Z = wy+tileHeight; mesh[1].X = wx+tileWidth; mesh[1].Y = height[x+1,y+1]; mesh[1].Z = wy+tileHeight; mesh[2].X = wx; mesh[2].Y = height[x,y]; mesh[2].Z = wy; mesh[3].X = wx+tileWidth; mesh[3].Y = height[x+1,y]; mesh[3].Z = wy; // Compute the face normals for the tow triangles faceNormal1 = ThreeDee.FaceNormal(this.mesh[0].Position, this.mesh[1].Position, this.mesh[2].Position); faceNormal2 = ThreeDee.FaceNormal(this.mesh[3].Position, this.mesh[2].Position, this.mesh[1].Position); // Initial vertex normals point in same direction as faces // I'll compute proper ones when all the tiles exist mesh[0].Normal = faceNormal1; mesh[1].Normal = faceNormal1; mesh[2].Normal = faceNormal1; mesh[3].Normal = faceNormal2; // Register the tile with the map Map.Add(this); } /// <summary> /// IDispose interface /// </summary> public override void Dispose() { // TODO: dispose of resources Debug.WriteLine("Disposing of tile resources "); } /// <summary> /// Define the tile texture /// </summary> /// <param name="t"></param> public void SetTexture(Texture t) { // Set the texture to use texture = t; // define the texture coordinates // Assume each quad has a complete texture on it mesh[0].Tu = 0.0f; mesh[0].Tv = 0.0f; mesh[1].Tu = 1.0f; mesh[1].Tv = 0.0f; mesh[2].Tu = 0.0f; mesh[2].Tv = 1.0f; mesh[3].Tu = 1.0f; mesh[3].Tv = 1.0f; } /// <summary> /// Set the vertex normals for the triangles in this tile. /// Each vertex normal is the average of the face normals for surrounding triangles /// (some of which are in different tiles) /// </summary> /// <param name="tile">the array of tiles</param> /// <param name="x">our location in the array</param> /// <param name="y"></param> public static void SetVertexNormal(Tile[,] tile, int x, int y) { // NW vertex tile[x,y].mesh[0].Normal = Vector3.Normalize( tile[x-1,y-1].FaceNormal2 + tile[x,y-1].FaceNormal1 + tile[x,y-1].FaceNormal2 + tile[x,y].FaceNormal1 + tile[x-1,y].FaceNormal2 + tile[x-1,y].FaceNormal1 ); // NE vertex tile[x,y].mesh[1].Normal = Vector3.Normalize( tile[x,y-1].FaceNormal2 + tile[x+1,y-1].FaceNormal1 + tile[x+1,y-1].FaceNormal2 + tile[x+1,y].FaceNormal1 + tile[x,y].FaceNormal2 + tile[x,y].FaceNormal1 ); // SW vertex tile[x,y].mesh[2].Normal = Vector3.Normalize( tile[x-1,y].FaceNormal2 + tile[x,y].FaceNormal1 + tile[x,y].FaceNormal2 + tile[x,y+1].FaceNormal1 + tile[x-1,y+1].FaceNormal2 + tile[x-1,y+1].FaceNormal1 ); // SE vertex tile[x,y].mesh[3].Normal = Vector3.Normalize( tile[x,y].FaceNormal2 + tile[x+1,y].FaceNormal1 + tile[x+1,y].FaceNormal2 + tile[x+1,y+1].FaceNormal1 + tile[x,y+1].FaceNormal2 + tile[x,y+1].FaceNormal1 ); } public override void Update() { // TODO: Add Tile.Update implementation } public override void Render() { // TODO: Add Tile.Render implementation } } /// <summary> /// The terrain /// </summary> public class Terrain : IDisposable { /// <summary> The library of terrain textures </summary> private Texture[] texturelib = null; private Texture texture = null; // TEMP SINGLE TEXTURE UNTIL LIBRARY IS WRITTEN! /// <summary> The 2D array of tiles </summary> private Tile[,] tile = null; /// <summary> size of one tile in world coords </summary> private float tileWidth = 0; private float tileHeight = 0; /// <summary> Size of tile grid </summary> private int gridWidth = 0; private int gridHeight = 0; public Terrain() { float[,] height = null; // Load the height map using (Bitmap bmp = (Bitmap)Bitmap.FromFile(FileResource.Fsp("heightfield.bmp"))) { // compute scale gridWidth = bmp.Width; // scale is determined by the size of the gridHeight = bmp.Height; // heightfield & the size of the map tileWidth = Map.MapWidth / bmp.Width; tileHeight = Map.MapHeight / bmp.Height; gridWidth = bmp.Height-1; // the grid of tiles will be 1 smaller than gridHeight = bmp.Height-1; // the grid of heights (last height = RH side of last tile) // Create the blank tiles tile = new Tile[gridWidth,gridHeight]; // get heightmap into a temp array, for faster access height = new float[bmp.Width,bmp.Height]; for (int y = 0; y<bmp.Height; y++) { for (int x=0; x<bmp.Width; x++) { height[x,y] = (float)bmp.GetPixel(x,y).R / 256.0f; } } } // dispose of the bitmap // Create the tiles and define their extents and heights for (int y = 0; y<gridHeight; y++) { for (int x=0; x<gridWidth; x++) { tile[x,y] = new Tile(x,y,tileWidth,tileHeight,ref height); } } // Now that the triangles exist, define the vertex normals, by averaging the // surface normals of surrounding triangles for (int y = 1; y<gridHeight-1; y++) { for (int x=1; x<gridWidth-1; x++) { Tile.SetVertexNormal(tile,x,y); } } /// TODO: Load the texture map here & create the texture library, /// then set the tile textures // Reload resources on reset of device Engine.Device.DeviceReset += new System.EventHandler(this.OnReset); // Load them for the first time now OnReset(null, null); } public void OnReset(object sender, EventArgs e) { Debug.WriteLine("Terrain.Reset()"); /// TODO: Load the whole library of textures! texture = TextureLoader.FromFile(Engine.Device,FileResource.Fsp("ground.bmp")); texture.GenerateMipSubLevels(); } /// <summary> /// IDispose interface /// </summary> public void Dispose() { // TODO: dispose of resources Debug.WriteLine("Disposing of terrain resources "); } /// <summary> /// Render the mesh /// </summary> public void Render() { Engine.Device.Transform.World = Matrix.Translation(0,0,0); Engine.Device.VertexFormat = CustomVertex.PositionNormalTextured.Format; Engine.Device.SetTexture(0,texture); // Use linear filtering on the magnified texels in mipmap Engine.Device.SamplerState[0].MagFilter = TextureFilter.Linear; Engine.Device.DrawUserPrimitives(PrimitiveType.TriangleStrip, 2, mesh); } /// <summary> /// Return the height of the terrain at x,y /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public static float AltitudeAt(float x, float y) { return 0; // TEMP!!!!!! } /// <summary> /// Return the height of the water surface /// </summary> /// <returns></returns> public static float SurfaceHeight() { return 30.0f; // TEMP !!!!!! } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.IO; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis; using System.Collections.Immutable; using Roslyn.Utilities; using System.Runtime.InteropServices; using System.Globalization; namespace Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests { // TODO: clean up and move to portable tests public class MetadataShadowCopyProviderTests : TestBase, IDisposable { private readonly MetadataShadowCopyProvider _provider; private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create( FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)), FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory())); public MetadataShadowCopyProviderTests() { _provider = CreateProvider(CultureInfo.InvariantCulture); } private static MetadataShadowCopyProvider CreateProvider(CultureInfo culture) { return new MetadataShadowCopyProvider(TempRoot.Root, s_systemNoShadowCopyDirectories, culture); } public override void Dispose() { _provider.Dispose(); Assert.False(Directory.Exists(_provider.ShadowCopyDirectory), "Shadow copy directory should have been deleted"); base.Dispose(); } [Fact] public void Errors() { Assert.Throws<ArgumentNullException>(() => _provider.NeedsShadowCopy(null)); Assert.Throws<ArgumentException>(() => _provider.NeedsShadowCopy("c:foo.dll")); Assert.Throws<ArgumentException>(() => _provider.NeedsShadowCopy("bar.dll")); Assert.Throws<ArgumentException>(() => _provider.NeedsShadowCopy(@"\bar.dll")); Assert.Throws<ArgumentException>(() => _provider.NeedsShadowCopy(@"../bar.dll")); Assert.Throws<ArgumentNullException>(() => _provider.SuppressShadowCopy(null)); Assert.Throws<ArgumentException>(() => _provider.SuppressShadowCopy("c:foo.dll")); Assert.Throws<ArgumentException>(() => _provider.SuppressShadowCopy("bar.dll")); Assert.Throws<ArgumentException>(() => _provider.SuppressShadowCopy(@"\bar.dll")); Assert.Throws<ArgumentException>(() => _provider.SuppressShadowCopy(@"../bar.dll")); Assert.Throws<ArgumentOutOfRangeException>(() => _provider.GetMetadataShadowCopy(@"c:\foo.dll", (MetadataImageKind)Byte.MaxValue)); Assert.Throws<ArgumentNullException>(() => _provider.GetMetadataShadowCopy(null, MetadataImageKind.Assembly)); Assert.Throws<ArgumentException>(() => _provider.GetMetadataShadowCopy("c:foo.dll", MetadataImageKind.Assembly)); Assert.Throws<ArgumentException>(() => _provider.GetMetadataShadowCopy("bar.dll", MetadataImageKind.Assembly)); Assert.Throws<ArgumentException>(() => _provider.GetMetadataShadowCopy(@"\bar.dll", MetadataImageKind.Assembly)); Assert.Throws<ArgumentException>(() => _provider.GetMetadataShadowCopy(@"../bar.dll", MetadataImageKind.Assembly)); Assert.Throws<ArgumentOutOfRangeException>(() => _provider.GetMetadata(@"c:\foo.dll", (MetadataImageKind)Byte.MaxValue)); Assert.Throws<ArgumentNullException>(() => _provider.GetMetadata(null, MetadataImageKind.Assembly)); Assert.Throws<ArgumentException>(() => _provider.GetMetadata("c:foo.dll", MetadataImageKind.Assembly)); } [Fact] public void Copy() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("a.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01); var doc = dir.CreateFile("a.xml").WriteAllText("<hello>"); var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); var sc2 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); Assert.Equal(sc2, sc1); Assert.Equal(dll.Path, sc1.PrimaryModule.OriginalPath); Assert.NotEqual(dll.Path, sc1.PrimaryModule.FullPath); Assert.False(sc1.Metadata.IsImageOwner, "Copy expected"); Assert.Equal(File.ReadAllBytes(dll.Path), File.ReadAllBytes(sc1.PrimaryModule.FullPath)); Assert.Equal(File.ReadAllBytes(doc.Path), File.ReadAllBytes(sc1.DocumentationFile.FullPath)); } [Fact] public void SuppressCopy1() { var dll = Temp.CreateFile().WriteAllText("blah"); _provider.SuppressShadowCopy(dll.Path); var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); Assert.Null(sc1); } [Fact] public void SuppressCopy_Framework() { // framework assemblies not copied: string mscorlib = typeof(object).Assembly.Location; var sc2 = _provider.GetMetadataShadowCopy(mscorlib, MetadataImageKind.Assembly); Assert.Null(sc2); } [Fact] public void SuppressCopy_ShadowCopyDirectory() { // shadow copies not copied: var dll = Temp.CreateFile("a.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01); // copy: var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); Assert.NotEqual(dll.Path, sc1.PrimaryModule.FullPath); // file not copied: var sc2 = _provider.GetMetadataShadowCopy(sc1.PrimaryModule.FullPath, MetadataImageKind.Assembly); Assert.Null(sc2); } [Fact] public void Modules() { // modules: { MultiModule.dll, mod2.netmodule, mod3.netmodule } var dir = Temp.CreateDirectory(); string path0 = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll).Path; string path1 = dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2).Path; string path2 = dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3).Path; var metadata1 = _provider.GetMetadata(path0, MetadataImageKind.Assembly) as AssemblyMetadata; Assert.NotNull(metadata1); Assert.Equal(3, metadata1.GetModules().Length); var scDir = Directory.GetFileSystemEntries(_provider.ShadowCopyDirectory).Single(); Assert.True(Directory.Exists(scDir)); var scFiles = Directory.GetFileSystemEntries(scDir); AssertEx.SetEqual(new[] { "MultiModule.dll", "mod2.netmodule", "mod3.netmodule" }, scFiles.Select(p => Path.GetFileName(p))); foreach (var sc in scFiles) { Assert.True(_provider.IsShadowCopy(sc)); // files should be locked: Assert.Throws<IOException>(() => File.Delete(sc)); } // should get the same metadata: var metadata2 = _provider.GetMetadata(path0, MetadataImageKind.Assembly) as AssemblyMetadata; Assert.Same(metadata1, metadata2); // modify the file: File.SetLastWriteTimeUtc(path0, DateTime.Now + TimeSpan.FromHours(1)); // we get an updated image if we ask again: var modifiedMetadata3 = _provider.GetMetadata(path0, MetadataImageKind.Assembly) as AssemblyMetadata; Assert.NotSame(modifiedMetadata3, metadata2); // the file has been modified - we get new metadata: for (int i = 0; i < metadata2.GetModules().Length; i++) { Assert.NotSame(metadata2.GetModules()[i], modifiedMetadata3.GetModules()[i]); } } [Fact] public unsafe void DisposalOnFailure() { var f0 = Temp.CreateFile().WriteAllText("bogus").Path; Assert.Throws<BadImageFormatException>(() => _provider.GetMetadata(f0, MetadataImageKind.Assembly)); string f1 = Temp.CreateFile().WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll).Path; Assert.Throws<FileNotFoundException>(() => _provider.GetMetadata(f1, MetadataImageKind.Assembly)); } [Fact] public void GetMetadata() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("a.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01); var doc = dir.CreateFile("a.xml").WriteAllText("<hello>"); var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); var sc2 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); var md1 = _provider.GetMetadata(dll.Path, MetadataImageKind.Assembly); Assert.NotNull(md1); Assert.Equal(MetadataImageKind.Assembly, md1.Kind); // This needs to be in different folder from referencesdir to cause the other code path // to be triggered for NeedsShadowCopy method var dir2 = Path.GetTempPath(); string dll2 = Path.Combine(dir2, "a2.dll"); File.WriteAllBytes(dll2, TestResources.MetadataTests.InterfaceAndClass.CSClasses01); Assert.Equal(1, _provider.CacheSize); var sc3a = _provider.GetMetadataShadowCopy(dll2, MetadataImageKind.Module); Assert.Equal(2, _provider.CacheSize); } [Fact] public void XmlDocComments_SpecificCulture() { var elGR = CultureInfo.GetCultureInfo("el-GR"); var arMA = CultureInfo.GetCultureInfo("ar-MA"); var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("a.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01); var docInvariant = dir.CreateFile("a.xml").WriteAllText("Invariant"); var docGreek = dir.CreateDirectory(elGR.Name).CreateFile("a.xml").WriteAllText("Greek"); // invariant culture var provider = CreateProvider(CultureInfo.InvariantCulture); var sc = provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); Assert.Equal(Path.Combine(Path.GetDirectoryName(sc.PrimaryModule.FullPath), @"a.xml"), sc.DocumentationFile.FullPath); Assert.Equal("Invariant", File.ReadAllText(sc.DocumentationFile.FullPath)); // greek culture provider = CreateProvider(elGR); sc = provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); Assert.Equal(Path.Combine(Path.GetDirectoryName(sc.PrimaryModule.FullPath), @"el-GR\a.xml"), sc.DocumentationFile.FullPath); Assert.Equal("Greek", File.ReadAllText(sc.DocumentationFile.FullPath)); // arabic culture (culture specific docs not found, use invariant) provider = CreateProvider(arMA); sc = provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); Assert.Equal(Path.Combine(Path.GetDirectoryName(sc.PrimaryModule.FullPath), @"a.xml"), sc.DocumentationFile.FullPath); Assert.Equal("Invariant", File.ReadAllText(sc.DocumentationFile.FullPath)); // no culture: provider = CreateProvider(null); sc = provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); Assert.Null(sc.DocumentationFile); } } }
// 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.MirrorPolymorphic { using Microsoft.Rest; using Models; /// <summary> /// Some cool documentation. /// </summary> public partial class PolymorphicAnimalStore : Microsoft.Rest.ServiceClient<PolymorphicAnimalStore>, IPolymorphicAnimalStore { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolymorphicAnimalStore(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore 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> public PolymorphicAnimalStore(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore 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> public PolymorphicAnimalStore(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PolymorphicAnimalStore(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("https://management.azure.com/"); SerializationSettings = new Newtonsoft.Json.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 Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<Animal>("dtype")); DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<Animal>("dtype")); CustomInitialize(); } /// <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='animalCreateOrUpdateParameter'> /// An Animal /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Error2Exception"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Animal>> CreateOrUpdatePolymorphicAnimalsWithHttpMessagesAsync(Animal animalCreateOrUpdateParameter = default(Animal), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("animalCreateOrUpdateParameter", animalCreateOrUpdateParameter); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdatePolymorphicAnimals", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "getpolymorphicAnimals").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _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 (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(animalCreateOrUpdateParameter != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, this.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"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Error2Exception(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error2 _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error2>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<Animal>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Animal>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// 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.AcceptanceTestsModelFlattening { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Resource Flattening for AutoRest /// </summary> public partial class AutoRestResourceFlatteningTestService : ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService { /// <summary> /// The base URI of the service. /// </summary> public 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> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestResourceFlatteningTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> public AutoRestResourceFlatteningTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> public AutoRestResourceFlatteningTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> public AutoRestResourceFlatteningTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("http://localhost"); SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); } /// <summary> /// Put External Resource as an Array /// </summary> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceArray", resourceArray); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/array").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as an Array /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetArray", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/array").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse<IList<FlattenedProduct>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IList<FlattenedProduct>>(_responseContent, this.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> /// Put External Resource as a Dictionary /// </summary> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceDictionary", resourceDictionary); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/dictionary").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as a Dictionary /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetDictionary", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/dictionary").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse<IDictionary<string, FlattenedProduct>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, FlattenedProduct>>(_responseContent, this.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> /// Put External Resource as a ResourceCollection /// </summary> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceComplexObject", resourceComplexObject); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/resourcecollection").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as a ResourceCollection /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/resourcecollection").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse<ResourceCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, this.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> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='simpleBodyProduct'> /// Simple body product to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<SimpleProduct>> PutSimpleProductWithHttpMessagesAsync(SimpleProduct simpleBodyProduct = default(SimpleProduct), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (simpleBodyProduct != null) { simpleBodyProduct.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutSimpleProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.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> /// Put Flattened Simple Product with client flattening true on the parameter /// </summary> /// <param name='productId'> /// Unique identifier representing a specific product for a given latitude /// &amp; longitude. For example, uberX in San Francisco will have a /// different product_id than uberX in Los Angeles. /// </param> /// <param name='maxProductDisplayName'> /// Display name of product. /// </param> /// <param name='description'> /// Description of product. /// </param> /// <param name='odatavalue'> /// URL value. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<SimpleProduct>> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (productId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "productId"); } if (maxProductDisplayName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "maxProductDisplayName"); } SimpleProduct simpleBodyProduct = default(SimpleProduct); if (productId != null || description != null || maxProductDisplayName != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostFlattenedSimpleProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.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> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='flattenParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<SimpleProduct>> PutSimpleProductWithGroupingWithHttpMessagesAsync(FlattenParameterGroup flattenParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (flattenParameterGroup == null) { throw new ValidationException(ValidationRules.CannotBeNull, "flattenParameterGroup"); } if (flattenParameterGroup != null) { flattenParameterGroup.Validate(); } string name = default(string); if (flattenParameterGroup != null) { name = flattenParameterGroup.Name; } string productId = default(string); if (flattenParameterGroup != null) { productId = flattenParameterGroup.ProductId; } string description = default(string); if (flattenParameterGroup != null) { description = flattenParameterGroup.Description; } string maxProductDisplayName = default(string); if (flattenParameterGroup != null) { maxProductDisplayName = flattenParameterGroup.MaxProductDisplayName; } string odatavalue = default(string); if (flattenParameterGroup != null) { odatavalue = flattenParameterGroup.Odatavalue; } SimpleProduct simpleBodyProduct = default(SimpleProduct); if (productId != null || description != null || maxProductDisplayName != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("name", name); tracingParameters.Add("productId", productId); tracingParameters.Add("description", description); tracingParameters.Add("maxProductDisplayName", maxProductDisplayName); tracingParameters.Add("odatavalue", odatavalue); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutSimpleProductWithGrouping", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening/parametergrouping/{name}/").ToString(); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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, this.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 HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.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 MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.Serialization; using System.Security.Principal; namespace System.Security.Claims { /// <summary> /// An Identity that is represented by a set of claims. /// </summary> public class ClaimsIdentity : IIdentity { private const string PreFix = "System.Security.ClaimsIdentity."; private const string AuthenticationTypeKey = PreFix + "authenticationType"; private const string LabelKey = PreFix + "label"; private const string NameClaimTypeKey = PreFix + "nameClaimType"; private const string RoleClaimTypeKey = PreFix + "roleClaimType"; private const string VersionKey = PreFix + "version"; private enum SerializationMask { None = 0, AuthenticationType = 1, BootstrapConext = 2, NameClaimType = 4, RoleClaimType = 8, HasClaims = 16, HasLabel = 32, Actor = 64, UserData = 128, } private byte[] _userSerializationData; private ClaimsIdentity _actor; private string _authenticationType; private object _bootstrapContext; private List<List<Claim>> _externalClaims; private string _label; private List<Claim> _instanceClaims = new List<Claim>(); private string _nameClaimType = DefaultNameClaimType; private string _roleClaimType = DefaultRoleClaimType; public const string DefaultIssuer = @"LOCAL AUTHORITY"; public const string DefaultNameClaimType = ClaimTypes.Name; public const string DefaultRoleClaimType = ClaimTypes.Role; // NOTE about _externalClaims. // GenericPrincpal and RolePrincipal set role claims here so that .IsInRole will be consistent with a 'role' claim found by querying the identity or principal. // _externalClaims are external to the identity and assumed to be dynamic, they not serialized or copied through Clone(). // Access through public method: ClaimProviders. /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> public ClaimsIdentity() : this((IIdentity)null, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IIdentity identity) : this(identity, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <remarks> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> /// </remarks> public ClaimsIdentity(IEnumerable<Claim> claims) : this((IIdentity)null, claims, (string)null, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="authenticationType">The authentication method used to establish this identity.</param> public ClaimsIdentity(string authenticationType) : this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The authentication method used to establish this identity.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType) : this((IIdentity)null, claims, authenticationType, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims) : this(identity, claims, (string)null, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(string authenticationType, string nameType, string roleType) : this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, nameType, roleType) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType) : this((IIdentity)null, claims, authenticationType, nameType, roleType) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks>If 'identity' is a <see cref="ClaimsIdentity"/>, then there are potentially multiple sources for AuthenticationType, NameClaimType, RoleClaimType. /// <para>Priority is given to the parameters: authenticationType, nameClaimType, roleClaimType.</para> /// <para>All <see cref="Claim"/>s are copied into this instance in a <see cref="List{Claim}"/>. Each Claim is examined and if Claim.Subject != this, then Claim.Clone(this) is called before the claim is added.</para> /// <para>Any 'External' claims are ignored.</para> /// </remarks> /// <exception cref="InvalidOperationException">if 'identity' is a <see cref="ClaimsIdentity"/> and <see cref="ClaimsIdentity.Actor"/> results in a circular refrence back to 'this'.</exception> public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType) { ClaimsIdentity claimsIdentity = identity as ClaimsIdentity; _authenticationType = (identity != null && string.IsNullOrEmpty(authenticationType)) ? identity.AuthenticationType : authenticationType; _nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity != null ? claimsIdentity._nameClaimType : DefaultNameClaimType); _roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity != null ? claimsIdentity._roleClaimType : DefaultRoleClaimType); if (claimsIdentity != null) { _label = claimsIdentity._label; _bootstrapContext = claimsIdentity._bootstrapContext; if (claimsIdentity.Actor != null) { // // Check if the Actor is circular before copying. That check is done while setting // the Actor property and so not really needed here. But checking just for sanity sake // if (!IsCircular(claimsIdentity.Actor)) { _actor = claimsIdentity.Actor; } else { throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular); } } SafeAddClaims(claimsIdentity._instanceClaims); } else { if (identity != null && !string.IsNullOrEmpty(identity.Name)) { SafeAddClaim(new Claim(_nameClaimType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this)); } } if (claims != null) { SafeAddClaims(claims); } } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/> using a <see cref="BinaryReader"/>. /// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> public ClaimsIdentity(BinaryReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Initialize(reader); } /// <summary> /// Copy constructor. /// </summary> /// <param name="other"><see cref="ClaimsIdentity"/> to copy.</param> /// <exception cref="ArgumentNullException">if 'other' is null.</exception> protected ClaimsIdentity(ClaimsIdentity other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } if (other._actor != null) { _actor = other._actor.Clone(); } _authenticationType = other._authenticationType; _bootstrapContext = other._bootstrapContext; _label = other._label; _nameClaimType = other._nameClaimType; _roleClaimType = other._roleClaimType; if (other._userSerializationData != null) { _userSerializationData = other._userSerializationData.Clone() as byte[]; } SafeAddClaims(other._instanceClaims); } protected ClaimsIdentity(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/> from a serialized stream created via /// <see cref="ISerializable"/>. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> to read from. /// </param> /// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception> [SecurityCritical] protected ClaimsIdentity(SerializationInfo info) { throw new PlatformNotSupportedException(); } /// <summary> /// Gets the authentication type that can be used to determine how this <see cref="ClaimsIdentity"/> authenticated to an authority. /// </summary> public virtual string AuthenticationType { get { return _authenticationType; } } /// <summary> /// Gets a value that indicates if the user has been authenticated. /// </summary> public virtual bool IsAuthenticated { get { return !string.IsNullOrEmpty(_authenticationType); } } /// <summary> /// Gets or sets a <see cref="ClaimsIdentity"/> that was granted delegation rights. /// </summary> /// <exception cref="InvalidOperationException">if 'value' results in a circular reference back to 'this'.</exception> public ClaimsIdentity Actor { get { return _actor; } set { if (value != null) { if (IsCircular(value)) { throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular); } } _actor = value; } } /// <summary> /// Gets or sets a context that was used to create this <see cref="ClaimsIdentity"/>. /// </summary> public object BootstrapContext { get { return _bootstrapContext; } set { _bootstrapContext = value; } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsIdentity"/>. /// </summary> /// <remarks>May contain nulls.</remarks> public virtual IEnumerable<Claim> Claims { get { if (_externalClaims == null) { return _instanceClaims; } return CombinedClaimsIterator(); } } private IEnumerable<Claim> CombinedClaimsIterator() { for (int i = 0; i < _instanceClaims.Count; i++) { yield return _instanceClaims[i]; } for (int j = 0; j < _externalClaims.Count; j++) { if (_externalClaims[j] != null) { foreach (Claim claim in _externalClaims[j]) { yield return claim; } } } } /// <summary> /// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>. /// </summary> protected virtual byte[] CustomSerializationData { get { return _userSerializationData; } } /// <summary> /// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>. /// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>. /// </summary> internal List<List<Claim>> ExternalClaims { get { if (_externalClaims == null) { _externalClaims = new List<List<Claim>>(); } return _externalClaims; } } /// <summary> /// Gets or sets the label for this <see cref="ClaimsIdentity"/> /// </summary> public string Label { get { return _label; } set { _label = value; } } /// <summary> /// Gets the Name of this <see cref="ClaimsIdentity"/>. /// </summary> /// <remarks>Calls <see cref="FindFirst(string)"/> where string == NameClaimType, if found, returns <see cref="Claim.Value"/> otherwise null.</remarks> public virtual string Name { // just an accessor for getting the name claim get { Claim claim = FindFirst(_nameClaimType); if (claim != null) { return claim.Value; } return null; } } /// <summary> /// Gets the value that identifies 'Name' claims. This is used when returning the property <see cref="ClaimsIdentity.Name"/>. /// </summary> public string NameClaimType { get { return _nameClaimType; } } /// <summary> /// Gets the value that identifies 'Role' claims. This is used when calling <see cref="ClaimsPrincipal.IsInRole"/>. /// </summary> public string RoleClaimType { get { return _roleClaimType; } } /// <summary> /// Creates a new instance of <see cref="ClaimsIdentity"/> with values copied from this object. /// </summary> public virtual ClaimsIdentity Clone() { return new ClaimsIdentity(this); } /// <summary> /// Adds a single <see cref="Claim"/> to an internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/>add.</param> /// <remarks>If <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks> /// <exception cref="ArgumentNullException">if 'claim' is null.</exception> public virtual void AddClaim(Claim claim) { if (claim == null) { throw new ArgumentNullException(nameof(claim)); } Contract.EndContractBlock(); if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } /// <summary> /// Adds a <see cref="IEnumerable{Claim}"/> to the internal list. /// </summary> /// <param name="claims">Enumeration of claims to add.</param> /// <remarks>Each claim is examined and if <see cref="Claim.Subject"/> != this, then then Claim.Clone(this) is called before the claim is added.</remarks> /// <exception cref="ArgumentNullException">if 'claims' is null.</exception> public virtual void AddClaims(IEnumerable<Claim> claims) { if (claims == null) { throw new ArgumentNullException(nameof(claims)); } Contract.EndContractBlock(); foreach (Claim claim in claims) { if (claim == null) { continue; } if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } } /// <summary> /// Attempts to remove a <see cref="Claim"/> the internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/> to match.</param> /// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference. /// <para>object.ReferenceEquals is used to 'match'.</para> /// </remarks> public virtual bool TryRemoveClaim(Claim claim) { if (claim == null) { return false; } bool removed = false; for (int i = 0; i < _instanceClaims.Count; i++) { if (object.ReferenceEquals(_instanceClaims[i], claim)) { _instanceClaims.RemoveAt(i); removed = true; break; } } return removed; } /// <summary> /// Removes a <see cref="Claim"/> from the internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/> to match.</param> /// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference. /// <para>object.ReferenceEquals is used to 'match'.</para> /// </remarks> /// <exception cref="InvalidOperationException">if 'claim' cannot be removed.</exception> public virtual void RemoveClaim(Claim claim) { if (!TryRemoveClaim(claim)) { throw new InvalidOperationException(string.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim)); } } /// <summary> /// Adds claims to internal list. Calling Claim.Clone if Claim.Subject != this. /// </summary> /// <param name="claims">a <see cref="IEnumerable{Claim}"/> to add to </param> /// <remarks>private only call from constructor, adds to internal list.</remarks> private void SafeAddClaims(IEnumerable<Claim> claims) { foreach (Claim claim in claims) { if (claim == null) continue; if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } } /// <summary> /// Adds claim to internal list. Calling Claim.Clone if Claim.Subject != this. /// </summary> /// <remarks>private only call from constructor, adds to internal list.</remarks> private void SafeAddClaim(Claim claim) { if (claim == null) return; if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } /// <summary> /// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <paramref name="match"/>. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); foreach (Claim claim in Claims) { if (match(claim)) { yield return claim; } } } /// <summary> /// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>. /// </summary> /// <param name="type">The type of the claim to match.</param> /// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> public virtual IEnumerable<Claim> FindAll(string type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); foreach (Claim claim in Claims) { if (claim != null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { yield return claim; } } } } /// <summary> /// Retrieves the first <see cref="Claim"/> that is matched by <paramref name="match"/>. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>A <see cref="Claim"/>, null if nothing matches.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual Claim FindFirst(Predicate<Claim> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); foreach (Claim claim in Claims) { if (match(claim)) { return claim; } } return null; } /// <summary> /// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>. /// </summary> /// <param name="type">The type of the claim to match.</param> /// <returns>A <see cref="Claim"/>, null if nothing matches.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> public virtual Claim FindFirst(string type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); foreach (Claim claim in Claims) { if (claim != null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { return claim; } } } return null; } /// <summary> /// Determines if a claim is contained within this ClaimsIdentity. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>true if a claim is found, false otherwise.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual bool HasClaim(Predicate<Claim> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); foreach (Claim claim in Claims) { if (match(claim)) { return true; } } return false; } /// <summary> /// Determines if a claim with type AND value is contained within this ClaimsIdentity. /// </summary> /// <param name="type">the type of the claim to match.</param> /// <param name="value">the value of the claim to match.</param> /// <returns>true if a claim is matched, false otherwise.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase for Claim.Type, StringComparison.Ordinal for Claim.Value.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> /// <exception cref="ArgumentNullException">if 'value' is null.</exception> public virtual bool HasClaim(string type, string value) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); foreach (Claim claim in Claims) { if (claim != null && string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase) && string.Equals(claim.Value, value, StringComparison.Ordinal)) { return true; } } return false; } /// <summary> /// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/> /// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> private void Initialize(BinaryReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesRead = 0; int numPropertiesToRead = reader.ReadInt32(); if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType) { _authenticationType = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext) { _bootstrapContext = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { _nameClaimType = reader.ReadString(); numPropertiesRead++; } else { _nameClaimType = ClaimsIdentity.DefaultNameClaimType; } if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { _roleClaimType = reader.ReadString(); numPropertiesRead++; } else { _roleClaimType = ClaimsIdentity.DefaultRoleClaimType; } if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel) { _label = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims) { int numberOfClaims = reader.ReadInt32(); for (int index = 0; index < numberOfClaims; index++) { _instanceClaims.Add(CreateClaim(reader)); } numPropertiesRead++; } if ((mask & SerializationMask.Actor) == SerializationMask.Actor) { _actor = new ClaimsIdentity(reader); numPropertiesRead++; } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { int cb = reader.ReadInt32(); _userSerializationData = reader.ReadBytes(cb); numPropertiesRead++; } for (int i = numPropertiesRead; i < numPropertiesToRead; i++) { reader.ReadString(); } } /// <summary> /// Provides an extensibility point for derived types to create a custom <see cref="Claim"/>. /// </summary> /// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param> /// <returns>a new <see cref="Claim"/>.</returns> protected virtual Claim CreateClaim(BinaryReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return new Claim(reader, this); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> public virtual void WriteTo(BinaryWriter writer) { WriteTo(writer, null); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <param name="userData">additional data provided by derived type.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> protected virtual void WriteTo(BinaryWriter writer, byte[] userData) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } int numberOfPropertiesWritten = 0; var mask = SerializationMask.None; if (_authenticationType != null) { mask |= SerializationMask.AuthenticationType; numberOfPropertiesWritten++; } if (_bootstrapContext != null) { string rawData = _bootstrapContext as string; if (rawData != null) { mask |= SerializationMask.BootstrapConext; numberOfPropertiesWritten++; } } if (!string.Equals(_nameClaimType, ClaimsIdentity.DefaultNameClaimType, StringComparison.Ordinal)) { mask |= SerializationMask.NameClaimType; numberOfPropertiesWritten++; } if (!string.Equals(_roleClaimType, ClaimsIdentity.DefaultRoleClaimType, StringComparison.Ordinal)) { mask |= SerializationMask.RoleClaimType; numberOfPropertiesWritten++; } if (!string.IsNullOrWhiteSpace(_label)) { mask |= SerializationMask.HasLabel; numberOfPropertiesWritten++; } if (_instanceClaims.Count > 0) { mask |= SerializationMask.HasClaims; numberOfPropertiesWritten++; } if (_actor != null) { mask |= SerializationMask.Actor; numberOfPropertiesWritten++; } if (userData != null && userData.Length > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.UserData; } writer.Write((int)mask); writer.Write(numberOfPropertiesWritten); if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType) { writer.Write(_authenticationType); } if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext) { writer.Write(_bootstrapContext as string); } if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { writer.Write(_nameClaimType); } if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { writer.Write(_roleClaimType); } if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel) { writer.Write(_label); } if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims) { writer.Write(_instanceClaims.Count); foreach (var claim in _instanceClaims) { claim.WriteTo(writer); } } if ((mask & SerializationMask.Actor) == SerializationMask.Actor) { _actor.WriteTo(writer); } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { writer.Write(userData.Length); writer.Write(userData); } writer.Flush(); } /// <summary> /// Checks if a circular reference exists to 'this' /// </summary> /// <param name="subject"></param> /// <returns></returns> private bool IsCircular(ClaimsIdentity subject) { if (ReferenceEquals(this, subject)) { return true; } ClaimsIdentity currSubject = subject; while (currSubject.Actor != null) { if (ReferenceEquals(this, currSubject.Actor)) { return true; } currSubject = currSubject.Actor; } return false; } /// <summary> /// Populates the specified <see cref="SerializationInfo"/> with the serialization data for the ClaimsIdentity /// </summary> /// <param name="info">The serialization information stream to write to. Satisfies ISerializable contract.</param> /// <param name="context">Context for serialization. Can be null.</param> /// <exception cref="ArgumentNullException">Thrown if the info parameter is null.</exception> protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.ExtractMethod; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod { public class ExtractMethodTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace) => new ExtractMethodCodeRefactoringProvider(); [WorkItem(540799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestPartialSelection() { await TestAsync( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) { return b != true; } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestCodeStyle1() { await TestAsync( @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine([|b != true|] ? b = true : b = false); } }", @"class Program { static void Main(string[] args) { bool b = true; System.Console.WriteLine({|Rename:NewMethod|}(b) ? b = true : b = false); } private static bool NewMethod(bool b) => b != true; }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CodeStyleOptions.TrueWithNoneEnforcement)); } [WorkItem(540796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540796")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestReadOfDataThatDoesNotFlowIn() { await TestAsync( @"class Program { static void Main(string[] args) { int x = 1; object y = 0; [|int s = true ? fun(x) : fun(y);|] } private static T fun<T>(T t) { return t; } }", @"class Program { static void Main(string[] args) { int x = 1; object y = 0; {|Rename:NewMethod|}(x, y); } private static void NewMethod(int x, object y) { int s = true ? fun(x) : fun(y); } private static T fun<T>(T t) { return t; } }", index: 0); } [WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnGoto() { await TestMissingAsync( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { [|goto label2; return x * x;|] }; label2: return; } }"); } [WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnStatementAfterUnconditionalGoto() { await TestAsync( @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; [|return x * x;|] }; label2: return; } }", @"delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; return {|Rename:NewMethod|}(x); }; label2: return; } private static int NewMethod(int x) { return x * x; } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnNamespace() { await TestAsync( @"class Program { void Main() { [|System|].Console.WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { System.Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnType() { await TestAsync( @"class Program { void Main() { [|System.Console|].WriteLine(4); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private static void NewMethod() { System.Console.WriteLine(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnBase() { await TestAsync( @"class Program { void Main() { [|base|].ToString(); } }", @"class Program { void Main() { {|Rename:NewMethod|}(); } private void NewMethod() { base.ToString(); } }"); } [WorkItem(545623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545623")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnActionInvocation() { await TestAsync( @"using System; class C { public static Action X { get; set; } } class Program { void Main() { [|C.X|](); } }", @"using System; class C { public static Action X { get; set; } } class Program { void Main() { {|Rename:GetX|}()(); } private static Action GetX() { return C.X; } }"); } [WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary1() { await TestAsync( @"using System; class Program { static void Main() { byte z = 0; Foo([|x => 0|], y => 0, z, z); } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Foo<byte, byte>({|Rename:NewMethod|}(), y => 0, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", compareTokens: false); } [WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary2() { await TestAsync( @"using System; class Program { static void Main() { byte z = 0; Foo([|x => 0|], y => { return 0; }, z, z); } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Foo<byte, byte>({|Rename:NewMethod|}(), y => { return 0; }, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", compareTokens: false); } [WorkItem(530709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530709")] [WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesize() { await TestAsync( @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex(), y), - -1); } } static class E { public static void Ex(this int x) { } }", @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesizeGenerics() { await TestAsync( @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1); } } static class E { public static void Ex<T>(this int x) { } }", @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex<T>(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_1() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do();|] obj1.Do(); obj2.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2; {|Rename:NewMethod|}(out obj1, out obj2); obj1.Do(); obj2.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); } }", compareTokens: false); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_2() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ Construct obj3 = new Construct(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ obj3 = new Construct(); obj3.Do(); } }", compareTokens: false); } [WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_3() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(), obj3 = new Construct(); obj2.Do(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj3 = new Construct(); obj2.Do(); obj3.Do(); } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTuple() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int, int) x = (1, 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationWithNames() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationWithSomeNames() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int a, int) x = (1, 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleLiteralWithNames() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int, int) x = (a: 1, b: 2);|] System.Console.WriteLine(x.Item1); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (a: 1, b: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleDeclarationAndLiteralWithNames() { await TestAsync( @"class Program { static void Main(string[] args) { [|(int a, int b) x = (c: 1, d: 2);|] System.Console.WriteLine(x.a); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleIntoVar() { await TestAsync( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int c, int d) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task RefactorWithoutSystemValueTuple() { await TestAsync( @"class Program { static void Main(string[] args) { [|var x = (c: 1, d: 2);|] System.Console.WriteLine(x.c); } }", @"class Program { static void Main(string[] args) { object x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static object NewMethod() { return (c: 1, d: 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] [WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")] public async Task TestTupleWithNestedNamedTuple() { // This is not the best refactoring, but this is an edge case await TestAsync( @"class Program { static void Main(string[] args) { [|var x = new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world""));|] System.Console.WriteLine(x.c); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { (int, int, int, int, int, int, int, string, string) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int, int, int, int, int, int, int, string, string) NewMethod() { return new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world"")); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] public async Task TestDeconstruction() { await TestAsync( @"class Program { static void Main(string[] args) { var (x, y) = [|(1, 2)|]; System.Console.WriteLine(x); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = {|Rename:NewMethod|}(); System.Console.WriteLine(x); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] public async Task TestDeconstruction2() { await TestAsync( @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); var z = [|3;|] System.Console.WriteLine(z); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs, @"class Program { static void Main(string[] args) { var (x, y) = (1, 2); int z = {|Rename:NewMethod|}(); System.Console.WriteLine(z); } private static int NewMethod() { return 3; } }" + TestResources.NetFX.ValueTuple.tuplelib_cs); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.OutVar)] public async Task TestOutVar() { await TestAsync( @"class C { static void M(int i) { int r; [|r = M1(out int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(int i, out int r, out int y) { r = M1(out y, i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)] public async Task TestIsPattern() { await TestAsync( @"class C { static void M(int i) { int r; [|r = M1(3 is int y, i);|] System.Console.WriteLine(r + y); } }", @"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(int i, out int r, out int y) { r = M1(3 is int {|Conflict:y|}, i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)] public async Task TestOutVarAndIsPattern() { await TestAsync( @"class C { static void M() { int r; [|r = M1(out /*out*/ int /*int*/ y /*y*/) + M2(3 is int z);|] System.Console.WriteLine(r + y + z); } } ", @"class C { static void M() { int r; int y, z; {|Rename:NewMethod|}(out r, out y, out z); System.Console.WriteLine(r + y + z); } private static void NewMethod(out int r, out int y, out int z) { r = M1(out /*out*/ /*int*/ y /*y*/) + M2(3 is int {|Conflict:z|}); } } ", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)] public async Task ConflictingOutVarLocals() { await TestAsync( @"class C { static void M() { int r; [|r = M1(out int y); { M2(out int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(out int r, out int y) { r = M1(out y); { M2(out int y); System.Console.Write(y); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] [Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)] public async Task ConflictingPatternLocals() { await TestAsync( @"class C { static void M() { int r; [|r = M1(1 is int y); { M2(2 is int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } }", @"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); } private static void NewMethod(out int r, out int y) { r = M1(1 is int {|Conflict:y|}); { M2(2 is int y); System.Console.Write(y); } } }"); } [WorkItem(15218, "https://github.com/dotnet/roslyn/issues/15218")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestCancellationTokenGoesLast() { await TestAsync( @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; [|if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); }|] } }", @"using System; using System.Threading; class C { void M(CancellationToken ct) { var v = 0; {|Rename:NewMethod|}(v, ct); } private static void NewMethod(int v, CancellationToken ct) { if (true) { ct.ThrowIfCancellationRequested(); Console.WriteLine(v); } } }"); } [WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseVar1() { await TestAsync( @"using System; class C { void Foo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Foo(int i) { var v = {|Rename:NewMethod|}(i); Console.WriteLine(v); } private static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } }", options: Option(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, CodeStyleOptions.TrueWithSuggestionEnforcement)); } [WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestUseVar2() { await TestAsync( @"using System; class C { void Foo(int i) { [|var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; }|] Console.WriteLine(v); } }", @"using System; class C { void Foo(int i) { string v = {|Rename:NewMethod|}(i); Console.WriteLine(v); } private static string NewMethod(int i) { var v = (string)null; switch (i) { case 0: v = ""0""; break; case 1: v = ""1""; break; } return v; } }", options: Option(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, CodeStyleOptions.TrueWithSuggestionEnforcement)); } } }
using System; using System.Collections; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Tamir.SharpSsh.jsch; /* * SshStream.cs * * THIS SOURCE CODE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * * Copyright (C) 2005 Tamir Gal, tamirgal@myrealbox.com. */ namespace Tamir.SharpSsh { /// <summary> /// A Stream based SSH class /// </summary> public class SshStream : Stream { private Stream m_in; private Stream m_out; private ChannelShell m_channel; private string m_host; private Regex m_prompt; private string m_escapeCharPattern; private bool m_removeTerminalChars = false; private Session m_session; /// <summary> /// Constructs a new SSH stream. /// </summary> /// <param name="host">The hostname or IP address of the remote SSH machine</param> /// <param name="username">The name of the user connecting to the remote machine</param> /// <param name="password">The password of the user connecting to the remote machine</param> public SshStream(string host, string username, string password) { this.m_host = host; JSch jsch = new JSch(); m_session = jsch.getSession(username, host, 22); m_session.setPassword(password); Hashtable config = new Hashtable(); config.Add("StrictHostKeyChecking", "no"); m_session.setConfig(config); m_session.connect(); m_channel = (ChannelShell) m_session.openChannel("shell"); m_in = m_channel.getInputStream(); m_out = m_channel.getOutputStream(); m_channel.connect(); m_channel.setPtySize(80, 132, 1024, 768); Prompt = "\n"; m_escapeCharPattern = "\\[[0-9;?]*[^0-9;]"; } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count- 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream. </param> /// <param name="count">The maximum number of bytes to be read from the current stream. </param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> public override int Read(byte[] buffer, int offset, int count) { return m_in.Read(buffer, offset, count); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count- 1) replaced by the bytes read from the current source.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> public virtual int Read(byte[] buffer) { return Read(buffer, 0, buffer.Length); } /// <summary> /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { return m_in.ReadByte(); } /// <summary> /// Writes a byte to the current position in the stream and advances the position within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream. </param> public override void WriteByte(byte value) { m_out.WriteByte(value); } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream. </param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream. </param> public override void Write(byte[] buffer, int offset, int count) { m_out.Write(buffer, offset, count); } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream. </param> public virtual void Write(byte[] buffer) { Write(buffer, 0, buffer.Length); } /// <summary> /// Writes a String into the SSH channel. This method appends an 'end of line' character to the input string. /// </summary> /// <param name="data">The String to write to the SSH channel.</param> public void Write(String data) { data += "\r"; Write(Encoding.Default.GetBytes(data)); Flush(); } /// <summary> /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. /// </summary> public override void Close() { try { base.Close(); m_in.Close(); m_out.Close(); m_channel.close(); m_channel.disconnect(); m_session.disconnect(); } catch { } } /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> public override bool CanRead { get { return m_in.CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> public override bool CanWrite { get { return m_out.CanWrite; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. This stream cannot seek, and will always return false. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> public override void Flush() { m_out.Flush(); } /// <summary> /// Gets the length in bytes of the stream. /// </summary> public override long Length { get { return 0; } } /// <summary> /// Gets or sets the position within the current stream. This Stream cannot seek. This property has no effect on the Stream and will always return 0. /// </summary> public override long Position { get { return 0; } set { } } /// <summary> /// This method has no effect on the Stream. /// </summary> public override void SetLength(long value) { } /// <summary> /// This method has no effect on the Stream. /// </summary> public override long Seek(long offset, SeekOrigin origin) { return 0; } /// <summary> /// A regular expression pattern string to match when reading the resonse using the ReadResponse() method. The default prompt value is "\n" which makes the ReadRespons() method return one line of response. /// </summary> public string Prompt { get { return m_prompt.ToString(); } set { m_prompt = new Regex(value, RegexOptions.Singleline); } } /// <summary> /// Gets or sets a value indicating wether this Steam sould remove the terminal emulation's escape sequence characters from the response String. /// </summary> public bool RemoveTerminalEmulationCharacters { get { return m_removeTerminalChars; } set { m_removeTerminalChars = value; } } /// <summary> /// Gets the Cipher algorithm name used in this SSH connection. /// </summary> public string Cipher { get { return m_session.getCipher(); } } /// <summary> /// Gets the MAC algorithm name used in this SSH connection. /// </summary> public string Mac { get { return m_session.getMac(); } } /// <summary> /// Gets the server SSH version string. /// </summary> public string ServerVersion { get { return m_session.getServerVersion(); } } /// <summary> /// Gets the client SSH version string. /// </summary> public string ClientVersion { get { return m_session.getClientVersion(); } } /// <summary> /// Reads a response string from the SSH channel. This method will block until the pattern in the 'Prompt' property is matched in the response. /// </summary> /// <returns>A response string from the SSH server.</returns> public string ReadResponse() { Thread.Sleep(5); // It will always take at least 5 milliseconds to get a response back. int readCount; StringBuilder resp = new StringBuilder(); byte[] buff = new byte[1024]; Match match; for (int i = 10; i > 0; i--) // Prevents infinite waiting. { readCount = this.Read(buff); if (readCount < 0) resp.Append(""); else { string nextTextPart = Encoding.Default.GetString(buff); resp.Append(nextTextPart, 0, readCount); if (!String.IsNullOrEmpty(nextTextPart)) i = 10; // As long as we're receiving text the loop keeps going. } string s = resp.ToString(); match = m_prompt.Match(s); Thread.Sleep(2*i); if (match.Success) break; } return HandleTerminalChars(resp.ToString()); } /// <summary> /// Removes escape sequence characters from the input string. /// </summary> /// <param name="str"></param> /// <returns></returns> private string HandleTerminalChars(string str) { if (RemoveTerminalEmulationCharacters) { str = str.Replace("(B)0", ""); str = Regex.Replace(str, m_escapeCharPattern, ""); str = str.Replace(((char) 15).ToString(), ""); str = Regex.Replace(str, ((char) 27).ToString() + "=*", ""); //str = Regex.Replace(str, "\\s*\r\n", "\r\n"); } return str; } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Models { /// <summary> /// PipelineActivity /// </summary> [DataContract(Name = "PipelineActivity")] public partial class PipelineActivity : IEquatable<PipelineActivity>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PipelineActivity" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="artifacts">artifacts.</param> /// <param name="durationInMillis">durationInMillis.</param> /// <param name="estimatedDurationInMillis">estimatedDurationInMillis.</param> /// <param name="enQueueTime">enQueueTime.</param> /// <param name="endTime">endTime.</param> /// <param name="id">id.</param> /// <param name="organization">organization.</param> /// <param name="pipeline">pipeline.</param> /// <param name="result">result.</param> /// <param name="runSummary">runSummary.</param> /// <param name="startTime">startTime.</param> /// <param name="state">state.</param> /// <param name="type">type.</param> /// <param name="commitId">commitId.</param> public PipelineActivity(string _class = default(string), List<PipelineActivityartifacts> artifacts = default(List<PipelineActivityartifacts>), int durationInMillis = default(int), int estimatedDurationInMillis = default(int), string enQueueTime = default(string), string endTime = default(string), string id = default(string), string organization = default(string), string pipeline = default(string), string result = default(string), string runSummary = default(string), string startTime = default(string), string state = default(string), string type = default(string), string commitId = default(string)) { this.Class = _class; this.Artifacts = artifacts; this.DurationInMillis = durationInMillis; this.EstimatedDurationInMillis = estimatedDurationInMillis; this.EnQueueTime = enQueueTime; this.EndTime = endTime; this.Id = id; this.Organization = organization; this.Pipeline = pipeline; this.Result = result; this.RunSummary = runSummary; this.StartTime = startTime; this.State = state; this.Type = type; this.CommitId = commitId; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets Artifacts /// </summary> [DataMember(Name = "artifacts", EmitDefaultValue = false)] public List<PipelineActivityartifacts> Artifacts { get; set; } /// <summary> /// Gets or Sets DurationInMillis /// </summary> [DataMember(Name = "durationInMillis", EmitDefaultValue = false)] public int DurationInMillis { get; set; } /// <summary> /// Gets or Sets EstimatedDurationInMillis /// </summary> [DataMember(Name = "estimatedDurationInMillis", EmitDefaultValue = false)] public int EstimatedDurationInMillis { get; set; } /// <summary> /// Gets or Sets EnQueueTime /// </summary> [DataMember(Name = "enQueueTime", EmitDefaultValue = false)] public string EnQueueTime { get; set; } /// <summary> /// Gets or Sets EndTime /// </summary> [DataMember(Name = "endTime", EmitDefaultValue = false)] public string EndTime { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name = "organization", EmitDefaultValue = false)] public string Organization { get; set; } /// <summary> /// Gets or Sets Pipeline /// </summary> [DataMember(Name = "pipeline", EmitDefaultValue = false)] public string Pipeline { get; set; } /// <summary> /// Gets or Sets Result /// </summary> [DataMember(Name = "result", EmitDefaultValue = false)] public string Result { get; set; } /// <summary> /// Gets or Sets RunSummary /// </summary> [DataMember(Name = "runSummary", EmitDefaultValue = false)] public string RunSummary { get; set; } /// <summary> /// Gets or Sets StartTime /// </summary> [DataMember(Name = "startTime", EmitDefaultValue = false)] public string StartTime { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name = "state", EmitDefaultValue = false)] public string State { get; set; } /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name = "type", EmitDefaultValue = false)] public string Type { get; set; } /// <summary> /// Gets or Sets CommitId /// </summary> [DataMember(Name = "commitId", EmitDefaultValue = false)] public string CommitId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PipelineActivity {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Artifacts: ").Append(Artifacts).Append("\n"); sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n"); sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n"); sb.Append(" EnQueueTime: ").Append(EnQueueTime).Append("\n"); sb.Append(" EndTime: ").Append(EndTime).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" Pipeline: ").Append(Pipeline).Append("\n"); sb.Append(" Result: ").Append(Result).Append("\n"); sb.Append(" RunSummary: ").Append(RunSummary).Append("\n"); sb.Append(" StartTime: ").Append(StartTime).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" CommitId: ").Append(CommitId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PipelineActivity); } /// <summary> /// Returns true if PipelineActivity instances are equal /// </summary> /// <param name="input">Instance of PipelineActivity to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineActivity input) { if (input == null) return false; return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.Artifacts == input.Artifacts || this.Artifacts != null && input.Artifacts != null && this.Artifacts.SequenceEqual(input.Artifacts) ) && ( this.DurationInMillis == input.DurationInMillis || this.DurationInMillis.Equals(input.DurationInMillis) ) && ( this.EstimatedDurationInMillis == input.EstimatedDurationInMillis || this.EstimatedDurationInMillis.Equals(input.EstimatedDurationInMillis) ) && ( this.EnQueueTime == input.EnQueueTime || (this.EnQueueTime != null && this.EnQueueTime.Equals(input.EnQueueTime)) ) && ( this.EndTime == input.EndTime || (this.EndTime != null && this.EndTime.Equals(input.EndTime)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Organization == input.Organization || (this.Organization != null && this.Organization.Equals(input.Organization)) ) && ( this.Pipeline == input.Pipeline || (this.Pipeline != null && this.Pipeline.Equals(input.Pipeline)) ) && ( this.Result == input.Result || (this.Result != null && this.Result.Equals(input.Result)) ) && ( this.RunSummary == input.RunSummary || (this.RunSummary != null && this.RunSummary.Equals(input.RunSummary)) ) && ( this.StartTime == input.StartTime || (this.StartTime != null && this.StartTime.Equals(input.StartTime)) ) && ( this.State == input.State || (this.State != null && this.State.Equals(input.State)) ) && ( this.Type == input.Type || (this.Type != null && this.Type.Equals(input.Type)) ) && ( this.CommitId == input.CommitId || (this.CommitId != null && this.CommitId.Equals(input.CommitId)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); if (this.Artifacts != null) hashCode = hashCode * 59 + this.Artifacts.GetHashCode(); hashCode = hashCode * 59 + this.DurationInMillis.GetHashCode(); hashCode = hashCode * 59 + this.EstimatedDurationInMillis.GetHashCode(); if (this.EnQueueTime != null) hashCode = hashCode * 59 + this.EnQueueTime.GetHashCode(); if (this.EndTime != null) hashCode = hashCode * 59 + this.EndTime.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Organization != null) hashCode = hashCode * 59 + this.Organization.GetHashCode(); if (this.Pipeline != null) hashCode = hashCode * 59 + this.Pipeline.GetHashCode(); if (this.Result != null) hashCode = hashCode * 59 + this.Result.GetHashCode(); if (this.RunSummary != null) hashCode = hashCode * 59 + this.RunSummary.GetHashCode(); if (this.StartTime != null) hashCode = hashCode * 59 + this.StartTime.GetHashCode(); if (this.State != null) hashCode = hashCode * 59 + this.State.GetHashCode(); if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); if (this.CommitId != null) hashCode = hashCode * 59 + this.CommitId.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Media3D; using System.Windows.Threading; namespace MaterialDesignThemes.Wpf { public static class DataGridAssist { private static DataGrid _suppressComboAutoDropDown; public static readonly DependencyProperty AutoGeneratedCheckBoxStyleProperty = DependencyProperty .RegisterAttached( "AutoGeneratedCheckBoxStyle", typeof (Style), typeof (DataGridAssist), new PropertyMetadata(default(Style), AutoGeneratedCheckBoxStylePropertyChangedCallback)); private static void AutoGeneratedCheckBoxStylePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { ((DataGrid) dependencyObject).AutoGeneratingColumn += (sender, args) => { var dataGridCheckBoxColumn = args.Column as DataGridCheckBoxColumn; if (dataGridCheckBoxColumn == null) return; dataGridCheckBoxColumn.ElementStyle = GetAutoGeneratedCheckBoxStyle(dependencyObject); }; } public static void SetAutoGeneratedCheckBoxStyle(DependencyObject element, Style value) { element.SetValue(AutoGeneratedCheckBoxStyleProperty, value); } public static Style GetAutoGeneratedCheckBoxStyle(DependencyObject element) { return (Style) element.GetValue(AutoGeneratedCheckBoxStyleProperty); } public static readonly DependencyProperty AutoGeneratedEditingCheckBoxStyleProperty = DependencyProperty .RegisterAttached( "AutoGeneratedEditingCheckBoxStyle", typeof (Style), typeof (DataGridAssist), new PropertyMetadata(default(Style), AutoGeneratedEditingCheckBoxStylePropertyChangedCallback)); private static void AutoGeneratedEditingCheckBoxStylePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { ((DataGrid) dependencyObject).AutoGeneratingColumn += (sender, args) => { var dataGridCheckBoxColumn = args.Column as DataGridCheckBoxColumn; if (dataGridCheckBoxColumn == null) return; dataGridCheckBoxColumn.EditingElementStyle = GetAutoGeneratedEditingCheckBoxStyle(dependencyObject); }; } public static void SetAutoGeneratedEditingCheckBoxStyle(DependencyObject element, Style value) { element.SetValue(AutoGeneratedEditingCheckBoxStyleProperty, value); } public static Style GetAutoGeneratedEditingCheckBoxStyle(DependencyObject element) { return (Style) element.GetValue(AutoGeneratedEditingCheckBoxStyleProperty); } public static readonly DependencyProperty AutoGeneratedEditingTextStyleProperty = DependencyProperty .RegisterAttached( "AutoGeneratedEditingTextStyle", typeof (Style), typeof (DataGridAssist), new PropertyMetadata(default(Style), AutoGeneratedEditingTextStylePropertyChangedCallback)); private static void AutoGeneratedEditingTextStylePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { ((DataGrid) dependencyObject).AutoGeneratingColumn += (sender, args) => { var dataGridTextColumn = args.Column as DataGridTextColumn; if (dataGridTextColumn == null) return; dataGridTextColumn.EditingElementStyle = GetAutoGeneratedEditingTextStyle(dependencyObject); }; } public static void SetAutoGeneratedEditingTextStyle(DependencyObject element, Style value) { element.SetValue(AutoGeneratedEditingTextStyleProperty, value); } public static Style GetAutoGeneratedEditingTextStyle(DependencyObject element) { return (Style) element.GetValue(AutoGeneratedEditingTextStyleProperty); } public static readonly DependencyProperty CellPaddingProperty = DependencyProperty.RegisterAttached( "CellPadding", typeof (Thickness), typeof (DataGridAssist), new FrameworkPropertyMetadata(new Thickness(13, 8, 8, 8), FrameworkPropertyMetadataOptions.Inherits)); public static void SetCellPadding(DependencyObject element, Thickness value) { element.SetValue(CellPaddingProperty, value); } public static Thickness GetCellPadding(DependencyObject element) { return (Thickness) element.GetValue(CellPaddingProperty); } public static readonly DependencyProperty ColumnHeaderPaddingProperty = DependencyProperty.RegisterAttached( "ColumnHeaderPadding", typeof (Thickness), typeof (DataGridAssist), new FrameworkPropertyMetadata(new Thickness(8), FrameworkPropertyMetadataOptions.Inherits)); public static void SetColumnHeaderPadding(DependencyObject element, Thickness value) { element.SetValue(ColumnHeaderPaddingProperty, value); } public static Thickness GetColumnHeaderPadding(DependencyObject element) { return (Thickness) element.GetValue(ColumnHeaderPaddingProperty); } public static readonly DependencyProperty EnableEditBoxAssistProperty = DependencyProperty.RegisterAttached( "EnableEditBoxAssist", typeof (bool), typeof (DataGridAssist), new PropertyMetadata(default(bool), EnableCheckBoxAssistPropertyChangedCallback)); public static void SetEnableEditBoxAssist(DependencyObject element, bool value) { element.SetValue(EnableEditBoxAssistProperty, value); } public static bool GetEnableEditBoxAssist(DependencyObject element) { return (bool) element.GetValue(EnableEditBoxAssistProperty); } private static void EnableCheckBoxAssistPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var dataGrid = dependencyObject as DataGrid; if (dataGrid == null) return; if ((bool) dependencyPropertyChangedEventArgs.NewValue) dataGrid.PreviewMouseLeftButtonDown += DataGridOnPreviewMouseLeftButtonDown; else dataGrid.PreviewMouseLeftButtonDown -= DataGridOnPreviewMouseLeftButtonDown; } private static void DataGridOnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs) { var dataGrid = (DataGrid) sender; var inputHitTest = dataGrid.InputHitTest(mouseButtonEventArgs.GetPosition((DataGrid) sender)) as DependencyObject; while (inputHitTest != null) { var dataGridCell = inputHitTest as DataGridCell; if (dataGridCell != null) { ToggleButton toggleButton; ComboBox comboBox; if (IsDirectHitOnEditComponent(dataGridCell, mouseButtonEventArgs, out toggleButton)) { dataGrid.CurrentCell = new DataGridCellInfo(dataGridCell); dataGrid.BeginEdit(); toggleButton.SetCurrentValue(ToggleButton.IsCheckedProperty, !toggleButton.IsChecked); dataGrid.CommitEdit(); mouseButtonEventArgs.Handled = true; } else if (IsDirectHitOnEditComponent(dataGridCell, mouseButtonEventArgs, out comboBox)) { if (_suppressComboAutoDropDown != null) return; dataGrid.CurrentCell = new DataGridCellInfo(dataGridCell); dataGrid.BeginEdit(); //check again, as we move to the edit template if (IsDirectHitOnEditComponent(dataGridCell, mouseButtonEventArgs, out comboBox)) { _suppressComboAutoDropDown = dataGrid; comboBox.DropDownClosed += ComboBoxOnDropDownClosed; comboBox.IsDropDownOpen = true; } mouseButtonEventArgs.Handled = true; } return; } inputHitTest = (inputHitTest is Visual || inputHitTest is Visual3D) ? VisualTreeHelper.GetParent(inputHitTest) : null; } } private static void ComboBoxOnDropDownClosed(object sender, EventArgs eventArgs) { _suppressComboAutoDropDown.CommitEdit(); _suppressComboAutoDropDown = null; ((ComboBox)sender).DropDownClosed -= ComboBoxOnDropDownClosed; } private static bool IsDirectHitOnEditComponent<TControl>(ContentControl contentControl, MouseEventArgs mouseButtonEventArgs, out TControl control) where TControl : Control { control = contentControl.Content as TControl; if (control == null) return false; var frameworkElement = VisualTreeHelper.GetChild(contentControl, 0) as FrameworkElement; if (frameworkElement == null) return false; var transformToAncestor = (MatrixTransform) control.TransformToAncestor(frameworkElement); var rect = new Rect( new Point(transformToAncestor.Value.OffsetX, transformToAncestor.Value.OffsetY), new Size(control.ActualWidth, control.ActualHeight)); return rect.Contains(mouseButtonEventArgs.GetPosition(frameworkElement)); } } }
// *********************************************************************** // Copyright (c) 2015 Charlie Poole, Rob Prouse // // 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 ASYNC using System; using System.Threading.Tasks; using NUnit.Framework; #if NET_4_0 using Task = System.Threading.Tasks.TaskEx; #endif namespace NUnit.TestData { public class AsyncRealFixture { [Test] public async void AsyncVoid() { var result = await ReturnOne(); Assert.AreEqual(1, result); } #region async Task [Test] public async System.Threading.Tasks.Task AsyncTaskSuccess() { var result = await ReturnOne(); Assert.AreEqual(1, result); } [Test] public async System.Threading.Tasks.Task AsyncTaskFailure() { var result = await ReturnOne(); Assert.AreEqual(2, result); } [Test] public async System.Threading.Tasks.Task AsyncTaskError() { await ThrowException(); Assert.Fail("Should never get here"); } #endregion #region non-async Task [Test] public System.Threading.Tasks.Task TaskSuccess() { return Task.Run(() => Assert.AreEqual(1, 1)); } [Test] public System.Threading.Tasks.Task TaskFailure() { return Task.Run(() => Assert.AreEqual(1, 2)); } [Test] public System.Threading.Tasks.Task TaskError() { throw new InvalidOperationException(); } #endregion [Test] public async Task<int> AsyncTaskResult() { return await ReturnOne(); } [Test] public Task<int> TaskResult() { return ReturnOne(); } #region async Task<T> [TestCase(ExpectedResult = 1)] public async Task<int> AsyncTaskResultCheckSuccess() { return await ReturnOne(); } [TestCase(ExpectedResult = 2)] public async Task<int> AsyncTaskResultCheckFailure() { return await ReturnOne(); } [TestCase(ExpectedResult = 0)] public async Task<int> AsyncTaskResultCheckError() { return await ThrowException(); } #endregion #region non-async Task<T> [TestCase(ExpectedResult = 1)] public Task<int> TaskResultCheckSuccess() { return ReturnOne(); } [TestCase(ExpectedResult = 2)] public Task<int> TaskResultCheckFailure() { return ReturnOne(); } [TestCase(ExpectedResult = 0)] public Task<int> TaskResultCheckError() { return ThrowException(); } #endregion [TestCase(1, 2)] public async System.Threading.Tasks.Task AsyncTaskTestCaseWithParametersSuccess(int a, int b) { Assert.AreEqual(await ReturnOne(), b - a); } [TestCase(ExpectedResult = null)] public async Task<object> AsyncTaskResultCheckSuccessReturningNull() { return await Task.Run(() => (object)null); } [TestCase(ExpectedResult = null)] public Task<object> TaskResultCheckSuccessReturningNull() { return Task.Run(() => (object)null); } [Test] public async System.Threading.Tasks.Task NestedAsyncTaskSuccess() { var result = await Task.Run(async () => await ReturnOne()); Assert.AreEqual(1, result); } [Test] public async System.Threading.Tasks.Task NestedAsyncTaskFailure() { var result = await Task.Run(async () => await ReturnOne()); Assert.AreEqual(2, result); } [Test] public async System.Threading.Tasks.Task NestedAsyncTaskError() { await Task.Run(async () => await ThrowException()); Assert.Fail("Should never get here"); } [Test] public async System.Threading.Tasks.Task AsyncTaskMultipleSuccess() { var result = await ReturnOne(); Assert.AreEqual(await ReturnOne(), result); } [Test] public async System.Threading.Tasks.Task AsyncTaskMultipleFailure() { var result = await ReturnOne(); Assert.AreEqual(await ReturnOne() + 1, result); } [Test] public async System.Threading.Tasks.Task AsyncTaskMultipleError() { await ThrowException(); Assert.Fail("Should never get here"); } [Test] public async System.Threading.Tasks.Task TaskCheckTestContextAcrossTasks() { var testName = await GetTestNameFromContext(); Assert.IsNotNull(testName); Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name); } [Test] public async System.Threading.Tasks.Task TaskCheckTestContextWithinTestBody() { var testName = TestContext.CurrentContext.Test.Name; await ReturnOne(); Assert.IsNotNull(testName); Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name); } private static Task<string> GetTestNameFromContext() { return Task.Run(() => TestContext.CurrentContext.Test.Name); } private static Task<int> ReturnOne() { return Task.Run(() => 1); } private static Task<int> ThrowException() { Func<int> throws = () => { throw new InvalidOperationException(); }; return Task.Run( throws ); } } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; using EnvDTE; using Microsoft.VisualStudio.ExtensionsExplorer; using NuGet.Dialog.PackageManagerUI; using NuGet.VisualStudio; namespace NuGet.Dialog.Providers { internal class UpdatesProvider : OnlineProvider { private readonly Project _project; private readonly IUpdateAllUIService _updateAllUIService; public UpdatesProvider( Project project, IPackageRepository localRepository, ResourceDictionary resources, IPackageRepositoryFactory packageRepositoryFactory, IPackageSourceProvider packageSourceProvider, IVsPackageManagerFactory packageManagerFactory, ProviderServices providerServices, IProgressProvider progressProvider, ISolutionManager solutionManager) : base( project, localRepository, resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, progressProvider, solutionManager) { _project = project; _updateAllUIService = providerServices.UpdateAllUIService; } public override string Name { get { return Resources.Dialog_UpdateProvider; } } public override float SortOrder { get { return 3.0f; } } public override bool RefreshOnNodeSelection { get { return true; } } public override bool SupportsExecuteAllCommand { get { return true; } } public override string OperationName { get { return RepositoryOperationNames.Update; } } protected override PackagesTreeNodeBase CreateTreeNodeForPackageSource(PackageSource source, IPackageRepository sourceRepository) { return new UpdatesTreeNode(this, source.Name, RootNode, LocalRepository, sourceRepository); } public override bool CanExecute(PackageItem item) { IPackage package = item.PackageIdentity; if (package == null) { return false; } // only enable command on a Package in the Update provider if it not updated yet. // the specified package can be updated if the local repository contains a package // with matching id and smaller version number. // Optimization due to bug #2008: if the LocalRepository is backed by a packages.config file, // check the packages information directly from the file, instead of going through // the IPackageRepository interface, which could potentially connect to TFS. var packageLookup = LocalRepository as ILatestPackageLookup; if (packageLookup != null) { SemanticVersion localPackageVersion; return packageLookup.TryFindLatestPackageById(item.Id, out localPackageVersion) && localPackageVersion < package.Version; } return LocalRepository.GetPackages().Any( p => p.Id.Equals(package.Id, StringComparison.OrdinalIgnoreCase) && p.Version < package.Version); } protected override void ExecuteCommand(IProjectManager projectManager, PackageItem item, IVsPackageManager activePackageManager, IList<PackageOperation> operations) { activePackageManager.UpdatePackages( projectManager, new [] { item.PackageIdentity }, operations, updateDependencies: true, allowPrereleaseVersions: IncludePrerelease, logger: this); } protected override bool ExecuteAllCore() { if (SelectedNode == null || SelectedNode.Extensions == null || SelectedNode.Extensions.Count == 0) { return false; } ShowProgressWindow(); IVsPackageManager activePackageManager = GetActivePackageManager(); Debug.Assert(activePackageManager != null); IDisposable action = activePackageManager.SourceRepository.StartOperation(OperationName, mainPackageId: null, mainPackageVersion: null); IProjectManager projectManager = activePackageManager.GetProjectManager(_project); IList<PackageOperation> allOperations; IList<IPackage> allUpdatePackagesByDependencyOrder; bool accepted = ShowLicenseAgreementForAllPackages(activePackageManager, out allOperations, out allUpdatePackagesByDependencyOrder); if (!accepted) { return false; } try { RegisterPackageOperationEvents(activePackageManager, projectManager); activePackageManager.UpdatePackages( projectManager, allUpdatePackagesByDependencyOrder, allOperations, updateDependencies: true, allowPrereleaseVersions: IncludePrerelease, logger: this); return true; } finally { UnregisterPackageOperationEvents(activePackageManager, projectManager); action.Dispose(); } } protected bool ShowLicenseAgreementForAllPackages(IVsPackageManager activePackageManager, out IList<PackageOperation> allOperations, out IList<IPackage> packagesByDependencyOrder) { allOperations = new List<PackageOperation>(); var installWalker = new InstallWalker( LocalRepository, activePackageManager.SourceRepository, _project.GetTargetFrameworkName(), logger: this, ignoreDependencies: false, allowPrereleaseVersions: IncludePrerelease, dependencyVersion: activePackageManager.DependencyVersion); var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease); allOperations = installWalker.ResolveOperations(allPackages, out packagesByDependencyOrder); return ShowLicenseAgreement(activePackageManager, allOperations); } protected override void OnExecuteCompleted(PackageItem item) { base.OnExecuteCompleted(item); // When this was the Update All command execution, // an individual Update command may have updated all remaining packages. // If there are no more updates left, we hide the Update All button. // // However, we only want to do so if there's only one page of result, because // we don't want to download all packages in all pages just to check for this condition. if (SelectedNode != null && SelectedNode.TotalNumberOfPackages > 1 && SelectedNode.TotalPages == 1) { if (SelectedNode.Extensions.OfType<PackageItem>().All(p => !p.IsEnabled)) { _updateAllUIService.Hide(); } } } public override void OnPackageLoadCompleted(PackagesTreeNodeBase selectedNode) { base.OnPackageLoadCompleted(selectedNode); UpdateNumberOfPackages(selectedNode); } private void UpdateNumberOfPackages(PackagesTreeNodeBase selectedNode) { // OnPackageLoadCompleted(selectedNode), which calls this method, is called by QueryExecutionCompleted // QueryExecutionCompleted is called when an asynchronous query execution completes // And, queries are executed from several places including SortSelectionChanged on the node which is always // called by default on the first node, not necessarily, the selected node by VsExtensionsProvider // This means the selectedNode, here, may not actually be THE selectedNode at this point // So, check if it is indeed selected before doing anything. Note that similar check is performed on QueryExecutionCompleted too if (selectedNode != null && selectedNode.IsSelected) { if (!selectedNode.IsSearchResultsNode && selectedNode.TotalNumberOfPackages > 1) { // After performing Update All, if user switches to another page, we don't want to show // the Update All button again. Here we check to make sure there's at least one enabled package. if (selectedNode.Extensions.OfType<PackageItem>().Any(p => p.IsEnabled)) { _updateAllUIService.Show(); } else { _updateAllUIService.Hide(); } } else { _updateAllUIService.Hide(); } } } public override IVsExtension CreateExtension(IPackage package) { var localPackage = LocalRepository.FindPackagesById(package.Id) .OrderByDescending(p => p.Version) .FirstOrDefault(); return new PackageItem(this, package, localPackage != null ? localPackage.Version : null) { CommandName = Resources.Dialog_UpdateButton, TargetFramework = _project.GetTargetFrameworkName() }; } public override string NoItemsMessage { get { return Resources.Dialog_UpdatesProviderNoItem; } } public override string ProgressWindowTitle { get { return Dialog.Resources.Dialog_UpdateProgress; } } protected override string GetProgressMessage(IPackage package) { if (package == null) { return Resources.Dialog_UpdateAllProgress; } return Resources.Dialog_UpdateProgress + package.ToString(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // X509Certificate2Collection.cs // namespace System.Security.Cryptography.X509Certificates { using System; using System.Collections; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Runtime.Versioning; using _FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; public enum X509FindType { FindByThumbprint = 0, FindBySubjectName = 1, FindBySubjectDistinguishedName = 2, FindByIssuerName = 3, FindByIssuerDistinguishedName = 4, FindBySerialNumber = 5, FindByTimeValid = 6, FindByTimeNotYetValid = 7, FindByTimeExpired = 8, FindByTemplateName = 9, FindByApplicationPolicy = 10, FindByCertificatePolicy = 11, FindByExtension = 12, FindByKeyUsage = 13, FindBySubjectKeyIdentifier = 14 } public class X509Certificate2Collection : X509CertificateCollection { public X509Certificate2Collection() {} public X509Certificate2Collection(X509Certificate2 certificate) { this.Add(certificate); } public X509Certificate2Collection(X509Certificate2Collection certificates) { this.AddRange(certificates); } public X509Certificate2Collection(X509Certificate2[] certificates) { this.AddRange(certificates); } public new X509Certificate2 this[int index] { get { return (X509Certificate2) List[index]; } set { if (value == null) throw new ArgumentNullException("value"); List[index] = value; } } public int Add(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException("certificate"); return List.Add(certificate); } public void AddRange(X509Certificate2[] certificates) { if (certificates == null) throw new ArgumentNullException("certificates"); int i=0; try { for (; i<certificates.Length; i++) { Add(certificates[i]); } } catch { for (int j=0; j<i; j++) { Remove(certificates[j]); } throw; } } public void AddRange(X509Certificate2Collection certificates) { if (certificates == null) throw new ArgumentNullException("certificates"); int i = 0; try { foreach (X509Certificate2 certificate in certificates) { Add(certificate); i++; } } catch { for (int j=0; j<i; j++) { Remove(certificates[j]); } throw; } } public bool Contains(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException("certificate"); return List.Contains(certificate); } public void Insert(int index, X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException("certificate"); List.Insert(index, certificate); } public new X509Certificate2Enumerator GetEnumerator() { return new X509Certificate2Enumerator(this); } public void Remove(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException("certificate"); List.Remove(certificate); } public void RemoveRange(X509Certificate2[] certificates) { if (certificates == null) throw new ArgumentNullException("certificates"); int i=0; try { for (; i<certificates.Length; i++) { Remove(certificates[i]); } } catch { for (int j=0; j<i; j++) { Add(certificates[j]); } throw; } } public void RemoveRange(X509Certificate2Collection certificates) { if (certificates == null) throw new ArgumentNullException("certificates"); int i = 0; try { foreach (X509Certificate2 certificate in certificates) { Remove(certificate); i++; } } catch { for (int j=0; j<i; j++) { Add(certificates[j]); } throw; } } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public X509Certificate2Collection Find(X509FindType findType, Object findValue, bool validOnly) { #if !FEATURE_CORESYSTEM // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to find certificates in a memory store. // StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); #endif SafeCertStoreHandle safeSourceStoreHandle = X509Utils.ExportToMemoryStore(this); SafeCertStoreHandle safeTargetStoreHandle = FindCertInStore(safeSourceStoreHandle, findType, findValue, validOnly); X509Certificate2Collection collection = X509Utils.GetCertificates(safeTargetStoreHandle); safeTargetStoreHandle.Dispose(); safeSourceStoreHandle.Dispose(); return collection; } public void Import(byte[] rawData) { Import(rawData, null, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle; #if !FEATURE_CORESYSTEM // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to import certificates to a memory store. // StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); #endif safeCertStoreHandle = LoadStoreFromBlob(rawData, password, dwFlags, (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) != 0); X509Certificate2Collection collection = X509Utils.GetCertificates(safeCertStoreHandle); safeCertStoreHandle.Dispose(); X509Certificate2[] x509Certs = new X509Certificate2[collection.Count]; collection.CopyTo(x509Certs, 0); this.AddRange(x509Certs); } [ResourceExposure(ResourceScope.Machine)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine)] #endif public void Import(string fileName) { Import(fileName, null, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine)] #endif public void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle; #if !FEATURE_CORESYSTEM // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to import certificates to a memory store. // StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); #endif safeCertStoreHandle = LoadStoreFromFile(fileName, password, dwFlags, (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) != 0); X509Certificate2Collection collection = X509Utils.GetCertificates(safeCertStoreHandle); safeCertStoreHandle.Dispose(); X509Certificate2[] x509Certs = new X509Certificate2[collection.Count]; collection.CopyTo(x509Certs, 0); this.AddRange(x509Certs); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public byte[] Export(X509ContentType contentType) { return Export(contentType, null); } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif public byte[] Export(X509ContentType contentType, string password) { #if !FEATURE_CORESYSTEM // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to export certificates to a memory store. // StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); #endif SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportToMemoryStore(this); byte[] result = ExportCertificatesToBlob(safeCertStoreHandle, contentType, password); safeCertStoreHandle.Dispose(); return result; } #if FEATURE_CORESYSTEM [SecurityCritical] #endif private unsafe static byte[] ExportCertificatesToBlob(SafeCertStoreHandle safeCertStoreHandle, X509ContentType contentType, string password) { SafeCertContextHandle safeCertContextHandle = SafeCertContextHandle.InvalidHandle; uint dwSaveAs = CAPI.CERT_STORE_SAVE_AS_PKCS7; byte[] pbBlob = null; CAPI.CRYPTOAPI_BLOB DataBlob = new CAPI.CRYPTOAPI_BLOB(); SafeLocalAllocHandle pbEncoded = SafeLocalAllocHandle.InvalidHandle; switch(contentType) { case X509ContentType.Cert: safeCertContextHandle = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, safeCertContextHandle); if (safeCertContextHandle != null && !safeCertContextHandle.IsInvalid) { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); pbBlob = new byte[pCertContext.cbCertEncoded]; Marshal.Copy(pCertContext.pbCertEncoded, pbBlob, 0, pbBlob.Length); } break; case X509ContentType.SerializedCert: safeCertContextHandle = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, safeCertContextHandle); uint cbEncoded = 0; if (safeCertContextHandle != null && !safeCertContextHandle.IsInvalid) { if (!CAPI.CertSerializeCertificateStoreElement(safeCertContextHandle, 0, pbEncoded, new IntPtr(&cbEncoded))) throw new CryptographicException(Marshal.GetLastWin32Error()); pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbEncoded)); if (!CAPI.CertSerializeCertificateStoreElement(safeCertContextHandle, 0, pbEncoded, new IntPtr(&cbEncoded))) throw new CryptographicException(Marshal.GetLastWin32Error()); pbBlob = new byte[cbEncoded]; Marshal.Copy(pbEncoded.DangerousGetHandle(), pbBlob, 0, pbBlob.Length); } break; case X509ContentType.Pkcs12: if (!CAPI.PFXExportCertStore(safeCertStoreHandle, new IntPtr(&DataBlob), password, CAPI.EXPORT_PRIVATE_KEYS | CAPI.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(DataBlob.cbData)); DataBlob.pbData = pbEncoded.DangerousGetHandle(); if (!CAPI.PFXExportCertStore(safeCertStoreHandle, new IntPtr(&DataBlob), password, CAPI.EXPORT_PRIVATE_KEYS | CAPI.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbBlob = new byte[DataBlob.cbData]; Marshal.Copy(DataBlob.pbData, pbBlob, 0, pbBlob.Length); break; case X509ContentType.SerializedStore: // falling through case X509ContentType.Pkcs7: if (contentType == X509ContentType.SerializedStore) dwSaveAs = CAPI.CERT_STORE_SAVE_AS_STORE; // determine the required length if (!CAPI.CertSaveStore(safeCertStoreHandle, CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, dwSaveAs, CAPI.CERT_STORE_SAVE_TO_MEMORY, new IntPtr(&DataBlob), 0)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbEncoded = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(DataBlob.cbData)); DataBlob.pbData = pbEncoded.DangerousGetHandle(); // now save the store to a memory blob if (!CAPI.CertSaveStore(safeCertStoreHandle, CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, dwSaveAs, CAPI.CERT_STORE_SAVE_TO_MEMORY, new IntPtr(&DataBlob), 0)) throw new CryptographicException(Marshal.GetLastWin32Error()); pbBlob = new byte[DataBlob.cbData]; Marshal.Copy(DataBlob.pbData, pbBlob, 0, pbBlob.Length); break; default: throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidContentType)); } pbEncoded.Dispose(); safeCertContextHandle.Dispose(); return pbBlob; } #if FEATURE_CORESYSTEM [SecurityCritical] #endif internal delegate int FindProcDelegate (SafeCertContextHandle safeCertContextHandle, object pvCallbackData); #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private unsafe static SafeCertStoreHandle FindCertInStore(SafeCertStoreHandle safeSourceStoreHandle, X509FindType findType, Object findValue, bool validOnly) { if (findValue == null) throw new ArgumentNullException("findValue"); IntPtr pvFindPara = IntPtr.Zero; object pvCallbackData1 = null; object pvCallbackData2 = null; FindProcDelegate pfnCertCallback1 = null; FindProcDelegate pfnCertCallback2 = null; uint dwFindType = CAPI.CERT_FIND_ANY; string subject, issuer; CAPI.CRYPTOAPI_BLOB HashBlob = new CAPI.CRYPTOAPI_BLOB(); SafeLocalAllocHandle pb = SafeLocalAllocHandle.InvalidHandle; _FILETIME ft = new _FILETIME(); string oidValue = null; switch(findType) { case X509FindType.FindByThumbprint: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); byte[] hex = X509Utils.DecodeHexString((string) findValue); pb = X509Utils.ByteToPtr(hex); HashBlob.pbData = pb.DangerousGetHandle(); HashBlob.cbData = (uint) hex.Length; dwFindType = CAPI.CERT_FIND_HASH; pvFindPara = new IntPtr(&HashBlob); break; case X509FindType.FindBySubjectName: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); subject = (string) findValue; dwFindType = CAPI.CERT_FIND_SUBJECT_STR; pb = X509Utils.StringToUniPtr(subject); pvFindPara = pb.DangerousGetHandle(); break; case X509FindType.FindBySubjectDistinguishedName: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); subject = (string) findValue; pfnCertCallback1 = new FindProcDelegate(FindSubjectDistinguishedNameCallback); pvCallbackData1 = subject; break; case X509FindType.FindByIssuerName: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); issuer = (string) findValue; dwFindType = CAPI.CERT_FIND_ISSUER_STR; pb = X509Utils.StringToUniPtr(issuer); pvFindPara = pb.DangerousGetHandle(); break; case X509FindType.FindByIssuerDistinguishedName: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); issuer = (string) findValue; pfnCertCallback1 = new FindProcDelegate(FindIssuerDistinguishedNameCallback); pvCallbackData1 = issuer; break; case X509FindType.FindBySerialNumber: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); pfnCertCallback1 = new FindProcDelegate(FindSerialNumberCallback); pfnCertCallback2 = new FindProcDelegate(FindSerialNumberCallback); BigInt h = new BigInt(); h.FromHexadecimal((string) findValue); pvCallbackData1 = (byte[]) h.ToByteArray(); h.FromDecimal((string) findValue); pvCallbackData2 = (byte[]) h.ToByteArray(); break; case X509FindType.FindByTimeValid: if (findValue.GetType() != typeof(DateTime)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); *((long*) &ft) = ((DateTime) findValue).ToFileTime(); pfnCertCallback1 = new FindProcDelegate(FindTimeValidCallback); pvCallbackData1 = ft; break; case X509FindType.FindByTimeNotYetValid: if (findValue.GetType() != typeof(DateTime)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); *((long*) &ft) = ((DateTime) findValue).ToFileTime(); pfnCertCallback1 = new FindProcDelegate(FindTimeNotBeforeCallback); pvCallbackData1 = ft; break; case X509FindType.FindByTimeExpired: if (findValue.GetType() != typeof(DateTime)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); *((long*) &ft) = ((DateTime) findValue).ToFileTime(); pfnCertCallback1 = new FindProcDelegate(FindTimeNotAfterCallback); pvCallbackData1 = ft; break; case X509FindType.FindByTemplateName: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); pvCallbackData1 = (string) findValue; pfnCertCallback1 = new FindProcDelegate(FindTemplateNameCallback); break; case X509FindType.FindByApplicationPolicy: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); // If we were passed the friendly name, retrieve the value string. oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string) findValue, OidGroup.Policy); if (oidValue == null) { oidValue = (string) findValue; X509Utils.ValidateOidValue(oidValue); } pvCallbackData1 = oidValue; pfnCertCallback1 = new FindProcDelegate(FindApplicationPolicyCallback); break; case X509FindType.FindByCertificatePolicy: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); // If we were passed the friendly name, retrieve the value string. oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string)findValue, OidGroup.Policy); if (oidValue == null) { oidValue = (string) findValue; X509Utils.ValidateOidValue(oidValue); } pvCallbackData1 = oidValue; pfnCertCallback1 = new FindProcDelegate(FindCertificatePolicyCallback); break; case X509FindType.FindByExtension: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); // If we were passed the friendly name, retrieve the value string. oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string)findValue, OidGroup.ExtensionOrAttribute); if (oidValue == null) { oidValue = (string) findValue; X509Utils.ValidateOidValue(oidValue); } pvCallbackData1 = oidValue; pfnCertCallback1 = new FindProcDelegate(FindExtensionCallback); break; case X509FindType.FindByKeyUsage: // The findValue object can be either a friendly name, a X509KeyUsageFlags enum or an integer. if (findValue.GetType() == typeof(string)) { CAPI.KEY_USAGE_STRUCT[] KeyUsages = new CAPI.KEY_USAGE_STRUCT[] { new CAPI.KEY_USAGE_STRUCT("DigitalSignature", CAPI.CERT_DIGITAL_SIGNATURE_KEY_USAGE), new CAPI.KEY_USAGE_STRUCT("NonRepudiation", CAPI.CERT_NON_REPUDIATION_KEY_USAGE), new CAPI.KEY_USAGE_STRUCT("KeyEncipherment", CAPI.CERT_KEY_ENCIPHERMENT_KEY_USAGE), new CAPI.KEY_USAGE_STRUCT("DataEncipherment", CAPI.CERT_DATA_ENCIPHERMENT_KEY_USAGE), new CAPI.KEY_USAGE_STRUCT("KeyAgreement", CAPI.CERT_KEY_AGREEMENT_KEY_USAGE), new CAPI.KEY_USAGE_STRUCT("KeyCertSign", CAPI.CERT_KEY_CERT_SIGN_KEY_USAGE), new CAPI.KEY_USAGE_STRUCT("CrlSign", CAPI.CERT_CRL_SIGN_KEY_USAGE), new CAPI.KEY_USAGE_STRUCT("EncipherOnly", CAPI.CERT_ENCIPHER_ONLY_KEY_USAGE), new CAPI.KEY_USAGE_STRUCT("DecipherOnly", CAPI.CERT_DECIPHER_ONLY_KEY_USAGE) }; for (uint index = 0; index < KeyUsages.Length; index++) { if (String.Compare(KeyUsages[index].pwszKeyUsage, (string) findValue, StringComparison.OrdinalIgnoreCase) == 0) { pvCallbackData1 = KeyUsages[index].dwKeyUsageBit; break; } } if (pvCallbackData1 == null) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType)); } else if (findValue.GetType() == typeof(X509KeyUsageFlags)) { pvCallbackData1 = findValue; } else if (findValue.GetType() == typeof(uint) || findValue.GetType() == typeof(int)) { // We got the actual DWORD pvCallbackData1 = findValue; } else throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType)); pfnCertCallback1 = new FindProcDelegate(FindKeyUsageCallback); break; case X509FindType.FindBySubjectKeyIdentifier: if (findValue.GetType() != typeof(string)) throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindValue)); pvCallbackData1 = (byte[]) X509Utils.DecodeHexString((string) findValue); pfnCertCallback1 = new FindProcDelegate(FindSubjectKeyIdentifierCallback); break; default: throw new CryptographicException(SR.GetString(SR.Cryptography_X509_InvalidFindType)); } // First, create a memory store SafeCertStoreHandle safeTargetStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY), CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, IntPtr.Zero, CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG, null); if (safeTargetStoreHandle == null || safeTargetStoreHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); // FindByCert will throw an exception in case of failures. FindByCert(safeSourceStoreHandle, dwFindType, pvFindPara, validOnly, pfnCertCallback1, pfnCertCallback2, pvCallbackData1, pvCallbackData2, safeTargetStoreHandle); pb.Dispose(); return safeTargetStoreHandle; } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif private static void FindByCert(SafeCertStoreHandle safeSourceStoreHandle, uint dwFindType, IntPtr pvFindPara, bool validOnly, FindProcDelegate pfnCertCallback1, FindProcDelegate pfnCertCallback2, object pvCallbackData1, object pvCallbackData2, SafeCertStoreHandle safeTargetStoreHandle) { int hr = CAPI.S_OK; SafeCertContextHandle pEnumContext = SafeCertContextHandle.InvalidHandle; pEnumContext = CAPI.CertFindCertificateInStore(safeSourceStoreHandle, CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, 0, dwFindType, pvFindPara, pEnumContext); while (pEnumContext != null && !pEnumContext.IsInvalid) { if (pfnCertCallback1 != null) { hr = pfnCertCallback1(pEnumContext, pvCallbackData1); if (hr == CAPI.S_FALSE) { if (pfnCertCallback2 != null) hr = pfnCertCallback2(pEnumContext, pvCallbackData2); if (hr == CAPI.S_FALSE) // skip this certificate goto skip; } if (hr != CAPI.S_OK) break; } if (validOnly) { hr = X509Utils.VerifyCertificate(pEnumContext, null, null, X509RevocationMode.NoCheck, X509RevocationFlag.ExcludeRoot, DateTime.Now, new TimeSpan(0, 0, 0), // default null, new IntPtr(CAPI.CERT_CHAIN_POLICY_BASE), IntPtr.Zero); if (hr == CAPI.S_FALSE) // skip this certificate goto skip; if (hr != CAPI.S_OK) break; } // // We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get // applied to the original store. This has a limit of 99 links per cert context however. // if (!CAPI.CertAddCertificateLinkToStore(safeTargetStoreHandle, pEnumContext, CAPI.CERT_STORE_ADD_ALWAYS, SafeCertContextHandle.InvalidHandle)) { hr = Marshal.GetHRForLastWin32Error(); break; } skip: // CertFindCertificateInStore always releases the context regardless of success // or failure so we don't need to manually release it GC.SuppressFinalize(pEnumContext); pEnumContext = CAPI.CertFindCertificateInStore(safeSourceStoreHandle, CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, 0, dwFindType, pvFindPara, pEnumContext); } if (pEnumContext != null && !pEnumContext.IsInvalid) pEnumContext.Dispose(); if (hr != CAPI.S_FALSE && hr != CAPI.S_OK) throw new CryptographicException(hr); } // // Callback method to find certificates by subject DN. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindSubjectDistinguishedNameCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { string rdn = CAPI.GetCertNameInfo(safeCertContextHandle, 0, CAPI.CERT_NAME_RDN_TYPE); if (String.Compare(rdn, (string) pvCallbackData, StringComparison.OrdinalIgnoreCase) != 0) return CAPI.S_FALSE; return CAPI.S_OK; } // // Callback method to find certificates by issuer DN. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindIssuerDistinguishedNameCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { string rdn = CAPI.GetCertNameInfo(safeCertContextHandle, CAPI.CERT_NAME_ISSUER_FLAG, CAPI.CERT_NAME_RDN_TYPE); if (String.Compare(rdn, (string) pvCallbackData, StringComparison.OrdinalIgnoreCase) != 0) return CAPI.S_FALSE; return CAPI.S_OK; } // // Callback method to find certificates by serial number. // This can be useful when using XML Digital Signature and X509Data. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindSerialNumberCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); byte[] hex = new byte[pCertInfo.SerialNumber.cbData]; Marshal.Copy(pCertInfo.SerialNumber.pbData, hex, 0, hex.Length); int size = X509Utils.GetHexArraySize(hex); byte[] serialNumber = (byte[]) pvCallbackData; if (serialNumber.Length != size) return CAPI.S_FALSE; for (int index = 0; index < serialNumber.Length; index++) { if (serialNumber[index] != hex[index]) return CAPI.S_FALSE; } return CAPI.S_OK; } // // Callback method to find certificates by validity time. // The callback data has to be a UTC FILETEME. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindTimeValidCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { _FILETIME ft = (_FILETIME) pvCallbackData; CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); if (CAPI.CertVerifyTimeValidity(ref ft, pCertContext.pCertInfo) == 0) return CAPI.S_OK; return CAPI.S_FALSE; } // // Callback method to find certificates expired at a certain DateTime. // The callback data has to be a UTC FILETEME. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindTimeNotAfterCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { _FILETIME ft = (_FILETIME) pvCallbackData; CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); if (CAPI.CertVerifyTimeValidity(ref ft, pCertContext.pCertInfo) == 1) return CAPI.S_OK; return CAPI.S_FALSE; } // // Callback method to find certificates effective after a certain DateTime. // The callback data has to be a UTC FILETEME. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindTimeNotBeforeCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { _FILETIME ft = (_FILETIME) pvCallbackData; CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); if (CAPI.CertVerifyTimeValidity(ref ft, pCertContext.pCertInfo) == -1) return CAPI.S_OK; return CAPI.S_FALSE; } // // Callback method to find certificates by template name. // The template name can have 2 different formats: V1 format (<= Win2K) is just a string // V2 format (XP only) can be a friendly name or an OID. // An example of Template Name can be "ClientAuth". // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindTemplateNameCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { IntPtr pV1Template = IntPtr.Zero; IntPtr pV2Template = IntPtr.Zero; CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); pV1Template = CAPI.CertFindExtension(CAPI.szOID_ENROLL_CERTTYPE_EXTENSION, pCertInfo.cExtension, pCertInfo.rgExtension); pV2Template = CAPI.CertFindExtension(CAPI.szOID_CERTIFICATE_TEMPLATE, pCertInfo.cExtension, pCertInfo.rgExtension); if (pV1Template == IntPtr.Zero && pV2Template == IntPtr.Zero) return CAPI.S_FALSE; if (pV1Template != IntPtr.Zero) { CAPI.CERT_EXTENSION extension = (CAPI.CERT_EXTENSION) Marshal.PtrToStructure(pV1Template, typeof(CAPI.CERT_EXTENSION)); byte[] rawData = new byte[extension.Value.cbData]; Marshal.Copy(extension.Value.pbData, rawData, 0, rawData.Length); uint cbDecoded = 0; SafeLocalAllocHandle decoded = null; // Decode the extension. bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_UNICODE_ANY_STRING), rawData, out decoded, out cbDecoded); if (result) { CAPI.CERT_NAME_VALUE pNameValue = (CAPI.CERT_NAME_VALUE) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_NAME_VALUE)); string s = Marshal.PtrToStringUni(pNameValue.Value.pbData); if (String.Compare(s, (string) pvCallbackData, StringComparison.OrdinalIgnoreCase) == 0) return CAPI.S_OK; } } if (pV2Template != IntPtr.Zero) { CAPI.CERT_EXTENSION extension = (CAPI.CERT_EXTENSION) Marshal.PtrToStructure(pV2Template, typeof(CAPI.CERT_EXTENSION)); byte[] rawData = new byte[extension.Value.cbData]; Marshal.Copy(extension.Value.pbData, rawData, 0, rawData.Length); uint cbDecoded = 0; SafeLocalAllocHandle decoded = null; // Decode the extension. bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_CERTIFICATE_TEMPLATE), rawData, out decoded, out cbDecoded); if (result) { CAPI.CERT_TEMPLATE_EXT pTemplate = (CAPI.CERT_TEMPLATE_EXT) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_TEMPLATE_EXT)); // If we were passed the friendly name, retrieve the value string. string oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, (string)pvCallbackData, OidGroup.Template); if (oidValue == null) oidValue = (string) pvCallbackData; if (String.Compare(pTemplate.pszObjId, oidValue, StringComparison.OrdinalIgnoreCase) == 0) return CAPI.S_OK; } } return CAPI.S_FALSE; } // // Callback method to find certificates by application policy (also known as EKU) // An example of application policy can be: "Encrypting File System" // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindApplicationPolicyCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { string eku = (string) pvCallbackData; if (eku.Length == 0) return CAPI.S_FALSE; IntPtr pCertContext = safeCertContextHandle.DangerousGetHandle(); int cNumOIDs = 0; uint cbOIDs = 0; SafeLocalAllocHandle rghOIDs = SafeLocalAllocHandle.InvalidHandle; if (!CAPI.CertGetValidUsages(1, new IntPtr(&pCertContext), new IntPtr(&cNumOIDs), rghOIDs, new IntPtr(&cbOIDs))) return CAPI.S_FALSE; rghOIDs = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbOIDs)); if (!CAPI.CertGetValidUsages(1, new IntPtr(&pCertContext), new IntPtr(&cNumOIDs), rghOIDs, new IntPtr(&cbOIDs))) return CAPI.S_FALSE; // -1 means the certificate is good for all usages. if (cNumOIDs == -1) return CAPI.S_OK; for (int index = 0; index < cNumOIDs; index++) { IntPtr pszOid = Marshal.ReadIntPtr(new IntPtr((long) rghOIDs.DangerousGetHandle() + index * Marshal.SizeOf(typeof(IntPtr)))); string oidValue = Marshal.PtrToStringAnsi(pszOid); if (String.Compare(eku, oidValue, StringComparison.OrdinalIgnoreCase) == 0) return CAPI.S_OK; } return CAPI.S_FALSE; } // // Callback method to find certificates by certificate policy. // This is only recognized in XP platforms. However, passing in an OID value should work on downlevel platforms as well. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindCertificatePolicyCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { string certPolicy = (string) pvCallbackData; if (certPolicy.Length == 0) return CAPI.S_FALSE; CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); IntPtr pExtension = CAPI.CertFindExtension(CAPI.szOID_CERT_POLICIES, pCertInfo.cExtension, pCertInfo.rgExtension); if (pExtension == IntPtr.Zero) return CAPI.S_FALSE; CAPI.CERT_EXTENSION extension = (CAPI.CERT_EXTENSION) Marshal.PtrToStructure(pExtension, typeof(CAPI.CERT_EXTENSION)); byte[] rawData = new byte[extension.Value.cbData]; Marshal.Copy(extension.Value.pbData, rawData, 0, rawData.Length); uint cbDecoded = 0; SafeLocalAllocHandle decoded = null; // Decode the extension. bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_CERT_POLICIES), rawData, out decoded, out cbDecoded); if (result) { CAPI.CERT_POLICIES_INFO pInfo = (CAPI.CERT_POLICIES_INFO) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_POLICIES_INFO)); for (int index = 0; index < pInfo.cPolicyInfo; index++) { IntPtr pPolicyInfoPtr = new IntPtr((long) pInfo.rgPolicyInfo + index * Marshal.SizeOf(typeof(CAPI.CERT_POLICY_INFO))); CAPI.CERT_POLICY_INFO pPolicyInfo = (CAPI.CERT_POLICY_INFO) Marshal.PtrToStructure(pPolicyInfoPtr, typeof(CAPI.CERT_POLICY_INFO)); if (String.Compare(certPolicy, pPolicyInfo.pszPolicyIdentifier, StringComparison.OrdinalIgnoreCase) == 0) return CAPI.S_OK; } } return CAPI.S_FALSE; } // // Callback method to find certificates that have a particular extension. // The callback data can be either an OID friendly name or value (all should be ANSI strings). // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindExtensionCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO)); IntPtr pExtension = CAPI.CertFindExtension((string) pvCallbackData, pCertInfo.cExtension, pCertInfo.rgExtension); if (pExtension == IntPtr.Zero) return CAPI.S_FALSE; return CAPI.S_OK; } // // Callback method to find certificates that have a particular Key Usage. // The callback data can be either a string (example: "KeyEncipherment") or a DWORD which can have multiple bits set in it. // If the callback data is a string, we can achieve the effect of a bit union by calling it multiple times, each time // further restricting the set of selected certificates. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindKeyUsageCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) safeCertContextHandle.DangerousGetHandle()); uint dwUsages = 0; if (!CAPI.CertGetIntendedKeyUsage(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, pCertContext.pCertInfo, new IntPtr(&dwUsages), 4 /* sizeof(DWORD) */)) return CAPI.S_OK; // no key usage means it is valid for all key usages. uint dwCheckUsage = Convert.ToUInt32(pvCallbackData, null); if ((dwUsages & dwCheckUsage) == dwCheckUsage) return CAPI.S_OK; return CAPI.S_FALSE; } // // Callback method to find certificates by subject key identifier. // This can be useful when using XML Digital Signature and X509Data. // #if FEATURE_CORESYSTEM [SecurityCritical] #endif private static unsafe int FindSubjectKeyIdentifierCallback(SafeCertContextHandle safeCertContextHandle, object pvCallbackData) { SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle; // We look for the Key Id extended property // this will first look if there is a V3 SKI extension // and then if that fails, It will return the Key Id extended property. uint cbData = 0; if (!CAPI.CertGetCertificateContextProperty(safeCertContextHandle, CAPI.CERT_KEY_IDENTIFIER_PROP_ID, ptr, ref cbData)) return CAPI.S_FALSE; ptr = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbData)); if (!CAPI.CertGetCertificateContextProperty(safeCertContextHandle, CAPI.CERT_KEY_IDENTIFIER_PROP_ID, ptr, ref cbData)) return CAPI.S_FALSE; byte[] subjectKeyIdentifier = (byte[]) pvCallbackData; if (subjectKeyIdentifier.Length != cbData) return CAPI.S_FALSE; byte[] hex = new byte[cbData]; Marshal.Copy(ptr.DangerousGetHandle(), hex, 0, hex.Length); ptr.Dispose(); for (uint index = 0; index < cbData; index++) { if (subjectKeyIdentifier[index] != hex[index]) return CAPI.S_FALSE; } return CAPI.S_OK; } private const uint X509_STORE_CONTENT_FLAGS = (CAPI.CERT_QUERY_CONTENT_FLAG_CERT | CAPI.CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | CAPI.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | CAPI.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | CAPI.CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED | CAPI.CERT_QUERY_CONTENT_FLAG_PFX | CAPI.CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE); #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.None)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] #endif private unsafe static SafeCertStoreHandle LoadStoreFromBlob(byte[] rawData, string password, uint dwFlags, bool persistKeyContainers) { uint contentType = 0; SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle; if (!CAPI.CryptQueryObject(CAPI.CERT_QUERY_OBJECT_BLOB, rawData, X509_STORE_CONTENT_FLAGS, CAPI.CERT_QUERY_FORMAT_FLAG_ALL, 0, IntPtr.Zero, new IntPtr(&contentType), IntPtr.Zero, ref safeCertStoreHandle, IntPtr.Zero, IntPtr.Zero)) throw new CryptographicException(Marshal.GetLastWin32Error()); if (contentType == CAPI.CERT_QUERY_CONTENT_PFX) { safeCertStoreHandle.Dispose(); safeCertStoreHandle = CAPI.PFXImportCertStore(CAPI.CERT_QUERY_OBJECT_BLOB, rawData, password, dwFlags, persistKeyContainers); } if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); return safeCertStoreHandle; } #if FEATURE_CORESYSTEM [SecuritySafeCritical] #endif [ResourceExposure(ResourceScope.Machine)] #if !FEATURE_CORESYSTEM [ResourceConsumption(ResourceScope.Machine)] #endif private unsafe static SafeCertStoreHandle LoadStoreFromFile(string fileName, string password, uint dwFlags, bool persistKeyContainers) { uint contentType = 0; SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle; if (!CAPI.CryptQueryObject(CAPI.CERT_QUERY_OBJECT_FILE, fileName, X509_STORE_CONTENT_FLAGS, CAPI.CERT_QUERY_FORMAT_FLAG_ALL, 0, IntPtr.Zero, new IntPtr(&contentType), IntPtr.Zero, ref safeCertStoreHandle, IntPtr.Zero, IntPtr.Zero)) throw new CryptographicException(Marshal.GetLastWin32Error()); if (contentType == CAPI.CERT_QUERY_CONTENT_PFX) { safeCertStoreHandle.Dispose(); safeCertStoreHandle = CAPI.PFXImportCertStore(CAPI.CERT_QUERY_OBJECT_FILE, fileName, password, dwFlags, persistKeyContainers); } if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); return safeCertStoreHandle; } } public sealed class X509Certificate2Enumerator : IEnumerator { private IEnumerator baseEnumerator; private X509Certificate2Enumerator() {} internal X509Certificate2Enumerator(X509Certificate2Collection mappings) { this.baseEnumerator = ((IEnumerable) mappings).GetEnumerator(); } public X509Certificate2 Current { get { return ((X509Certificate2)(baseEnumerator.Current)); } } /// <internalonly/> object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } /// <internalonly/> bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } /// <internalonly/> void IEnumerator.Reset() { baseEnumerator.Reset(); } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if SPATIAL namespace Microsoft.Data.Spatial #else namespace Microsoft.Data.OData.Json #endif { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; #if SPATIAL using System.Spatial; #endif using System.Text; #endregion Namespaces /// <summary> /// Reader for the JSON format. http://www.json.org /// </summary> [DebuggerDisplay("{NodeType}: {Value}")] #if ODATALIB_PUBLICJSONREADER public #else internal #endif class JsonReader { /// <summary> /// The initial size of the buffer of characters. /// </summary> /// <remarks> /// 4K (page size) divided by the size of a single character 2 and a little less /// so that array structures also fit into that page. /// The goal is for the entire buffer to fit into one page so that we don't cause /// too many L1 cache misses. /// </remarks> private const int InitialCharacterBufferSize = ((4 * 1024) / 2) - 8; /// <summary> /// Maximum number of characters to move in the buffer. If the current token size is bigger than this, we will allocate a larger buffer. /// </summary> /// <remarks>This treshhold is copied from the XmlReader implementation.</remarks> private const int MaxCharacterCountToMove = 128 / 2; /// <summary> /// The text which every date time value starts with. /// </summary> private const string DateTimeFormatPrefix = "/Date("; /// <summary> /// The text which every date time value ends with. /// </summary> private const string DateTimeFormatSuffix = ")/"; /// <summary> /// The text reader to read input characters from. /// </summary> private readonly TextReader reader; /// <summary> /// Stack of scopes. /// </summary> /// <remarks> /// At the begining the Root scope is pushed to the stack and stays there for the entire parsing /// (so that we don't have to check for empty stack and also to track the number of root-level values) /// Each time a new object or array is started the Object or Array scope is pushed to the stack. /// If a property inside an Object is found, the Property scope is pushed to the stack. /// The Property is popped once we find the value for the property. /// The Object and Array scopes are popped when their end is found. /// </remarks> private readonly Stack<Scope> scopes; /// <summary> /// End of input from the reader was already reached. /// </summary> /// <remarks>This is used to avoid calling Read on the text reader multiple times /// even though it already reported the end of input.</remarks> private bool endOfInputReached; /// <summary> /// Buffer of characters from the input. /// </summary> private char[] characterBuffer; /// <summary> /// Number of characters available in the input buffer. /// </summary> /// <remarks>This can have value of 0 to characterBuffer.Length.</remarks> private int storedCharacterCount; /// <summary> /// Index into the characterBuffer which points to the first character /// of the token being currently processed (while in the Read method) /// or of the next token to be processed (while in the caller code). /// </summary> /// <remarks>This can have value from 0 to storedCharacterCount.</remarks> private int tokenStartIndex; /// <summary> /// The last reported node type. /// </summary> private JsonNodeType nodeType; /// <summary> /// The value of the last reported node. /// </summary> private object nodeValue; /// <summary> /// Cached string builder to be used when constructing string values (needed to resolve escape sequences). /// </summary> /// <remarks>The string builder instance is cached to avoid excessive allocation when many string values with escape sequences /// are found in the payload.</remarks> private StringBuilder stringValueBuilder; /// <summary> /// Constructor. /// </summary> /// <param name="reader">The text reader to read input characters from.</param> public JsonReader(TextReader reader) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(reader != null, "reader != null"); this.nodeType = JsonNodeType.None; this.nodeValue = null; this.reader = reader; this.characterBuffer = new char[InitialCharacterBufferSize]; this.storedCharacterCount = 0; this.tokenStartIndex = 0; this.endOfInputReached = false; this.scopes = new Stack<Scope>(); this.scopes.Push(new Scope(ScopeType.Root)); } /// <summary> /// Various scope types for Json writer. /// </summary> private enum ScopeType { /// <summary> /// Root scope - the top-level of the JSON content. /// </summary> /// <remarks>This scope is only once on the stack and that is at the bottom, always. /// It's used to track the fact that only one top-level value is allowed.</remarks> Root, /// <summary> /// Array scope - inside an array. /// </summary> /// <remarks>This scope is pushed when [ is found and is active before the first and between the elements in the array. /// Between the elements it's active when the parser is in front of the comma, the parser is never after comma as then /// it always immediately processed the next token.</remarks> Array, /// <summary> /// Object scope - inside the object (but not in a property value). /// </summary> /// <remarks>This scope is pushed when { is found and is active before the first and between the properties in the object. /// Between the properties it's active when the parser is in front of the comma, the parser is never after comma as then /// it always immediately processed the next token.</remarks> Object, /// <summary> /// Property scope - after the property name and colon and througout the value. /// </summary> /// <remarks>This scope is pushed when a property name and colon is found. /// The scope remains on the stack while the property value is parsed, but once the property value ends, it's immediately removed /// so that it doesn't appear on the stack after the value (ever).</remarks> Property, } /// <summary> /// The value of the last reported node. /// </summary> /// <remarks>This is non-null only if the last node was a PrimitiveValue or Property. /// If the last node is a PrimitiveValue this property returns the value: /// - null if the null token was found. /// - boolean if the true or false token was found. /// - string if a string token was found. /// - DateTime if a string token formatted as DateTime was found. /// - Int32 if a number which fits into the Int32 was found. /// - Double if a number which doesn't fit into Int32 was found. /// If the last node is a Property this property returns a string which is the name of the property. /// </remarks> public virtual object Value { get { DebugUtils.CheckNoExternalCallers(); return this.nodeValue; } } /// <summary> /// The type of the last node read. /// </summary> public virtual JsonNodeType NodeType { get { DebugUtils.CheckNoExternalCallers(); return this.nodeType; } } /// <summary> /// Reads the next node from the input. /// </summary> /// <returns>true if a new node was found, or false if end of input was reached.</returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Not realy feasible to extract code to methods without introducing unnecessary complexity.")] public virtual bool Read() { DebugUtils.CheckNoExternalCallers(); // Reset the node value. this.nodeValue = null; #if DEBUG // Reset the node type to None - so that we can verify that the Read method actually sets it. this.nodeType = JsonNodeType.None; #endif // Skip any whitespace characters. // This also makes sure that we have at least one non-whitespace character available. if (!this.SkipWhitespaces()) { return this.EndOfInput(); } Debug.Assert( this.tokenStartIndex < this.storedCharacterCount && !IsWhitespaceCharacter(this.characterBuffer[this.tokenStartIndex]), "The SkipWhitespaces didn't correctly skip all whitespace characters from the input."); Scope currentScope = this.scopes.Peek(); bool commaFound = false; if (this.characterBuffer[this.tokenStartIndex] == ',') { commaFound = true; this.tokenStartIndex++; // Note that validity of the comma is verified below depending on the current scope. // Skip all whitespaces after comma. // Note that this causes "Unexpected EOF" error if the comma is the last thing in the input. // It might not be the best error message in certain cases, but it's still correct (a JSON payload can never end in comma). if (!this.SkipWhitespaces()) { return this.EndOfInput(); } Debug.Assert( this.tokenStartIndex < this.storedCharacterCount && !IsWhitespaceCharacter(this.characterBuffer[this.tokenStartIndex]), "The SkipWhitespaces didn't correctly skip all whitespace characters from the input."); } switch (currentScope.Type) { case ScopeType.Root: if (commaFound) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Root)); } if (currentScope.ValueCount > 0) { // We already found the top-level value, so fail throw JsonReaderExtensions.CreateException(Strings.JsonReader_MultipleTopLevelValues); } // We expect a "value" - start array, start object or primitive value this.nodeType = this.ParseValue(); break; case ScopeType.Array: if (commaFound && currentScope.ValueCount == 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Array)); } // We might see end of array here if (this.characterBuffer[this.tokenStartIndex] == ']') { this.tokenStartIndex++; // End of array is only valid when there was no comma before it. if (commaFound) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Array)); } this.PopScope(); this.nodeType = JsonNodeType.EndArray; break; } if (!commaFound && currentScope.ValueCount > 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_MissingComma(ScopeType.Array)); } // We expect element which is a "value" - start array, start object or primitive value this.nodeType = this.ParseValue(); break; case ScopeType.Object: if (commaFound && currentScope.ValueCount == 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Object)); } // We might see end of object here if (this.characterBuffer[this.tokenStartIndex] == '}') { this.tokenStartIndex++; // End of object is only valid when there was no comma before it. if (commaFound) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Object)); } this.PopScope(); this.nodeType = JsonNodeType.EndObject; break; } else { if (!commaFound && currentScope.ValueCount > 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_MissingComma(ScopeType.Object)); } // We expect a property here this.nodeType = this.ParseProperty(); break; } case ScopeType.Property: if (commaFound) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Property)); } // We expect the property value, which is a "value" - start array, start object or primitive value this.nodeType = this.ParseValue(); break; default: #if SPATIAL throw JsonReaderExtensions.CreateException(Strings.JsonReader_InternalError); #else throw JsonReaderExtensions.CreateException(Strings.General_InternalError(InternalErrorCodes.JsonReader_Read)); #endif } Debug.Assert( this.nodeType != JsonNodeType.None && this.nodeType != JsonNodeType.EndOfInput, "Read should never go back to None and EndOfInput should be reported by directly returning."); return true; } /// <summary> /// Determines if a given character is a whitespace character. /// </summary> /// <param name="character">The character to test.</param> /// <returns>true if the <paramref name="character"/> is a whitespace; false otherwise.</returns> /// <remarks>Note that the behavior of this method is different from Char.IsWhitespace, since that method /// returns true for all characters defined as whitespace by the Unicode spec (which is a lot of characters), /// this one on the other hand recognizes just the whitespaces as defined by the JSON spec.</remarks> private static bool IsWhitespaceCharacter(char character) { // The whitespace characters are 0x20 (space), 0x09 (tab), 0x0A (new line), 0x0D (carriage return) // Anything above 0x20 is a non-whitespace character. if (character > (char)0x20 || character != (char)0x20 && character != (char)0x09 && character != (char)0x0A && character != (char)0x0D) { return false; } else { return true; } } /// <summary> /// Parses a date time primitive value. /// </summary> /// <param name="stringValue">The string value to parse.</param> /// <returns>The parsed date time value, or null if the string value doesn't represent a date time value.</returns> private static object TryParseDateTimePrimitiveValue(string stringValue) { if (!stringValue.StartsWith(DateTimeFormatPrefix, StringComparison.Ordinal) || !stringValue.EndsWith(DateTimeFormatSuffix, StringComparison.Ordinal)) { return null; } // Note that WCF DS does not fail if the format uses offset (and thus should be DateTimeOffset). // As a result it actually reads the value as a string. // It might be a breaking change to support DateTimeOffset without versioning or something similar. string tickStringValue = stringValue.Substring( DateTimeFormatPrefix.Length, stringValue.Length - (DateTimeFormatPrefix.Length + DateTimeFormatSuffix.Length)); // Datetime ticks can be negative if it is less than the json reference datetime. // Hence while looking for the offset ticks, we need to start searching after the first // character. int index = tickStringValue.IndexOfAny(new char[] { '+', '-' }, 1); if (index == -1) { long ticks; if (long.TryParse(tickStringValue, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out ticks)) { return new DateTime(JsonValueUtils.JsonTicksToDateTimeTicks(ticks), DateTimeKind.Utc); } } else { string offsetMinutesStringValue = tickStringValue.Substring(index); tickStringValue = tickStringValue.Substring(0, index); long ticks; int offsetMinutes; if (long.TryParse(tickStringValue, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out ticks) && int.TryParse(offsetMinutesStringValue, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out offsetMinutes)) { return new DateTimeOffset(JsonValueUtils.JsonTicksToDateTimeTicks(ticks), new TimeSpan(0, offsetMinutes, 0)); } } return null; } /// <summary> /// Parses a "value", that is an array, object or primitive value. /// </summary> /// <returns>The node type to report to the user.</returns> private JsonNodeType ParseValue() { Debug.Assert( this.tokenStartIndex < this.storedCharacterCount && !IsWhitespaceCharacter(this.characterBuffer[this.tokenStartIndex]), "The SkipWhitespaces wasn't called or it didn't correctly skip all whitespace characters from the input."); Debug.Assert(this.scopes.Count >= 1 && this.scopes.Peek().Type != ScopeType.Object, "Value can only occure at the root, in array or as a property value."); // Increase the count of values under the current scope. this.scopes.Peek().ValueCount++; char currentCharacter = this.characterBuffer[this.tokenStartIndex]; switch (currentCharacter) { case '{': // Start of object this.PushScope(ScopeType.Object); this.tokenStartIndex++; return JsonNodeType.StartObject; case '[': // Start of array this.PushScope(ScopeType.Array); this.tokenStartIndex++; return JsonNodeType.StartArray; case '"': case '\'': // String primitive value bool hasLeadingBackslash; this.nodeValue = this.ParseStringPrimitiveValue(out hasLeadingBackslash); // If the value started with \ then try to parse it as a date time value. if (hasLeadingBackslash) { object dateTimeValue = TryParseDateTimePrimitiveValue((string)this.nodeValue); if (dateTimeValue != null) { this.nodeValue = dateTimeValue; } } break; case 'n': this.nodeValue = this.ParseNullPrimitiveValue(); break; case 't': case 'f': this.nodeValue = this.ParseBooleanPrimitiveValue(); break; default: if (Char.IsDigit(currentCharacter) || (currentCharacter == '-') || (currentCharacter == '.')) { this.nodeValue = this.ParseNumberPrimitiveValue(); break; } else { // Unknown token - fail. throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnrecognizedToken); } } this.TryPopPropertyScope(); return JsonNodeType.PrimitiveValue; } /// <summary> /// Parses a property name and the colon after it. /// </summary> /// <returns>The node type to report to the user.</returns> private JsonNodeType ParseProperty() { // Increase the count of values under the object (the number of properties). Debug.Assert(this.scopes.Count >= 1 && this.scopes.Peek().Type == ScopeType.Object, "Property can only occur in an object."); this.scopes.Peek().ValueCount++; this.PushScope(ScopeType.Property); // Parse the name of the property this.nodeValue = this.ParseName(); if (string.IsNullOrEmpty((string)this.nodeValue)) { // The name can't be empty. throw JsonReaderExtensions.CreateException(Strings.JsonReader_InvalidPropertyNameOrUnexpectedComma((string)this.nodeValue)); } if (!this.SkipWhitespaces() || this.characterBuffer[this.tokenStartIndex] != ':') { // We need the colon character after the property name throw JsonReaderExtensions.CreateException(Strings.JsonReader_MissingColon((string)this.nodeValue)); } // Consume the colon. Debug.Assert(this.characterBuffer[this.tokenStartIndex] == ':', "The above should verify that there's a colon."); this.tokenStartIndex++; return JsonNodeType.Property; } /// <summary> /// Parses a primitive string value. /// </summary> /// <returns>The value of the string primitive value.</returns> /// <remarks> /// Assumes that the current token position points to the opening quote. /// Note that the string parsing can never end with EndOfInput, since we're already seen the quote. /// So it can either return a string succesfully or fail.</remarks> private string ParseStringPrimitiveValue() { bool hasLeadingBackslash; return this.ParseStringPrimitiveValue(out hasLeadingBackslash); } /// <summary> /// Parses a primitive string value. /// </summary> /// <param name="hasLeadingBackslash">Set to true if the first character in the string was a backslash. This is used when parsing DateTime values /// since they must start with an escaped slash character (\/).</param> /// <returns>The value of the string primitive value.</returns> /// <remarks> /// Assumes that the current token position points to the opening quote. /// Note that the string parsing can never end with EndOfInput, since we're already seen the quote. /// So it can either return a string succesfully or fail.</remarks> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Splitting the function would make it hard to understand.")] private string ParseStringPrimitiveValue(out bool hasLeadingBackslash) { Debug.Assert(this.tokenStartIndex < this.storedCharacterCount, "At least the quote must be present."); hasLeadingBackslash = false; char openingQuoteCharacter = this.characterBuffer[this.tokenStartIndex]; Debug.Assert(openingQuoteCharacter == '"' || openingQuoteCharacter == '\'', "The quote character must be the current character when this method is called."); // Consume the quote character this.tokenStartIndex++; // String builder to be used if we need to resolve escape sequences. StringBuilder valueBuilder = null; int currentCharacterTokenRelativeIndex = 0; while ((this.tokenStartIndex + currentCharacterTokenRelativeIndex) < this.storedCharacterCount || this.ReadInput()) { Debug.Assert((this.tokenStartIndex + currentCharacterTokenRelativeIndex) < this.storedCharacterCount, "ReadInput didn't read more data but returned true."); char character = this.characterBuffer[this.tokenStartIndex + currentCharacterTokenRelativeIndex]; if (character == '\\') { // If we're at the begining of the string // (means that relative token index must be 0 and we must not have consumed anything into our value builder yet) if (currentCharacterTokenRelativeIndex == 0 && valueBuilder == null) { hasLeadingBackslash = true; } // We will need the stringbuilder to resolve the escape sequences. if (valueBuilder == null) { if (this.stringValueBuilder == null) { this.stringValueBuilder = new StringBuilder(); } else { this.stringValueBuilder.Length = 0; } valueBuilder = this.stringValueBuilder; } // Append everything up to the \ character to the value. valueBuilder.Append(this.ConsumeTokenToString(currentCharacterTokenRelativeIndex)); currentCharacterTokenRelativeIndex = 0; Debug.Assert(this.characterBuffer[this.tokenStartIndex] == '\\', "We should have consumed everything up to the escape character."); // Escape sequence - we need at least two characters, the backslash and the one character after it. if (!this.EnsureAvailableCharacters(2)) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnrecognizedEscapeSequence("\\")); } // To simplify the code, consume the character after the \ as well, since that is the start of the escape sequence. character = this.characterBuffer[this.tokenStartIndex + 1]; this.tokenStartIndex += 2; switch (character) { case 'b': valueBuilder.Append('\b'); break; case 'f': valueBuilder.Append('\f'); break; case 'n': valueBuilder.Append('\n'); break; case 'r': valueBuilder.Append('\r'); break; case 't': valueBuilder.Append('\t'); break; case '\\': case '\"': case '\'': case '/': valueBuilder.Append(character); break; case 'u': Debug.Assert(currentCharacterTokenRelativeIndex == 0, "The token should be starting at the first character after the \\u"); // We need 4 hex characters if (!this.EnsureAvailableCharacters(4)) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnrecognizedEscapeSequence("\\uXXXX")); } string unicodeHexValue = this.ConsumeTokenToString(4); int characterValue; if (!Int32.TryParse(unicodeHexValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out characterValue)) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnrecognizedEscapeSequence("\\u" + unicodeHexValue)); } valueBuilder.Append((char)characterValue); break; default: throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnrecognizedEscapeSequence("\\" + character)); } } else if (character == openingQuoteCharacter) { // Consume everything up to the quote character string result = this.ConsumeTokenToString(currentCharacterTokenRelativeIndex); Debug.Assert(this.characterBuffer[this.tokenStartIndex] == openingQuoteCharacter, "We should have consumed everything up to the quote character."); // Consume the quote character as well. this.tokenStartIndex++; if (valueBuilder != null) { valueBuilder.Append(result); result = valueBuilder.ToString(); } return result; } else { // Normal character, just skip over it - it will become part of the value as is. currentCharacterTokenRelativeIndex++; } } throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedEndOfString); } /// <summary> /// Parses the null primitive value. /// </summary> /// <returns>Always returns null if successful. Otherwise throws.</returns> /// <remarks>Assumes that the current token position points to the 'n' character.</remarks> private object ParseNullPrimitiveValue() { Debug.Assert( this.tokenStartIndex < this.storedCharacterCount && this.characterBuffer[this.tokenStartIndex] == 'n', "The method should only be called when the 'n' character is the start of the token."); // We can call ParseName since we know the first character is 'n' and thus it won't be quoted. string token = this.ParseName(); if (!string.Equals(token, JsonConstants.JsonNullLiteral)) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedToken(token)); } return null; } /// <summary> /// Parses the true or false primitive values. /// </summary> /// <returns>true of false boolean value if successful. Otherwise throws.</returns> /// <remarks>Assumes that the current token position points to the 't' or 'f' character.</remarks> private object ParseBooleanPrimitiveValue() { Debug.Assert( this.tokenStartIndex < this.storedCharacterCount && (this.characterBuffer[this.tokenStartIndex] == 't' || this.characterBuffer[this.tokenStartIndex] == 'f'), "The method should only be called when the 't' or 'f' character is the start of the token."); // We can call ParseName since we know the first character is 't' or 'f' and thus it won't be quoted. string token = this.ParseName(); if (string.Equals(token, JsonConstants.JsonFalseLiteral)) { return false; } if (string.Equals(token, JsonConstants.JsonTrueLiteral)) { return true; } throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedToken(token)); } /// <summary> /// Parses the number primitive values. /// </summary> /// <returns>Int32 or Double value if successful. Otherwise throws.</returns> /// <remarks>Assumes that the current token position points to the first character of the number, so either digit, dot or dash.</remarks> private object ParseNumberPrimitiveValue() { Debug.Assert( this.tokenStartIndex < this.storedCharacterCount && (this.characterBuffer[this.tokenStartIndex] == '.' || this.characterBuffer[this.tokenStartIndex] == '-' || Char.IsDigit(this.characterBuffer[this.tokenStartIndex])), "The method should only be called when a digit, dash or dot character is the start of the token."); // Walk over all characters which might belong to the number // Skip the first one since we already verified it belongs to the number. int currentCharacterTokenRelativeIndex = 1; while ((this.tokenStartIndex + currentCharacterTokenRelativeIndex) < this.storedCharacterCount || this.ReadInput()) { char character = this.characterBuffer[this.tokenStartIndex + currentCharacterTokenRelativeIndex]; if (Char.IsDigit(character) || (character == '.') || (character == 'E') || (character == 'e') || (character == '-') || (character == '+')) { currentCharacterTokenRelativeIndex++; } else { break; } } // We now have all the characters which belong to the number, consume it into a string. string numberString = this.ConsumeTokenToString(currentCharacterTokenRelativeIndex); double doubleValue; int intValue; // We will first try and convert the value to Int32. If it succeeds, use that. // Otherwise, we will try and convert the value into a double. if (Int32.TryParse(numberString, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out intValue)) { return intValue; } if (Double.TryParse(numberString, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out doubleValue)) { return doubleValue; } throw JsonReaderExtensions.CreateException(Strings.JsonReader_InvalidNumberFormat(numberString)); } /// <summary> /// Parses a name token. /// </summary> /// <returns>The value of the name token.</returns> /// <remarks>Name tokens are (for backward compat reasons) either /// - string value quoted with double quotes. /// - string value quoted with single quotes. /// - sequence of letters, digits, underscores and dollar signs (without quoted and in any order).</remarks> private string ParseName() { Debug.Assert(this.tokenStartIndex < this.storedCharacterCount, "Must have at least one character available."); char firstCharacter = this.characterBuffer[this.tokenStartIndex]; if ((firstCharacter == '"') || (firstCharacter == '\'')) { return this.ParseStringPrimitiveValue(); } int currentCharacterTokenRelativeIndex = 0; do { Debug.Assert(this.tokenStartIndex < this.storedCharacterCount, "Must have at least one character available."); char character = this.characterBuffer[this.tokenStartIndex + currentCharacterTokenRelativeIndex]; if ((character == '_') || Char.IsLetterOrDigit(character) || (character == '$')) { currentCharacterTokenRelativeIndex++; } else { break; } } while ((this.tokenStartIndex + currentCharacterTokenRelativeIndex) < this.storedCharacterCount || this.ReadInput()); return this.ConsumeTokenToString(currentCharacterTokenRelativeIndex); } /// <summary> /// Called when end of input is reached. /// </summary> /// <returns>Always returns false, used for easy readability of the callers.</returns> private bool EndOfInput() { // We should be ending the input only with Root in the scope. if (this.scopes.Count > 1) { // Not all open scopes were closed. throw JsonReaderExtensions.CreateException(Strings.JsonReader_EndOfInputWithOpenScope); } Debug.Assert( this.scopes.Count > 0 && this.scopes.Peek().Type == ScopeType.Root && this.scopes.Peek().ValueCount <= 1, "The end of input should only occure with root at the top of the stack with zero or one value."); Debug.Assert(this.nodeValue == null, "The node value should have been reset to null."); this.nodeType = JsonNodeType.EndOfInput; return false; } /// <summary> /// Creates a new scope of type <paramref name="newScopeType"/> and pushes the stack. /// </summary> /// <param name="newScopeType">The scope type to push.</param> private void PushScope(ScopeType newScopeType) { Debug.Assert(this.scopes.Count >= 1, "The root must always be on the stack."); Debug.Assert(newScopeType != ScopeType.Root, "We should never try to push root scope."); Debug.Assert(newScopeType != ScopeType.Property || this.scopes.Peek().Type == ScopeType.Object, "We should only try to push property onto an object."); Debug.Assert(newScopeType == ScopeType.Property || this.scopes.Peek().Type != ScopeType.Object, "We should only try to push property onto an object."); this.scopes.Push(new Scope(newScopeType)); } /// <summary> /// Pops a scope from the stack. /// </summary> private void PopScope() { Debug.Assert(this.scopes.Count > 1, "We can never pop the root."); Debug.Assert(this.scopes.Peek().Type != ScopeType.Property, "We should never try to pop property alone."); this.scopes.Pop(); this.TryPopPropertyScope(); } /// <summary> /// Pops a property scope if it's present on the stack. /// </summary> private void TryPopPropertyScope() { Debug.Assert(this.scopes.Count > 0, "There should always be at least root on the stack."); if (this.scopes.Peek().Type == ScopeType.Property) { Debug.Assert(this.scopes.Count > 2, "If the property is at the top of the stack there must be an object after it and then root."); this.scopes.Pop(); Debug.Assert(this.scopes.Peek().Type == ScopeType.Object, "The parent of a property must be an object."); } } /// <summary> /// Skips all whitespace characters in the input. /// </summary> /// <returns>true if a non-whitespace character was found in which case the tokenStartIndex is pointing at that character. /// false if there are no non-whitespace characters left in the input.</returns> private bool SkipWhitespaces() { do { for (; this.tokenStartIndex < this.storedCharacterCount; this.tokenStartIndex++) { if (!IsWhitespaceCharacter(this.characterBuffer[this.tokenStartIndex])) { return true; } } } while (this.ReadInput()); return false; } /// <summary> /// Ensures that a specified number of characters after the token start is available in the buffer. /// </summary> /// <param name="characterCountAfterTokenStart">The number of character after the token to make available.</param> /// <returns>true if at least the required number of characters is available; false if end of input was reached.</returns> private bool EnsureAvailableCharacters(int characterCountAfterTokenStart) { while (this.tokenStartIndex + characterCountAfterTokenStart > this.storedCharacterCount) { if (!this.ReadInput()) { return false; } } return true; } /// <summary> /// Consumes the <paramref name="characterCount"/> characters starting at the start of the token /// and returns them as a string. /// </summary> /// <param name="characterCount">The number of characters after the token start to consume.</param> /// <returns>The string value of the consumed token.</returns> private string ConsumeTokenToString(int characterCount) { Debug.Assert(characterCount >= 0, "characterCount >= 0"); Debug.Assert(this.tokenStartIndex + characterCount <= this.storedCharacterCount, "characterCount specified characters outside of the available range."); string result = new string(this.characterBuffer, this.tokenStartIndex, characterCount); this.tokenStartIndex += characterCount; return result; } /// <summary> /// Reads more characters from the input. /// </summary> /// <returns>true if more characters are available; false if end of input was reached.</returns> /// <remarks>This may move characters in the characterBuffer, so after this is called /// all indeces to the characterBuffer are invalid except for tokenStartIndex.</remarks> private bool ReadInput() { Debug.Assert(this.storedCharacterCount <= this.characterBuffer.Length, "We can only store as many characters as fit into our buffer."); Debug.Assert(this.tokenStartIndex >= 0 && this.tokenStartIndex <= this.storedCharacterCount, "The token start is out of stored characters range."); if (this.endOfInputReached) { return false; } // We need to make sure we have more room in the buffer to read characters into if (this.storedCharacterCount == this.characterBuffer.Length) { // No more room in the buffer, move or grow the buffer. if (this.tokenStartIndex == this.storedCharacterCount) { // If the buffer is empty (all characters were consumed from it) // just start over. this.tokenStartIndex = 0; this.storedCharacterCount = 0; } else if (this.tokenStartIndex > (this.characterBuffer.Length - MaxCharacterCountToMove)) { // Some characters were consumed, we can just move them in the buffer // to get more room without allocating. Array.Copy( this.characterBuffer, this.tokenStartIndex, this.characterBuffer, 0, this.storedCharacterCount - this.tokenStartIndex); this.storedCharacterCount -= this.tokenStartIndex; this.tokenStartIndex = 0; } else { // The entire buffer is full of unconsumed characters // We need to grow the buffer. // Double the size of the buffer. int newBufferSize = this.characterBuffer.Length * 2; char[] newCharacterBuffer = new char[newBufferSize]; // Copy the existing characters to the new buffer. Array.Copy( this.characterBuffer, 0, // The tokenStartIndex is 0 - we checked above. newCharacterBuffer, 0, this.characterBuffer.Length); // The storedCharacterCount is the size of the old buffer // And switch the buffers this.characterBuffer = newCharacterBuffer; // Note that the number of characters stored in the buffer remains unchanged // as well as the token start index which is 0. } } Debug.Assert( this.storedCharacterCount < this.characterBuffer.Length, "We should have more room in the buffer by now."); // Read more characters from the input. // Use the Read method which returns any character as soon as it's available // we don't want to wait for the entire buffer to fill if the input doesn't have // the characters ready. int readCount = this.reader.Read( this.characterBuffer, this.storedCharacterCount, this.characterBuffer.Length - this.storedCharacterCount); if (readCount == 0) { // No more characters available, end of input. this.endOfInputReached = true; return false; } this.storedCharacterCount += readCount; return true; } /// <summary> /// Class representing scope information. /// </summary> private sealed class Scope { /// <summary> /// The type of the scope. /// </summary> private readonly ScopeType type; /// <summary> /// Constructor. /// </summary> /// <param name="type">The type of the scope.</param> public Scope(ScopeType type) { this.type = type; } /// <summary> /// Get/Set the number of values found under the current scope. /// </summary> public int ValueCount { get; set; } /// <summary> /// Gets the scope type for this scope. /// </summary> public ScopeType Type { get { return this.type; } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Lucene.Net.Analysis { /// <summary> A simple class that stores Strings as char[]'s in a /// hash table. Note that this is not a general purpose /// class. For example, it cannot remove items from the /// set, nor does it resize its hash table to be smaller, /// etc. It is designed to be quick to test if a char[] /// is in the set without the necessity of converting it /// to a String first. /// </summary> public class CharArraySet : System.Collections.Hashtable { public override int Count { get { return count; } } private const int INIT_SIZE = 8; private char[][] entries; private int count; private bool ignoreCase; /// <summary>Create set with enough capacity to hold startSize /// terms /// </summary> public CharArraySet(int startSize, bool ignoreCase) { this.ignoreCase = ignoreCase; int size = INIT_SIZE; while (startSize + (startSize >> 2) > size) size <<= 1; entries = new char[size][]; } /// <summary>Create set from a Collection of char[] or String </summary> public CharArraySet(System.Collections.ICollection c, bool ignoreCase) : this(c.Count, ignoreCase) { System.Collections.IEnumerator e = c.GetEnumerator(); while (e.MoveNext()) { Add(e.Current); } } /// <summary>true if the <code>len</code> chars of <code>text</code> starting at <code>off</code> /// are in the set /// </summary> public virtual bool Contains(char[] text, int off, int len) { return entries[GetSlot(text, off, len)] != null; } private int GetSlot(char[] text, int off, int len) { int code = GetHashCode(text, off, len); int pos = code & (entries.Length - 1); char[] text2 = entries[pos]; if (text2 != null && !Equals(text, off, len, text2)) { int inc = ((code >> 8) + code) | 1; do { code += inc; pos = code & (entries.Length - 1); text2 = entries[pos]; } while (text2 != null && !Equals(text, off, len, text2)); } return pos; } /// <summary>Add this String into the set </summary> public virtual bool Add(System.String text) { return Add(text.ToCharArray()); } /// <summary>Add this char[] directly to the set. /// If ignoreCase is true for this Set, the text array will be directly modified. /// The user should never modify this text array after calling this method. /// </summary> public virtual bool Add(char[] text) { if (ignoreCase) for (int i = 0; i < text.Length; i++) text[i] = System.Char.ToLower(text[i]); int slot = GetSlot(text, 0, text.Length); if (entries[slot] != null) return false; entries[slot] = text; count++; if (count + (count >> 2) > entries.Length) { Rehash(); } return true; } private bool Equals(char[] text1, int off, int len, char[] text2) { if (len != text2.Length) return false; if (ignoreCase) { for (int i = 0; i < len; i++) { if (System.Char.ToLower(text1[off + i]) != text2[i]) return false; } } else { for (int i = 0; i < len; i++) { if (text1[off + i] != text2[i]) return false; } } return true; } private void Rehash() { int newSize = 2 * entries.Length; char[][] oldEntries = entries; entries = new char[newSize][]; for (int i = 0; i < oldEntries.Length; i++) { char[] text = oldEntries[i]; if (text != null) { // todo: could be faster... no need to compare strings on collision entries[GetSlot(text, 0, text.Length)] = text; } } } private int GetHashCode(char[] text, int offset, int len) { int code = 0; int stop = offset + len; if (ignoreCase) { for (int i = offset; i < stop; i++) { code = code * 31 + System.Char.ToLower(text[i]); } } else { for (int i = offset; i < stop; i++) { code = code * 31 + text[i]; } } return code; } public virtual int Size() { return count; } public virtual bool IsEmpty() { return count == 0; } public override bool Contains(object o) { if (o is char[]) { char[] text = (char[]) o; return Contains(text, 0, text.Length); } else if (o is String) { String s = (String)o; return Contains(s.ToCharArray(), 0, s.Length); } return false; } public virtual bool Add(object o) { if (o is char[]) { return Add((char[]) o); } else if (o is System.String) { return Add((System.String) o); } else { return Add(o.ToString()); } } /// <summary>The Iterator<String> for this set. Strings are constructed on the fly, so /// use <code>nextCharArray</code> for more efficient access. /// </summary> public class CharArraySetIterator : System.Collections.IEnumerator { private void InitBlock(CharArraySet enclosingInstance) { this.enclosingInstance = enclosingInstance; } private CharArraySet enclosingInstance; /// <summary>Returns the next String, as a Set<String> would... /// use nextCharArray() for better efficiency. /// </summary> public virtual object Current { get { return new System.String(NextCharArray()); } } public CharArraySet Enclosing_Instance { get { return enclosingInstance; } } internal int pos = - 1; internal char[] next_Renamed_Field; internal CharArraySetIterator(CharArraySet enclosingInstance) { InitBlock(enclosingInstance); GoNext(); } private void GoNext() { next_Renamed_Field = null; pos++; while (pos < Enclosing_Instance.entries.Length && (next_Renamed_Field = Enclosing_Instance.entries[pos]) == null) pos++; } public virtual bool MoveNext() { return next_Renamed_Field != null; } /// <summary>do not modify the returned char[] </summary> public virtual char[] NextCharArray() { char[] ret = next_Renamed_Field; GoNext(); return ret; } public virtual void Remove() { throw new System.NotSupportedException(); } virtual public void Reset() { } } public new System.Collections.IEnumerator GetEnumerator() { return new CharArraySetIterator(this); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using PORTS = System.IO.Ports; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class BaseSerialStream : System.IO.Ports.SerialStream { public struct Configuration { // // State // public readonly string PortName; public int BaudRate; public PORTS.Parity Parity; public int DataBits; public PORTS.StopBits StopBits; public int ReadBufferSize; public int WriteBufferSize; public int ReadTimeout; public int WriteTimeout; public PORTS.Handshake Handshake; public bool DtrEnable; public bool RtsEnable; public bool CtsEnable; public bool DiscardNull; public byte ParityReplace; public int TxPin; public int RxPin; public int CtsPin; public int RtsPin; // // Constructor Methods // public Configuration(string portName) { this.PortName = portName; this.BaudRate = 9600; this.Parity = PORTS.Parity.None; this.DataBits = 8; this.StopBits = PORTS.StopBits.One; this.ReadBufferSize = 256; this.WriteBufferSize = 256; this.ReadTimeout = Timeout.Infinite; this.WriteTimeout = Timeout.Infinite; this.Handshake = PORTS.Handshake.None; this.DtrEnable = false; this.RtsEnable = false; this.CtsEnable = false; this.DiscardNull = false; this.ParityReplace = 0; // Temporary variable here to avoid multiple virtual calls int invalidPin = HardwareProvider.Instance.InvalidPin; this.TxPin = invalidPin; this.RxPin = invalidPin; this.CtsPin = invalidPin; this.RtsPin = invalidPin; } } // // State // protected Configuration m_cfg; protected KernelCircularBuffer<byte> m_receiveQueue; protected KernelCircularBuffer<byte> m_transmitQueue; // // Constructor Methods // protected BaseSerialStream(ref Configuration cfg) { m_cfg = cfg; m_receiveQueue = new KernelCircularBuffer<byte>(cfg.ReadBufferSize); m_transmitQueue = new KernelCircularBuffer<byte>(cfg.WriteBufferSize); } // // Helper Methods // public override void DiscardInBuffer() { using (SmartHandles.InterruptState.Disable()) { m_receiveQueue.Clear(); } } public override void DiscardOutBuffer() { using (SmartHandles.InterruptState.Disable()) { m_transmitQueue.Clear(); } } public override int Read(byte[] array, int offset, int count, int timeout) { int got = 0; while (got < count) { byte val; if (!m_receiveQueue.DequeueBlocking(timeout, out val)) { if (timeout != 0) { throw new TimeoutException(); } break; } array[offset++] = val; got++; } return got; } public override int ReadByte(int timeout) { byte val; if (!m_receiveQueue.DequeueBlocking(timeout, out val)) { if (timeout != 0) { throw new TimeoutException(); } return -1; } return val; } public override void Write(byte[] array, int offset, int count, int timeout) { for (int pos = 0; pos < count; pos++) { if (!m_transmitQueue.EnqueueBlocking(timeout, array[offset])) { throw new TimeoutException(); } offset++; } } public override void WriteByte(byte value, int timeout) { if (!m_transmitQueue.EnqueueBlocking(timeout, value)) { throw new TimeoutException(); } } // TODO: Consider Yield or SpinWait // TODO: This also won't do anything as Write isn't currently async public override void Flush() { while (!m_transmitQueue.IsEmpty) { Thread.Sleep(0); } } // // Access Methods // public override int BaudRate { set { throw new NotImplementedException(); } } public override bool BreakState { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override int DataBits { set { throw new NotImplementedException(); } } public override bool DiscardNull { set { throw new NotImplementedException(); } } public override bool DtrEnable { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override System.IO.Ports.Handshake Handshake { set { throw new NotImplementedException(); } } public override System.IO.Ports.Parity Parity { set { throw new NotImplementedException(); } } public override byte ParityReplace { set { throw new NotImplementedException(); } } public override int ReadTimeout { get { return m_cfg.ReadTimeout; } set { m_cfg.ReadTimeout = value; } } public override bool RtsEnable { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override System.IO.Ports.StopBits StopBits { set { throw new NotImplementedException(); } } public override int WriteTimeout { get { return m_cfg.WriteTimeout; } set { m_cfg.WriteTimeout = value; } } public override bool CDHolding { get { throw new NotImplementedException(); } } public override bool CtsHolding { get { throw new NotImplementedException(); } } public override bool DsrHolding { get { throw new NotImplementedException(); } } public override int BytesToRead { get { return m_receiveQueue.Count; } } public override int BytesToWrite { get { return m_transmitQueue.Count; } } } }
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/openiddict/openiddict-core for more information concerning * the license and the contributors participating to this project. */ using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using Xunit; namespace OpenIddict.Abstractions.Tests.Primitives; public class OpenIddictMessageTests { [Fact] public void Constructor_ThrowsAnExceptionForInvalidJsonElement() { // Arrange, act and assert var exception = Assert.Throws<ArgumentException>(delegate { return new OpenIddictMessage(JsonSerializer.Deserialize<JsonElement>("[0,1,2,3]")); }); Assert.Equal("parameters", exception.ParamName); Assert.StartsWith(SR.GetResourceString(SR.ID0189), exception.Message); } [Fact] public void Constructor_ThrowsAnExceptionForDuplicateParameters() { // Arrange, act and assert var exception = Assert.Throws<ArgumentException>(delegate { return new OpenIddictMessage(new[] { new KeyValuePair<string, OpenIddictParameter>("parameter", "Fabrikam"), new KeyValuePair<string, OpenIddictParameter>("parameter", "Contoso") }); }); Assert.Equal("name", exception.ParamName); Assert.StartsWith(SR.GetResourceString(SR.ID0191), exception.Message); } [Fact] public void Constructor_ImportsParameters() { // Arrange and act var message = new OpenIddictMessage(new[] { new KeyValuePair<string, OpenIddictParameter>("parameter", 42) }); // Assert Assert.Equal(42, (long) message.GetParameter("parameter")); } [Theory] [InlineData(null)] [InlineData("")] public void Constructor_IgnoresNullOrEmptyParameterNames(string name) { // Arrange and act var message = new OpenIddictMessage(new[] { new KeyValuePair<string, OpenIddictParameter>(name, "Fabrikam") }); // Assert Assert.Equal(0, message.Count); } [Fact] public void Constructor_PreservesEmptyParameters() { // Arrange and act var message = new OpenIddictMessage(new[] { new KeyValuePair<string, OpenIddictParameter>("null-parameter", (string?) null), new KeyValuePair<string, OpenIddictParameter>("empty-parameter", string.Empty) }); // Assert Assert.Equal(2, message.Count); } [Fact] public void Constructor_CombinesDuplicateParameters() { // Arrange and act var message = new OpenIddictMessage(new[] { new KeyValuePair<string, string?>("parameter", "Fabrikam"), new KeyValuePair<string, string?>("parameter", "Contoso") }); // Assert Assert.Equal(1, message.Count); Assert.Equal(new[] { "Fabrikam", "Contoso" }, (string[]?) message.GetParameter("parameter")); } [Fact] public void Constructor_SupportsMultiValuedParameters() { // Arrange and act var message = new OpenIddictMessage(new[] { new KeyValuePair<string, string?[]?>("parameter", new[] { "Fabrikam", "Contoso" }) }); // Assert Assert.Equal(1, message.Count); Assert.Equal(new[] { "Fabrikam", "Contoso" }, (string[]?) message.GetParameter("parameter")); } [Fact] public void Constructor_ExtractsSingleValuedParameters() { // Arrange and act var message = new OpenIddictMessage(new[] { new KeyValuePair<string, string?[]?>("parameter", new[] { "Fabrikam" }) }); // Assert Assert.Equal(1, message.Count); Assert.Equal("Fabrikam", message.GetParameter("parameter")?.Value); } [Theory] [InlineData(null)] [InlineData("")] public void AddParameter_ThrowsAnExceptionForNullOrEmptyName(string name) { // Arrange var message = new OpenIddictMessage(); // Act and assert var exception = Assert.Throws<ArgumentException>(() => { message.AddParameter(name, new OpenIddictParameter()); }); Assert.Equal("name", exception.ParamName); Assert.StartsWith(SR.GetResourceString(SR.ID0190), exception.Message); } [Fact] public void AddParameter_AddsExpectedParameter() { // Arrange var message = new OpenIddictMessage(); // Act message.AddParameter("parameter", 42); // Assert Assert.Equal(42, message.GetParameter("parameter")); } [Fact] public void AddParameter_IsCaseSensitive() { // Arrange var message = new OpenIddictMessage(); // Act message.AddParameter("PARAMETER", 42); // Assert Assert.Null(message.GetParameter("parameter")); } [Fact] public void AddParameter_PreservesEmptyParameters() { // Arrange var message = new OpenIddictMessage(); // Act message.AddParameter("string", string.Empty); message.AddParameter("array", JsonSerializer.Deserialize<JsonElement>("[]")); message.AddParameter("object", JsonSerializer.Deserialize<JsonElement>("{}")); message.AddParameter("value", JsonSerializer.Deserialize<JsonElement>( @"{""property"":""""}").GetProperty("property").GetString()); // Assert Assert.Empty((string?) message.GetParameter("string")); Assert.NotNull((JsonElement?) message.GetParameter("array")); Assert.NotNull((JsonElement?) message.GetParameter("object")); Assert.NotNull((JsonElement?) message.GetParameter("value")); } [Theory] [InlineData(null)] [InlineData("")] public void GetParameter_ThrowsAnExceptionForNullOrEmptyName(string name) { // Arrange var message = new OpenIddictMessage(); // Act and assert var exception = Assert.Throws<ArgumentException>(() => message.GetParameter(name)); Assert.Equal("name", exception.ParamName); Assert.StartsWith(SR.GetResourceString(SR.ID0190), exception.Message); } [Fact] public void GetParameter_ReturnsExpectedParameter() { // Arrange var message = new OpenIddictMessage(); message.SetParameter("parameter", 42); // Act and assert Assert.Equal(42, (int) message.GetParameter("parameter")); } [Fact] public void GetParameter_IsCaseSensitive() { // Arrange var message = new OpenIddictMessage(); message.SetParameter("parameter", 42); // Act and assert Assert.Null(message.GetParameter("PARAMETER")); } [Fact] public void GetParameter_ReturnsNullForUnsetParameter() { // Arrange var message = new OpenIddictMessage(); // Act and assert Assert.Null(message.GetParameter("parameter")); } [Fact] public void GetParameters_EnumeratesParameters() { // Arrange var parameters = new Dictionary<string, OpenIddictParameter> { ["int"] = int.MaxValue, ["long"] = long.MaxValue, ["string"] = "value" }; var message = new OpenIddictMessage(parameters); // Act and assert Assert.Equal(parameters, message.GetParameters()); } [Theory] [InlineData(null)] [InlineData("")] public void HasParameter_ThrowsAnExceptionForNullOrEmptyName(string name) { // Arrange var message = new OpenIddictMessage(); // Act and assert var exception = Assert.Throws<ArgumentException>(() => message.HasParameter(name)); Assert.Equal("name", exception.ParamName); Assert.StartsWith(SR.GetResourceString(SR.ID0190), exception.Message); } [Theory] [InlineData("parameter", true)] [InlineData("PARAMETER", false)] [InlineData("missing_parameter", false)] public void HasParameter_ReturnsExpectedResult(string parameter, bool result) { // Arrange var message = new OpenIddictMessage(); message.SetParameter("parameter", "value"); // Act and assert Assert.Equal(result, message.HasParameter(parameter)); } [Theory] [InlineData(null)] [InlineData("")] public void RemoveParameter_ThrowsAnExceptionForNullOrEmptyName(string name) { // Arrange var message = new OpenIddictMessage(); // Act and assert var exception = Assert.Throws<ArgumentException>(() => message.RemoveParameter(name)); Assert.Equal("name", exception.ParamName); Assert.StartsWith(SR.GetResourceString(SR.ID0190), exception.Message); } [Fact] public void RemoveParameter_RemovesExpectedParameter() { // Arrange var message = new OpenIddictMessage(); message.AddParameter("parameter", 42); // Act message.RemoveParameter("parameter"); // Assert Assert.Null(message.GetParameter("parameter")); } [Theory] [InlineData(null)] [InlineData("")] public void SetParameter_ThrowsAnExceptionForNullOrEmptyName(string name) { // Arrange var message = new OpenIddictMessage(); // Act and assert var exception = Assert.Throws<ArgumentException>(() => message.SetParameter(name, null)); Assert.Equal("name", exception.ParamName); Assert.StartsWith(SR.GetResourceString(SR.ID0190), exception.Message); } [Fact] public void SetParameter_AddsExpectedParameter() { // Arrange var message = new OpenIddictMessage(); // Act message.SetParameter("parameter", 42); // Assert Assert.Equal(42, message.GetParameter("parameter")); } [Fact] public void SetParameter_IsCaseSensitive() { // Arrange var message = new OpenIddictMessage(); // Act message.SetParameter("PARAMETER", 42); // Assert Assert.Null(message.GetParameter("parameter")); } [Fact] public void SetParameter_RemovesNullParameters() { // Arrange var message = new OpenIddictMessage(); // Act message.SetParameter("null", null); // Assert Assert.Empty(message.GetParameters()); } [Fact] public void SetParameter_RemovesEmptyParameters() { // Arrange var message = new OpenIddictMessage(); // Act message.SetParameter("string", string.Empty); message.SetParameter("array", JsonSerializer.Deserialize<JsonElement>("[]")); message.SetParameter("object", JsonSerializer.Deserialize<JsonElement>("{}")); message.SetParameter("value", JsonSerializer.Deserialize<JsonElement>( @"{""property"":""""}").GetProperty("property").GetString()); // Assert Assert.Empty(message.GetParameters()); } [Theory] [InlineData(null)] [InlineData("")] public void TryGetParameter_ThrowsAnExceptionForNullOrEmptyName(string name) { // Arrange var message = new OpenIddictMessage(); // Act var exception = Assert.Throws<ArgumentException>(() => message.TryGetParameter(name, out var parameter)); // Assert Assert.Equal("name", exception.ParamName); Assert.StartsWith(SR.GetResourceString(SR.ID0190), exception.Message); } [Fact] public void TryGetParameter_ReturnsTrueAndExpectedParameter() { // Arrange var message = new OpenIddictMessage(); message.SetParameter("parameter", 42); // Act and assert Assert.True(message.TryGetParameter("parameter", out var parameter)); Assert.Equal(42, (long?) parameter.Value); } [Fact] public void TryGetParameter_ReturnsFalseForUnsetParameter() { // Arrange var message = new OpenIddictMessage(); // Act and assert Assert.False(message.TryGetParameter("parameter", out OpenIddictParameter parameter)); Assert.Null(parameter.Value); } [Fact] public void ToString_ReturnsJsonRepresentation() { // Arrange var message = JsonSerializer.Deserialize<OpenIddictMessage>(@"{ ""redirect_uris"": [ ""https://client.example.org/callback"", ""https://client.example.org/callback2"" ], ""client_name"": ""My Example Client"", ""token_endpoint_auth_method"": ""client_secret_basic"", ""logo_uri"": ""https://client.example.org/logo.png"", ""jwks_uri"": ""https://client.example.org/my_public_keys.jwks"", ""example_extension_parameter"": ""example_value"" }")!; var options = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, WriteIndented = true }; // Act and assert Assert.Equal(JsonSerializer.Serialize(message, options), message.ToString()); } [Theory] [InlineData(Parameters.AccessToken)] [InlineData(Parameters.Assertion)] [InlineData(Parameters.ClientAssertion)] [InlineData(Parameters.ClientSecret)] [InlineData(Parameters.Code)] [InlineData(Parameters.IdToken)] [InlineData(Parameters.IdTokenHint)] [InlineData(Parameters.Password)] [InlineData(Parameters.RefreshToken)] [InlineData(Parameters.Token)] public void ToString_ExcludesSensitiveParameters(string parameter) { // Arrange var message = new OpenIddictMessage(); message.AddParameter(parameter, "secret value"); // Act and assert var element = JsonSerializer.Deserialize<JsonElement>(message.ToString()); Assert.DoesNotContain("secret value", message.ToString()); Assert.Equal("[redacted]", element.GetProperty(parameter).GetString()); } [Fact] public void WriteTo_ThrowsAnExceptionForNullWriter() { // Arrange var message = new OpenIddictMessage(); // Act and assert var exception = Assert.Throws<ArgumentNullException>(() => message.WriteTo(writer: null!)); Assert.Equal("writer", exception.ParamName); } [Fact] public void WriteTo_WritesUtf8JsonRepresentation() { // Arrange var message = new OpenIddictMessage { ["redirect_uris"] = new[] { "https://abc.org/callback" }, ["client_name"] = "My Example Client" }; using var stream = new MemoryStream(); using var writer = new Utf8JsonWriter(stream); // Act message.WriteTo(writer); writer.Flush(); // Assert Assert.Equal(@"{""redirect_uris"":[""https://abc.org/callback""],""client_name"":""My Example Client""}", Encoding.UTF8.GetString(stream.ToArray())); } }
/* * Copyright (c) 2007-2008, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; namespace OpenMetaverse { /// <summary> /// Particle system specific enumerators, flags and methods. /// </summary> public partial class Primitive { #region Subclasses /// <summary> /// Complete structure for the particle system /// </summary> public struct ParticleSystem { /// <summary> /// Particle source pattern /// </summary> public enum SourcePattern : byte { /// <summary>None</summary> None = 0, /// <summary>Drop particles from source position with no force</summary> Drop = 0x01, /// <summary>"Explode" particles in all directions</summary> Explode = 0x02, /// <summary>Particles shoot across a 2D area</summary> Angle = 0x04, /// <summary>Particles shoot across a 3D Cone</summary> AngleCone = 0x08, /// <summary>Inverse of AngleCone (shoot particles everywhere except the 3D cone defined</summary> AngleConeEmpty = 0x10 } /// <summary> /// Particle Data Flags /// </summary> [Flags] public enum ParticleDataFlags : uint { /// <summary>None</summary> None = 0, /// <summary>Interpolate color and alpha from start to end</summary> InterpColor = 0x001, /// <summary>Interpolate scale from start to end</summary> InterpScale = 0x002, /// <summary>Bounce particles off particle sources Z height</summary> Bounce = 0x004, /// <summary>velocity of particles is dampened toward the simulators wind</summary> Wind = 0x008, /// <summary>Particles follow the source</summary> FollowSrc = 0x010, /// <summary>Particles point towards the direction of source's velocity</summary> FollowVelocity = 0x020, /// <summary>Target of the particles</summary> TargetPos = 0x040, /// <summary>Particles are sent in a straight line</summary> TargetLinear = 0x080, /// <summary>Particles emit a glow</summary> Emissive = 0x100, /// <summary>used for point/grab/touch</summary> Beam = 0x200 } /// <summary> /// Particle Flags Enum /// </summary> [Flags] public enum ParticleFlags : uint { /// <summary>None</summary> None = 0, /// <summary>Acceleration and velocity for particles are /// relative to the object rotation</summary> ObjectRelative = 0x01, /// <summary>Particles use new 'correct' angle parameters</summary> UseNewAngle = 0x02 } public uint CRC; /// <summary>Particle Flags</summary> /// <remarks>There appears to be more data packed in to this area /// for many particle systems. It doesn't appear to be flag values /// and serialization breaks unless there is a flag for every /// possible bit so it is left as an unsigned integer</remarks> public uint PartFlags; /// <summary><seealso cref="T:SourcePattern"/> pattern of particles</summary> public SourcePattern Pattern; /// <summary>A <see langword="float"/> representing the maximimum age (in seconds) particle will be displayed</summary> /// <remarks>Maximum value is 30 seconds</remarks> public float MaxAge; /// <summary>A <see langword="float"/> representing the number of seconds, /// from when the particle source comes into view, /// or the particle system's creation, that the object will emits particles; /// after this time period no more particles are emitted</summary> public float StartAge; /// <summary>A <see langword="float"/> in radians that specifies where particles will not be created</summary> public float InnerAngle; /// <summary>A <see langword="float"/> in radians that specifies where particles will be created</summary> public float OuterAngle; /// <summary>A <see langword="float"/> representing the number of seconds between burts.</summary> public float BurstRate; /// <summary>A <see langword="float"/> representing the number of meters /// around the center of the source where particles will be created.</summary> public float BurstRadius; /// <summary>A <see langword="float"/> representing in seconds, the minimum speed between bursts of new particles /// being emitted</summary> public float BurstSpeedMin; /// <summary>A <see langword="float"/> representing in seconds the maximum speed of new particles being emitted.</summary> public float BurstSpeedMax; /// <summary>A <see langword="byte"/> representing the maximum number of particles emitted per burst</summary> public byte BurstPartCount; /// <summary>A <see cref="T:Vector3"/> which represents the velocity (speed) from the source which particles are emitted</summary> public Vector3 AngularVelocity; /// <summary>A <see cref="T:Vector3"/> which represents the Acceleration from the source which particles are emitted</summary> public Vector3 PartAcceleration; /// <summary>The <see cref="T:UUID"/> Key of the texture displayed on the particle</summary> public UUID Texture; /// <summary>The <see cref="T:UUID"/> Key of the specified target object or avatar particles will follow</summary> public UUID Target; /// <summary>Flags of particle from <seealso cref="T:ParticleDataFlags"/></summary> public ParticleDataFlags PartDataFlags; /// <summary>Max Age particle system will emit particles for</summary> public float PartMaxAge; /// <summary>The <see cref="T:Color4"/> the particle has at the beginning of its lifecycle</summary> public Color4 PartStartColor; /// <summary>The <see cref="T:Color4"/> the particle has at the ending of its lifecycle</summary> public Color4 PartEndColor; /// <summary>A <see langword="float"/> that represents the starting X size of the particle</summary> /// <remarks>Minimum value is 0, maximum value is 4</remarks> public float PartStartScaleX; /// <summary>A <see langword="float"/> that represents the starting Y size of the particle</summary> /// <remarks>Minimum value is 0, maximum value is 4</remarks> public float PartStartScaleY; /// <summary>A <see langword="float"/> that represents the ending X size of the particle</summary> /// <remarks>Minimum value is 0, maximum value is 4</remarks> public float PartEndScaleX; /// <summary>A <see langword="float"/> that represents the ending Y size of the particle</summary> /// <remarks>Minimum value is 0, maximum value is 4</remarks> public float PartEndScaleY; /// <summary> /// Decodes a byte[] array into a ParticleSystem Object /// </summary> /// <param name="data">ParticleSystem object</param> /// <param name="pos">Start position for BitPacker</param> public ParticleSystem(byte[] data, int pos) { // TODO: Not sure exactly how many bytes we need here, so partial // (truncated) data will cause an exception to be thrown if (data.Length > 0) { BitPack pack = new BitPack(data, pos); CRC = pack.UnpackUBits(32); PartFlags = pack.UnpackUBits(32); Pattern = (SourcePattern)pack.UnpackByte(); MaxAge = pack.UnpackFixed(false, 8, 8); StartAge = pack.UnpackFixed(false, 8, 8); InnerAngle = pack.UnpackFixed(false, 3, 5); OuterAngle = pack.UnpackFixed(false, 3, 5); BurstRate = pack.UnpackFixed(false, 8, 8); BurstRadius = pack.UnpackFixed(false, 8, 8); BurstSpeedMin = pack.UnpackFixed(false, 8, 8); BurstSpeedMax = pack.UnpackFixed(false, 8, 8); BurstPartCount = pack.UnpackByte(); float x = pack.UnpackFixed(true, 8, 7); float y = pack.UnpackFixed(true, 8, 7); float z = pack.UnpackFixed(true, 8, 7); AngularVelocity = new Vector3(x, y, z); x = pack.UnpackFixed(true, 8, 7); y = pack.UnpackFixed(true, 8, 7); z = pack.UnpackFixed(true, 8, 7); PartAcceleration = new Vector3(x, y, z); Texture = pack.UnpackUUID(); Target = pack.UnpackUUID(); PartDataFlags = (ParticleDataFlags)pack.UnpackUBits(32); PartMaxAge = pack.UnpackFixed(false, 8, 8); byte r = pack.UnpackByte(); byte g = pack.UnpackByte(); byte b = pack.UnpackByte(); byte a = pack.UnpackByte(); PartStartColor = new Color4(r, g, b, a); r = pack.UnpackByte(); g = pack.UnpackByte(); b = pack.UnpackByte(); a = pack.UnpackByte(); PartEndColor = new Color4(r, g, b, a); PartStartScaleX = pack.UnpackFixed(false, 3, 5); PartStartScaleY = pack.UnpackFixed(false, 3, 5); PartEndScaleX = pack.UnpackFixed(false, 3, 5); PartEndScaleY = pack.UnpackFixed(false, 3, 5); } else { CRC = PartFlags = 0; Pattern = SourcePattern.None; MaxAge = StartAge = InnerAngle = OuterAngle = BurstRate = BurstRadius = BurstSpeedMin = BurstSpeedMax = 0.0f; BurstPartCount = 0; AngularVelocity = PartAcceleration = Vector3.Zero; Texture = Target = UUID.Zero; PartDataFlags = ParticleDataFlags.None; PartMaxAge = 0.0f; PartStartColor = PartEndColor = Color4.Black; PartStartScaleX = PartStartScaleY = PartEndScaleX = PartEndScaleY = 0.0f; } } /// <summary> /// Generate byte[] array from particle data /// </summary> /// <returns>Byte array</returns> public byte[] GetBytes() { byte[] bytes = new byte[86]; BitPack pack = new BitPack(bytes, 0); pack.PackBits(CRC, 32); pack.PackBits((uint)PartFlags, 32); pack.PackBits((uint)Pattern, 8); pack.PackFixed(MaxAge, false, 8, 8); pack.PackFixed(StartAge, false, 8, 8); pack.PackFixed(InnerAngle, false, 3, 5); pack.PackFixed(OuterAngle, false, 3, 5); pack.PackFixed(BurstRate, false, 8, 8); pack.PackFixed(BurstRadius, false, 8, 8); pack.PackFixed(BurstSpeedMin, false, 8, 8); pack.PackFixed(BurstSpeedMax, false, 8, 8); pack.PackBits(BurstPartCount, 8); pack.PackFixed(AngularVelocity.X, true, 8, 7); pack.PackFixed(AngularVelocity.Y, true, 8, 7); pack.PackFixed(AngularVelocity.Z, true, 8, 7); pack.PackFixed(PartAcceleration.X, true, 8, 7); pack.PackFixed(PartAcceleration.Y, true, 8, 7); pack.PackFixed(PartAcceleration.Z, true, 8, 7); pack.PackUUID(Texture); pack.PackUUID(Target); pack.PackBits((uint)PartDataFlags, 32); pack.PackFixed(PartMaxAge, false, 8, 8); pack.PackColor(PartStartColor); pack.PackColor(PartEndColor); pack.PackFixed(PartStartScaleX, false, 3, 5); pack.PackFixed(PartStartScaleY, false, 3, 5); pack.PackFixed(PartEndScaleX, false, 3, 5); pack.PackFixed(PartEndScaleY, false, 3, 5); return bytes; } } #endregion Subclasses #region Public Members /// <summary></summary> public ParticleSystem ParticleSys; #endregion Public Members } }
// // This file is generated by GenericDelegateTypes.tt // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // using System; using System.Reflection; namespace ReactNative.Bridge { static class GenericDelegateTypes { public static Type[] ActionTypes = { typeof(SignatureAction0), typeof(SignatureAction1<>), typeof(SignatureAction2<,>), typeof(SignatureAction3<,,>), typeof(SignatureAction4<,,,>), typeof(SignatureAction5<,,,,>), typeof(SignatureAction6<,,,,,>), typeof(SignatureAction7<,,,,,,>), typeof(SignatureAction8<,,,,,,,>), typeof(SignatureAction9<,,,,,,,,>), typeof(SignatureAction10<,,,,,,,,,>), typeof(SignatureAction11<,,,,,,,,,,>), typeof(SignatureAction12<,,,,,,,,,,,>), typeof(SignatureAction13<,,,,,,,,,,,,>), typeof(SignatureAction14<,,,,,,,,,,,,,>), typeof(SignatureAction15<,,,,,,,,,,,,,,>), typeof(SignatureAction16<,,,,,,,,,,,,,,,>), }; public static Type[] FuncTypes = { typeof(SignatureFunc0<>), typeof(SignatureFunc1<,>), typeof(SignatureFunc2<,,>), typeof(SignatureFunc3<,,,>), typeof(SignatureFunc4<,,,,>), typeof(SignatureFunc5<,,,,,>), typeof(SignatureFunc6<,,,,,,>), typeof(SignatureFunc7<,,,,,,,>), typeof(SignatureFunc8<,,,,,,,,>), typeof(SignatureFunc9<,,,,,,,,,>), typeof(SignatureFunc10<,,,,,,,,,,>), typeof(SignatureFunc11<,,,,,,,,,,,>), typeof(SignatureFunc12<,,,,,,,,,,,,>), typeof(SignatureFunc13<,,,,,,,,,,,,,>), typeof(SignatureFunc14<,,,,,,,,,,,,,,>), typeof(SignatureFunc15<,,,,,,,,,,,,,,,>), typeof(SignatureFunc16<,,,,,,,,,,,,,,,,>), }; class SignatureAction0 : IGenericDelegate { Action _instancedDelegate; public SignatureAction0(MethodInfo method) { _instancedDelegate = (Action)method.CreateDelegate(typeof(Action)); } public SignatureAction0(object instance, MethodInfo method) { _instancedDelegate = (Action)method.CreateDelegate(typeof(Action), instance); } public object Invoke(object[] args) { _instancedDelegate(); return null; } } class SignatureFunc0<TResult> : IGenericDelegate { Func<TResult> _instancedDelegate; public SignatureFunc0(MethodInfo method) { _instancedDelegate = (Func<TResult>)method.CreateDelegate(typeof(Func<TResult>)); } public SignatureFunc0(object instance, MethodInfo method) { _instancedDelegate = (Func<TResult>)method.CreateDelegate(typeof(Func<TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate(); } class SignatureAction1<T0> : IGenericDelegate { Action<T0> _instancedDelegate; public SignatureAction1(MethodInfo method) { _instancedDelegate = (Action<T0>)method.CreateDelegate(typeof(Action<T0>)); } public SignatureAction1(object instance, MethodInfo method) { _instancedDelegate = (Action<T0>)method.CreateDelegate(typeof(Action<T0>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0]); return null; } } class SignatureFunc1<T0, TResult> : IGenericDelegate { Func<T0, TResult> _instancedDelegate; public SignatureFunc1(MethodInfo method) { _instancedDelegate = (Func<T0, TResult>)method.CreateDelegate(typeof(Func<T0, TResult>)); } public SignatureFunc1(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, TResult>)method.CreateDelegate(typeof(Func<T0, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0]); } class SignatureAction2<T0, T1> : IGenericDelegate { Action<T0, T1> _instancedDelegate; public SignatureAction2(MethodInfo method) { _instancedDelegate = (Action<T0, T1>)method.CreateDelegate(typeof(Action<T0, T1>)); } public SignatureAction2(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1>)method.CreateDelegate(typeof(Action<T0, T1>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1]); return null; } } class SignatureFunc2<T0, T1, TResult> : IGenericDelegate { Func<T0, T1, TResult> _instancedDelegate; public SignatureFunc2(MethodInfo method) { _instancedDelegate = (Func<T0, T1, TResult>)method.CreateDelegate(typeof(Func<T0, T1, TResult>)); } public SignatureFunc2(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, TResult>)method.CreateDelegate(typeof(Func<T0, T1, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1]); } class SignatureAction3<T0, T1, T2> : IGenericDelegate { Action<T0, T1, T2> _instancedDelegate; public SignatureAction3(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2>)method.CreateDelegate(typeof(Action<T0, T1, T2>)); } public SignatureAction3(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2>)method.CreateDelegate(typeof(Action<T0, T1, T2>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2]); return null; } } class SignatureFunc3<T0, T1, T2, TResult> : IGenericDelegate { Func<T0, T1, T2, TResult> _instancedDelegate; public SignatureFunc3(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, TResult>)); } public SignatureFunc3(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2]); } class SignatureAction4<T0, T1, T2, T3> : IGenericDelegate { Action<T0, T1, T2, T3> _instancedDelegate; public SignatureAction4(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3>)); } public SignatureAction4(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3]); return null; } } class SignatureFunc4<T0, T1, T2, T3, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, TResult> _instancedDelegate; public SignatureFunc4(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, TResult>)); } public SignatureFunc4(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3]); } class SignatureAction5<T0, T1, T2, T3, T4> : IGenericDelegate { Action<T0, T1, T2, T3, T4> _instancedDelegate; public SignatureAction5(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4>)); } public SignatureAction5(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4]); return null; } } class SignatureFunc5<T0, T1, T2, T3, T4, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, TResult> _instancedDelegate; public SignatureFunc5(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, TResult>)); } public SignatureFunc5(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4]); } class SignatureAction6<T0, T1, T2, T3, T4, T5> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5> _instancedDelegate; public SignatureAction6(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5>)); } public SignatureAction6(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5]); return null; } } class SignatureFunc6<T0, T1, T2, T3, T4, T5, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, TResult> _instancedDelegate; public SignatureFunc6(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, TResult>)); } public SignatureFunc6(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5]); } class SignatureAction7<T0, T1, T2, T3, T4, T5, T6> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6> _instancedDelegate; public SignatureAction7(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6>)); } public SignatureAction7(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6]); return null; } } class SignatureFunc7<T0, T1, T2, T3, T4, T5, T6, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, TResult> _instancedDelegate; public SignatureFunc7(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, TResult>)); } public SignatureFunc7(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6]); } class SignatureAction8<T0, T1, T2, T3, T4, T5, T6, T7> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7> _instancedDelegate; public SignatureAction8(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7>)); } public SignatureAction8(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7]); return null; } } class SignatureFunc8<T0, T1, T2, T3, T4, T5, T6, T7, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, TResult> _instancedDelegate; public SignatureFunc8(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, TResult>)); } public SignatureFunc8(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7]); } class SignatureAction9<T0, T1, T2, T3, T4, T5, T6, T7, T8> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7, T8> _instancedDelegate; public SignatureAction9(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8>)); } public SignatureAction9(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8]); return null; } } class SignatureFunc9<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult> _instancedDelegate; public SignatureFunc9(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult>)); } public SignatureFunc9(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8]); } class SignatureAction10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> _instancedDelegate; public SignatureAction10(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>)); } public SignatureAction10(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9]); return null; } } class SignatureFunc10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> _instancedDelegate; public SignatureFunc10(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>)); } public SignatureFunc10(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9]); } class SignatureAction11<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> _instancedDelegate; public SignatureAction11(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>)); } public SignatureAction11(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10]); return null; } } class SignatureFunc11<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> _instancedDelegate; public SignatureFunc11(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>)); } public SignatureFunc11(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10]); } class SignatureAction12<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> _instancedDelegate; public SignatureAction12(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>)); } public SignatureAction12(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11]); return null; } } class SignatureFunc12<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> _instancedDelegate; public SignatureFunc12(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>)); } public SignatureFunc12(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11]); } class SignatureAction13<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> _instancedDelegate; public SignatureAction13(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>)); } public SignatureAction13(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11], (T12)args[12]); return null; } } class SignatureFunc13<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> _instancedDelegate; public SignatureFunc13(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>)); } public SignatureFunc13(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11], (T12)args[12]); } class SignatureAction14<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> _instancedDelegate; public SignatureAction14(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>)); } public SignatureAction14(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11], (T12)args[12], (T13)args[13]); return null; } } class SignatureFunc14<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> _instancedDelegate; public SignatureFunc14(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>)); } public SignatureFunc14(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11], (T12)args[12], (T13)args[13]); } class SignatureAction15<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> _instancedDelegate; public SignatureAction15(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>)); } public SignatureAction15(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11], (T12)args[12], (T13)args[13], (T14)args[14]); return null; } } class SignatureFunc15<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> _instancedDelegate; public SignatureFunc15(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>)); } public SignatureFunc15(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11], (T12)args[12], (T13)args[13], (T14)args[14]); } class SignatureAction16<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> : IGenericDelegate { Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> _instancedDelegate; public SignatureAction16(MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>)); } public SignatureAction16(object instance, MethodInfo method) { _instancedDelegate = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>)method.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>), instance); } public object Invoke(object[] args) { _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11], (T12)args[12], (T13)args[13], (T14)args[14], (T15)args[15]); return null; } } class SignatureFunc16<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> : IGenericDelegate { Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> _instancedDelegate; public SignatureFunc16(MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>)); } public SignatureFunc16(object instance, MethodInfo method) { _instancedDelegate = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>)method.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>), instance); } public object Invoke(object[] args) => _instancedDelegate((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5], (T6)args[6], (T7)args[7], (T8)args[8], (T9)args[9], (T10)args[10], (T11)args[11], (T12)args[12], (T13)args[13], (T14)args[14], (T15)args[15]); } } }
using Microsoft.Data.Entity.Migrations; namespace AllReady.Migrations { public partial class OrganizationSkills : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddColumn<int>( name: "OwningOrganizationId", table: "Skill", nullable: true); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Skill_Tenant_OwningOrganizationId", table: "Skill", column: "OwningOrganizationId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Contact_ContactId", table: "TenantContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_Skill_Tenant_OwningOrganizationId", table: "Skill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "OwningOrganizationId", table: "Skill"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Contact_ContactId", table: "TenantContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
namespace Caps.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class RenameSitemapEntityBranch : DbMigration { public override void Up() { DropForeignKey("dbo.SitemapNodeContentPartResources", "SitemapNodeContentPartId", "dbo.SitemapNodeContentParts"); DropForeignKey("dbo.SitemapNodeContentParts", "SitemapNodeContentId", "dbo.SitemapNodeContents"); DropForeignKey("dbo.SitemapNodeContentFiles", "SitemapNodeContentId", "dbo.SitemapNodeContents"); DropForeignKey("dbo.SitemapNodes", "ParentNodeId", "dbo.SitemapNodes"); DropForeignKey("dbo.SitemapNodeResources", "SitemapNodeId", "dbo.SitemapNodes"); DropForeignKey("dbo.Sitemaps", "WebsiteId", "dbo.Websites"); DropForeignKey("dbo.SitemapNodes", "SitemapId", "dbo.Sitemaps"); DropForeignKey("dbo.SitemapNodes", "ContentId", "dbo.SitemapNodeContents"); DropForeignKey("dbo.SitemapNodeContentFileResources", "SitemapNodeContentFileId", "dbo.SitemapNodeContentFiles"); DropForeignKey("dbo.SitemapNodeContentFileResources", "DbFileId", "dbo.DbFiles"); DropIndex("dbo.SitemapNodeContentPartResources", new[] { "SitemapNodeContentPartId" }); DropIndex("dbo.SitemapNodeContentParts", new[] { "SitemapNodeContentId" }); DropIndex("dbo.SitemapNodeContentFiles", new[] { "SitemapNodeContentId" }); DropIndex("dbo.SitemapNodes", new[] { "ParentNodeId" }); DropIndex("dbo.SitemapNodeResources", new[] { "SitemapNodeId" }); DropIndex("dbo.Sitemaps", new[] { "WebsiteId" }); DropIndex("dbo.SitemapNodes", new[] { "SitemapId" }); DropIndex("dbo.SitemapNodes", new[] { "ContentId" }); DropIndex("dbo.SitemapNodeContentFileResources", new[] { "SitemapNodeContentFileId" }); DropIndex("dbo.SitemapNodeContentFileResources", new[] { "DbFileId" }); CreateTable( "dbo.PublicationFileResources", c => new { PublicationFileId = c.Int(nullable: false), Language = c.String(nullable: false, maxLength: 10), DbFileId = c.Int(), Title = c.String(maxLength: 50), Description = c.String(), Credits = c.String(maxLength: 250), }) .PrimaryKey(t => new { t.PublicationFileId, t.Language }) .ForeignKey("dbo.PublicationFiles", t => t.PublicationFileId, cascadeDelete: true) .ForeignKey("dbo.DbFiles", t => t.DbFileId) .Index(t => t.PublicationFileId) .Index(t => t.DbFileId); CreateTable( "dbo.PublicationFiles", c => new { Id = c.Int(nullable: false, identity: true), PublicationId = c.Int(nullable: false), Name = c.String(maxLength: 50), IsEmbedded = c.Boolean(nullable: false), Determination = c.String(maxLength: 50), Group = c.String(maxLength: 50), Ranking = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Publications", t => t.PublicationId, cascadeDelete: true) .Index(t => t.PublicationId); CreateTable( "dbo.Publications", c => new { Id = c.Int(nullable: false, identity: true), EntityType = c.String(maxLength: 50), EntityKey = c.String(maxLength: 50), ContentVersion = c.Int(nullable: false), ContentDate = c.DateTime(nullable: false), AuthorName = c.String(maxLength: 50), TemplateData = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.PublicationContentParts", c => new { Id = c.Int(nullable: false, identity: true), PublicationId = c.Int(nullable: false), PartType = c.String(maxLength: 50), ContentType = c.String(maxLength: 50), Ranking = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Publications", t => t.PublicationId, cascadeDelete: true) .Index(t => t.PublicationId); CreateTable( "dbo.PublicationContentPartResources", c => new { PublicationContentPartId = c.Int(nullable: false), Language = c.String(nullable: false, maxLength: 10), Content = c.String(), TranslationAuthor = c.String(), TranslationDate = c.DateTime(nullable: false), Created_By = c.String(maxLength: 50), Created_At = c.DateTime(nullable: false), Modified_By = c.String(maxLength: 50), Modified_At = c.DateTime(nullable: false), }) .PrimaryKey(t => new { t.PublicationContentPartId, t.Language }) .ForeignKey("dbo.PublicationContentParts", t => t.PublicationContentPartId, cascadeDelete: true) .Index(t => t.PublicationContentPartId); CreateTable( "dbo.DbSiteMapNodes", c => new { Id = c.Int(nullable: false, identity: true), SiteMapId = c.Int(nullable: false), ParentNodeId = c.Int(), ContentId = c.Int(), ExternalName = c.String(maxLength: 50), Ranking = c.Int(nullable: false), NodeType = c.String(maxLength: 50), IsDeleted = c.Boolean(nullable: false), Redirect = c.String(maxLength: 250), RedirectType = c.String(maxLength: 50), Created_By = c.String(maxLength: 50), Created_At = c.DateTime(nullable: false), Modified_By = c.String(maxLength: 50), Modified_At = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.DbSiteMapNodes", t => t.ParentNodeId) .ForeignKey("dbo.DbSiteMaps", t => t.SiteMapId, cascadeDelete: true) .ForeignKey("dbo.Publications", t => t.ContentId) .Index(t => t.ParentNodeId) .Index(t => t.SiteMapId) .Index(t => t.ContentId); CreateTable( "dbo.DbSiteMapNodeResources", c => new { SiteMapNodeId = c.Int(nullable: false), Language = c.String(nullable: false, maxLength: 10), Title = c.String(maxLength: 50), Keywords = c.String(maxLength: 500), Description = c.String(maxLength: 500), }) .PrimaryKey(t => new { t.SiteMapNodeId, t.Language }) .ForeignKey("dbo.DbSiteMapNodes", t => t.SiteMapNodeId, cascadeDelete: true) .Index(t => t.SiteMapNodeId); CreateTable( "dbo.DbSiteMaps", c => new { Id = c.Int(nullable: false, identity: true), WebsiteId = c.Int(nullable: false), Version = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Websites", t => t.WebsiteId, cascadeDelete: true) .Index(t => t.WebsiteId); DropTable("dbo.SitemapNodeContentFileResources"); DropTable("dbo.SitemapNodeContentFiles"); DropTable("dbo.SitemapNodeContents"); DropTable("dbo.SitemapNodeContentParts"); DropTable("dbo.SitemapNodeContentPartResources"); DropTable("dbo.SitemapNodes"); DropTable("dbo.SitemapNodeResources"); DropTable("dbo.Sitemaps"); } public override void Down() { CreateTable( "dbo.Sitemaps", c => new { Id = c.Int(nullable: false, identity: true), WebsiteId = c.Int(nullable: false), Version = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SitemapNodeResources", c => new { SitemapNodeId = c.Int(nullable: false), Language = c.String(nullable: false, maxLength: 10), Title = c.String(maxLength: 50), Keywords = c.String(maxLength: 500), Description = c.String(maxLength: 500), }) .PrimaryKey(t => new { t.SitemapNodeId, t.Language }); CreateTable( "dbo.SitemapNodes", c => new { Id = c.Int(nullable: false, identity: true), SitemapId = c.Int(nullable: false), ParentNodeId = c.Int(), ContentId = c.Int(), ExternalName = c.String(maxLength: 50), Ranking = c.Int(nullable: false), NodeType = c.String(maxLength: 50), IsDeleted = c.Boolean(nullable: false), Redirect = c.String(maxLength: 250), RedirectType = c.String(maxLength: 50), Created_By = c.String(maxLength: 50), Created_At = c.DateTime(nullable: false), Modified_By = c.String(maxLength: 50), Modified_At = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SitemapNodeContentPartResources", c => new { SitemapNodeContentPartId = c.Int(nullable: false), Language = c.String(nullable: false, maxLength: 10), Content = c.String(), TranslationAuthor = c.String(), TranslationDate = c.DateTime(nullable: false), Created_By = c.String(maxLength: 50), Created_At = c.DateTime(nullable: false), Modified_By = c.String(maxLength: 50), Modified_At = c.DateTime(nullable: false), }) .PrimaryKey(t => new { t.SitemapNodeContentPartId, t.Language }); CreateTable( "dbo.SitemapNodeContentParts", c => new { Id = c.Int(nullable: false, identity: true), SitemapNodeContentId = c.Int(nullable: false), PartType = c.String(maxLength: 50), ContentType = c.String(maxLength: 50), Ranking = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SitemapNodeContents", c => new { Id = c.Int(nullable: false, identity: true), EntityType = c.String(maxLength: 50), EntityKey = c.String(maxLength: 50), ContentVersion = c.Int(nullable: false), ContentDate = c.DateTime(nullable: false), AuthorName = c.String(maxLength: 50), TemplateData = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SitemapNodeContentFiles", c => new { Id = c.Int(nullable: false, identity: true), SitemapNodeContentId = c.Int(nullable: false), Name = c.String(maxLength: 50), IsEmbedded = c.Boolean(nullable: false), Determination = c.String(maxLength: 50), Group = c.String(maxLength: 50), Ranking = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SitemapNodeContentFileResources", c => new { SitemapNodeContentFileId = c.Int(nullable: false), Language = c.String(nullable: false, maxLength: 10), DbFileId = c.Int(), Title = c.String(maxLength: 50), Description = c.String(), Credits = c.String(maxLength: 250), }) .PrimaryKey(t => new { t.SitemapNodeContentFileId, t.Language }); DropForeignKey("dbo.PublicationFileResources", "DbFileId", "dbo.DbFiles"); DropForeignKey("dbo.PublicationFileResources", "PublicationFileId", "dbo.PublicationFiles"); DropForeignKey("dbo.DbSiteMapNodes", "ContentId", "dbo.Publications"); DropForeignKey("dbo.DbSiteMapNodes", "SiteMapId", "dbo.DbSiteMaps"); DropForeignKey("dbo.DbSiteMaps", "WebsiteId", "dbo.Websites"); DropForeignKey("dbo.DbSiteMapNodeResources", "SiteMapNodeId", "dbo.DbSiteMapNodes"); DropForeignKey("dbo.DbSiteMapNodes", "ParentNodeId", "dbo.DbSiteMapNodes"); DropForeignKey("dbo.PublicationFiles", "PublicationId", "dbo.Publications"); DropForeignKey("dbo.PublicationContentParts", "PublicationId", "dbo.Publications"); DropForeignKey("dbo.PublicationContentPartResources", "PublicationContentPartId", "dbo.PublicationContentParts"); DropIndex("dbo.PublicationFileResources", new[] { "DbFileId" }); DropIndex("dbo.PublicationFileResources", new[] { "PublicationFileId" }); DropIndex("dbo.DbSiteMapNodes", new[] { "ContentId" }); DropIndex("dbo.DbSiteMapNodes", new[] { "SiteMapId" }); DropIndex("dbo.DbSiteMaps", new[] { "WebsiteId" }); DropIndex("dbo.DbSiteMapNodeResources", new[] { "SiteMapNodeId" }); DropIndex("dbo.DbSiteMapNodes", new[] { "ParentNodeId" }); DropIndex("dbo.PublicationFiles", new[] { "PublicationId" }); DropIndex("dbo.PublicationContentParts", new[] { "PublicationId" }); DropIndex("dbo.PublicationContentPartResources", new[] { "PublicationContentPartId" }); DropTable("dbo.DbSiteMaps"); DropTable("dbo.DbSiteMapNodeResources"); DropTable("dbo.DbSiteMapNodes"); DropTable("dbo.PublicationContentPartResources"); DropTable("dbo.PublicationContentParts"); DropTable("dbo.Publications"); DropTable("dbo.PublicationFiles"); DropTable("dbo.PublicationFileResources"); CreateIndex("dbo.SitemapNodeContentFileResources", "DbFileId"); CreateIndex("dbo.SitemapNodeContentFileResources", "SitemapNodeContentFileId"); CreateIndex("dbo.SitemapNodes", "ContentId"); CreateIndex("dbo.SitemapNodes", "SitemapId"); CreateIndex("dbo.Sitemaps", "WebsiteId"); CreateIndex("dbo.SitemapNodeResources", "SitemapNodeId"); CreateIndex("dbo.SitemapNodes", "ParentNodeId"); CreateIndex("dbo.SitemapNodeContentFiles", "SitemapNodeContentId"); CreateIndex("dbo.SitemapNodeContentParts", "SitemapNodeContentId"); CreateIndex("dbo.SitemapNodeContentPartResources", "SitemapNodeContentPartId"); AddForeignKey("dbo.SitemapNodeContentFileResources", "DbFileId", "dbo.DbFiles", "Id"); AddForeignKey("dbo.SitemapNodeContentFileResources", "SitemapNodeContentFileId", "dbo.SitemapNodeContentFiles", "Id", cascadeDelete: true); AddForeignKey("dbo.SitemapNodes", "ContentId", "dbo.SitemapNodeContents", "Id"); AddForeignKey("dbo.SitemapNodes", "SitemapId", "dbo.Sitemaps", "Id", cascadeDelete: true); AddForeignKey("dbo.Sitemaps", "WebsiteId", "dbo.Websites", "Id", cascadeDelete: true); AddForeignKey("dbo.SitemapNodeResources", "SitemapNodeId", "dbo.SitemapNodes", "Id", cascadeDelete: true); AddForeignKey("dbo.SitemapNodes", "ParentNodeId", "dbo.SitemapNodes", "Id"); AddForeignKey("dbo.SitemapNodeContentFiles", "SitemapNodeContentId", "dbo.SitemapNodeContents", "Id", cascadeDelete: true); AddForeignKey("dbo.SitemapNodeContentParts", "SitemapNodeContentId", "dbo.SitemapNodeContents", "Id", cascadeDelete: true); AddForeignKey("dbo.SitemapNodeContentPartResources", "SitemapNodeContentPartId", "dbo.SitemapNodeContentParts", "Id", cascadeDelete: true); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Definition of cloud service for the automation extension. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> internal partial class CloudServiceOperations : IServiceOperations<AutomationManagementClient>, ICloudServiceOperations { /// <summary> /// Initializes a new instance of the CloudServiceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal CloudServiceOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve a list of Cloud services (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list cloud service operation. /// </returns> public async Task<CloudServiceListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices?"; url = url + "resourceType=AutomationAccount"; url = url + "&detailLevel=Full"; url = url + "&resourceProviderNamespace=automation"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result CloudServiceListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CloudServiceListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement cloudServicesSequenceElement = responseDoc.Element(XName.Get("CloudServices", "http://schemas.microsoft.com/windowsazure")); if (cloudServicesSequenceElement != null) { foreach (XElement cloudServicesElement in cloudServicesSequenceElement.Elements(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure"))) { CloudService cloudServiceInstance = new CloudService(); result.CloudServices.Add(cloudServiceInstance); XElement nameElement = cloudServicesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; cloudServiceInstance.Name = nameInstance; } XElement labelElement = cloudServicesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; cloudServiceInstance.Label = labelInstance; } XElement descriptionElement = cloudServicesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; cloudServiceInstance.Description = descriptionInstance; } XElement geoRegionElement = cloudServicesElement.Element(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure")); if (geoRegionElement != null) { string geoRegionInstance = geoRegionElement.Value; cloudServiceInstance.GeoRegion = geoRegionInstance; } XElement resourcesSequenceElement = cloudServicesElement.Element(XName.Get("Resources", "http://schemas.microsoft.com/windowsazure")); if (resourcesSequenceElement != null) { foreach (XElement resourcesElement in resourcesSequenceElement.Elements(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"))) { AutomationResource resourceInstance = new AutomationResource(); cloudServiceInstance.Resources.Add(resourceInstance); XElement resourceProviderNamespaceElement = resourcesElement.Element(XName.Get("ResourceProviderNamespace", "http://schemas.microsoft.com/windowsazure")); if (resourceProviderNamespaceElement != null) { string resourceProviderNamespaceInstance = resourceProviderNamespaceElement.Value; resourceInstance.Namespace = resourceProviderNamespaceInstance; } XElement typeElement = resourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; resourceInstance.Type = typeInstance; } XElement nameElement2 = resourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; resourceInstance.Name = nameInstance2; } XElement planElement = resourcesElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); if (planElement != null) { string planInstance = planElement.Value; resourceInstance.Plan = planInstance; } XElement schemaVersionElement = resourcesElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure")); if (schemaVersionElement != null) { string schemaVersionInstance = schemaVersionElement.Value; resourceInstance.SchemaVersion = schemaVersionInstance; } XElement eTagElement = resourcesElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure")); if (eTagElement != null) { string eTagInstance = eTagElement.Value; resourceInstance.ETag = eTagInstance; } XElement stateElement = resourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; resourceInstance.State = stateInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Collections { public sealed partial class BitArray : System.Collections.ICollection, System.Collections.IEnumerable, System.ICloneable { public BitArray(bool[] values) { } public BitArray(byte[] bytes) { } public BitArray(System.Collections.BitArray bits) { } public BitArray(int length) { } public BitArray(int length, bool defaultValue) { } public BitArray(int[] values) { } public bool this[int index] { get { throw null; } set { } } public int Length { get { throw null; } set { } } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object Clone() { throw null; } public object SyncRoot { get { throw null; } } public System.Collections.BitArray And(System.Collections.BitArray value) { throw null; } public bool Get(int index) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } public System.Collections.BitArray Not() { throw null; } public System.Collections.BitArray Or(System.Collections.BitArray value) { throw null; } public void Set(int index, bool value) { } public void SetAll(bool value) { } public void CopyTo(System.Array array, int index) { } public System.Collections.BitArray Xor(System.Collections.BitArray value) { throw null; } public System.Collections.BitArray RightShift(int count) { throw null; } public System.Collections.BitArray LeftShift(int count) { throw null; } } public static partial class StructuralComparisons { public static System.Collections.IComparer StructuralComparer { get { throw null; } } public static System.Collections.IEqualityComparer StructuralEqualityComparer { get { throw null; } } } } namespace System.Collections.Generic { public static class CollectionExtensions { public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) { throw null; } public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) { throw null; } public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { throw null; } public static bool Remove<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, out TValue value) { throw null; } } public abstract partial class Comparer<T> : System.Collections.Generic.IComparer<T>, System.Collections.IComparer { protected Comparer() { } public static System.Collections.Generic.Comparer<T> Default { get { throw null; } } public abstract int Compare(T x, T y); public static System.Collections.Generic.Comparer<T> Create(System.Comparison<T> comparison) { throw null; } int System.Collections.IComparer.Compare(object x, object y) { throw null; } } public partial class Dictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public Dictionary() { } public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer) { } public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection) { } public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer) { } public Dictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer) { } protected Dictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public Dictionary(int capacity) { } public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer) { } public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { throw null; } } public int Count { get { throw null; } } public TValue this[TKey key] { get { throw null; } set { } } public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { throw null; } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { throw null; } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { throw null; } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { throw null; } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } bool System.Collections.IDictionary.IsReadOnly { get { throw null; } } object System.Collections.IDictionary.this[object key] { get { throw null; } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } } System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } } public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection Values { get { throw null; } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { throw null; } public bool ContainsValue(TValue value) { throw null; } public System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual void OnDeserialization(object sender) { } public bool Remove(TKey key) { throw null; } public bool Remove(TKey key, out TValue value) { throw null; } public bool TryAdd(TKey key, TValue value) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { throw null; } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(TKey key, out TValue value) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { throw null; } } System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { throw null; } } object System.Collections.IDictionaryEnumerator.Key { get { throw null; } } object System.Collections.IDictionaryEnumerator.Value { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { public KeyCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TKey[] array, int index) { } public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; } System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public TKey Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { public ValueCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TValue[] array, int index) { } public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; } System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public TValue Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } } public abstract partial class EqualityComparer<T> : System.Collections.Generic.IEqualityComparer<T>, System.Collections.IEqualityComparer { protected EqualityComparer() { } public static System.Collections.Generic.EqualityComparer<T> Default { get { throw null; } } public abstract bool Equals(T x, T y); public abstract int GetHashCode(T obj); bool System.Collections.IEqualityComparer.Equals(object x, object y) { throw null; } int System.Collections.IEqualityComparer.GetHashCode(object obj) { throw null; } } public partial class HashSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public HashSet() { } public HashSet(int capacity) { } public HashSet(int capacity, System.Collections.Generic.IEqualityComparer<T> comparer) { } public HashSet(System.Collections.Generic.IEnumerable<T> collection) { } public HashSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T> comparer) { } public HashSet(System.Collections.Generic.IEqualityComparer<T> comparer) { } protected HashSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Collections.Generic.IEqualityComparer<T> Comparer { get { throw null; } } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } } public bool Add(T item) { throw null; } public void Clear() { } public bool Contains(T item) { throw null; } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int arrayIndex) { } public void CopyTo(T[] array, int arrayIndex, int count) { } public static IEqualityComparer<HashSet<T>> CreateSetComparer() { throw null; } public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { } public System.Collections.Generic.HashSet<T>.Enumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { } public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public virtual void OnDeserialization(object sender) { } public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool Remove(T item) { throw null; } public int RemoveWhere(System.Predicate<T> match) { throw null; } public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { throw null; } public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { } void System.Collections.Generic.ICollection<T>.Add(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public void TrimExcess() { } public bool TryGetValue(T equalValue, out T actualValue) { throw null; } public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial class LinkedList<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public LinkedList() { } public LinkedList(System.Collections.Generic.IEnumerable<T> collection) { } protected LinkedList(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public int Count { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> First { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> Last { get { throw null; } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> AddAfter(System.Collections.Generic.LinkedListNode<T> node, T value) { throw null; } public void AddAfter(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { } public System.Collections.Generic.LinkedListNode<T> AddBefore(System.Collections.Generic.LinkedListNode<T> node, T value) { throw null; } public void AddBefore(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { } public System.Collections.Generic.LinkedListNode<T> AddFirst(T value) { throw null; } public void AddFirst(System.Collections.Generic.LinkedListNode<T> node) { } public System.Collections.Generic.LinkedListNode<T> AddLast(T value) { throw null; } public void AddLast(System.Collections.Generic.LinkedListNode<T> node) { } public void Clear() { } public bool Contains(T value) { throw null; } public void CopyTo(T[] array, int index) { } public System.Collections.Generic.LinkedListNode<T> Find(T value) { throw null; } public System.Collections.Generic.LinkedListNode<T> FindLast(T value) { throw null; } public System.Collections.Generic.LinkedList<T>.Enumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual void OnDeserialization(object sender) { } public bool Remove(T value) { throw null; } public void Remove(System.Collections.Generic.LinkedListNode<T> node) { } public void RemoveFirst() { } public void RemoveLast() { } void System.Collections.Generic.ICollection<T>.Add(T value) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public bool MoveNext() { throw null; } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(Object sender) { } void System.Collections.IEnumerator.Reset() { } } } public sealed partial class LinkedListNode<T> { public LinkedListNode(T value) { } public System.Collections.Generic.LinkedList<T> List { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> Next { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> Previous { get { throw null; } } public T Value { get { throw null; } set { } } } public partial class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { public List() { } public List(System.Collections.Generic.IEnumerable<T> collection) { } public List(int capacity) { } public int Capacity { get { throw null; } set { } } public int Count { get { throw null; } } public T this[int index] { get { throw null; } set { } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public void Add(T item) { } public void AddRange(System.Collections.Generic.IEnumerable<T> collection) { } public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly() { throw null; } public int BinarySearch(T item) { throw null; } public int BinarySearch(T item, System.Collections.Generic.IComparer<T> comparer) { throw null; } public int BinarySearch(int index, int count, T item, System.Collections.Generic.IComparer<T> comparer) { throw null; } public void Clear() { } public bool Contains(T item) { throw null; } public List<TOutput> ConvertAll<TOutput>(System.Converter<T,TOutput> converter) { throw null; } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int arrayIndex) { } public void CopyTo(int index, T[] array, int arrayIndex, int count) { } public bool Exists(System.Predicate<T> match) { throw null; } public T Find(System.Predicate<T> match) { throw null; } public System.Collections.Generic.List<T> FindAll(System.Predicate<T> match) { throw null; } public int FindIndex(int startIndex, int count, System.Predicate<T> match) { throw null; } public int FindIndex(int startIndex, System.Predicate<T> match) { throw null; } public int FindIndex(System.Predicate<T> match) { throw null; } public T FindLast(System.Predicate<T> match) { throw null; } public int FindLastIndex(int startIndex, int count, System.Predicate<T> match) { throw null; } public int FindLastIndex(int startIndex, System.Predicate<T> match) { throw null; } public int FindLastIndex(System.Predicate<T> match) { throw null; } public void ForEach(System.Action<T> action) { } public System.Collections.Generic.List<T>.Enumerator GetEnumerator() { throw null; } public System.Collections.Generic.List<T> GetRange(int index, int count) { throw null; } public int IndexOf(T item) { throw null; } public int IndexOf(T item, int index) { throw null; } public int IndexOf(T item, int index, int count) { throw null; } public void Insert(int index, T item) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable<T> collection) { } public int LastIndexOf(T item) { throw null; } public int LastIndexOf(T item, int index) { throw null; } public int LastIndexOf(T item, int index, int count) { throw null; } public bool Remove(T item) { throw null; } public int RemoveAll(System.Predicate<T> match) { throw null; } public void RemoveAt(int index) { } public void RemoveRange(int index, int count) { } public void Reverse() { } public void Reverse(int index, int count) { } public void Sort() { } public void Sort(System.Collections.Generic.IComparer<T> comparer) { } public void Sort(System.Comparison<T> comparison) { } public void Sort(int index, int count, System.Collections.Generic.IComparer<T> comparer) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object item) { throw null; } bool System.Collections.IList.Contains(object item) { throw null; } int System.Collections.IList.IndexOf(object item) { throw null; } void System.Collections.IList.Insert(int index, object item) { } void System.Collections.IList.Remove(object item) { } public T[] ToArray() { throw null; } public void TrimExcess() { } public bool TrueForAll(System.Predicate<T> match) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial class Queue<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public Queue() { } public Queue(System.Collections.Generic.IEnumerable<T> collection) { } public Queue(int capacity) { } public int Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Clear() { } public bool Contains(T item) { throw null; } public void CopyTo(T[] array, int arrayIndex) { } public T Dequeue() { throw null; } public void Enqueue(T item) { } public System.Collections.Generic.Queue<T>.Enumerator GetEnumerator() { throw null; } public T Peek() { throw null; } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public T[] ToArray() { throw null; } public void TrimExcess() { } public bool TryDequeue(out T result) { throw null; } public bool TryPeek(out T result) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial class SortedDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public SortedDictionary() { } public SortedDictionary(System.Collections.Generic.IComparer<TKey> comparer) { } public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { } public System.Collections.Generic.IComparer<TKey> Comparer { get { throw null; } } public int Count { get { throw null; } } public TValue this[TKey key] { get { throw null; } set { } } public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { throw null; } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { throw null; } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { throw null; } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { throw null; } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } bool System.Collections.IDictionary.IsReadOnly { get { throw null; } } object System.Collections.IDictionary.this[object key] { get { throw null; } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } } System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } } public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection Values { get { throw null; } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { throw null; } public bool ContainsValue(TValue value) { throw null; } public void CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator GetEnumerator() { throw null; } public bool Remove(TKey key) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { throw null; } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(TKey key, out TValue value) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { throw null; } } System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { throw null; } } object System.Collections.IDictionaryEnumerator.Key { get { throw null; } } object System.Collections.IDictionaryEnumerator.Value { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { public KeyCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TKey[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; } System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public TKey Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { public ValueCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TValue[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; } System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public TValue Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } } public partial class SortedList<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public SortedList() { } public SortedList(System.Collections.Generic.IComparer<TKey> comparer) { } public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { } public SortedList(int capacity) { } public SortedList(int capacity, System.Collections.Generic.IComparer<TKey> comparer) { } public int Capacity { get { throw null; } set { } } public System.Collections.Generic.IComparer<TKey> Comparer { get { throw null; } } public int Count { get { throw null; } } public TValue this[TKey key] { get { throw null; } set { } } public System.Collections.Generic.IList<TKey> Keys { get { throw null; } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { throw null; } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { throw null; } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { throw null; } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { throw null; } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } bool System.Collections.IDictionary.IsReadOnly { get { throw null; } } object System.Collections.IDictionary.this[object key] { get { throw null; } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } } System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } } public System.Collections.Generic.IList<TValue> Values { get { throw null; } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { throw null; } public bool ContainsValue(TValue value) { throw null; } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { throw null; } public int IndexOfKey(TKey key) { throw null; } public int IndexOfValue(TValue value) { throw null; } public bool Remove(TKey key) { throw null; } public void RemoveAt(int index) { } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { throw null; } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public void TrimExcess() { } public bool TryGetValue(TKey key, out TValue value) { throw null; } } public partial class SortedSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public SortedSet() { } public SortedSet(System.Collections.Generic.IComparer<T> comparer) { } public SortedSet(System.Collections.Generic.IEnumerable<T> collection) { } public SortedSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IComparer<T> comparer) { } protected SortedSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Collections.Generic.IComparer<T> Comparer { get { throw null; } } public int Count { get { throw null; } } public T Max { get { throw null; } } public T Min { get { throw null; } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public bool Add(T item) { throw null; } public virtual void Clear() { } public virtual bool Contains(T item) { throw null; } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int index) { } public void CopyTo(T[] array, int index, int count) { } public static IEqualityComparer<SortedSet<T>> CreateSetComparer() { throw null; } public static IEqualityComparer<SortedSet<T>> CreateSetComparer(IEqualityComparer<T> memberEqualityComparer) { throw null; } public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { } public System.Collections.Generic.SortedSet<T>.Enumerator GetEnumerator() { throw null; } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual System.Collections.Generic.SortedSet<T> GetViewBetween(T lowerValue, T upperValue) { throw null; } public virtual void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { } public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } protected virtual void OnDeserialization(object sender) { } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool Remove(T item) { throw null; } public int RemoveWhere(System.Predicate<T> match) { throw null; } public System.Collections.Generic.IEnumerable<T> Reverse() { throw null; } public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { throw null; } public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { } void System.Collections.Generic.ICollection<T>.Add(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(T equalValue, out T actualValue) { throw null; } public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public bool MoveNext() { throw null; } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } void System.Collections.IEnumerator.Reset() { } } } public partial class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public Stack() { } public Stack(System.Collections.Generic.IEnumerable<T> collection) { } public Stack(int capacity) { } public int Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Clear() { } public bool Contains(T item) { throw null; } public void CopyTo(T[] array, int arrayIndex) { } public System.Collections.Generic.Stack<T>.Enumerator GetEnumerator() { throw null; } public T Peek() { throw null; } public T Pop() { throw null; } public void Push(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public T[] ToArray() { throw null; } public void TrimExcess() { } public bool TryPeek(out T result) { throw null; } public bool TryPop(out T result) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } }
namespace Unosquare.FFplayDotNet.Rendering.Wave { using System; using System.Runtime.InteropServices; /// <summary> /// MME Wave function interop /// </summary> internal class WaveInterop { [Flags] public enum WaveInOutOpenFlags { /// <summary> /// CALLBACK_NULL /// No callback /// </summary> CallbackNull = 0, /// <summary> /// CALLBACK_FUNCTION /// dwCallback is a FARPROC /// </summary> CallbackFunction = 0x30000, /// <summary> /// CALLBACK_EVENT /// dwCallback is an EVENT handle /// </summary> CallbackEvent = 0x50000, /// <summary> /// CALLBACK_WINDOW /// dwCallback is a HWND /// </summary> CallbackWindow = 0x10000, /// <summary> /// CALLBACK_THREAD /// callback is a thread ID /// </summary> CallbackThread = 0x20000, /* WAVE_FORMAT_QUERY = 1, WAVE_MAPPED = 4, WAVE_FORMAT_DIRECT = 8*/ } //public const int TIME_MS = 0x0001; // time in milliseconds //public const int TIME_SAMPLES = 0x0002; // number of wave samples //public const int TIME_BYTES = 0x0004; // current byte offset public enum WaveMessage { /// <summary> /// WIM_OPEN /// </summary> WaveInOpen = 0x3BE, /// <summary> /// WIM_CLOSE /// </summary> WaveInClose = 0x3BF, /// <summary> /// WIM_DATA /// </summary> WaveInData = 0x3C0, /// <summary> /// WOM_CLOSE /// </summary> WaveOutClose = 0x3BC, /// <summary> /// WOM_DONE /// </summary> WaveOutDone = 0x3BD, /// <summary> /// WOM_OPEN /// </summary> WaveOutOpen = 0x3BB } // use the userdata as a reference // WaveOutProc http://msdn.microsoft.com/en-us/library/dd743869%28VS.85%29.aspx // WaveInProc http://msdn.microsoft.com/en-us/library/dd743849%28VS.85%29.aspx public delegate void WaveCallback(IntPtr hWaveOut, WaveMessage message, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved); [DllImport("winmm.dll")] public static extern Int32 waveOutGetNumDevs(); [DllImport("winmm.dll")] public static extern MmResult waveOutPrepareHeader(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult waveOutUnprepareHeader(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult waveOutWrite(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize); // http://msdn.microsoft.com/en-us/library/dd743866%28VS.85%29.aspx [DllImport("winmm.dll")] public static extern MmResult waveOutOpen(out IntPtr hWaveOut, IntPtr uDeviceID, WaveFormat lpFormat, WaveCallback dwCallback, IntPtr dwInstance, WaveInOutOpenFlags dwFlags); [DllImport("winmm.dll", EntryPoint = "waveOutOpen")] public static extern MmResult waveOutOpenWindow(out IntPtr hWaveOut, IntPtr uDeviceID, WaveFormat lpFormat, IntPtr callbackWindowHandle, IntPtr dwInstance, WaveInOutOpenFlags dwFlags); [DllImport("winmm.dll")] public static extern MmResult waveOutReset(IntPtr hWaveOut); [DllImport("winmm.dll")] public static extern MmResult waveOutClose(IntPtr hWaveOut); [DllImport("winmm.dll")] public static extern MmResult waveOutPause(IntPtr hWaveOut); [DllImport("winmm.dll")] public static extern MmResult waveOutRestart(IntPtr hWaveOut); // http://msdn.microsoft.com/en-us/library/dd743863%28VS.85%29.aspx [DllImport("winmm.dll")] public static extern MmResult waveOutGetPosition(IntPtr hWaveOut, out MmTime mmTime, int uSize); // http://msdn.microsoft.com/en-us/library/dd743874%28VS.85%29.aspx [DllImport("winmm.dll")] public static extern MmResult waveOutSetVolume(IntPtr hWaveOut, int dwVolume); [DllImport("winmm.dll")] public static extern MmResult waveOutSetPitch(IntPtr hWaveOut, int dwPitch); [DllImport("winmm.dll")] public static extern MmResult waveOutSetPlaybackRate(IntPtr hWaveOut, int dwRate); [DllImport("winmm.dll")] public static extern MmResult waveOutGetVolume(IntPtr hWaveOut, out int dwVolume); // http://msdn.microsoft.com/en-us/library/dd743857%28VS.85%29.aspx [DllImport("winmm.dll", CharSet = CharSet.Auto)] public static extern MmResult waveOutGetDevCaps(IntPtr deviceID, out WaveOutCapabilities waveOutCaps, int waveOutCapsSize); } /// <summary> /// A wrapper class for MmException. /// </summary> internal class MmException : Exception { private MmResult result; private string function; /// <summary> /// Creates a new MmException /// </summary> /// <param name="result">The result returned by the Windows API call</param> /// <param name="function">The name of the Windows API that failed</param> public MmException(MmResult result, string function) : base(MmException.ErrorMessage(result, function)) { this.result = result; this.function = function; } private static string ErrorMessage(MmResult result, string function) { return String.Format("{0} calling {1}", result, function); } /// <summary> /// Helper function to automatically raise an exception on failure /// </summary> /// <param name="result">The result of the API call</param> /// <param name="function">The API function name</param> public static void Try(MmResult result, string function) { if (result != MmResult.NoError) throw new MmException(result, function); } /// <summary> /// Returns the Windows API result /// </summary> public MmResult Result { get { return result; } } } /// <summary> /// Windows multimedia error codes from mmsystem.h. /// </summary> internal enum MmResult { /// <summary>no error, MMSYSERR_NOERROR</summary> NoError = 0, /// <summary>unspecified error, MMSYSERR_ERROR</summary> UnspecifiedError = 1, /// <summary>device ID out of range, MMSYSERR_BADDEVICEID</summary> BadDeviceId = 2, /// <summary>driver failed enable, MMSYSERR_NOTENABLED</summary> NotEnabled = 3, /// <summary>device already allocated, MMSYSERR_ALLOCATED</summary> AlreadyAllocated = 4, /// <summary>device handle is invalid, MMSYSERR_INVALHANDLE</summary> InvalidHandle = 5, /// <summary>no device driver present, MMSYSERR_NODRIVER</summary> NoDriver = 6, /// <summary>memory allocation error, MMSYSERR_NOMEM</summary> MemoryAllocationError = 7, /// <summary>function isn't supported, MMSYSERR_NOTSUPPORTED</summary> NotSupported = 8, /// <summary>error value out of range, MMSYSERR_BADERRNUM</summary> BadErrorNumber = 9, /// <summary>invalid flag passed, MMSYSERR_INVALFLAG</summary> InvalidFlag = 10, /// <summary>invalid parameter passed, MMSYSERR_INVALPARAM</summary> InvalidParameter = 11, /// <summary>handle being used simultaneously on another thread (eg callback),MMSYSERR_HANDLEBUSY</summary> HandleBusy = 12, /// <summary>specified alias not found, MMSYSERR_INVALIDALIAS</summary> InvalidAlias = 13, /// <summary>bad registry database, MMSYSERR_BADDB</summary> BadRegistryDatabase = 14, /// <summary>registry key not found, MMSYSERR_KEYNOTFOUND</summary> RegistryKeyNotFound = 15, /// <summary>registry read error, MMSYSERR_READERROR</summary> RegistryReadError = 16, /// <summary>registry write error, MMSYSERR_WRITEERROR</summary> RegistryWriteError = 17, /// <summary>registry delete error, MMSYSERR_DELETEERROR</summary> RegistryDeleteError = 18, /// <summary>registry value not found, MMSYSERR_VALNOTFOUND</summary> RegistryValueNotFound = 19, /// <summary>driver does not call DriverCallback, MMSYSERR_NODRIVERCB</summary> NoDriverCallback = 20, /// <summary>more data to be returned, MMSYSERR_MOREDATA</summary> MoreData = 21, /// <summary>unsupported wave format, WAVERR_BADFORMAT</summary> WaveBadFormat = 32, /// <summary>still something playing, WAVERR_STILLPLAYING</summary> WaveStillPlaying = 33, /// <summary>header not prepared, WAVERR_UNPREPARED</summary> WaveHeaderUnprepared = 34, /// <summary>device is synchronous, WAVERR_SYNC</summary> WaveSync = 35, // ACM error codes, found in msacm.h /// <summary>Conversion not possible (ACMERR_NOTPOSSIBLE)</summary> AcmNotPossible = 512, /// <summary>Busy (ACMERR_BUSY)</summary> AcmBusy = 513, /// <summary>Header Unprepared (ACMERR_UNPREPARED)</summary> AcmHeaderUnprepared = 514, /// <summary>Cancelled (ACMERR_CANCELED)</summary> AcmCancelled = 515, // Mixer error codes, found in mmresult.h /// <summary>invalid line (MIXERR_INVALLINE)</summary> MixerInvalidLine = 1024, /// <summary>invalid control (MIXERR_INVALCONTROL)</summary> MixerInvalidControl = 1025, /// <summary>invalid value (MIXERR_INVALVALUE)</summary> MixerInvalidValue = 1026, } /// <summary> /// http://msdn.microsoft.com/en-us/library/dd757347(v=VS.85).aspx /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct MmTime { public const int TIME_MS = 0x0001; public const int TIME_SAMPLES = 0x0002; public const int TIME_BYTES = 0x0004; [FieldOffset(0)] public UInt32 wType; [FieldOffset(4)] public UInt32 ms; [FieldOffset(4)] public UInt32 sample; [FieldOffset(4)] public UInt32 cb; [FieldOffset(4)] public UInt32 ticks; [FieldOffset(4)] public Byte smpteHour; [FieldOffset(5)] public Byte smpteMin; [FieldOffset(6)] public Byte smpteSec; [FieldOffset(7)] public Byte smpteFrame; [FieldOffset(8)] public Byte smpteFps; [FieldOffset(9)] public Byte smpteDummy; [FieldOffset(10)] public Byte smptePad0; [FieldOffset(11)] public Byte smptePad1; [FieldOffset(4)] public UInt32 midiSongPtrPos; } /// <summary> /// Flags indicating what features this WaveOut device supports /// </summary> [Flags] internal enum WaveOutSupport { /// <summary>supports pitch control (WAVECAPS_PITCH)</summary> Pitch = 0x0001, /// <summary>supports playback rate control (WAVECAPS_PLAYBACKRATE)</summary> PlaybackRate = 0x0002, /// <summary>supports volume control (WAVECAPS_VOLUME)</summary> Volume = 0x0004, /// <summary>supports separate left-right volume control (WAVECAPS_LRVOLUME)</summary> LRVolume = 0x0008, /// <summary>(WAVECAPS_SYNC)</summary> Sync = 0x0010, /// <summary>(WAVECAPS_SAMPLEACCURATE)</summary> SampleAccurate = 0x0020, } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Using directives #define USE_TRACING using System; using System.Xml; using System.Globalization; using System.ComponentModel; using System.Runtime.InteropServices; #endregion ////////////////////////////////////////////////////////////////////// // <summary>Handles atom:person element.</summary> ////////////////////////////////////////////////////////////////////// namespace Google.GData.Client { #if WindowsCE || PocketPC #else ////////////////////////////////////////////////////////////////////// /// <summary>TypeConverter, so that AtomHead shows up in the property pages /// </summary> ////////////////////////////////////////////////////////////////////// [ComVisible(false)] public class AtomPersonConverter : ExpandableObjectConverter { ///<summary>Standard type converter method</summary> public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(AtomPerson)) return true; return base.CanConvertTo(context, destinationType); } ///<summary>Standard type converter method</summary> public override object ConvertTo(ITypeDescriptorContext context,CultureInfo culture, object value, System.Type destinationType) { AtomPerson person = value as AtomPerson; if (destinationType == typeof(System.String) && person != null) { return "Person: " + person.Name; } return base.ConvertTo(context, culture, value, destinationType); } } ///////////////////////////////////////////////////////////////////////////// #endif ////////////////////////////////////////////////////////////////////// /// <summary>enum to describe the different person types /// </summary> ////////////////////////////////////////////////////////////////////// public enum AtomPersonType { /// <summary>is an author</summary> Author, /// <summary>is an contributor</summary> Contributor, /// /// <summary>parsing error</summary> Unknown } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>generic Person object, used for the feed and for the entry /// </summary> ////////////////////////////////////////////////////////////////////// #if WindowsCE || PocketPC #else [TypeConverterAttribute(typeof(AtomPersonConverter)), DescriptionAttribute("Expand to see the person object for the feed/entry.")] #endif public class AtomPerson : AtomBase { /// <summary>name holds the Name property as a string</summary> private string name; /// <summary>email holds the email property as a string</summary> private string email; /// <summary>link holds an Uri, representing the link atribute</summary> private AtomUri uri; /// <summary>holds the type for persistence</summary> private AtomPersonType type; /// <summary>public default constructor, usefull only for property pages</summary> public AtomPerson() { this.type = AtomPersonType.Author; } ////////////////////////////////////////////////////////////////////// /// <summary>Constructor taking a type to indicate whether person is author or contributor.</summary> /// <param name="type">indicates if author or contributor</param> ////////////////////////////////////////////////////////////////////// public AtomPerson(AtomPersonType type) { this.type = type; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Constructor taking a type to indicate whether person is author or contributor, plus the person's name</summary> /// <param name="type">indicates if author or contributor</param> /// <param name="name">person's name</param> ////////////////////////////////////////////////////////////////////// public AtomPerson(AtomPersonType type, string name) : this(type) { this.name = name; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Name</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Name { get {return this.name;} set {this.Dirty =true; this.name = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public Uri Uri</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public AtomUri Uri { get { if (this.uri == null) { this.uri = new AtomUri(""); } return this.uri; } set {this.Dirty = true; this.uri = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public Uri Email</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Email { get {return this.email;} set {this.Dirty = true; this.email = value;} } ///////////////////////////////////////////////////////////////////////////// #region Persistence overloads ////////////////////////////////////////////////////////////////////// /// <summary>Just returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public override string XmlName { get { return this.type == AtomPersonType.Author ? AtomParserNameTable.XmlAuthorElement : AtomParserNameTable.XmlContributorElement; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>saves the inner state of the element</summary> /// <param name="writer">the xmlWriter to save into </param> ////////////////////////////////////////////////////////////////////// protected override void SaveInnerXml(XmlWriter writer) { base.SaveInnerXml(writer); // now save our state... WriteEncodedElementString(writer, BaseNameTable.XmlName, this.Name); WriteEncodedElementString(writer, AtomParserNameTable.XmlEmailElement, this.Email); WriteEncodedElementString(writer, AtomParserNameTable.XmlUriElement, this.Uri); } ////////////////////////////////////////////////////////////////////// /// <summary>figures out if this object should be persisted</summary> /// <returns> true, if it's worth saving</returns> ////////////////////////////////////////////////////////////////////// public override bool ShouldBePersisted() { if (base.ShouldBePersisted() == false) { if (Utilities.IsPersistable(this.name)) { return true; } if (Utilities.IsPersistable(this.email)) { return true; } if (Utilities.IsPersistable(this.uri)) { return true; } return false; } return true; } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// #endregion } ///////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////
#region License /* Copyright (c) 2006 Leslie Sanford * * 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 #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections.Generic; using System.Diagnostics; namespace Sanford.Collections.Generic { /// <summary> /// Represents a list with undo/redo functionality. /// </summary> /// <typeparam name="T"> /// The type of elements in the list. /// </typeparam> public partial class UndoableList<T> : IList<T> { #region UndoableList<T> Members #region Fields private List<T> theList; private UndoManager undoManager = new UndoManager(); #endregion #region Construction public UndoableList() { theList = new List<T>(); } public UndoableList(IEnumerable<T> collection) { theList = new List<T>(collection); } public UndoableList(int capacity) { theList = new List<T>(capacity); } #endregion #region Methods /// <summary> /// Undoes the last operation. /// </summary> /// <returns> /// <b>true</b> if the last operation was undone, <b>false</b> if there /// are no more operations left to undo. /// </returns> public bool Undo() { return undoManager.Undo(); } /// <summary> /// Redoes the last operation. /// </summary> /// <returns> /// <b>true</b> if the last operation was redone, <b>false</b> if there /// are no more operations left to redo. /// </returns> public bool Redo() { return undoManager.Redo(); } /// <summary> /// Clears the undo/redo history. /// </summary> public void ClearHistory() { undoManager.ClearHistory(); } #region List Wrappers public int BinarySearch(T item) { return theList.BinarySearch(item); } public int BinarySearch(T item, IComparer<T> comparer) { return theList.BinarySearch(item, comparer); } public int BinarySearch(int index, int count, T item, IComparer<T> comparer) { return theList.BinarySearch(index, count, item, comparer); } public bool Contains(T item) { return theList.Contains(item); } public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter) { return theList.ConvertAll<TOutput>(converter); } public bool Exists(Predicate<T> match) { return theList.Exists(match); } public T Find(Predicate<T> match) { return theList.Find(match); } public List<T> FindAll(Predicate<T> match) { return theList.FindAll(match); } public int FindIndex(Predicate<T> match) { return theList.FindIndex(match); } public int FindIndex(int startIndex, Predicate<T> match) { return theList.FindIndex(startIndex, match); } public int FindIndex(int startIndex, int count, Predicate<T> match) { return theList.FindIndex(startIndex, count, match); } public int FindLastIndex(Predicate<T> match) { return theList.FindLastIndex(match); } public int FindLastIndex(int startIndex, Predicate<T> match) { return theList.FindLastIndex(startIndex, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { return theList.FindLastIndex(startIndex, count, match); } public T FindLast(Predicate<T> match) { return theList.FindLast(match); } public int LastIndexOf(T item) { return theList.LastIndexOf(item); } public int LastIndexOf(T item, int index) { return theList.LastIndexOf(item, index); } public int LastIndexOf(T item, int index, int count) { return theList.LastIndexOf(item, index, count); } public bool TrueForAll(Predicate<T> match) { return theList.TrueForAll(match); } public T[] ToArray() { return theList.ToArray(); } public void TrimExcess() { theList.TrimExcess(); } public void AddRange(IEnumerable<T> collection) { InsertRangeCommand command = new InsertRangeCommand(theList, theList.Count, collection); undoManager.Execute(command); } public void InsertRange(int index, IEnumerable<T> collection) { InsertRangeCommand command = new InsertRangeCommand(theList, index, collection); undoManager.Execute(command); } public void RemoveRange(int index, int count) { RemoveRangeCommand command = new RemoveRangeCommand(theList, index, count); undoManager.Execute(command); } public void Reverse() { ReverseCommand command = new ReverseCommand(theList); undoManager.Execute(command); } public void Reverse(int index, int count) { ReverseCommand command = new ReverseCommand(theList, index, count); undoManager.Execute(command); } #endregion #endregion #region Properties /// <summary> /// The number of operations left to undo. /// </summary> public int UndoCount { get { return undoManager.UndoCount; } } /// <summary> /// The number of operations left to redo. /// </summary> public int RedoCount { get { return undoManager.RedoCount; } } #endregion #endregion #region IList<T> Members public int IndexOf(T item) { return theList.IndexOf(item); } public void Insert(int index, T item) { InsertCommand command = new InsertCommand(theList, index, item); undoManager.Execute(command); } public void RemoveAt(int index) { RemoveAtCommand command = new RemoveAtCommand(theList, index); undoManager.Execute(command); } public T this[int index] { get { return theList[index]; } set { SetCommand command = new SetCommand(theList, index, value); undoManager.Execute(command); } } #endregion #region ICollection<T> Members public void Add(T item) { InsertCommand command = new InsertCommand(theList, Count, item); undoManager.Execute(command); } public void Clear() { #region Guard if(Count == 0) { return; } #endregion ClearCommand command = new ClearCommand(theList); undoManager.Execute(command); } public void CopyTo(T[] array, int arrayIndex) { theList.CopyTo(array, arrayIndex); } public int Count { get { return theList.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { int index = IndexOf(item); bool result; if(index >= 0) { RemoveAtCommand command = new RemoveAtCommand(theList, index); undoManager.Execute(command); result = true; } else { result = false; } return result; } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return theList.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return theList.GetEnumerator(); } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.DocumentAI.V1Beta3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedDocumentProcessorServiceClientTest { [xunit::FactAttribute] public void ProcessDocumentRequestObject() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ProcessRequest request = new ProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), #pragma warning disable CS0612 Document = new Document(), #pragma warning restore CS0612 SkipHumanReview = true, InlineDocument = new Document(), RawDocument = new RawDocument(), }; ProcessResponse expectedResponse = new ProcessResponse { Document = new Document(), #pragma warning disable CS0612 HumanReviewOperation = "human_review_operationb1fb7921", #pragma warning restore CS0612 HumanReviewStatus = new HumanReviewStatus(), }; mockGrpcClient.Setup(x => x.ProcessDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); ProcessResponse response = client.ProcessDocument(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ProcessDocumentRequestObjectAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ProcessRequest request = new ProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), #pragma warning disable CS0612 Document = new Document(), #pragma warning restore CS0612 SkipHumanReview = true, InlineDocument = new Document(), RawDocument = new RawDocument(), }; ProcessResponse expectedResponse = new ProcessResponse { Document = new Document(), #pragma warning disable CS0612 HumanReviewOperation = "human_review_operationb1fb7921", #pragma warning restore CS0612 HumanReviewStatus = new HumanReviewStatus(), }; mockGrpcClient.Setup(x => x.ProcessDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ProcessResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); ProcessResponse responseCallSettings = await client.ProcessDocumentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ProcessResponse responseCancellationToken = await client.ProcessDocumentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ProcessDocument() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ProcessRequest request = new ProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), }; ProcessResponse expectedResponse = new ProcessResponse { Document = new Document(), #pragma warning disable CS0612 HumanReviewOperation = "human_review_operationb1fb7921", #pragma warning restore CS0612 HumanReviewStatus = new HumanReviewStatus(), }; mockGrpcClient.Setup(x => x.ProcessDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); ProcessResponse response = client.ProcessDocument(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ProcessDocumentAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ProcessRequest request = new ProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), }; ProcessResponse expectedResponse = new ProcessResponse { Document = new Document(), #pragma warning disable CS0612 HumanReviewOperation = "human_review_operationb1fb7921", #pragma warning restore CS0612 HumanReviewStatus = new HumanReviewStatus(), }; mockGrpcClient.Setup(x => x.ProcessDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ProcessResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); ProcessResponse responseCallSettings = await client.ProcessDocumentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ProcessResponse responseCancellationToken = await client.ProcessDocumentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ProcessDocumentResourceNames() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ProcessRequest request = new ProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), }; ProcessResponse expectedResponse = new ProcessResponse { Document = new Document(), #pragma warning disable CS0612 HumanReviewOperation = "human_review_operationb1fb7921", #pragma warning restore CS0612 HumanReviewStatus = new HumanReviewStatus(), }; mockGrpcClient.Setup(x => x.ProcessDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); ProcessResponse response = client.ProcessDocument(request.ProcessorName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ProcessDocumentResourceNamesAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ProcessRequest request = new ProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), }; ProcessResponse expectedResponse = new ProcessResponse { Document = new Document(), #pragma warning disable CS0612 HumanReviewOperation = "human_review_operationb1fb7921", #pragma warning restore CS0612 HumanReviewStatus = new HumanReviewStatus(), }; mockGrpcClient.Setup(x => x.ProcessDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ProcessResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); ProcessResponse responseCallSettings = await client.ProcessDocumentAsync(request.ProcessorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ProcessResponse responseCancellationToken = await client.ProcessDocumentAsync(request.ProcessorName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void FetchProcessorTypesRequestObject() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); FetchProcessorTypesRequest request = new FetchProcessorTypesRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; FetchProcessorTypesResponse expectedResponse = new FetchProcessorTypesResponse { ProcessorTypes = { new ProcessorType(), }, }; mockGrpcClient.Setup(x => x.FetchProcessorTypes(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); FetchProcessorTypesResponse response = client.FetchProcessorTypes(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task FetchProcessorTypesRequestObjectAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); FetchProcessorTypesRequest request = new FetchProcessorTypesRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; FetchProcessorTypesResponse expectedResponse = new FetchProcessorTypesResponse { ProcessorTypes = { new ProcessorType(), }, }; mockGrpcClient.Setup(x => x.FetchProcessorTypesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FetchProcessorTypesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); FetchProcessorTypesResponse responseCallSettings = await client.FetchProcessorTypesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FetchProcessorTypesResponse responseCancellationToken = await client.FetchProcessorTypesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void FetchProcessorTypes() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); FetchProcessorTypesRequest request = new FetchProcessorTypesRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; FetchProcessorTypesResponse expectedResponse = new FetchProcessorTypesResponse { ProcessorTypes = { new ProcessorType(), }, }; mockGrpcClient.Setup(x => x.FetchProcessorTypes(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); FetchProcessorTypesResponse response = client.FetchProcessorTypes(request.Parent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task FetchProcessorTypesAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); FetchProcessorTypesRequest request = new FetchProcessorTypesRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; FetchProcessorTypesResponse expectedResponse = new FetchProcessorTypesResponse { ProcessorTypes = { new ProcessorType(), }, }; mockGrpcClient.Setup(x => x.FetchProcessorTypesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FetchProcessorTypesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); FetchProcessorTypesResponse responseCallSettings = await client.FetchProcessorTypesAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FetchProcessorTypesResponse responseCancellationToken = await client.FetchProcessorTypesAsync(request.Parent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void FetchProcessorTypesResourceNames() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); FetchProcessorTypesRequest request = new FetchProcessorTypesRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; FetchProcessorTypesResponse expectedResponse = new FetchProcessorTypesResponse { ProcessorTypes = { new ProcessorType(), }, }; mockGrpcClient.Setup(x => x.FetchProcessorTypes(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); FetchProcessorTypesResponse response = client.FetchProcessorTypes(request.ParentAsLocationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task FetchProcessorTypesResourceNamesAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); FetchProcessorTypesRequest request = new FetchProcessorTypesRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; FetchProcessorTypesResponse expectedResponse = new FetchProcessorTypesResponse { ProcessorTypes = { new ProcessorType(), }, }; mockGrpcClient.Setup(x => x.FetchProcessorTypesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FetchProcessorTypesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); FetchProcessorTypesResponse responseCallSettings = await client.FetchProcessorTypesAsync(request.ParentAsLocationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FetchProcessorTypesResponse responseCancellationToken = await client.FetchProcessorTypesAsync(request.ParentAsLocationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateProcessorRequestObject() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProcessorRequest request = new CreateProcessorRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Processor = new Processor(), }; Processor expectedResponse = new Processor { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), Type = "typee2cc9d59", DisplayName = "display_name137f65c2", State = Processor.Types.State.Failed, ProcessEndpoint = "process_endpoint4445f26d", CreateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", DefaultProcessorVersion = "default_processor_versiona99cda5e", }; mockGrpcClient.Setup(x => x.CreateProcessor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); Processor response = client.CreateProcessor(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateProcessorRequestObjectAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProcessorRequest request = new CreateProcessorRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Processor = new Processor(), }; Processor expectedResponse = new Processor { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), Type = "typee2cc9d59", DisplayName = "display_name137f65c2", State = Processor.Types.State.Failed, ProcessEndpoint = "process_endpoint4445f26d", CreateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", DefaultProcessorVersion = "default_processor_versiona99cda5e", }; mockGrpcClient.Setup(x => x.CreateProcessorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Processor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); Processor responseCallSettings = await client.CreateProcessorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Processor responseCancellationToken = await client.CreateProcessorAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateProcessor() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProcessorRequest request = new CreateProcessorRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Processor = new Processor(), }; Processor expectedResponse = new Processor { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), Type = "typee2cc9d59", DisplayName = "display_name137f65c2", State = Processor.Types.State.Failed, ProcessEndpoint = "process_endpoint4445f26d", CreateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", DefaultProcessorVersion = "default_processor_versiona99cda5e", }; mockGrpcClient.Setup(x => x.CreateProcessor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); Processor response = client.CreateProcessor(request.Parent, request.Processor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateProcessorAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProcessorRequest request = new CreateProcessorRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Processor = new Processor(), }; Processor expectedResponse = new Processor { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), Type = "typee2cc9d59", DisplayName = "display_name137f65c2", State = Processor.Types.State.Failed, ProcessEndpoint = "process_endpoint4445f26d", CreateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", DefaultProcessorVersion = "default_processor_versiona99cda5e", }; mockGrpcClient.Setup(x => x.CreateProcessorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Processor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); Processor responseCallSettings = await client.CreateProcessorAsync(request.Parent, request.Processor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Processor responseCancellationToken = await client.CreateProcessorAsync(request.Parent, request.Processor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateProcessorResourceNames() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProcessorRequest request = new CreateProcessorRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Processor = new Processor(), }; Processor expectedResponse = new Processor { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), Type = "typee2cc9d59", DisplayName = "display_name137f65c2", State = Processor.Types.State.Failed, ProcessEndpoint = "process_endpoint4445f26d", CreateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", DefaultProcessorVersion = "default_processor_versiona99cda5e", }; mockGrpcClient.Setup(x => x.CreateProcessor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); Processor response = client.CreateProcessor(request.ParentAsLocationName, request.Processor); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateProcessorResourceNamesAsync() { moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient> mockGrpcClient = new moq::Mock<DocumentProcessorService.DocumentProcessorServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProcessorRequest request = new CreateProcessorRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Processor = new Processor(), }; Processor expectedResponse = new Processor { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), Type = "typee2cc9d59", DisplayName = "display_name137f65c2", State = Processor.Types.State.Failed, ProcessEndpoint = "process_endpoint4445f26d", CreateTime = new wkt::Timestamp(), KmsKeyName = "kms_key_name06bd122b", DefaultProcessorVersion = "default_processor_versiona99cda5e", }; mockGrpcClient.Setup(x => x.CreateProcessorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Processor>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentProcessorServiceClient client = new DocumentProcessorServiceClientImpl(mockGrpcClient.Object, null); Processor responseCallSettings = await client.CreateProcessorAsync(request.ParentAsLocationName, request.Processor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Processor responseCancellationToken = await client.CreateProcessorAsync(request.ParentAsLocationName, request.Processor, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#region Imported Types using DeviceSQL.Device.ROC.Data; using DeviceSQL.Devices.Device.ROC.Data; using Microsoft.SqlServer.Server; using System; using System.Data.SqlTypes; using System.IO; #endregion namespace DeviceSQL.SQLTypes.ROCMaster { [Serializable()] [SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 61)] public struct ROCMaster_Parameter : INullable, IBinarySerialize { #region Fields private byte parameterType; private byte[] rawValue; #endregion #region Properties public bool IsNull { get; private set; } public static ROCMaster_Parameter Null { get { return (new ROCMaster_Parameter() { IsNull = true }); } } public byte PointType { get; set; } public byte LogicalNumber { get; set; } public byte Parameter { get; set; } public string Type { get { return RawType.ToString(); } } internal ParameterType RawType { get { return (ParameterType)parameterType; } set { parameterType = (byte)value; } } internal byte[] RawValue { get { if (rawValue == null) { switch ((ParameterType)parameterType) { case ParameterType.AC3: rawValue = new byte[3]; break; case ParameterType.AC7: rawValue = new byte[3]; break; case ParameterType.AC10: rawValue = new byte[10]; break; case ParameterType.AC12: rawValue = new byte[12]; break; case ParameterType.AC20: rawValue = new byte[20]; break; case ParameterType.AC30: rawValue = new byte[30]; break; case ParameterType.AC40: rawValue = new byte[40]; break; case ParameterType.BIN: rawValue = new byte[1]; break; case ParameterType.FL: rawValue = new byte[4]; break; case ParameterType.DOUBLE: rawValue = new byte[8]; break; case ParameterType.INT16: rawValue = new byte[2]; break; case ParameterType.INT32: rawValue = new byte[4]; break; case ParameterType.INT8: rawValue = new byte[1]; break; case ParameterType.TLP: rawValue = new byte[3]; break; case ParameterType.UINT16: rawValue = new byte[2]; break; case ParameterType.UINT32: rawValue = new byte[4]; break; case ParameterType.TIME: rawValue = new byte[4]; break; case ParameterType.UINT8: rawValue = new byte[10]; break; } } return rawValue; } set { rawValue = value; } } #endregion #region Helper Methods public override string ToString() { if (this.IsNull) { return "NULL"; } else { switch ((ParameterType)parameterType) { case ParameterType.AC3: return (new Ac3Parameter() { Data = RawValue }).Value; case ParameterType.AC7: return (new Ac7Parameter() { Data = RawValue }).Value; case ParameterType.AC10: return (new Ac10Parameter() { Data = RawValue }).Value; case ParameterType.AC12: return (new Ac12Parameter() { Data = RawValue }).Value; case ParameterType.AC20: return (new Ac20Parameter() { Data = RawValue }).Value; case ParameterType.AC30: return (new Ac30Parameter() { Data = RawValue }).Value; case ParameterType.AC40: return (new Ac40Parameter() { Data = RawValue }).Value; case ParameterType.BIN: return (new BinParameter() { Data = RawValue }).Value.ToString(); case ParameterType.FL: return (new FlpParameter() { Data = RawValue }).Value.ToString(); case ParameterType.DOUBLE: return (new DoubleParameter() { Data = RawValue }).Value.ToString(); case ParameterType.INT16: return (new Int16Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.INT32: return (new Int32Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.INT8: return (new Int8Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.TLP: { var tlpParameter = new TlpParameter() { Data = RawValue }; return string.Format("{0}.{1}.{2}", tlpParameter.Value.PointType.ToString(), tlpParameter.Value.LogicalNumber.ToString(), tlpParameter.Value.Parameter.ToString()); } case ParameterType.UINT16: return (new UInt16Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.UINT32: return (new Int32Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.TIME: return (new TimeParameter() { Data = RawValue }).Value.ToString(); case ParameterType.UINT8: return (new UInt8Parameter() { Data = RawValue }).Value.ToString(); default: return "NULL"; } } } public SqlByte ToBin() { return (new BinParameter() { Data = RawValue }).Value; } public SqlByte ToUInt8() { return (new UInt8Parameter() { Data = RawValue }).Value; } public SqlInt16 ToInt8() { return (new Int8Parameter() { Data = RawValue }).Value; } public SqlInt16 ToInt16() { return (new Int16Parameter() { Data = RawValue }).Value; } public SqlInt32 ToUInt16() { return (new UInt16Parameter() { Data = RawValue }).Value; } public SqlInt32 ToInt32() { return (new Int32Parameter() { Data = RawValue }).Value; } public SqlInt64 ToUInt32() { return (new UInt32Parameter() { Data = RawValue }).Value; } public SqlDateTime ToTime() { return (new TimeParameter() { Data = RawValue }).Value; } public SqlSingle ToFl() { var flpValue = new FlpParameter() { Data = RawValue }.NullableValue; return flpValue.HasValue ? flpValue.Value : SqlSingle.Null; } public SqlDouble ToDouble() { var doubleValue = new DoubleParameter() { Data = RawValue }.NullableValue; return doubleValue.HasValue ? doubleValue.Value : SqlDouble.Null; } public static ROCMaster_Parameter Parse(SqlString stringToParse) { if (stringToParse.IsNull) { return Null; } var parsedROCPointData = stringToParse.Value.Split(",".ToCharArray()); var parsedROCParameter = new ROCMaster_Parameter() { PointType = byte.Parse(parsedROCPointData[0]), LogicalNumber = byte.Parse(parsedROCPointData[1]), Parameter = byte.Parse(parsedROCPointData[2]) }; parsedROCParameter.parameterType = (byte)((ParameterType)Enum.Parse(typeof(ParameterType), parsedROCPointData[3])); switch (parsedROCPointData[3]) { case "AC3": parsedROCParameter.rawValue = (new Ac3Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC7": parsedROCParameter.rawValue = (new Ac7Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC10": parsedROCParameter.rawValue = (new Ac10Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC12": parsedROCParameter.rawValue = (new Ac12Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC20": parsedROCParameter.rawValue = (new Ac20Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC30": parsedROCParameter.rawValue = (new Ac30Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC40": parsedROCParameter.rawValue = (new Ac40Parameter() { Value = parsedROCPointData[4] }).Data; break; case "BIN": parsedROCParameter.rawValue = (new BinParameter() { Value = byte.Parse(parsedROCPointData[4]) }).Data; break; case "FL": parsedROCParameter.rawValue = (new FlpParameter() { Value = float.Parse(parsedROCPointData[4]) }).Data; break; case "DOUBLE": parsedROCParameter.rawValue = (new DoubleParameter() { Value = double.Parse(parsedROCPointData[8]) }).Data; break; case "INT16": parsedROCParameter.rawValue = (new Int16Parameter() { Value = short.Parse(parsedROCPointData[4]) }).Data; break; case "INT32": parsedROCParameter.rawValue = (new Int32Parameter() { Value = int.Parse(parsedROCPointData[4]) }).Data; break; case "Int8": parsedROCParameter.rawValue = (new Int8Parameter() { Value = SByte.Parse(parsedROCPointData[4]) }).Data; break; case "TLP": { var parsedTlp = parsedROCPointData[4].Split(".".ToCharArray()); parsedROCParameter.rawValue = (new TlpParameter() { Value = new Tlp(byte.Parse(parsedTlp[0]), byte.Parse(parsedTlp[1]), byte.Parse(parsedTlp[2])) }).Data; } break; case "UINT16": parsedROCParameter.rawValue = (new UInt16Parameter() { Value = ushort.Parse(parsedROCPointData[4]) }).Data; break; case "UINT32": parsedROCParameter.rawValue = (new UInt32Parameter() { Value = uint.Parse(parsedROCPointData[4]) }).Data; break; case "TIME": parsedROCParameter.rawValue = (new TimeParameter() { Value = (new DateTime(1970, 01, 01).AddSeconds(uint.Parse(parsedROCPointData[4]))) }).Data; break; case "UINT8": parsedROCParameter.rawValue = (new UInt8Parameter() { Value = byte.Parse(parsedROCPointData[4]) }).Data; break; } return parsedROCParameter; } public static ROCMaster_Parameter ParseTlp(byte pointType, byte logicalNumber, byte parameter, byte pointTypeValue, byte logicalNumberValue, byte parameterValue) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.TLP, rawValue = (new TlpParameter() { Value = new Tlp(pointTypeValue, logicalNumberValue, parameterValue) }).Data }; } public static ROCMaster_Parameter ParseAc3(byte pointType, byte logicalNumber, byte parameter, string value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.AC3, rawValue = (new Ac3Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseAc7(byte pointType, byte logicalNumber, byte parameter, string value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.AC7, rawValue = (new Ac3Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseAc10(byte pointType, byte logicalNumber, byte parameter, string value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.AC10, rawValue = (new Ac10Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseAc12(byte pointType, byte logicalNumber, byte parameter, string value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.AC12, rawValue = (new Ac12Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseAc20(byte pointType, byte logicalNumber, byte parameter, string value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.AC20, rawValue = (new Ac20Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseAc30(byte pointType, byte logicalNumber, byte parameter, string value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.AC30, rawValue = (new Ac30Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseAc40(byte pointType, byte logicalNumber, byte parameter, string value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.AC40, rawValue = (new Ac40Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseBin(byte pointType, byte logicalNumber, byte parameter, byte value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.BIN, rawValue = (new BinParameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseInt8(byte pointType, byte logicalNumber, byte parameter, short value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.INT8, rawValue = (new Int8Parameter() { Value = Convert.ToSByte(value) }).Data }; } public static ROCMaster_Parameter ParseUInt8(byte pointType, byte logicalNumber, byte parameter, byte value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.UINT8, rawValue = (new UInt8Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseInt16(byte pointType, byte logicalNumber, byte parameter, short value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.INT16, rawValue = (new Int16Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseUInt16(byte pointType, byte logicalNumber, byte parameter, int value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.UINT16, rawValue = (new UInt16Parameter() { Value = Convert.ToUInt16(value) }).Data }; } public static ROCMaster_Parameter ParseInt32(byte pointType, byte logicalNumber, byte parameter, int value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.INT32, rawValue = (new Int32Parameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseUInt32(byte pointType, byte logicalNumber, byte parameter, long value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.UINT32, rawValue = (new UInt32Parameter() { Value = Convert.ToUInt32(value) }).Data }; } public static ROCMaster_Parameter ParseTime(byte pointType, byte logicalNumber, byte parameter, DateTime value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.TIME, rawValue = (new TimeParameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseFl(byte pointType, byte logicalNumber, byte parameter, float value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.FL, rawValue = (new FlpParameter() { Value = value }).Data }; } public static ROCMaster_Parameter ParseDouble(byte pointType, byte logicalNumber, byte parameter, double value) { return new ROCMaster_Parameter() { PointType = pointType, LogicalNumber = logicalNumber, Parameter = parameter, parameterType = (byte)ParameterType.DOUBLE, rawValue = (new DoubleParameter() { Value = value }).Data }; } #endregion #region Serialization Methods public void Read(BinaryReader binaryReader) { IsNull = binaryReader.ReadBoolean(); if (!IsNull) { PointType = binaryReader.ReadByte(); LogicalNumber = binaryReader.ReadByte(); Parameter = binaryReader.ReadByte(); parameterType = binaryReader.ReadByte(); rawValue = new byte[binaryReader.ReadInt32()]; binaryReader.Read(rawValue, 0, rawValue.Length); } } public void Write(BinaryWriter binaryWriter) { binaryWriter.Write(IsNull); if (!IsNull) { binaryWriter.Write(PointType); binaryWriter.Write(LogicalNumber); binaryWriter.Write(Parameter); binaryWriter.Write(parameterType); binaryWriter.Write(RawValue.Length); binaryWriter.Write(RawValue); } } #endregion } }
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.Tests.Serialization { using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Builders; using MassTransit.Serialization; using MassTransit.Testing; using NUnit.Framework; using Shouldly; using TestFramework; [TestFixture(typeof(JsonMessageSerializer))] [TestFixture(typeof(BsonMessageSerializer))] [TestFixture(typeof(XmlMessageSerializer))] [TestFixture(typeof(EncryptedMessageSerializer))] public class Deserializing_an_interface : SerializationTest { [Test] public void Should_create_a_proxy_for_the_interface() { var user = new UserImpl("Chris", "noone@nowhere.com"); ComplaintAdded complaint = new ComplaintAddedImpl(user, "No toilet paper", BusinessArea.Appearance) { Body = "There was no toilet paper in the stall, forcing me to use my treasured issue of .NET Developer magazine." }; var result = SerializeAndReturn(complaint); complaint.Equals(result).ShouldBe(true); } [Test] public async Task Should_dispatch_an_interface_via_the_pipeline() { var pipe = new ConsumePipeBuilder().Build(); var consumer = new MultiTestConsumer(TestTimeout); consumer.Consume<ComplaintAdded>(); consumer.Connect(pipe); var user = new UserImpl("Chris", "noone@nowhere.com"); ComplaintAdded complaint = new ComplaintAddedImpl(user, "No toilet paper", BusinessArea.Appearance) { Body = "There was no toilet paper in the stall, forcing me to use my treasured issue of .NET Developer magazine." }; await pipe.Send(new TestConsumeContext<ComplaintAdded>(complaint)); consumer.Received.Select<ComplaintAdded>().Any().ShouldBe(true); } public Deserializing_an_interface(Type serializerType) : base(serializerType) { } } public interface ComplaintAdded { User AddedBy { get; } DateTime AddedAt { get; } string Subject { get; } string Body { get; } BusinessArea Area { get; } } public enum BusinessArea { Unknown = 0, Appearance, Courtesy } public interface User { string Name { get; } string Email { get; } } public class UserImpl : User { public UserImpl(string name, string email) { Name = name; Email = email; } protected UserImpl() { } public string Name { get; set; } public string Email { get; set; } public bool Equals(User other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.Name, Name) && Equals(other.Email, Email); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (!typeof(User).IsAssignableFrom(obj.GetType())) return false; return Equals((User)obj); } public override int GetHashCode() { unchecked { return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ (Email != null ? Email.GetHashCode() : 0); } } } public class ComplaintAddedImpl : ComplaintAdded { public ComplaintAddedImpl(User addedBy, string subject, BusinessArea area) { var dateTime = DateTime.UtcNow; AddedAt = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Utc); AddedBy = addedBy; Subject = subject; Area = area; Body = string.Empty; } protected ComplaintAddedImpl() { } public User AddedBy { get; set; } public DateTime AddedAt { get; set; } public string Subject { get; set; } public string Body { get; set; } public BusinessArea Area { get; set; } public bool Equals(ComplaintAdded other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return AddedBy.Equals(other.AddedBy) && other.AddedAt.Equals(AddedAt) && Equals(other.Subject, Subject) && Equals(other.Body, Body) && Equals(other.Area, Area); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (!typeof(ComplaintAdded).GetTypeInfo().IsAssignableFrom(obj.GetType())) return false; return Equals((ComplaintAdded)obj); } public override int GetHashCode() { unchecked { var result = (AddedBy != null ? AddedBy.GetHashCode() : 0); result = (result * 397) ^ AddedAt.GetHashCode(); result = (result * 397) ^ (Subject != null ? Subject.GetHashCode() : 0); result = (result * 397) ^ (Body != null ? Body.GetHashCode() : 0); result = (result * 397) ^ Area.GetHashCode(); return result; } } } }
using ServiceStack.ServiceHost; using System; using System.IO; namespace RestBus.ServiceStack { public class ResponseWrapper : IHttpResponse { //TODO: Fix this class -- See ServiceStacks HttpListenerResponseWrapper class System.Collections.Specialized.NameValueCollection headers = new System.Collections.Specialized.NameValueCollection(); public System.Collections.Specialized.NameValueCollection Headers { get { return headers; } } public void AddHeader(string name, string value) { //TODO: Make sure header name is valid headers.Add(name, value); } public void Close() { //TODO: Close outputstream //Also close request inputstream if (!_isClosed) { _isClosed = true; if (outputStream != null) { outputStream.Close(); } } } public string ContentType { get { return headers["Content-Type"]; } set { headers["Content-Type"] = value; } } Cookies cookies; public ICookies Cookies { get { if (cookies == null) { cookies = new Cookies(this); } return cookies; } } public void End() { Close(); } public void Flush() { outputStream.Flush(); } private bool _isClosed = false; public bool IsClosed { //TODO: Look at the proper way to implement this -- does this refer to the strem's closed state get { return _isClosed; } } public object OriginalResponse { get { return this; } } private MemoryStream outputStream = null; public System.IO.Stream OutputStream { get { if (outputStream == null) { outputStream = new MemoryStream(); } return outputStream; } } public void Redirect(string url) { //TODO: Write code that sets the redirection URL and status and/or Figure out what HttpListenerResponse.Redirecte throw new NotImplementedException(); } private int _statuscode = (int)System.Net.HttpStatusCode.OK; public int StatusCode { get { return _statuscode; } set { _statuscode = value; } } private string _statusDescription; public string StatusDescription { get { if (_statusDescription == null) { _statusDescription = GetStatusDescription(_statuscode) ?? String.Empty; } return _statusDescription; } set { _statusDescription = value; } } public void Write(string text) { try { var output = System.Text.Encoding.UTF8.GetBytes(text); outputStream.Write(output, 0, output.Length); Close(); } catch (Exception ex) { //TODO : Log this throw; } } public void SetContentLength(long contentLength) { //headers["Content-Length"] = contentLength.ToString(); } private string GetStatusDescription(int statusCode) { switch (statusCode) { #region 1xx Informational codes case 100: return "Continue"; case 101: return "Switching Protocols"; #endregion #region 2xx Successful codes case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; #endregion #region 3xx Redirection codes case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; #endregion #region 4xx Client Error codes case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-URI Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; #endregion #region 5xx Server Error codes case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "HTTP Version Not Supported"; #endregion default: return null; } } } }
using System; using System.Runtime.InteropServices; using Kitware.VTK; namespace ActiViz.Examples { class Program { struct Frame { private float[] origin; private float[] xDirection; private float[] yDirection; private float[] zDirection; internal float[] Origin { get { return origin; } } internal float[] XDirection { get { return xDirection; } } internal float[] YDirection { get { return yDirection; } } internal float[] ZDirection { get { return zDirection; } } internal Frame(float[] origin, float[] xDirection, float[] yDirection, float[] zDirection) { this.origin = new float[3]; this.xDirection = new float[3]; this.yDirection = new float[3]; this.zDirection = new float[3]; origin.CopyTo(this.origin, 0); xDirection.CopyTo(this.xDirection, 0); yDirection.CopyTo(this.yDirection, 0); zDirection.CopyTo(this.zDirection, 0); Normalize(ref xDirection); Normalize(ref yDirection); Normalize(ref zDirection); Console.WriteLine("Origin: " + this.origin[0] + " " + this.origin[1] + " " + this.origin[2]); Console.WriteLine("xDirection: " + this.xDirection[0] + " " + this.xDirection[1] + " " + this.xDirection[2]); Console.WriteLine("yDirection: " + this.yDirection[0] + " " + this.yDirection[1] + " " + this.yDirection[2]); Console.WriteLine("zDirection: " + this.zDirection[0] + " " + this.zDirection[1] + " " + this.zDirection[2]); } private void Normalize(ref float[] vector) { IntPtr pDirection = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(float)) * 3); Marshal.Copy(vector, 0, pDirection, 3); vtkMath.Normalize(pDirection); Marshal.FreeHGlobal(pDirection); } internal void ApplyTransform(ref vtkTransform transform, string filename) { vtkPolyData polydata = vtkPolyData.New(); CreatePolydata(ref polydata); vtkTransformFilter transformFilter = vtkTransformFilter.New(); #if VTK_MAJOR_VERSION_5 transformFilter.SetInputConnection(polydata.GetProducerPort()); #else transformFilter.SetInputData(polydata); #endif transformFilter.SetTransform(transform); transformFilter.Update(); vtkXMLPolyDataWriter writer = vtkXMLPolyDataWriter.New(); writer.SetFileName(filename); #if VTK_MAJOR_VERSION_5 writer.SetInputConnection(transformFilter.GetOutputPort()); #else writer.SetInputData(transformFilter); #endif writer.Write(); } internal void CreatePolydata(ref vtkPolyData polydata) { vtkPoints points = vtkPoints.New(); points.InsertNextPoint(this.origin[0], this.origin[1], this.origin[2]); float[] x = new float[3]; float[] y = new float[3]; float[] z = new float[3]; Add(this.origin, this.xDirection, ref x); Add(this.origin, this.yDirection, ref y); Add(this.origin, this.zDirection, ref z); points.InsertNextPoint(x[0], x[1], x[2]); points.InsertNextPoint(y[0], y[1], y[2]); points.InsertNextPoint(z[0], z[1], z[2]); polydata.SetPoints(points); vtkVertexGlyphFilter vertexGlyphFilter = vtkVertexGlyphFilter.New(); #if VTK_MAJOR_VERSION_5 vertexGlyphFilter.AddInput(polydata); #else vertexGlyphFilter.AddInputData(polydata); #endif vertexGlyphFilter.Update(); polydata.ShallowCopy(vertexGlyphFilter.GetOutput()); } internal void Write(string filename) { vtkPolyData polydata = vtkPolyData.New(); CreatePolydata(ref polydata); vtkXMLPolyDataWriter writer = vtkXMLPolyDataWriter.New(); writer.SetFileName(filename); #if VTK_MAJOR_VERSION_5 writer.SetInputConnection(polydata.GetProducerPort()); #else writer.SetInputData(polydata); #endif writer.Write(); } } static void Main(string[] args) { float[] frame1origin = new float[] { 0, 0, 0 }; float[] frame1XDirection = new float[] { 1, 0, 0 }; float[] frame1YDirection = new float[] { 0, 1, 0 }; Console.WriteLine(frame1YDirection[0] + " " + frame1YDirection[1] + " " + frame1YDirection[2]); float[] frame1ZDirection = new float[] { 0, 0, 1 }; Frame frame1 = new Frame(frame1origin, frame1XDirection, frame1YDirection, frame1ZDirection); Console.WriteLine("\nWriting frame1.vtp..."); // adjust path frame1.Write(@"c:\vtk\vtkdata-5.8.0\Data\frame1.vtp"); float[] frame2origin = new float[] { 0, 0, 0 }; float[] frame2XDirection = new float[] { .707f, .707f, 0 }; float[] frame2YDirection = new float[] { -.707f, .707f, 0 }; float[] frame2ZDirection = new float[] { 0, 0, 1 }; Frame frame2 = new Frame(frame2origin, frame2XDirection, frame2YDirection, frame2ZDirection); Console.WriteLine("\nWriting frame2.vtp..."); // adjust path frame2.Write(@"c:\vtk\vtkdata-5.8.0\Data\frame2.vtp"); vtkTransform transform = vtkTransform.New(); AlignFrames(frame2, frame1, ref transform); // Brings frame2 to frame1 Console.WriteLine("\nWriting transformed.vtp..."); // adjust path frame2.ApplyTransform(ref transform, @"c:\vtk\vtkdata-5.8.0\Data\transformed.vtp"); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } static void AlignFrames(Frame sourceFrame, Frame targetFrame, ref vtkTransform transform) { // This function takes two frames and finds the matrix M between them. vtkLandmarkTransform landmarkTransform = vtkLandmarkTransform.New(); // Setup source points vtkPoints sourcePoints = vtkPoints.New(); sourcePoints.InsertNextPoint( sourceFrame.Origin[0], sourceFrame.Origin[1], sourceFrame.Origin[2]); float[] sourceX = new float[3]; float[] sourceY = new float[3]; float[] sourceZ = new float[3]; Add(sourceFrame.Origin, sourceFrame.XDirection, ref sourceX); Add(sourceFrame.Origin, sourceFrame.YDirection, ref sourceY); Add(sourceFrame.Origin, sourceFrame.ZDirection, ref sourceZ); sourcePoints.InsertNextPoint(sourceX[0], sourceX[1], sourceX[2]); sourcePoints.InsertNextPoint(sourceY[0], sourceY[1], sourceY[2]); sourcePoints.InsertNextPoint(sourceZ[0], sourceZ[1], sourceZ[2]); // Setup target points vtkPoints targetPoints = vtkPoints.New(); targetPoints.InsertNextPoint(targetFrame.Origin[0], targetFrame.Origin[1], targetFrame.Origin[2]); float[] targetX = new float[3]; float[] targetY = new float[3]; float[] targetZ = new float[3]; Add(targetFrame.Origin, targetFrame.XDirection, ref targetX); Add(targetFrame.Origin, targetFrame.YDirection, ref targetY); Add(targetFrame.Origin, targetFrame.ZDirection, ref targetZ); targetPoints.InsertNextPoint(targetX[0], targetX[1], targetX[2]); targetPoints.InsertNextPoint(targetY[0], targetY[1], targetY[2]); targetPoints.InsertNextPoint(targetZ[0], targetZ[1], targetZ[2]); landmarkTransform.SetSourceLandmarks(sourcePoints); landmarkTransform.SetTargetLandmarks(targetPoints); landmarkTransform.SetModeToRigidBody(); landmarkTransform.Update(); vtkMatrix4x4 M = landmarkTransform.GetMatrix(); transform.SetMatrix(M); } // helper function static void Add(float[] vec1, float[] vec2, ref float[] vec) { vec[0] = vec1[0] + vec2[0]; vec[1] = vec1[1] + vec2[1]; vec[2] = vec1[2] + vec2[2]; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Mail.Net.IO { #region usings using System; using System.Collections.Generic; using System.IO; #endregion /// <summary> /// This class implements base64 encoder/decoder. Defined in RFC 4648. /// </summary> public class Base64Stream : Stream, IDisposable { #region Members private static readonly short[] BASE64_DECODE_TABLE = new short[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0 - 9 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //10 - 19 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //20 - 29 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //30 - 39 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, //40 - 49 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, //50 - 59 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, //60 - 69 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, //70 - 79 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, //80 - 89 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, //90 - 99 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, //100 - 109 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, //110 - 119 49, 50, 51, -1, -1, -1, -1, -1 //120 - 127 }; private static readonly byte[] BASE64_ENCODE_TABLE = new[] { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; private readonly FileAccess m_AccessMode = FileAccess.ReadWrite; private readonly bool m_AddLineBreaks = true; private readonly bool m_IsOwner; private readonly Queue<byte> m_pDecodeReminder; private readonly byte[] m_pEncode3x8Block = new byte[3]; private readonly byte[] m_pEncodeBuffer = new byte[78]; private readonly Stream m_pStream; private int m_EncodeBufferOffset; private bool m_IsDisposed; private bool m_IsFinished; private int m_OffsetInEncode3x8Block; private static string[] padding_tails = new string[4] { "", "===", "==", "=" }; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanRead { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return true; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanSeek { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public override bool CanWrite { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } return false; } } /// <summary> /// Gets the length in bytes of the stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Length { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } } /// <summary> /// Gets or sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Position { get { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } set { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } throw new NotSupportedException(); } } #endregion private MemoryStream decodedDataStream = null; #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream which to encode/decode.</param> /// <param name="owner">Specifies if Base64Stream is owner of <b>stream</b>.</param> /// <param name="addLineBreaks">Specifies if encoder inserts CRLF after each 76 bytes.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> public Base64Stream(Stream stream, bool owner, bool addLineBreaks) : this(stream, owner, addLineBreaks, FileAccess.ReadWrite) {} /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream which to encode/decode.</param> /// <param name="owner">Specifies if Base64Stream is owner of <b>stream</b>.</param> /// <param name="addLineBreaks">Specifies if encoder inserts CRLF after each 76 bytes.</param> /// <param name="access">This stream access mode.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> public Base64Stream(Stream stream, bool owner, bool addLineBreaks, FileAccess access) { if (stream == null) { throw new ArgumentNullException("stream"); } // Parse all stream if (stream.Length > 0) { stream.Seek(0, SeekOrigin.Begin); decodedDataStream = new MemoryStream(); using (StreamReader reader = new StreamReader(stream)) { List<string> lines = new List<string>(); while (!reader.EndOfStream) { string next_line = reader.ReadLine(); lines.Add(next_line); int exc_bytes = next_line.Length & 0x03; // If the line length is not multiple of 4 then we need to process possible wrong message content (it really happens) if (exc_bytes != 0) { // Process even part of the line first string even_part = next_line.Substring(0, next_line.Length - exc_bytes); byte[] decoded = Convert.FromBase64String(even_part); decodedDataStream.Write(decoded, 0, decoded.Length); // then try to recover the odd part by appending "=" to it try { string rest = next_line.Substring(next_line.Length - exc_bytes, exc_bytes); byte[] rest_decoded = Convert.FromBase64String(rest + padding_tails[exc_bytes]); decodedDataStream.Write(decoded, 0, decoded.Length); } catch (System.FormatException) {} } else { byte[] decoded = Convert.FromBase64String(next_line); decodedDataStream.Write(decoded, 0, decoded.Length); } } decodedDataStream.Seek(0, SeekOrigin.Begin); } } m_pStream = stream; m_IsOwner = owner; m_AddLineBreaks = addLineBreaks; m_AccessMode = access; m_pDecodeReminder = new Queue<byte>(); } #endregion #region Methods /// <summary> /// Celans up any resources being used. /// </summary> public new void Dispose() { if (m_IsDisposed) { return; } try { Finish(); } catch {} m_IsDisposed = true; if (m_IsOwner) { m_pStream.Close(); } if (decodedDataStream!=null) { decodedDataStream.Close(); decodedDataStream.Dispose(); } } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public override void Flush() { if (m_IsDisposed) { throw new ObjectDisposedException("Base64Stream"); } } /// <summary> /// Sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override long Seek(long offset, SeekOrigin origin) { if (m_IsDisposed) { throw new ObjectDisposedException("Base64Stream"); } throw new NotSupportedException(); } /// <summary> /// Sets the length of the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="Seek">Is raised when this method is accessed.</exception> public override void SetLength(long value) { if (m_IsDisposed) { throw new ObjectDisposedException("Base64Stream"); } throw new NotSupportedException(); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="NotSupportedException">Is raised when reading not supported.</exception> public override int Read(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException("Base64Stream"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if ((m_AccessMode & FileAccess.Read) == 0) { throw new NotSupportedException(); } if (decodedDataStream!=null) { //read from it return decodedDataStream.Read(buffer, offset, count); } /* RFC 4648. Base64 is processed from left to right by 4 6-bit byte block, 4 6-bit byte block are converted to 3 8-bit bytes. If base64 4 byte block doesn't have 3 8-bit bytes, missing bytes are marked with =. Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y NOTE: 4 base64 6-bit bytes = 3 8-bit bytes // | 6-bit | 6-bit | 6-bit | 6-bit | // | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | // | 8-bit | 8-bit | 8-bit | */ int storedInBuffer = 0; // If we have decoded-buffered bytes, use them first. while (m_pDecodeReminder.Count > 0) { buffer[offset++] = m_pDecodeReminder.Dequeue(); storedInBuffer++; count--; // We filled whole "buffer", no more room. if (count == 0) { return storedInBuffer; } } // 1) Calculate as much we can decode to "buffer". !!! We need to read as 4x7-bit blocks. int rawBytesToRead = (int) Math.Ceiling(count/3.0)*4; byte[] readBuffer = new byte[rawBytesToRead]; short[] decodeBlock = new short[4]; byte[] decodedBlock = new byte[3]; int decodeBlockOffset = 0; int paddedCount = 0; // Decode while we have room in "buffer". while (storedInBuffer < count) { int readedCount = m_pStream.Read(readBuffer, 0, rawBytesToRead); // We reached end of stream, no more data. if (readedCount == 0) { // We have last block without padding 1 char. if (decodeBlockOffset == 3) { buffer[offset + storedInBuffer++] = (byte) (decodeBlock[0] << 2 | decodeBlock[1] >> 4); // See if "buffer" can accomodate 2 byte. if (storedInBuffer < count) { buffer[offset + storedInBuffer++] = (byte) ((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2); } else { m_pDecodeReminder.Enqueue( (byte) ((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2)); } } // We have last block without padding 2 chars. else if (decodeBlockOffset == 2) { buffer[offset + storedInBuffer++] = (byte) (decodeBlock[0] << 2 | decodeBlock[1] >> 4); } // We have invalid base64 data. else if (decodeBlockOffset == 1) { throw new InvalidDataException("Incomplete base64 data.."); } return storedInBuffer; } // Process readed bytes. for (int i = 0; i < readedCount; i++) { byte b = readBuffer[i]; // If padding char. if (b == '=') { decodeBlock[decodeBlockOffset++] = (byte) '='; paddedCount++; rawBytesToRead--; } // If base64 char. else if (BASE64_DECODE_TABLE[b] != -1) { decodeBlock[decodeBlockOffset++] = BASE64_DECODE_TABLE[b]; rawBytesToRead--; } // Non-base64 char, skip it. else {} // Decode block full, decode bytes. if (decodeBlockOffset == 4) { // Decode 3x8-bit block. decodedBlock[0] = (byte) (decodeBlock[0] << 2 | decodeBlock[1] >> 4); decodedBlock[1] = (byte) ((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2); decodedBlock[2] = (byte) ((decodeBlock[2] & 0x3) << 6 | decodeBlock[3] >> 0); // Invalid base64 data. Base64 final quantum may have max 2 padding chars. if (paddedCount > 2) { throw new InvalidDataException( "Invalid base64 data, more than 2 padding chars(=)."); } for (int n = 0; n < (3 - paddedCount); n++) { // We have room in "buffer", store byte there. if (storedInBuffer < count) { buffer[offset + storedInBuffer++] = decodedBlock[n]; } //No room in "buffer", store reminder. else { m_pDecodeReminder.Enqueue(decodedBlock[n]); } } decodeBlockOffset = 0; paddedCount = 0; } } } return storedInBuffer; } /// <summary> /// Encodes a sequence of bytes, writes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this.Finish has been called and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="NotSupportedException">Is raised when reading not supported.</exception> public override void Write(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsFinished) { throw new InvalidOperationException("Stream is marked as finished by calling Finish method."); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentException("Invalid argument 'offset' value."); } if (count < 0 || count > (buffer.Length - offset)) { throw new ArgumentException("Invalid argument 'count' value."); } if ((m_AccessMode & FileAccess.Write) == 0) { throw new NotSupportedException(); } /* RFC 4648. Base64 is processed from left to right by 4 6-bit byte block, 4 6-bit byte block are converted to 3 8-bit bytes. If base64 4 byte block doesn't have 3 8-bit bytes, missing bytes are marked with =. Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y NOTE: 4 base64 6-bit bytes = 3 8-bit bytes // | 6-bit | 6-bit | 6-bit | 6-bit | // | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | // | 8-bit | 8-bit | 8-bit | */ int encodeBufSize = m_pEncodeBuffer.Length; // Process all bytes. for (int i = 0; i < count; i++) { m_pEncode3x8Block[m_OffsetInEncode3x8Block++] = buffer[offset + i]; // 3x8-bit encode block is full, encode it. if (m_OffsetInEncode3x8Block == 3) { m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[m_pEncode3x8Block[0] >> 2]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4 | m_pEncode3x8Block[1] >> 4]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[1] & 0x0F) << 2 | m_pEncode3x8Block[2] >> 6]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[2] & 0x3F)]; // Encode buffer is full, write buffer to underlaying stream (we reserved 2 bytes for CRLF). if (m_EncodeBufferOffset >= (encodeBufSize - 2)) { if (m_AddLineBreaks) { m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '\r'; m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '\n'; } m_pStream.Write(m_pEncodeBuffer, 0, m_EncodeBufferOffset); m_EncodeBufferOffset = 0; } m_OffsetInEncode3x8Block = 0; } } } /// <summary> /// Completes encoding. Call this method if all data has written and no more data. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public void Finish() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsFinished) { return; } m_IsFinished = true; // PADD left-over, if any. Write encode buffer to underlaying stream. if (m_OffsetInEncode3x8Block == 1) { m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[m_pEncode3x8Block[0] >> 2]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4]; m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '='; m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '='; } else if (m_OffsetInEncode3x8Block == 2) { m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[m_pEncode3x8Block[0] >> 2]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4 | m_pEncode3x8Block[1] >> 4]; m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[1] & 0x0F) << 2]; m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte) '='; } if (m_EncodeBufferOffset > 0) { m_pStream.Write(m_pEncodeBuffer, 0, m_EncodeBufferOffset); } } #endregion } }
using System.Reflection; namespace Tmds.DBus.Protocol; public ref partial struct MessageWriter { public void WriteStruct<T1>(ValueTuple<T1> value) where T1 : notnull { WriteStructureStart(); Write<T1>(value.Item1); } sealed class ValueTupleTypeWriter<T1> : ITypeWriter<ValueTuple<T1>> where T1 : notnull { public void Write(ref MessageWriter writer, ValueTuple<T1> value) { writer.WriteStruct<T1>(new ValueTuple<T1>(value.Item1)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1>(ref writer); Write(ref writer, (ValueTuple<T1>)value); } } sealed class TupleTypeWriter<T1> : ITypeWriter<Tuple<T1>> where T1 : notnull { public void Write(ref MessageWriter writer, Tuple<T1> value) { writer.WriteStruct<T1>(new ValueTuple<T1>(value.Item1)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1>(ref writer); Write(ref writer, (Tuple<T1>)value); } } public static void AddValueTupleTypeWriter<T1>() where T1 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1>()); } } } public static void AddTupleTypeWriter<T1>() where T1 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1) { Type writerType = typeof(ValueTupleTypeWriter<>).MakeGenericType(new[] { type1 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1) { Type writerType = typeof(TupleTypeWriter<>).MakeGenericType(new[] { type1 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1>>()); } public void WriteStruct<T1, T2>((T1, T2) value) where T1 : notnull where T2 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); } sealed class ValueTupleTypeWriter<T1, T2> : ITypeWriter<ValueTuple<T1, T2>> where T1 : notnull where T2 : notnull { public void Write(ref MessageWriter writer, ValueTuple<T1, T2> value) { writer.WriteStruct<T1, T2>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2>(ref writer); Write(ref writer, (ValueTuple<T1, T2>)value); } } sealed class TupleTypeWriter<T1, T2> : ITypeWriter<Tuple<T1, T2>> where T1 : notnull where T2 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2> value) { writer.WriteStruct<T1, T2>((value.Item1, value.Item2)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2>(ref writer); Write(ref writer, (Tuple<T1, T2>)value); } } public static void AddValueTupleTypeWriter<T1, T2>() where T1 : notnull where T2 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2>()); } } } public static void AddTupleTypeWriter<T1, T2>() where T1 : notnull where T2 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2) { Type writerType = typeof(ValueTupleTypeWriter<,>).MakeGenericType(new[] { type1, type2 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2) { Type writerType = typeof(TupleTypeWriter<,>).MakeGenericType(new[] { type1, type2 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2>>()); } public void WriteStruct<T1, T2, T3>((T1, T2, T3) value) where T1 : notnull where T2 : notnull where T3 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); Write<T3>(value.Item3); } sealed class ValueTupleTypeWriter<T1, T2, T3> : ITypeWriter<ValueTuple<T1, T2, T3>> where T1 : notnull where T2 : notnull where T3 : notnull { public void Write(ref MessageWriter writer, ValueTuple<T1, T2, T3> value) { writer.WriteStruct<T1, T2, T3>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3>(ref writer); Write(ref writer, (ValueTuple<T1, T2, T3>)value); } } sealed class TupleTypeWriter<T1, T2, T3> : ITypeWriter<Tuple<T1, T2, T3>> where T1 : notnull where T2 : notnull where T3 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2, T3> value) { writer.WriteStruct<T1, T2, T3>((value.Item1, value.Item2, value.Item3)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3>(ref writer); Write(ref writer, (Tuple<T1, T2, T3>)value); } } public static void AddValueTupleTypeWriter<T1, T2, T3>() where T1 : notnull where T2 : notnull where T3 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2, T3>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2, T3>()); } } } public static void AddTupleTypeWriter<T1, T2, T3>() where T1 : notnull where T2 : notnull where T3 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2, T3>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2, T3>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2, Type type3) { Type writerType = typeof(ValueTupleTypeWriter<,,>).MakeGenericType(new[] { type1, type2, type3 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2, Type type3) { Type writerType = typeof(TupleTypeWriter<,,>).MakeGenericType(new[] { type1, type2, type3 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2, T3>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2, T3>>()); } public void WriteStruct<T1, T2, T3, T4>((T1, T2, T3, T4) value) where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); Write<T3>(value.Item3); Write<T4>(value.Item4); } sealed class ValueTupleTypeWriter<T1, T2, T3, T4> : ITypeWriter<ValueTuple<T1, T2, T3, T4>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { public void Write(ref MessageWriter writer, ValueTuple<T1, T2, T3, T4> value) { writer.WriteStruct<T1, T2, T3, T4>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4>(ref writer); Write(ref writer, (ValueTuple<T1, T2, T3, T4>)value); } } sealed class TupleTypeWriter<T1, T2, T3, T4> : ITypeWriter<Tuple<T1, T2, T3, T4>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2, T3, T4> value) { writer.WriteStruct<T1, T2, T3, T4>((value.Item1, value.Item2, value.Item3, value.Item4)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4>(ref writer); Write(ref writer, (Tuple<T1, T2, T3, T4>)value); } } public static void AddValueTupleTypeWriter<T1, T2, T3, T4>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2, T3, T4>()); } } } public static void AddTupleTypeWriter<T1, T2, T3, T4>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2, T3, T4>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2, T3, T4>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2, Type type3, Type type4) { Type writerType = typeof(ValueTupleTypeWriter<,,,>).MakeGenericType(new[] { type1, type2, type3, type4 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2, Type type3, Type type4) { Type writerType = typeof(TupleTypeWriter<,,,>).MakeGenericType(new[] { type1, type2, type3, type4 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2, T3, T4>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2, T3, T4>>()); } public void WriteStruct<T1, T2, T3, T4, T5>((T1, T2, T3, T4, T5) value) where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); Write<T3>(value.Item3); Write<T4>(value.Item4); Write<T5>(value.Item5); } sealed class ValueTupleTypeWriter<T1, T2, T3, T4, T5> : ITypeWriter<ValueTuple<T1, T2, T3, T4, T5>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { public void Write(ref MessageWriter writer, ValueTuple<T1, T2, T3, T4, T5> value) { writer.WriteStruct<T1, T2, T3, T4, T5>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5>(ref writer); Write(ref writer, (ValueTuple<T1, T2, T3, T4, T5>)value); } } sealed class TupleTypeWriter<T1, T2, T3, T4, T5> : ITypeWriter<Tuple<T1, T2, T3, T4, T5>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2, T3, T4, T5> value) { writer.WriteStruct<T1, T2, T3, T4, T5>((value.Item1, value.Item2, value.Item3, value.Item4, value.Item5)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5>(ref writer); Write(ref writer, (Tuple<T1, T2, T3, T4, T5>)value); } } public static void AddValueTupleTypeWriter<T1, T2, T3, T4, T5>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2, T3, T4, T5>()); } } } public static void AddTupleTypeWriter<T1, T2, T3, T4, T5>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2, T3, T4, T5>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5) { Type writerType = typeof(ValueTupleTypeWriter<,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5) { Type writerType = typeof(TupleTypeWriter<,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2, T3, T4, T5>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2, T3, T4, T5>>()); } public void WriteStruct<T1, T2, T3, T4, T5, T6>((T1, T2, T3, T4, T5, T6) value) where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); Write<T3>(value.Item3); Write<T4>(value.Item4); Write<T5>(value.Item5); Write<T6>(value.Item6); } sealed class ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6> : ITypeWriter<ValueTuple<T1, T2, T3, T4, T5, T6>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { public void Write(ref MessageWriter writer, ValueTuple<T1, T2, T3, T4, T5, T6> value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6>(ref writer); Write(ref writer, (ValueTuple<T1, T2, T3, T4, T5, T6>)value); } } sealed class TupleTypeWriter<T1, T2, T3, T4, T5, T6> : ITypeWriter<Tuple<T1, T2, T3, T4, T5, T6>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2, T3, T4, T5, T6> value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6>((value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6>(ref writer); Write(ref writer, (Tuple<T1, T2, T3, T4, T5, T6>)value); } } public static void AddValueTupleTypeWriter<T1, T2, T3, T4, T5, T6>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6>()); } } } public static void AddTupleTypeWriter<T1, T2, T3, T4, T5, T6>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2, T3, T4, T5, T6>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6) { Type writerType = typeof(ValueTupleTypeWriter<,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6) { Type writerType = typeof(TupleTypeWriter<,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2, T3, T4, T5, T6>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2, T3, T4, T5, T6>>()); } public void WriteStruct<T1, T2, T3, T4, T5, T6, T7>((T1, T2, T3, T4, T5, T6, T7) value) where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); Write<T3>(value.Item3); Write<T4>(value.Item4); Write<T5>(value.Item5); Write<T6>(value.Item6); Write<T7>(value.Item7); } sealed class ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7> : ITypeWriter<ValueTuple<T1, T2, T3, T4, T5, T6, T7>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { public void Write(ref MessageWriter writer, ValueTuple<T1, T2, T3, T4, T5, T6, T7> value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6, T7>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6, T7>(ref writer); Write(ref writer, (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)value); } } sealed class TupleTypeWriter<T1, T2, T3, T4, T5, T6, T7> : ITypeWriter<Tuple<T1, T2, T3, T4, T5, T6, T7>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2, T3, T4, T5, T6, T7> value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6, T7>((value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6, T7>(ref writer); Write(ref writer, (Tuple<T1, T2, T3, T4, T5, T6, T7>)value); } } public static void AddValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6, T7>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7>()); } } } public static void AddTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6, T7>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2, T3, T4, T5, T6, T7>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7) { Type writerType = typeof(ValueTupleTypeWriter<,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7) { Type writerType = typeof(TupleTypeWriter<,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2, T3, T4, T5, T6, T7>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>()); } public void WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8>((T1, T2, T3, T4, T5, T6, T7, T8) value) where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); Write<T3>(value.Item3); Write<T4>(value.Item4); Write<T5>(value.Item5); Write<T6>(value.Item6); Write<T7>(value.Item7); Write<T8>(value.Rest.Item1); } sealed class ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8> : ITypeWriter<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { public void Write(ref MessageWriter writer, (T1, T2, T3, T4, T5, T6, T7, T8) value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8>(ref writer); Write(ref writer, (ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>)value); } } sealed class TupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8> : ITypeWriter<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8>((value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, value.Rest.Item1)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8>(ref writer); Write(ref writer, (Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>)value); } } public static void AddValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8>()); } } } public static void AddTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8) { Type writerType = typeof(ValueTupleTypeWriter<,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8) { Type writerType = typeof(TupleTypeWriter<,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>>()); } public void WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9>((T1, T2, T3, T4, T5, T6, T7, T8, T9) value) where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); Write<T3>(value.Item3); Write<T4>(value.Item4); Write<T5>(value.Item5); Write<T6>(value.Item6); Write<T7>(value.Item7); Write<T8>(value.Rest.Item1); Write<T9>(value.Rest.Item2); } sealed class ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9> : ITypeWriter<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { public void Write(ref MessageWriter writer, (T1, T2, T3, T4, T5, T6, T7, T8, T9) value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8, T9>(ref writer); Write(ref writer, (ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>)value); } } sealed class TupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9> : ITypeWriter<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9>((value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, value.Rest.Item1, value.Rest.Item2)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8, T9>(ref writer); Write(ref writer, (Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>)value); } } public static void AddValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9>()); } } } public static void AddTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8, Type type9) { Type writerType = typeof(ValueTupleTypeWriter<,,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8, Type type9) { Type writerType = typeof(TupleTypeWriter<,,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8, type9 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8, T9>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>>()); } public void WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>((T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) value) where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { WriteStructureStart(); Write<T1>(value.Item1); Write<T2>(value.Item2); Write<T3>(value.Item3); Write<T4>(value.Item4); Write<T5>(value.Item5); Write<T6>(value.Item6); Write<T7>(value.Item7); Write<T8>(value.Rest.Item1); Write<T9>(value.Rest.Item2); Write<T10>(value.Rest.Item3); } sealed class ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : ITypeWriter<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { public void Write(ref MessageWriter writer, (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(value); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(ref writer); Write(ref writer, (ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>)value); } } sealed class TupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : ITypeWriter<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { public void Write(ref MessageWriter writer, Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> value) { writer.WriteStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>((value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, value.Rest.Item1, value.Rest.Item2, value.Rest.Item3)); } public void WriteVariant(ref MessageWriter writer, object value) { WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(ref writer); Write(ref writer, (Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>)value); } } public static void AddValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { lock (_typeWriters) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new ValueTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>()); } } } public static void AddTupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { lock (_typeWriters) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>); if (!_typeWriters.ContainsKey(keyType)) { _typeWriters.Add(keyType, new TupleTypeWriter<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>()); } } } private ITypeWriter CreateValueTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8, Type type9, Type type10) { Type writerType = typeof(ValueTupleTypeWriter<,,,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8, type10 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private ITypeWriter CreateTupleTypeWriter(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8, Type type9, Type type10) { Type writerType = typeof(TupleTypeWriter<,,,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8, type9, type10 }); return (ITypeWriter)Activator.CreateInstance(writerType)!; } private static void WriteStructSignature<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(ref MessageWriter writer) { writer.WriteSignature(TypeModel.GetSignature<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>>()); } }
// 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.Text; using System.Collections.Generic; public class BringUpTest { const int Pass = 100; const int Fail = -1; public static int Main() { if (TestInterfaceCache() == Fail) return Fail; if (TestMultipleInterfaces() == Fail) return Fail; if (TestArrayInterfaces() == Fail) return Fail; if (TestVariantInterfaces() == Fail) return Fail; return Pass; } #region Interface Dispatch Cache Test private static int TestInterfaceCache() { MyInterface[] itfs = new MyInterface[50]; itfs[0] = new Foo0(); itfs[1] = new Foo1(); itfs[2] = new Foo2(); itfs[3] = new Foo3(); itfs[4] = new Foo4(); itfs[5] = new Foo5(); itfs[6] = new Foo6(); itfs[7] = new Foo7(); itfs[8] = new Foo8(); itfs[9] = new Foo9(); itfs[10] = new Foo10(); itfs[11] = new Foo11(); itfs[12] = new Foo12(); itfs[13] = new Foo13(); itfs[14] = new Foo14(); itfs[15] = new Foo15(); itfs[16] = new Foo16(); itfs[17] = new Foo17(); itfs[18] = new Foo18(); itfs[19] = new Foo19(); itfs[20] = new Foo20(); itfs[21] = new Foo21(); itfs[22] = new Foo22(); itfs[23] = new Foo23(); itfs[24] = new Foo24(); itfs[25] = new Foo25(); itfs[26] = new Foo26(); itfs[27] = new Foo27(); itfs[28] = new Foo28(); itfs[29] = new Foo29(); itfs[30] = new Foo30(); itfs[31] = new Foo31(); itfs[32] = new Foo32(); itfs[33] = new Foo33(); itfs[34] = new Foo34(); itfs[35] = new Foo35(); itfs[36] = new Foo36(); itfs[37] = new Foo37(); itfs[38] = new Foo38(); itfs[39] = new Foo39(); itfs[40] = new Foo40(); itfs[41] = new Foo41(); itfs[42] = new Foo42(); itfs[43] = new Foo43(); itfs[44] = new Foo44(); itfs[45] = new Foo45(); itfs[46] = new Foo46(); itfs[47] = new Foo47(); itfs[48] = new Foo48(); itfs[49] = new Foo49(); StringBuilder sb = new StringBuilder(); int counter = 0; for (int i = 0; i < 50; i++) { sb.Append(itfs[i].GetAString()); counter += itfs[i].GetAnInt(); } string expected = "Foo0Foo1Foo2Foo3Foo4Foo5Foo6Foo7Foo8Foo9Foo10Foo11Foo12Foo13Foo14Foo15Foo16Foo17Foo18Foo19Foo20Foo21Foo22Foo23Foo24Foo25Foo26Foo27Foo28Foo29Foo30Foo31Foo32Foo33Foo34Foo35Foo36Foo37Foo38Foo39Foo40Foo41Foo42Foo43Foo44Foo45Foo46Foo47Foo48Foo49"; if (!expected.Equals(sb.ToString())) { Console.WriteLine("Concatenating strings from interface calls failed."); Console.Write("Expected: "); Console.WriteLine(expected); Console.Write(" Actual: "); Console.WriteLine(sb.ToString()); return Fail; } if (counter != 1225) { Console.WriteLine("Summing ints from interface calls failed."); Console.WriteLine("Expected: 1225"); Console.Write("Actual: "); Console.WriteLine(counter); return Fail; } return 100; } interface MyInterface { int GetAnInt(); string GetAString(); } class Foo0 : MyInterface { public int GetAnInt() { return 0; } public string GetAString() { return "Foo0"; } } class Foo1 : MyInterface { public int GetAnInt() { return 1; } public string GetAString() { return "Foo1"; } } class Foo2 : MyInterface { public int GetAnInt() { return 2; } public string GetAString() { return "Foo2"; } } class Foo3 : MyInterface { public int GetAnInt() { return 3; } public string GetAString() { return "Foo3"; } } class Foo4 : MyInterface { public int GetAnInt() { return 4; } public string GetAString() { return "Foo4"; } } class Foo5 : MyInterface { public int GetAnInt() { return 5; } public string GetAString() { return "Foo5"; } } class Foo6 : MyInterface { public int GetAnInt() { return 6; } public string GetAString() { return "Foo6"; } } class Foo7 : MyInterface { public int GetAnInt() { return 7; } public string GetAString() { return "Foo7"; } } class Foo8 : MyInterface { public int GetAnInt() { return 8; } public string GetAString() { return "Foo8"; } } class Foo9 : MyInterface { public int GetAnInt() { return 9; } public string GetAString() { return "Foo9"; } } class Foo10 : MyInterface { public int GetAnInt() { return 10; } public string GetAString() { return "Foo10"; } } class Foo11 : MyInterface { public int GetAnInt() { return 11; } public string GetAString() { return "Foo11"; } } class Foo12 : MyInterface { public int GetAnInt() { return 12; } public string GetAString() { return "Foo12"; } } class Foo13 : MyInterface { public int GetAnInt() { return 13; } public string GetAString() { return "Foo13"; } } class Foo14 : MyInterface { public int GetAnInt() { return 14; } public string GetAString() { return "Foo14"; } } class Foo15 : MyInterface { public int GetAnInt() { return 15; } public string GetAString() { return "Foo15"; } } class Foo16 : MyInterface { public int GetAnInt() { return 16; } public string GetAString() { return "Foo16"; } } class Foo17 : MyInterface { public int GetAnInt() { return 17; } public string GetAString() { return "Foo17"; } } class Foo18 : MyInterface { public int GetAnInt() { return 18; } public string GetAString() { return "Foo18"; } } class Foo19 : MyInterface { public int GetAnInt() { return 19; } public string GetAString() { return "Foo19"; } } class Foo20 : MyInterface { public int GetAnInt() { return 20; } public string GetAString() { return "Foo20"; } } class Foo21 : MyInterface { public int GetAnInt() { return 21; } public string GetAString() { return "Foo21"; } } class Foo22 : MyInterface { public int GetAnInt() { return 22; } public string GetAString() { return "Foo22"; } } class Foo23 : MyInterface { public int GetAnInt() { return 23; } public string GetAString() { return "Foo23"; } } class Foo24 : MyInterface { public int GetAnInt() { return 24; } public string GetAString() { return "Foo24"; } } class Foo25 : MyInterface { public int GetAnInt() { return 25; } public string GetAString() { return "Foo25"; } } class Foo26 : MyInterface { public int GetAnInt() { return 26; } public string GetAString() { return "Foo26"; } } class Foo27 : MyInterface { public int GetAnInt() { return 27; } public string GetAString() { return "Foo27"; } } class Foo28 : MyInterface { public int GetAnInt() { return 28; } public string GetAString() { return "Foo28"; } } class Foo29 : MyInterface { public int GetAnInt() { return 29; } public string GetAString() { return "Foo29"; } } class Foo30 : MyInterface { public int GetAnInt() { return 30; } public string GetAString() { return "Foo30"; } } class Foo31 : MyInterface { public int GetAnInt() { return 31; } public string GetAString() { return "Foo31"; } } class Foo32 : MyInterface { public int GetAnInt() { return 32; } public string GetAString() { return "Foo32"; } } class Foo33 : MyInterface { public int GetAnInt() { return 33; } public string GetAString() { return "Foo33"; } } class Foo34 : MyInterface { public int GetAnInt() { return 34; } public string GetAString() { return "Foo34"; } } class Foo35 : MyInterface { public int GetAnInt() { return 35; } public string GetAString() { return "Foo35"; } } class Foo36 : MyInterface { public int GetAnInt() { return 36; } public string GetAString() { return "Foo36"; } } class Foo37 : MyInterface { public int GetAnInt() { return 37; } public string GetAString() { return "Foo37"; } } class Foo38 : MyInterface { public int GetAnInt() { return 38; } public string GetAString() { return "Foo38"; } } class Foo39 : MyInterface { public int GetAnInt() { return 39; } public string GetAString() { return "Foo39"; } } class Foo40 : MyInterface { public int GetAnInt() { return 40; } public string GetAString() { return "Foo40"; } } class Foo41 : MyInterface { public int GetAnInt() { return 41; } public string GetAString() { return "Foo41"; } } class Foo42 : MyInterface { public int GetAnInt() { return 42; } public string GetAString() { return "Foo42"; } } class Foo43 : MyInterface { public int GetAnInt() { return 43; } public string GetAString() { return "Foo43"; } } class Foo44 : MyInterface { public int GetAnInt() { return 44; } public string GetAString() { return "Foo44"; } } class Foo45 : MyInterface { public int GetAnInt() { return 45; } public string GetAString() { return "Foo45"; } } class Foo46 : MyInterface { public int GetAnInt() { return 46; } public string GetAString() { return "Foo46"; } } class Foo47 : MyInterface { public int GetAnInt() { return 47; } public string GetAString() { return "Foo47"; } } class Foo48 : MyInterface { public int GetAnInt() { return 48; } public string GetAString() { return "Foo48"; } } class Foo49 : MyInterface { public int GetAnInt() { return 49; } public string GetAString() { return "Foo49"; } } #endregion #region Implicit Interface Test private static int TestMultipleInterfaces() { TestClass<int> testInt = new TestClass<int>(5); MyInterface myInterface = testInt as MyInterface; if (!myInterface.GetAString().Equals("TestClass")) { Console.Write("On type TestClass, MyInterface.GetAString() returned "); Console.Write(myInterface.GetAString()); Console.WriteLine(" Expected: TestClass"); return Fail; } if (myInterface.GetAnInt() != 1) { Console.Write("On type TestClass, MyInterface.GetAnInt() returned "); Console.Write(myInterface.GetAnInt()); Console.WriteLine(" Expected: 1"); return Fail; } Interface<int> itf = testInt as Interface<int>; if (itf.GetT() != 5) { Console.Write("On type TestClass, Interface<int>::GetT() returned "); Console.Write(itf.GetT()); Console.WriteLine(" Expected: 5"); return Fail; } return Pass; } interface Interface<T> { T GetT(); } class TestClass<T> : MyInterface, Interface<T> { T _t; public TestClass(T t) { _t = t; } public T GetT() { return _t; } public int GetAnInt() { return 1; } public string GetAString() { return "TestClass"; } } #endregion #region Array Interfaces Test private static int TestArrayInterfaces() { { object stringArray = new string[] { "A", "B", "C", "D" }; Console.WriteLine("Testing IEnumerable<T> on array..."); string result = String.Empty; foreach (var s in (System.Collections.Generic.IEnumerable<string>)stringArray) result += s; if (result != "ABCD") { Console.WriteLine("Failed."); return Fail; } } { object stringArray = new string[] { "A", "B", "C", "D" }; Console.WriteLine("Testing IEnumerable on array..."); string result = String.Empty; foreach (var s in (System.Collections.IEnumerable)stringArray) result += s; if (result != "ABCD") { Console.WriteLine("Failed."); return Fail; } } { object intArray = new int[5, 5]; Console.WriteLine("Testing IList on MDArray..."); if (((System.Collections.IList)intArray).Count != 25) { Console.WriteLine("Failed."); return Fail; } } return Pass; } #endregion #region Variant interface tests interface IContravariantInterface<in T> { string DoContravariant(T value); } interface ICovariantInterface<out T> { T DoCovariant(object value); } class TypeWithVariantInterfaces<T> : IContravariantInterface<T>, ICovariantInterface<T> { public string DoContravariant(T value) { return value.ToString(); } public T DoCovariant(object value) { return value is T ? (T)value : default(T); } } static IContravariantInterface<string> s_contravariantObject = new TypeWithVariantInterfaces<object>(); static ICovariantInterface<object> s_covariantObject = new TypeWithVariantInterfaces<string>(); static IEnumerable<int> s_arrayCovariantObject = (IEnumerable<int>)(object)new uint[] { 5, 10, 15 }; private static int TestVariantInterfaces() { if (s_contravariantObject.DoContravariant("Hello") != "Hello") return Fail; if (s_covariantObject.DoCovariant("World") as string != "World") return Fail; int sum = 0; foreach (var e in s_arrayCovariantObject) sum += e; if (sum != 30) return Fail; return Pass; } #endregion }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Boolean ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Diagnostics.Contracts; // The Boolean class provides the // object representation of the boolean primitive type. [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public struct Boolean : IComparable, IConvertible #if GENERICS_WORK , IComparable<Boolean>, IEquatable<Boolean> #endif { // // Member Variables // private bool m_value; // The true value. // internal const int True = 1; // The false value. // internal const int False = 0; // // Internal Constants are real consts for performance. // // The internal string representation of true. // internal const String TrueLiteral = "True"; // The internal string representation of false. // internal const String FalseLiteral = "False"; // // Public Constants // // The public string representation of true. // public static readonly String TrueString = TrueLiteral; // The public string representation of false. // public static readonly String FalseString = FalseLiteral; // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return (m_value)?True:False; } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override String ToString() { if (false == m_value) { return FalseLiteral; } return TrueLiteral; } public String ToString(IFormatProvider provider) { if (false == m_value) { return FalseLiteral; } return TrueLiteral; } // Determines whether two Boolean objects are equal. public override bool Equals (Object obj) { //If it's not a boolean, we're definitely not equal if (!(obj is Boolean)) { return false; } return (m_value==((Boolean)obj).m_value); } [System.Runtime.Versioning.NonVersionable] public bool Equals(Boolean obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(Object obj) { if (obj==null) { return 1; } if (!(obj is Boolean)) { throw new ArgumentException (Environment.GetResourceString("Arg_MustBeBoolean")); } if (m_value==((Boolean)obj).m_value) { return 0; } else if (m_value==false) { return -1; } return 1; } public int CompareTo(Boolean value) { if (m_value==value) { return 0; } else if (m_value==false) { return -1; } return 1; } // // Static Methods // // Determines whether a String represents true or false. // public static Boolean Parse (String value) { if (value==null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); Boolean result = false; if (!TryParse(value, out result)) { throw new FormatException(Environment.GetResourceString("Format_BadBoolean")); } else { return result; } } // Determines whether a String represents true or false. // public static Boolean TryParse (String value, out Boolean result) { result = false; if (value==null) { return false; } // For perf reasons, let's first see if they're equal, then do the // trim to get rid of white space, and check again. if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) { result = false; return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) { result = false; return true; } return false; } private static String TrimWhiteSpaceAndNull(String value) { int start = 0; int end = value.Length-1; char nullChar = (char) 0x0000; while (start < value.Length) { if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } while (end >= start) { if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Substring(start, end - start + 1); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Boolean; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return m_value; } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "Char")); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Sheet.cs // using System; using System.Html; namespace Spreadsheet { public class Sheet { private readonly TableElement _table; // Table element that will contain the spreadsheet /// <summary> /// Spreadsheet Constructor /// </summary> public Sheet() { // Create a Table Element in memory _table = (TableElement)Document.CreateElement("table"); // Render Column Headers RenderColumnHeaders(); // Render Row Headers RenderRows(25); } /// <summary> /// Create rows in the spreadsheet /// </summary> /// <param name="rowCount">Number of rows to create</param> private void RenderRows(int rowCount) { // We're iterating from row index 1 because we want the title of the rows // to be equal to the index. In addition, row 0 is the column header row for (int rowIndex = 1; rowIndex <= rowCount; rowIndex++) { // Create a new row in the table TableRowElement row = _table.InsertRow(rowIndex); // Create a row header cell and set its id and value to the row index TableCellElement cell = row.InsertCell(0); cell.ID = rowIndex.ToString(); cell.TextContent = rowIndex.ToString(); // Create cells for each column in the spreadsheet from A to Z for (int cellIndex = 65; cellIndex < 91; cellIndex++) { // Insert cells at the corresponding column index (starting from column 1) cell = row.InsertCell(cellIndex - 64); // Create a text input element inside the cell InputElement input = (InputElement)Document.CreateElement("input"); input.Type = "text"; // Set the ID of the element to the Column Letter and Row Number like A1, B1, etc. input.ID = string.FromCharCode(cellIndex) + rowIndex; // Add the input element as a child of the cell cell.AppendChild(input); // Create and attach spreadsheet events to this input element AttachEvents(input); } } } /// <summary> /// Create various events that tie the functionality of the spreadsheet /// </summary> /// <param name="input">Input element to attach events to</param> private void AttachEvents(InputElement input) { input.AddEventListener("blur", delegate(ElementEvent @event) { GetRowHeader(@event.SrcElement).ClassList.Remove("selected"); GetColumnHeader(@event.SrcElement).ClassList.Remove("selected"); ProcessCell((InputElement)@event.SrcElement); }, false); input.AddEventListener("focus", delegate(ElementEvent @event) { GetRowHeader(@event.SrcElement).ClassList.Add("selected"); GetColumnHeader(@event.SrcElement).ClassList.Add("selected"); object formula = @event.SrcElement.GetAttribute("data-formula"); if (formula != null && formula.ToString().Length > 1) { input.Value = formula.ToString(); } }, false); input.AddEventListener("keydown", delegate(ElementEvent @event) { if (@event.KeyCode == 27) //Escape { input.Value = ""; input.Blur(); } else if (@event.KeyCode == 38) // up arrow { SetFocusFromCellTo(@event.SrcElement.ID, 0, -1); @event.PreventDefault(); } else if (@event.KeyCode == 40) // down arrow { SetFocusFromCellTo(@event.SrcElement.ID, 0, 1); @event.PreventDefault(); } else if (@event.KeyCode == 37) // left arrow { SetFocusFromCellTo(@event.SrcElement.ID, -1, 0); @event.PreventDefault(); } else if (@event.KeyCode == 39) // right arrow { SetFocusFromCellTo(@event.SrcElement.ID, 1, 0); @event.PreventDefault(); } }, true); input.AddEventListener("keypress", delegate(ElementEvent @event) { if (@event.KeyCode == 13) // Enter Key { input.Blur(); SetFocusFromCellTo(@event.SrcElement.ID, 0, 1); @event.PreventDefault(); } }, false); } /// <summary> /// This method allows us to specify a cell and set focus to one of its neighboring cells /// </summary> /// <param name="id">Text Input Element id for the source cell</param> /// <param name="horizontal">Direction to move horizontally. Negative value moves left.</param> /// <param name="vertical">Direction to move vertically. Negative value moves up.</param> private void SetFocusFromCellTo(string id, int horizontal, int vertical) { int row = int.Parse(id.Substring(1)); string column = id.Substring(0, 1); InputElement element = Document.GetElementById<InputElement>(string.Format("{0}{1}", string.FromCharCode(column.CharCodeAt(0) + horizontal), row + vertical)); if (element != null) { element.Focus(); } } private TableCellElement GetColumnHeader(Element element) { return Document.GetElementById<TableCellElement>(element.ID.Substring(0, 1)); } private TableRowElement GetRowHeader(Element element) { return Document.GetElementById<TableRowElement>(element.ID.Substring(1)); } private void RenderColumnHeaders() { // Create a row for the column headers TableRowElement header = _table.InsertRow(); header.ID = "headerRow"; // Create a cell for the first column where we will also add row headers TableCellElement blankCell = header.InsertCell(0); blankCell.ID = "blankCell"; // Create 26 Column Headers and name them with the letters of the English Alphabets // Iterating through the ASCII indexes for A-Z for (int i = 65; i < 91; i++) { // Create a cell element in the header row starting at index 1 TableCellElement cell = header.InsertCell(i - 64); // Set the cell id to the letter corresponding to the ASCII index cell.ID = string.FromCharCode(i); // Set the value of the cell toe the letter corresponding to the ASCII index cell.TextContent = string.FromCharCode(i); } } /// <summary> /// Process the text entered in a text input element. /// Extract a formula and store it as part of the element. /// Process the formula and display the result in the text element. /// </summary> /// <param name="input">Input element of a cell to process</param> private void ProcessCell(InputElement input) { // Ensure that there's a value in the input element that is a formula involving another cell if (input.Value.Length > 4 && input.Value.StartsWith("=")) { // Set the input value as a data-formula attribute on the text input element input.SetAttribute("data-formula", input.Value); // For this tutorial, we will split the formula on the "+" operation only string[] items = input.Value.Substring(1).Split("+"); Number result = 0; // Traverse through each item in the equation foreach (string item in items) { // If the item is not a number, it is assumed to be a formula if (Number.IsNaN((Number)(object)item)) { // Get a reference to the cell, parse its value and then add it to our result result += Number.Parse(((InputElement)Document.GetElementById(item)).Value); } else { result += Number.Parse(item); } } // Replace the input's formula with the result. We've stored a reference to the formula as part of its data-formula attribute input.Value = result.ToString(); } } /// <summary> /// This function renders the spreadsheet in an HTML element /// </summary> /// <param name="divName">Name of a container div to create the spreadsheet in</param> public void Render(string divName) { // Get a reference to the Div Element and add the table as its child element Document.GetElementById<DivElement>(divName).AppendChild(_table); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using OpenMetaverse; using log4net; namespace OpenSim.Framework { public abstract class TerrainData { // Terrain always is a square public int SizeX { get; protected set; } public int SizeY { get; protected set; } public int SizeZ { get; protected set; } // A height used when the user doesn't specify anything public const float DefaultTerrainHeight = 21f; public abstract float this[int x, int y] { get; set; } // Someday terrain will have caves // at most holes :p public abstract float this[int x, int y, int z] { get; set; } public abstract bool IsTaintedAt(int xx, int yy); public abstract bool IsTaintedAt(int xx, int yy, bool clearOnTest); public abstract void TaintAllTerrain(); public abstract void ClearTaint(); public abstract void ClearLand(); public abstract void ClearLand(float height); // Return a representation of this terrain for storing as a blob in the database. // Returns 'true' to say blob was stored in the 'out' locations. public abstract bool GetDatabaseBlob(out int DBFormatRevisionCode, out Array blob); // Given a revision code and a blob from the database, create and return the right type of TerrainData. // The sizes passed are the expected size of the region. The database info will be used to // initialize the heightmap of that sized region with as much data is in the blob. // Return created TerrainData or 'null' if unsuccessful. public static TerrainData CreateFromDatabaseBlobFactory(int pSizeX, int pSizeY, int pSizeZ, int pFormatCode, byte[] pBlob) { // For the moment, there is only one implementation class return new HeightmapTerrainData(pSizeX, pSizeY, pSizeZ, pFormatCode, pBlob); } // return a special compressed representation of the heightmap in ushort public abstract float[] GetCompressedMap(); public abstract float CompressionFactor { get; } public abstract float[] GetFloatsSerialized(); public abstract double[,] GetDoubles(); public abstract TerrainData Clone(); } // The terrain is stored in the database as a blob with a 'revision' field. // Some implementations of terrain storage would fill the revision field with // the time the terrain was stored. When real revisions were added and this // feature removed, that left some old entries with the time in the revision // field. // Thus, if revision is greater than 'RevisionHigh' then terrain db entry is // left over and it is presumed to be 'Legacy256'. // Numbers are arbitrary and are chosen to to reduce possible mis-interpretation. // If a revision does not match any of these, it is assumed to be Legacy256. public enum DBTerrainRevision { // Terrain is 'double[256,256]' Legacy256 = 11, // Terrain is 'int32, int32, float[,]' where the ints are X and Y dimensions // The dimensions are presumed to be multiples of 16 and, more likely, multiples of 256. Variable2D = 22, Variable2DGzip = 23, // Terrain is 'int32, int32, int32, int16[]' where the ints are X and Y dimensions // and third int is the 'compression factor'. The heights are compressed as // "ushort compressedHeight = (ushort)(height * compressionFactor);" // The dimensions are presumed to be multiples of 16 and, more likely, multiples of 256. Compressed2D = 27, // A revision that is not listed above or any revision greater than this value is 'Legacy256'. RevisionHigh = 1234 } // Version of terrain that is a heightmap. // This should really be 'LLOptimizedHeightmapTerrainData' as it includes knowledge // of 'patches' which are 16x16 terrain areas which can be sent separately to the viewer. // The heighmap is kept as an array of ushorts. The ushort values are converted to // and from floats by TerrainCompressionFactor. public class HeightmapTerrainData : TerrainData { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[HEIGHTMAP TERRAIN DATA]"; // TerrainData.this[x, y] public override float this[int x, int y] { get { return m_heightmap[x, y]; } set { if (m_heightmap[x, y] != value) { m_heightmap[x, y] = value; m_taint[x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize] = true; } } } // TerrainData.this[x, y, z] public override float this[int x, int y, int z] { get { return this[x, y]; } set { this[x, y] = value; } } // TerrainData.ClearTaint public override void ClearTaint() { SetAllTaint(false); } // TerrainData.TaintAllTerrain public override void TaintAllTerrain() { SetAllTaint(true); } private void SetAllTaint(bool setting) { for (int ii = 0; ii < m_taint.GetLength(0); ii++) for (int jj = 0; jj < m_taint.GetLength(1); jj++) m_taint[ii, jj] = setting; } // TerrainData.ClearLand public override void ClearLand() { ClearLand(DefaultTerrainHeight); } // TerrainData.ClearLand(float) public override void ClearLand(float pHeight) { for (int xx = 0; xx < SizeX; xx++) for (int yy = 0; yy < SizeY; yy++) m_heightmap[xx, yy] = pHeight; } // Return 'true' of the patch that contains these region coordinates has been modified. // Note that checking the taint clears it. // There is existing code that relies on this feature. public override bool IsTaintedAt(int xx, int yy, bool clearOnTest) { int tx = xx / Constants.TerrainPatchSize; int ty = yy / Constants.TerrainPatchSize; bool ret = m_taint[tx, ty]; if (ret && clearOnTest) m_taint[tx, ty] = false; return ret; } // Old form that clears the taint flag when we check it. // ubit: this dangerus naming should be only check without clear // keeping for old modules outthere public override bool IsTaintedAt(int xx, int yy) { return IsTaintedAt(xx, yy, true /* clearOnTest */); } // TerrainData.GetDatabaseBlob // The user wants something to store in the database. public override bool GetDatabaseBlob(out int DBRevisionCode, out Array blob) { bool ret = false; /* save all as Variable2DGzip if (SizeX == Constants.RegionSize && SizeY == Constants.RegionSize) { DBRevisionCode = (int)DBTerrainRevision.Legacy256; blob = ToLegacyTerrainSerialization(); ret = true; } else { */ DBRevisionCode = (int)DBTerrainRevision.Variable2DGzip; // DBRevisionCode = (int)DBTerrainRevision.Variable2D; blob = ToCompressedTerrainSerializationV2DGzip(); // blob = ToCompressedTerrainSerializationV2D(); ret = true; // } return ret; } // TerrainData.CompressionFactor private float m_compressionFactor = 100.0f; public override float CompressionFactor { get { return m_compressionFactor; } } // TerrainData.GetCompressedMap public override float[] GetCompressedMap() { float[] newMap = new float[SizeX * SizeY]; int ind = 0; for (int xx = 0; xx < SizeX; xx++) for (int yy = 0; yy < SizeY; yy++) newMap[ind++] = m_heightmap[xx, yy]; return newMap; } // TerrainData.Clone public override TerrainData Clone() { HeightmapTerrainData ret = new HeightmapTerrainData(SizeX, SizeY, SizeZ); ret.m_heightmap = (float[,])this.m_heightmap.Clone(); return ret; } // TerrainData.GetFloatsSerialized // This one dimensional version is ordered so height = map[y*sizeX+x]; // DEPRECATED: don't use this function as it does not retain the dimensions of the terrain // and the caller will probably do the wrong thing if the terrain is not the legacy 256x256. public override float[] GetFloatsSerialized() { int points = SizeX * SizeY; float[] heights = new float[points]; int idx = 0; for (int jj = 0; jj < SizeY; jj++) for (int ii = 0; ii < SizeX; ii++) { heights[idx++] = m_heightmap[ii, jj]; } return heights; } // TerrainData.GetDoubles public override double[,] GetDoubles() { double[,] ret = new double[SizeX, SizeY]; for (int xx = 0; xx < SizeX; xx++) for (int yy = 0; yy < SizeY; yy++) ret[xx, yy] = (double)m_heightmap[xx, yy]; return ret; } // ============================================================= private float[,] m_heightmap; // Remember subregions of the heightmap that has changed. private bool[,] m_taint; // that is coded as the float height times the compression factor (usually '100' // to make for two decimal points). public short ToCompressedHeightshort(float pHeight) { // clamp into valid range pHeight *= CompressionFactor; if (pHeight < short.MinValue) return short.MinValue; else if (pHeight > short.MaxValue) return short.MaxValue; return (short)pHeight; } public ushort ToCompressedHeightushort(float pHeight) { // clamp into valid range pHeight *= CompressionFactor; if (pHeight < ushort.MinValue) return ushort.MinValue; else if (pHeight > ushort.MaxValue) return ushort.MaxValue; return (ushort)pHeight; } public float FromCompressedHeight(short pHeight) { return ((float)pHeight) / CompressionFactor; } public float FromCompressedHeight(ushort pHeight) { return ((float)pHeight) / CompressionFactor; } // To keep with the legacy theme, create an instance of this class based on the // way terrain used to be passed around. public HeightmapTerrainData(double[,] pTerrain) { SizeX = pTerrain.GetLength(0); SizeY = pTerrain.GetLength(1); SizeZ = (int)Constants.RegionHeight; m_compressionFactor = 100.0f; m_heightmap = new float[SizeX, SizeY]; for (int ii = 0; ii < SizeX; ii++) { for (int jj = 0; jj < SizeY; jj++) { m_heightmap[ii, jj] = (float)pTerrain[ii, jj]; } } // m_log.DebugFormat("{0} new by doubles. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ); m_taint = new bool[SizeX / Constants.TerrainPatchSize, SizeY / Constants.TerrainPatchSize]; ClearTaint(); } // Create underlying structures but don't initialize the heightmap assuming the caller will immediately do that public HeightmapTerrainData(int pX, int pY, int pZ) { SizeX = pX; SizeY = pY; SizeZ = pZ; m_compressionFactor = 100.0f; m_heightmap = new float[SizeX, SizeY]; m_taint = new bool[SizeX / Constants.TerrainPatchSize, SizeY / Constants.TerrainPatchSize]; // m_log.DebugFormat("{0} new by dimensions. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ); ClearTaint(); ClearLand(0f); } public HeightmapTerrainData(float[] cmap, float pCompressionFactor, int pX, int pY, int pZ) : this(pX, pY, pZ) { m_compressionFactor = pCompressionFactor; int ind = 0; for (int xx = 0; xx < SizeX; xx++) for (int yy = 0; yy < SizeY; yy++) m_heightmap[xx, yy] = cmap[ind++]; // m_log.DebugFormat("{0} new by compressed map. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ); } // Create a heighmap from a database blob public HeightmapTerrainData(int pSizeX, int pSizeY, int pSizeZ, int pFormatCode, byte[] pBlob) : this(pSizeX, pSizeY, pSizeZ) { switch ((DBTerrainRevision)pFormatCode) { case DBTerrainRevision.Variable2DGzip: FromCompressedTerrainSerializationV2DGZip(pBlob); m_log.DebugFormat("{0} HeightmapTerrainData create from Variable2DGzip serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY); break; case DBTerrainRevision.Variable2D: FromCompressedTerrainSerializationV2D(pBlob); m_log.DebugFormat("{0} HeightmapTerrainData create from Variable2D serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY); break; case DBTerrainRevision.Compressed2D: FromCompressedTerrainSerialization2D(pBlob); m_log.DebugFormat("{0} HeightmapTerrainData create from Compressed2D serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY); break; default: FromLegacyTerrainSerialization(pBlob); m_log.DebugFormat("{0} HeightmapTerrainData create from legacy serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY); break; } } // Just create an array of doubles. Presumes the caller implicitly knows the size. public Array ToLegacyTerrainSerialization() { Array ret = null; using (MemoryStream str = new MemoryStream((int)Constants.RegionSize * (int)Constants.RegionSize * sizeof(double))) { using (BinaryWriter bw = new BinaryWriter(str)) { for (int xx = 0; xx < Constants.RegionSize; xx++) { for (int yy = 0; yy < Constants.RegionSize; yy++) { double height = this[xx, yy]; if (height == 0.0) height = double.Epsilon; bw.Write(height); } } } ret = str.ToArray(); } return ret; } // Presumes the caller implicitly knows the size. public void FromLegacyTerrainSerialization(byte[] pBlob) { // In case database info doesn't match real terrain size, initialize the whole terrain. ClearLand(); try { using (MemoryStream mstr = new MemoryStream(pBlob)) { using (BinaryReader br = new BinaryReader(mstr)) { for (int xx = 0; xx < (int)Constants.RegionSize; xx++) { for (int yy = 0; yy < (int)Constants.RegionSize; yy++) { float val = (float)br.ReadDouble(); if (xx < SizeX && yy < SizeY) m_heightmap[xx, yy] = val; } } } } } catch { ClearLand(); } ClearTaint(); } // stores as variable2D // int32 sizeX // int32 sizeY // float[,] array public Array ToCompressedTerrainSerializationV2D() { Array ret = null; try { using (MemoryStream str = new MemoryStream((2 * sizeof(Int32)) + (SizeX * SizeY * sizeof(float)))) { using (BinaryWriter bw = new BinaryWriter(str)) { bw.Write((Int32)SizeX); bw.Write((Int32)SizeY); for (int yy = 0; yy < SizeY; yy++) for (int xx = 0; xx < SizeX; xx++) { // reduce to 1cm resolution float val = (float)Math.Round(m_heightmap[xx, yy],2,MidpointRounding.ToEven); bw.Write(val); } } ret = str.ToArray(); } } catch { } m_log.DebugFormat("{0} V2D {1} bytes", LogHeader, ret.Length); return ret; } // as above with Gzip compression public Array ToCompressedTerrainSerializationV2DGzip() { Array ret = null; try { using (MemoryStream inp = new MemoryStream((2 * sizeof(Int32)) + (SizeX * SizeY * sizeof(float)))) { using (BinaryWriter bw = new BinaryWriter(inp)) { bw.Write((Int32)SizeX); bw.Write((Int32)SizeY); for (int yy = 0; yy < SizeY; yy++) for (int xx = 0; xx < SizeX; xx++) { bw.Write((float)m_heightmap[xx, yy]); } bw.Flush(); inp.Seek(0, SeekOrigin.Begin); using (MemoryStream outputStream = new MemoryStream()) { using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress)) { inp.CopyStream(compressionStream, int.MaxValue); compressionStream.Close(); ret = outputStream.ToArray(); } } } } } catch { } m_log.DebugFormat("{0} V2DGzip {1} bytes", LogHeader, ret.Length); return ret; } // Initialize heightmap from blob consisting of: // int32, int32, int32, int32, int16[] // where the first int32 is format code, next two int32s are the X and y of heightmap data and // the forth int is the compression factor for the following int16s // This is just sets heightmap info. The actual size of the region was set on this instance's // creation and any heights not initialized by theis blob are set to the default height. public void FromCompressedTerrainSerialization2D(byte[] pBlob) { Int32 hmFormatCode, hmSizeX, hmSizeY, hmCompressionFactor; using (MemoryStream mstr = new MemoryStream(pBlob)) { using (BinaryReader br = new BinaryReader(mstr)) { hmFormatCode = br.ReadInt32(); hmSizeX = br.ReadInt32(); hmSizeY = br.ReadInt32(); hmCompressionFactor = br.ReadInt32(); m_compressionFactor = hmCompressionFactor; // In case database info doesn't match real terrain size, initialize the whole terrain. ClearLand(); for (int yy = 0; yy < hmSizeY; yy++) { for (int xx = 0; xx < hmSizeX; xx++) { float val = FromCompressedHeight(br.ReadInt16()); if (xx < SizeX && yy < SizeY) m_heightmap[xx, yy] = val; } } } ClearTaint(); m_log.DebugFormat("{0} Read (compressed2D) heightmap. Heightmap size=<{1},{2}>. Region size=<{3},{4}>. CompFact={5}", LogHeader, hmSizeX, hmSizeY, SizeX, SizeY, hmCompressionFactor); } } // Initialize heightmap from blob consisting of: // int32, int32, int32, float[] // where the first int32 is format code, next two int32s are the X and y of heightmap data // This is just sets heightmap info. The actual size of the region was set on this instance's // creation and any heights not initialized by theis blob are set to the default height. public void FromCompressedTerrainSerializationV2D(byte[] pBlob) { Int32 hmSizeX, hmSizeY; try { using (MemoryStream mstr = new MemoryStream(pBlob)) { using (BinaryReader br = new BinaryReader(mstr)) { hmSizeX = br.ReadInt32(); hmSizeY = br.ReadInt32(); // In case database info doesn't match real terrain size, initialize the whole terrain. ClearLand(); for (int yy = 0; yy < hmSizeY; yy++) { for (int xx = 0; xx < hmSizeX; xx++) { float val = br.ReadSingle(); if (xx < SizeX && yy < SizeY) m_heightmap[xx, yy] = val; } } } } } catch (Exception e) { ClearTaint(); m_log.ErrorFormat("{0} 2D error: {1} - terrain may be damaged", LogHeader, e.Message); return; } ClearTaint(); m_log.DebugFormat("{0} V2D Heightmap size=<{1},{2}>. Region size=<{3},{4}>", LogHeader, hmSizeX, hmSizeY, SizeX, SizeY); } // as above but Gzip compressed public void FromCompressedTerrainSerializationV2DGZip(byte[] pBlob) { m_log.InfoFormat("{0} VD2Gzip {1} bytes input", LogHeader, pBlob.Length); Int32 hmSizeX, hmSizeY; try { using (MemoryStream outputStream = new MemoryStream()) { using (MemoryStream inputStream = new MemoryStream(pBlob)) { using (GZipStream decompressionStream = new GZipStream(inputStream, CompressionMode.Decompress)) { decompressionStream.Flush(); decompressionStream.CopyTo(outputStream); } } outputStream.Seek(0, SeekOrigin.Begin); using (BinaryReader br = new BinaryReader(outputStream)) { hmSizeX = br.ReadInt32(); hmSizeY = br.ReadInt32(); // In case database info doesn't match real terrain size, initialize the whole terrain. ClearLand(); for (int yy = 0; yy < hmSizeY; yy++) { for (int xx = 0; xx < hmSizeX; xx++) { float val = br.ReadSingle(); if (xx < SizeX && yy < SizeY) m_heightmap[xx, yy] = val; } } } } } catch( Exception e) { ClearTaint(); m_log.ErrorFormat("{0} V2DGzip error: {1} - terrain may be damaged", LogHeader, e.Message); return; } ClearTaint(); m_log.DebugFormat("{0} V2DGzip. Heightmap size=<{1},{2}>. Region size=<{3},{4}>", LogHeader, hmSizeX, hmSizeY, SizeX, SizeY); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IdentityManagement.Model { /// <summary> /// Container for the parameters to the SimulatePrincipalPolicy operation. /// Simulate the set of IAM policies attached to an IAM entity against a list of API actions /// and AWS resources to determine the policies' effective permissions. The entity can /// be an IAM user, group, or role. If you specify a user, then the simulation also includes /// all of the policies attached to groups that the user is a member of. /// /// /// <para> /// You can optionally include a list of one or more additional policies specified as /// strings to include in the simulation. If you want to simulate only policies specified /// as strings, use <a>SimulateCustomPolicy</a> instead. /// </para> /// /// <para> /// The simulation does not perform the API actions, it only checks the authorization /// to determine if the simulated policies allow or deny the actions. /// </para> /// /// <para> /// <b>Note:</b> This API discloses information about the permissions granted to other /// users. If you do not want users to see other user's permissions, then consider allowing /// them to use <a>SimulateCustomPolicy</a> instead. /// </para> /// /// <para> /// Context keys are variables maintained by AWS and its services that provide details /// about the context of an API query request, and can be evaluated by using the <code>Condition</code> /// element of an IAM policy. To get the list of context keys required by the policies /// to simulate them correctly, use <a>GetContextKeysForPrincipalPolicy</a>. /// </para> /// /// <para> /// If the output is long, you can paginate the results using the <code>MaxItems</code> /// and <code>Marker</code> parameters. /// </para> /// </summary> public partial class SimulatePrincipalPolicyRequest : AmazonIdentityManagementServiceRequest { private List<string> _actionNames = new List<string>(); private List<ContextEntry> _contextEntries = new List<ContextEntry>(); private string _marker; private int? _maxItems; private List<string> _policyInputList = new List<string>(); private string _policySourceArn; private List<string> _resourceArns = new List<string>(); /// <summary> /// Gets and sets the property ActionNames. /// <para> /// A list of names of API actions to evaluate in the simulation. Each action is evaluated /// for each resource. Each action must include the service identifier, such as <code>iam:CreateUser</code>. /// </para> /// </summary> public List<string> ActionNames { get { return this._actionNames; } set { this._actionNames = value; } } // Check to see if ActionNames property is set internal bool IsSetActionNames() { return this._actionNames != null && this._actionNames.Count > 0; } /// <summary> /// Gets and sets the property ContextEntries. /// <para> /// A list of context keys and corresponding values that are used by the simulation. Whenever /// a context key is evaluated by a <code>Condition</code> element in one of the simulated /// IAM permission policies, the corresponding value is supplied. /// </para> /// </summary> public List<ContextEntry> ContextEntries { get { return this._contextEntries; } set { this._contextEntries = value; } } // Check to see if ContextEntries property is set internal bool IsSetContextEntries() { return this._contextEntries != null && this._contextEntries.Count > 0; } /// <summary> /// Gets and sets the property Marker. /// <para> /// Use this parameter only when paginating results and only after you receive a response /// indicating that the results are truncated. Set it to the value of the <code>Marker</code> /// element in the response you received to inform the next call about where to start. /// </para> /// </summary> public string Marker { get { return this._marker; } set { this._marker = value; } } // Check to see if Marker property is set internal bool IsSetMarker() { return this._marker != null; } /// <summary> /// Gets and sets the property MaxItems. /// <para> /// Use this only when paginating results to indicate the maximum number of items you /// want in the response. If there are additional items beyond the maximum you specify, /// the <code>IsTruncated</code> response element is <code>true</code>. /// </para> /// /// <para> /// This parameter is optional. If you do not include it, it defaults to 100. /// </para> /// </summary> public int MaxItems { get { return this._maxItems.GetValueOrDefault(); } set { this._maxItems = value; } } // Check to see if MaxItems property is set internal bool IsSetMaxItems() { return this._maxItems.HasValue; } /// <summary> /// Gets and sets the property PolicyInputList. /// <para> /// An optional list of additional policy documents to include in the simulation. Each /// document is specified as a string containing the complete, valid JSON text of an IAM /// policy. /// </para> /// </summary> public List<string> PolicyInputList { get { return this._policyInputList; } set { this._policyInputList = value; } } // Check to see if PolicyInputList property is set internal bool IsSetPolicyInputList() { return this._policyInputList != null && this._policyInputList.Count > 0; } /// <summary> /// Gets and sets the property PolicySourceArn. /// <para> /// The Amazon Resource Name (ARN) of a user, group, or role whose policies you want to /// include in the simulation. If you specify a user, group, or role, the simulation includes /// all policies associated with that entity. If you specify a user, the simulation also /// includes all policies attached to any groups the user is a member of. /// </para> /// </summary> public string PolicySourceArn { get { return this._policySourceArn; } set { this._policySourceArn = value; } } // Check to see if PolicySourceArn property is set internal bool IsSetPolicySourceArn() { return this._policySourceArn != null; } /// <summary> /// Gets and sets the property ResourceArns. /// <para> /// A list of ARNs of AWS resources to include in the simulation. If this parameter is /// not provided then the value defaults to <code>*</code> (all resources). Each API in /// the <code>ActionNames</code> parameter is evaluated for each resource in this list. /// The simulation determines the access result (allowed or denied) of each combination /// and reports it in the response. /// </para> /// </summary> public List<string> ResourceArns { get { return this._resourceArns; } set { this._resourceArns = value; } } // Check to see if ResourceArns property is set internal bool IsSetResourceArns() { return this._resourceArns != null && this._resourceArns.Count > 0; } } }
using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Serialization; namespace SIL.Xml { public static class XmlSerializationHelper { #region InternalXmlReader class /// ------------------------------------------------------------------------------------ /// <summary> /// Custom XmlTextReader that can preserve whitespace characters (spaces, tabs, etc.) /// that are in XML elements. This allows us to properly handle deserialization of /// paragraph runs that contain runs that contain only whitespace characters. /// </summary> /// ------------------------------------------------------------------------------------ private class InternalXmlReader : XmlTextReader { private readonly bool m_fKeepWhitespaceInElements; /// -------------------------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="InternalXmlReader"/> class. /// </summary> /// <param name="reader">The stream reader.</param> /// <param name="fKeepWhitespaceInElements">if set to <c>true</c>, the reader /// will preserve and return elements that contain only whitespace, otherwise /// these elements will be ignored during a deserialization.</param> /// -------------------------------------------------------------------------------- public InternalXmlReader(TextReader reader, bool fKeepWhitespaceInElements) : base(reader) { m_fKeepWhitespaceInElements = fKeepWhitespaceInElements; } /// -------------------------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="InternalXmlReader"/> class. /// </summary> /// <param name="filename">The filename.</param> /// <param name="fKeepWhitespaceInElements">if set to <c>true</c>, the reader /// will preserve and return elements that contain only whitespace, otherwise /// these elements will be ignored during a deserialization.</param> /// -------------------------------------------------------------------------------- public InternalXmlReader(string filename, bool fKeepWhitespaceInElements) : base(new StreamReader(filename)) { m_fKeepWhitespaceInElements = fKeepWhitespaceInElements; } /// -------------------------------------------------------------------------------- /// <summary> /// Gets the namespace URI (as defined in the W3C Namespace specification) of the /// node on which the reader is positioned. /// </summary> /// <value></value> /// <returns>The namespace URI of the current node; otherwise an empty string.</returns> /// -------------------------------------------------------------------------------- public override string NamespaceURI { get { return string.Empty; } } /// -------------------------------------------------------------------------------- /// <summary> /// Reads the next node from the stream. /// </summary> /// -------------------------------------------------------------------------------- public override bool Read() { // Since we use this class only for deserialization, catch file not found // exceptions for the case when the XML file contains a !DOCTYPE declaration // and the specified DTD file is not found. (This is because the base class // attempts to open the DTD by merely reading the !DOCTYPE node from the // current directory instead of relative to the XML document location.) try { return base.Read(); } catch (FileNotFoundException) { return true; } } /// -------------------------------------------------------------------------------- /// <summary> /// Gets the type of the current node. /// </summary> /// -------------------------------------------------------------------------------- public override XmlNodeType NodeType { get { if (m_fKeepWhitespaceInElements && (base.NodeType == XmlNodeType.Whitespace || base.NodeType == XmlNodeType.SignificantWhitespace) && Value.IndexOf('\n') < 0 && Value.Trim().Length == 0) { // We found some whitespace that was most // likely whitespace we want to keep. return XmlNodeType.Text; } return base.NodeType; } } } #endregion #region Methods for XML serializing and deserializing data /// ------------------------------------------------------------------------------------ /// <summary> /// Serializes an object to an XML represented in an array of UTF-8 bytes. /// </summary> /// ------------------------------------------------------------------------------------ public static byte[] SerializeToByteArray<T>(T data) { return SerializeToByteArray(data, false); } /// ------------------------------------------------------------------------------------ /// <summary> /// Serializes an object to an XML represented in an array of UTF-8 bytes. /// </summary> /// ------------------------------------------------------------------------------------ public static byte[] SerializeToByteArray<T>(T data, bool omitXmlDeclaration) { var utf16 = SerializeToString(data, omitXmlDeclaration); return Encoding.UTF8.GetBytes(utf16); } /// ------------------------------------------------------------------------------------ /// <summary> /// Serializes an object to an XML string. /// </summary> /// ------------------------------------------------------------------------------------ public static string SerializeToString<T>(T data) { return SerializeToString(data, false); } /// ------------------------------------------------------------------------------------ /// <summary> /// Serializes an object to an XML string. (Of course, the string is a UTF-16 string.) /// </summary> /// ------------------------------------------------------------------------------------ public static string SerializeToString<T>(T data, bool omitXmlDeclaration) { try { using (var strWriter = new StringWriter()) { var settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; settings.CheckCharacters = true; settings.OmitXmlDeclaration = omitXmlDeclaration; using (var xmlWriter = XmlWriter.Create(strWriter, settings)) { var nameSpace = new XmlSerializerNamespaces(); nameSpace.Add(string.Empty, string.Empty); var serializer = new XmlSerializer(typeof(T)); serializer.Serialize(xmlWriter, data, nameSpace); xmlWriter.Flush(); xmlWriter.Close(); strWriter.Flush(); strWriter.Close(); var result = strWriter.ToString(); return (result == string.Empty ? null : result); } } } catch (Exception e) { Debug.Fail(e.Message); } return null; } /// ------------------------------------------------------------------------------------ public static bool SerializeToFile<T>(string filename, T data) { return SerializeToFile(filename, data, null); } /// ------------------------------------------------------------------------------------ public static bool SerializeToFile<T>(string filename, T data, out Exception e) { return SerializeToFile(filename, data, null, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Serializes an object to a the specified file. /// </summary> /// ------------------------------------------------------------------------------------ public static bool SerializeToFile<T>(string filename, T data, string rootElementName) { Exception e; return SerializeToFile(filename, data, rootElementName, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Serializes an object to a the specified file. /// </summary> /// ------------------------------------------------------------------------------------ public static bool SerializeToFile<T>(string filename, T data, string rootElementName, out Exception e) { e = null; try { using (TextWriter writer = new StreamWriter(filename)) { XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces(); nameSpace.Add(string.Empty, string.Empty); XmlSerializer serializer; if (string.IsNullOrEmpty(rootElementName)) serializer = new XmlSerializer(typeof(T)); else { var rootAttrib = new XmlRootAttribute(); rootAttrib.ElementName = rootElementName; rootAttrib.IsNullable = true; serializer = new XmlSerializer(typeof(T), rootAttrib); } serializer.Serialize(writer, data, nameSpace); writer.Close(); } //var xe = XElement.Load(filename); //xe.SetAttributeValue("version", "2.0"); //xe.Save(filename); return true; } catch (Exception ex) { e = ex; Debug.Fail(ex.Message); } return false; } /// ------------------------------------------------------------------------------------ /// <summary> /// Serializes the specified data to a string and writes that XML using the specified /// writer. Since strings in .Net are UTF16, the serialized XML data string is, of /// course, UTF16. Before the string is written it is converted to UTF8. So the /// assumption is the writer is expecting UTF8 data. /// </summary> /// ------------------------------------------------------------------------------------ public static bool SerializeDataAndWriteAsNode<T>(XmlWriter writer, T data) { string xmlData = SerializeToString(data); using (XmlReader reader = XmlReader.Create(new StringReader(xmlData))) { // Read past declaration and whitespace. while (reader.NodeType != XmlNodeType.Element && reader.Read()) { } if (!reader.EOF) { xmlData = reader.ReadOuterXml(); if (xmlData.Length > 0) { writer.WriteWhitespace(Environment.NewLine); writer.WriteRaw(xmlData); writer.WriteWhitespace(Environment.NewLine); } return true; } } return false; } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified string to an object of the specified type. /// </summary> /// ------------------------------------------------------------------------------------ public static T DeserializeFromString<T>(string input) { Exception e; return (DeserializeFromString<T>(input, out e)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified string to an object of the specified type. /// </summary> /// ------------------------------------------------------------------------------------ public static T DeserializeFromString<T>(string input, bool fKeepWhitespaceInElements) { Exception e; return (DeserializeFromString<T>(input, fKeepWhitespaceInElements, out e)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified string to an object of the specified type. /// </summary> /// ------------------------------------------------------------------------------------ public static T DeserializeFromString<T>(string input, out Exception e) { return DeserializeFromString<T>(input, false, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified string to an object of the specified type. /// </summary> /// ------------------------------------------------------------------------------------ public static T DeserializeFromString<T>(string input, bool fKeepWhitespaceInElements, out Exception e) { T data = default(T); e = null; try { if (string.IsNullOrEmpty(input)) return default(T); // Whitespace is not allowed before the XML declaration, // so get rid of any that exists. input = input.TrimStart(); using (InternalXmlReader reader = new InternalXmlReader( new StringReader(input), fKeepWhitespaceInElements)) { data = DeserializeInternal<T>(reader, null); } } catch (Exception outEx) { e = outEx; } return data; } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified file to an object of the specified type. /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="filename">The filename from which to load</param> /// ------------------------------------------------------------------------------------ public static T DeserializeFromFile<T>(string filename) { Exception e; return DeserializeFromFile<T>(filename, false, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified file to an object of the specified type. /// </summary> /// ------------------------------------------------------------------------------------ public static T DeserializeFromFile<T>(string filename, string rootElementName) { Exception e; return DeserializeFromFile<T>(filename, rootElementName, false, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified file to an object of the specified type. /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="filename">The filename from which to load</param> /// <param name="fKeepWhitespaceInElements">if set to <c>true</c>, the reader /// will preserve and return elements that contain only whitespace, otherwise /// these elements will be ignored during a deserialization.</param> /// ------------------------------------------------------------------------------------ public static T DeserializeFromFile<T>(string filename, bool fKeepWhitespaceInElements) { Exception e; return DeserializeFromFile<T>(filename, fKeepWhitespaceInElements, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified file to an object of the specified type. /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="filename">The filename from which to load</param> /// <param name="rootElementName">Name to expect for the root element. This is /// good when T is a generic list of some type (e.g. List of strings).</param> /// <param name="fKeepWhitespaceInElements">if set to <c>true</c>, the reader /// will preserve and return elements that contain only whitespace, otherwise /// these elements will be ignored during a deserialization.</param> /// ------------------------------------------------------------------------------------ public static T DeserializeFromFile<T>(string filename, string rootElementName, bool fKeepWhitespaceInElements) { Exception e; return DeserializeFromFile<T>(filename, rootElementName, fKeepWhitespaceInElements, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified file to an object of the specified type. /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="filename">The filename from which to load</param> /// <param name="e">The exception generated during the deserialization.</param> /// ------------------------------------------------------------------------------------ public static T DeserializeFromFile<T>(string filename, out Exception e) { return DeserializeFromFile<T>(filename, false, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified file to an object of the specified type. /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="filename">The filename from which to load</param> /// <param name="rootElementName">Name to expect for the root element. This is /// good when T is a generic list of some type (e.g. List of string).</param> /// <param name="e">The exception generated during the deserialization.</param> /// <returns></returns> /// ------------------------------------------------------------------------------------ public static T DeserializeFromFile<T>(string filename, string rootElementName, out Exception e) { return DeserializeFromFile<T>(filename, rootElementName, false, out e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes XML from the specified file to an object of the specified type. /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="filename">The filename from which to load</param> /// <param name="fKeepWhitespaceInElements">if set to <c>true</c>, the reader /// will preserve and return elements that contain only whitespace, otherwise /// these elements will be ignored during a deserialization.</param> /// <param name="e">The exception generated during the deserialization.</param> /// ------------------------------------------------------------------------------------ public static T DeserializeFromFile<T>(string filename, bool fKeepWhitespaceInElements, out Exception e) { return DeserializeFromFile<T>(filename, null, fKeepWhitespaceInElements, out e); } /// -------------------------------------------------------------------------------- /// <summary> /// Deserializes XML from the specified file to an object of the specified type. /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="filename">The filename from which to load</param> /// <param name="rootElementName">Name to expect for the root element. This is /// good when T is a generic list of some type (e.g. List of strings).</param> /// <param name="fKeepWhitespaceInElements">if set to <c>true</c>, the reader /// will preserve and return elements that contain only whitespace, otherwise /// these elements will be ignored during a deserialization.</param> /// <param name="e">The exception generated during the deserialization.</param> /// <returns></returns> /// -------------------------------------------------------------------------------- public static T DeserializeFromFile<T>(string filename, string rootElementName, bool fKeepWhitespaceInElements, out Exception e) { T data = default(T); e = null; try { if (!File.Exists(filename)) return default(T); using (InternalXmlReader reader = new InternalXmlReader( filename, fKeepWhitespaceInElements)) { data = DeserializeInternal<T>(reader, rootElementName); } } catch (Exception outEx) { e = outEx; } return data; } /// ------------------------------------------------------------------------------------ /// <summary> /// Deserializes an object using the specified reader. /// </summary> /// <typeparam name="T">The type of object to deserialize</typeparam> /// <param name="reader">The reader.</param> /// <param name="rootElementName">Name to expect for the of the root element.</param> /// <returns>The deserialized object</returns> /// ------------------------------------------------------------------------------------ private static T DeserializeInternal<T>(XmlReader reader, string rootElementName) { XmlSerializer deserializer; if (string.IsNullOrEmpty(rootElementName)) deserializer = new XmlSerializer(typeof(T)); else { var rootAttrib = new XmlRootAttribute(); rootAttrib.ElementName = rootElementName; rootAttrib.IsNullable = true; deserializer = new XmlSerializer(typeof(T), rootAttrib); } deserializer.UnknownAttribute += deserializer_UnknownAttribute; return (T)deserializer.Deserialize(reader); } /// ------------------------------------------------------------------------------------ /// <summary> /// Handles the UnknownAttribute event of the deserializer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Xml.Serialization.XmlAttributeEventArgs"/> /// instance containing the event data.</param> /// ------------------------------------------------------------------------------------ static void deserializer_UnknownAttribute(object sender, XmlAttributeEventArgs e) { if (e.Attr.LocalName == "lang") { // This is special handling for the xml:lang attribute that is used to specify // the WS for the current paragraph, run in a paragraph, etc. The XmlTextReader // treats xml:lang as a special case and basically skips over it (but it does // set the current XmlLang to the specified value). This keeps the deserializer // from getting xml:lang as an attribute which keeps us from getting these values. // The fix for this is to look at the object that is being deserialized and, // using reflection, see if it has any fields that have an XmlAttribute looking // for the xml:lang and setting it to the value we get here. (TE-8328) object obj = e.ObjectBeingDeserialized; Type type = obj.GetType(); foreach (FieldInfo field in type.GetFields()) { object[] bla = field.GetCustomAttributes(typeof(XmlAttributeAttribute), false); if (bla.Length == 1 && ((XmlAttributeAttribute)bla[0]).AttributeName == "xml:lang") { field.SetValue(obj, e.Attr.Value); return; } } foreach (PropertyInfo prop in type.GetProperties()) { object[] bla = prop.GetCustomAttributes(typeof(XmlAttributeAttribute), false); if (bla.Length == 1 && ((XmlAttributeAttribute)bla[0]).AttributeName == "xml:lang") { prop.SetValue(obj, e.Attr.Value, null); return; } } } } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using Microsoft.Web.Services3; using WebsitePanel.EnterpriseServer; using WebsitePanel.EnterpriseServer.HostedSolution; namespace WebsitePanel.Import.CsvBulk { /// <summary> /// ES Proxy class /// </summary> public class ES { private static ServerContext serverContext = null; public static void InitializeServices(ServerContext context) { serverContext = context; } public static ES Services { get { return new ES(); } } public esSystem System { get { return GetCachedProxy<esSystem>(); } } public esApplicationsInstaller ApplicationsInstaller { get { return GetCachedProxy<esApplicationsInstaller>(); } } public esAuditLog AuditLog { get { return GetCachedProxy<esAuditLog>(); } } public esAuthentication Authentication { get { return GetCachedProxy<esAuthentication>(false); } } public esComments Comments { get { return GetCachedProxy<esComments>(); } } public esDatabaseServers DatabaseServers { get { return GetCachedProxy<esDatabaseServers>(); } } public esFiles Files { get { return GetCachedProxy<esFiles>(); } } public esFtpServers FtpServers { get { return GetCachedProxy<esFtpServers>(); } } public esMailServers MailServers { get { return GetCachedProxy<esMailServers>(); } } public esOperatingSystems OperatingSystems { get { return GetCachedProxy<esOperatingSystems>(); } } public esPackages Packages { get { return GetCachedProxy<esPackages>(); } } public esScheduler Scheduler { get { return GetCachedProxy<esScheduler>(); } } public esTasks Tasks { get { return GetCachedProxy<esTasks>(); } } public esServers Servers { get { return GetCachedProxy<esServers>(); } } public esStatisticsServers StatisticsServers { get { return GetCachedProxy<esStatisticsServers>(); } } public esUsers Users { get { return GetCachedProxy<esUsers>(); } } public esWebServers WebServers { get { return GetCachedProxy<esWebServers>(); } } public esSharePointServers SharePointServers { get { return GetCachedProxy<esSharePointServers>(); } } public esImport Import { get { return GetCachedProxy<esImport>(); } } public esBackup Backup { get { return GetCachedProxy<esBackup>(); } } public esExchangeServer ExchangeServer { get { return GetCachedProxy<esExchangeServer>(); } } public esOrganizations Organizations { get { return GetCachedProxy<esOrganizations>(); } } protected ES() { } protected virtual T GetCachedProxy<T>() { return GetCachedProxy<T>(true); } protected virtual T GetCachedProxy<T>(bool secureCalls) { if (serverContext == null) { throw new Exception("Server context is not specified"); } Type t = typeof(T); string key = t.FullName + ".ServiceProxy"; T proxy = (T)Activator.CreateInstance(t); object p = proxy; // configure proxy EnterpriseServerProxyConfigurator cnfg = new EnterpriseServerProxyConfigurator(); cnfg.EnterpriseServerUrl = serverContext.Server; if (secureCalls) { cnfg.Username = serverContext.Username; cnfg.Password = serverContext.Password; } cnfg.Configure((WebServicesClientProtocol)p); return proxy; } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; namespace nzy3D.Plot3D.Builder.Delaunay.Jdt { /// <summary> /// Grid Index is a simple spatial index for fast point/triangle location. /// The idea is to divide a predefined geographic extent into equal sized /// cell matrix (tiles). Every cell will be associated with a triangle which lies inside. /// Therfore, one can easily locate a triangle in close proximity of the required /// point by searching from the point's cell triangle. If the triangulation is /// more or less uniform and bound in space, this index is very effective, /// roughly recuing the searched triangles by square(xCellCount * yCellCount), /// as only the triangles inside the cell are searched. /// /// The index takes xCellCount * yCellCount capacity. While more cells allow /// faster searches, even a small grid is helpfull. /// /// This implementation holds the cells in a memory matrix, but such a grid can /// be easily mapped to a DB table or file where it is usually used for it's fullest. /// /// Note that the index is geographically bound - only the region given in the /// c'tor is indexed. Added Triangles outside the indexed region will cause rebuilding of /// the whole index. Since triangulation is mostly always used for static raster data, /// and usually is never updated outside the initial zone (only refininf existing triangles) /// this is never an issue in real life. /// </summary> public class GridIndex { /// <summary> The triangulation of the index </summary> private Delaunay_Triangulation indexDelaunay; /// <summary> Horizontal geographic size of a cell index </summary> private double x_size; /// <summary> Vertical geographic size of a cell index </summary> private double y_size; /// <summary> The indexed geographic size </summary> private BoundingBox indexRegion; /// <summary> A division of indexRegion to a cell matrix, where each cell holds a triangle which lies in it </summary> private Triangle_dt[,] grid; /// <summary> /// Constructs a grid index holding the triangles of a delaunay triangulation. /// This version uses the bounding box of the triangulation as the region to index. /// </summary> /// <param name="delaunay">delaunay triangulation to index</param> /// <param name="xCellCount">number of grid cells in a row</param> /// <param name="yCellCount">number of grid cells in a column</param> /// <remarks></remarks> public GridIndex(Delaunay_Triangulation delaunay, int xCellCount, int yCellCount) : this(delaunay, xCellCount, yCellCount, delaunay.BoundingBox) { } /// <summary> /// Constructs a grid index holding the triangles of a delaunay triangulation. /// The grid will be made of (xCellCount * yCellCount) cells. /// The smaller the cells the less triangles that fall in them, whuch means better /// indexing, but also more cells in the index, which mean more storage. /// The smaller the indexed region is, the smaller the cells can be and still /// maintain the same capacity, but adding geometries outside the initial region /// will invalidate the index ! /// </summary> /// <param name="delaunay">delaunay triangulation to index</param> /// <param name="xCellCount">number of grid cells in a row</param> /// <param name="yCellCount">number of grid cells in a column</param> /// <param name="region">geographic region to index</param> /// <remarks></remarks> public GridIndex(Delaunay_Triangulation delaunay, int xCellCount, int yCellCount, BoundingBox region) { init(delaunay, xCellCount, yCellCount, region); } public void init(Delaunay_Triangulation delaunay, int xCellCount, int yCellCount, BoundingBox region) { indexDelaunay = delaunay; indexRegion = region; x_size = region.Width / yCellCount; y_size = region.Height / xCellCount; // The grid will hold a trinagle for each cell, so a point (x,y) will lie // in the cell representing the grid partition of region to a // xCellCount on yCellCount grid grid = new Triangle_dt[xCellCount + 1, yCellCount + 1]; Triangle_dt colStartTriangle = indexDelaunay.Find(middleOfCell(0, 0)); updateCellValues(0, 0, xCellCount - 1, yCellCount - 1, colStartTriangle); } /// <summary> /// Finds a triangle near the given point /// </summary> /// <param name="point">a query point</param> /// <returns>a triangle at the same cell of the point</returns> public Triangle_dt findCellTriangleOf(Point_dt point) { int x_index = Convert.ToInt32((point.x - indexRegion.minX) / x_size); int y_index = Convert.ToInt32((point.y - indexRegion.minY) / y_size); return grid[x_index, y_index]; } /// <summary> /// Updates the grid index to reflect changes to the triangulation. Note that added /// triangles outside the indexed region will force to recompute the whole index /// with the enlarged region /// </summary> /// <param name="updatedTriangles">Changed triangles of the triangulation. This may be added triangles, /// removed triangles or both. All that matter is that they cover the /// changed area. /// </param> public void updateIndex(IEnumerator<Triangle_dt> updatedTriangles) { // Gather the bounding box of the updated area BoundingBox updatedRegion = new BoundingBox(); while (((updatedTriangles.Current != null))) { updatedRegion = updatedRegion.UnionWith(updatedTriangles.Current.BoundingBox); updatedTriangles.MoveNext(); } if ((updatedRegion.isNull)) return; // No update... // Bad news - the updated region lies outside the indexed region. // The whole index must be recalculated if ((!indexRegion.contains(updatedRegion))) { init(indexDelaunay, Convert.ToInt32(indexRegion.Width / x_size), Convert.ToInt32(indexRegion.Height / y_size), indexRegion.UnionWith(updatedRegion)); } else { // Find the cell region to be updated Point_dt minInvalidCell = getCellOf(updatedRegion.MinPoint); Point_dt maxInvalidCell = getCellOf(updatedRegion.MaxPoint); // And update it with fresh triangles Triangle_dt adjacentValidTriangle = findValidTriangle(minInvalidCell); updateCellValues((int)minInvalidCell.x, (int)minInvalidCell.y, (int)maxInvalidCell.x, (int)maxInvalidCell.y, adjacentValidTriangle); } } /// <summary> /// Go over each grid cell and locate a triangle in it to be the cell's /// starting search triangle. Since we only pass between adjacent cells /// we can search from the last triangle found and not from the start. /// Add triangles for each column cells /// </summary> /// <param name="startXCell"></param> /// <param name="startYCell"></param> /// <param name="lastXCell"></param> /// <param name="lastYCell"></param> /// <param name="startTriangle"></param> /// <remarks></remarks> private void updateCellValues(int startXCell, int startYCell, int lastXCell, int lastYCell, Triangle_dt startTriangle) { for (int i = startXCell; i <= lastXCell; i++) { // Find a triangle at the begining of the current column startTriangle = indexDelaunay.Find(middleOfCell(i, startYCell), startTriangle); grid[i, startYCell] = startTriangle; Triangle_dt prevRowTriangle = startTriangle; // Add triangles for the next row cells for (int j = startYCell + 1; j <= lastYCell; j++) { grid[i, j] = indexDelaunay.Find(middleOfCell(i, j), prevRowTriangle); prevRowTriangle = grid[i, j]; } } } /// <summary> /// Finds a valid (existing) trinagle adjacent to a given invalid cell /// </summary> /// <param name="minInvalidCell">minimum bounding box invalid cell</param> /// <returns>a valid triangle adjacent to the invalid cell</returns> private Triangle_dt findValidTriangle(Point_dt minInvalidCell) { // If the invalid cell is the minimal one in the grid we are forced to search the // triangulation for a trinagle at that location if ((minInvalidCell.x == 0 & minInvalidCell.y == 0)) { return indexDelaunay.Find(middleOfCell((int)minInvalidCell.x, (int)minInvalidCell.y), null); } else { // Otherwise we can take an adjacent cell triangle that is still valid return grid[(int)Math.Min(0, minInvalidCell.x), (int)Math.Min(0, minInvalidCell.y)]; } } /// <summary> /// Locates the grid cell point covering the given coordinat /// </summary> /// <param name="coordinate">World coordinate to locate</param> /// <returns>Cell covering the coordinate</returns> private Point_dt getCellOf(Point_dt coordinate) { int x_cell = Convert.ToInt32((coordinate.x - indexRegion.minX) / x_size); int y_cell = Convert.ToInt32((coordinate.y - indexRegion.minY) / y_size); return new Point_dt(x_cell, y_cell); } /// <summary> /// Create a point at the center of a cell /// </summary> /// <param name="x_index">Horizontal cell index</param> /// <param name="y_index">Vertical cell index</param> /// <returns>Point at the center of the cell at (x_index, y_index)</returns> private Point_dt middleOfCell(int x_index, int y_index) { double middleXCell = indexRegion.minX + x_index * x_size + x_size / 2; double middleYCell = indexRegion.minY + y_index * y_size + y_size / 2; return new Point_dt(middleXCell, middleYCell); } } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> //----------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace WootzJs.Compiler { public static class Cs { public static GotoStatementSyntax Goto(int label) { return SyntaxFactory.GotoStatement( SyntaxKind.GotoCaseStatement, SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(label))); } public static IdentifierNameSyntax IdentifierName(string name) { return SyntaxFactory.IdentifierName(name); } public static LiteralExpressionSyntax True() { return SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression); } public static LiteralExpressionSyntax False() { return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); } public static PredefinedTypeSyntax Bool() { return SyntaxFactory.PredefinedType(Token(SyntaxKind.BoolKeyword)); } public static PredefinedTypeSyntax Void() { return SyntaxFactory.PredefinedType(Token(SyntaxKind.VoidKeyword)); } public static PredefinedTypeSyntax Int() { return SyntaxFactory.PredefinedType(Token(SyntaxKind.IntKeyword)); } public static SyntaxToken Ref() { return Token(SyntaxKind.RefKeyword); } public static SyntaxToken Out() { return Token(SyntaxKind.OutKeyword); } public static SyntaxToken Token(SyntaxKind kind) { return SyntaxFactory.Token(kind); } public static LiteralExpressionSyntax Integer(int value) { return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(value)); } public static BinaryExpressionSyntax Assign(this ExpressionSyntax left, ExpressionSyntax right) { return SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, left, right); } public static ThisExpressionSyntax This() { return SyntaxFactory.ThisExpression(); } public static TypeSyntax Var() { return SyntaxFactory.ParseTypeName("var"); // return SyntaxFactory.PredefinedType(Token(SyntaxKind.TypeVarKeyword)); } public static MemberAccessExpressionSyntax Member(this ExpressionSyntax target, string member) { return target.Member(SyntaxFactory.IdentifierName(member)); } public static MemberAccessExpressionSyntax Member(this ExpressionSyntax target, SyntaxToken member) { return target.Member(SyntaxFactory.IdentifierName(member)); } public static MemberAccessExpressionSyntax Member(this ExpressionSyntax target, SimpleNameSyntax member) { return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, target, member); } public static ExpressionStatementSyntax Express(this ExpressionSyntax expression) { return SyntaxFactory.ExpressionStatement(expression); } public static ReturnStatementSyntax Return() { return SyntaxFactory.ReturnStatement(); } public static ReturnStatementSyntax Return(ExpressionSyntax expression) { return SyntaxFactory.ReturnStatement(expression); } public static WhileStatementSyntax While(ExpressionSyntax condition, StatementSyntax statement) { return SyntaxFactory.WhileStatement(condition, statement); } public static SwitchStatementSyntax Switch(ExpressionSyntax target, params SwitchSectionSyntax[] sections) { return SyntaxFactory.SwitchStatement(target, SyntaxFactory.List(sections)); } public static SwitchSectionSyntax Section(ExpressionSyntax label, params StatementSyntax[] statements) { return Section(SyntaxFactory.CaseSwitchLabel(label), statements); } public static SyntaxToken Public() { return SyntaxFactory.Token(SyntaxKind.PublicKeyword); } public static SyntaxToken Override() { return SyntaxFactory.Token(SyntaxKind.OverrideKeyword); } // public static ClassDeclarationSyntax WithBaseList(this ClassDeclarationSyntax declaration, params TypeSyntax[] baseTypes) // { // return declaration.WithBaseList(SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(baseTypes, baseTypes.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))))); // } public static ClassDeclarationSyntax WithMembers(this ClassDeclarationSyntax declaration, params MemberDeclarationSyntax[] members) { return declaration.WithMembers(SyntaxFactory.List(members)); } public static ConstructorDeclarationSyntax WithParameterList(this ConstructorDeclarationSyntax constructor, params ParameterSyntax[] parameters) { return constructor.WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters, parameters.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))))); } public static MethodDeclarationSyntax WithParameterList(this MethodDeclarationSyntax method, params ParameterSyntax[] parameters) { return method.WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters, parameters.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))))); } public static VariableDeclaratorSyntax Declarator(string name, ExpressionSyntax initializer = null) { var result = SyntaxFactory.VariableDeclarator(name); if (initializer != null) result = result.WithInitializer(SyntaxFactory.EqualsValueClause(initializer)); return result; } public static VariableDeclarationSyntax Variable(TypeSyntax type, string name, ExpressionSyntax initializer = null) { return SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SeparatedList(new[] { Declarator(name, initializer) })); } public static LocalDeclarationStatementSyntax Local(TypeSyntax type, string name, ExpressionSyntax initializer = null) { return Local(Variable(type, name, initializer)); } public static LocalDeclarationStatementSyntax Local(VariableDeclarationSyntax variable) { return SyntaxFactory.LocalDeclarationStatement(variable); } public static FieldDeclarationSyntax Field(TypeSyntax type, string name) { return SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SeparatedList(new[] { SyntaxFactory.VariableDeclarator(name) }))); } public static FieldDeclarationSyntax Field(TypeSyntax type, SyntaxToken name) { return SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SeparatedList(new[] { SyntaxFactory.VariableDeclarator(name) }))); } public static BlockSyntax WithStatements(this BlockSyntax block, IEnumerable<StatementSyntax> statements) { return block.WithStatements(SyntaxFactory.List(statements)); } public static BreakStatementSyntax Break() { return SyntaxFactory.BreakStatement(); } public static ClassDeclarationSyntax WithTypeParameters(this ClassDeclarationSyntax classDeclaration, params TypeParameterSyntax[] typeParameters) { return classDeclaration .WithTypeParameterList(SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameters, typeParameters.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))))); } public static IfStatementSyntax If(ExpressionSyntax condition, StatementSyntax statement) { return SyntaxFactory.IfStatement(condition, statement); } public static IfStatementSyntax If(ExpressionSyntax condition, StatementSyntax statement, StatementSyntax @else) { return SyntaxFactory.IfStatement(condition, statement, SyntaxFactory.ElseClause(@else)); } public static BlockSyntax Block(params StatementSyntax[] statements) { return SyntaxFactory.Block(statements); } public static SwitchStatementSyntax Switch(ExpressionSyntax expression) { return SyntaxFactory.SwitchStatement(expression); } public static SwitchSectionSyntax Section(SwitchLabelSyntax label, params StatementSyntax[] statements) { return SyntaxFactory.SwitchSection(SyntaxFactory.List(new[] { label }), SyntaxFactory.List(statements)); } public static SwitchSectionSyntax Section(SyntaxList<SwitchLabelSyntax> labels, params StatementSyntax[] statements) { return SyntaxFactory.SwitchSection(labels, SyntaxFactory.List(statements)); } public static TryStatementSyntax Try() { return SyntaxFactory.TryStatement(); } public static FinallyClauseSyntax Finally(params StatementSyntax[] statements) { return SyntaxFactory.FinallyClause(Block(statements)); } public static TryStatementSyntax WithFinally(this TryStatementSyntax tryStatement, params StatementSyntax[] statements) { return tryStatement.WithFinally(Finally(statements)); } public static TryStatementSyntax WithCatch(this TryStatementSyntax tryStatement, TypeSyntax exceptionType, string exceptionIdentifier, params StatementSyntax[] statements) { return tryStatement .WithCatches(SyntaxFactory.List(tryStatement.Catches.Concat(new[] { SyntaxFactory.CatchClause() .WithDeclaration(SyntaxFactory.CatchDeclaration(exceptionType, SyntaxFactory.Identifier(exceptionIdentifier))) .WithBlock(Block(statements)) }))); } public static BinaryExpressionSyntax NotEqualTo(this ExpressionSyntax left, ExpressionSyntax right) { return SyntaxFactory.BinaryExpression(SyntaxKind.NotEqualsExpression, left, right); } public static BinaryExpressionSyntax EqualTo(this ExpressionSyntax left, ExpressionSyntax right) { return SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, left, right); } public static LiteralExpressionSyntax Null() { return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); } public static ThrowStatementSyntax Rethrow() { return SyntaxFactory.ThrowStatement(); } public static ThrowStatementSyntax Throw(ExpressionSyntax expression) { return SyntaxFactory.ThrowStatement(expression); } public static AnonymousObjectCreationExpressionSyntax Anonymous(params Tuple<string, ExpressionSyntax>[] initializers) { return SyntaxFactory.AnonymousObjectCreationExpression(SyntaxFactory.SeparatedList( initializers.Select(x => SyntaxFactory.AnonymousObjectMemberDeclarator(SyntaxFactory.NameEquals(x.Item1), x.Item2) ), initializers.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken)))); } public static BlockSyntax Local(this BlockSyntax block, string name, ExpressionSyntax initializer, out VariableDeclaratorSyntax variable) { var declaration = Local(name, initializer, out variable); block = block.AddStatements(declaration); return block; } public static LocalDeclarationStatementSyntax Local(string name, ExpressionSyntax initializer, out VariableDeclaratorSyntax variable) { variable = SyntaxFactory.VariableDeclarator(name).WithInitializer(SyntaxFactory.EqualsValueClause(initializer)); var declaration = SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseTypeName("var"), SyntaxFactory.SeparatedList(new[] { variable }))); return declaration; } public static LocalDeclarationStatementSyntax Local(string name, ExpressionSyntax initializer) { VariableDeclaratorSyntax variable; return Local(name, initializer, out variable); } public static BlockSyntax If(this BlockSyntax block, ExpressionSyntax condition, StatementSyntax ifTrue, StatementSyntax ifFalse = null) { var result = SyntaxFactory.IfStatement(condition, ifTrue); if (ifFalse != null) result = result.WithElse(SyntaxFactory.ElseClause(ifFalse)); return block.AddStatements(result); } public static ExpressionSyntax Reference(this VariableDeclaratorSyntax variable) { return SyntaxFactory.IdentifierName(variable.Identifier); } public static InvocationExpressionSyntax Invoke(this ExpressionSyntax target, params ExpressionSyntax[] arguments) { return target.Invoke(arguments.Select(x => SyntaxFactory.Argument(x)).ToArray()); } public static InvocationExpressionSyntax Invoke(this ExpressionSyntax target) { return target.Invoke(new ArgumentSyntax[0]); } public static InvocationExpressionSyntax Invoke(this ExpressionSyntax target, params ArgumentSyntax[] arguments) { return SyntaxFactory.InvocationExpression(target, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList( arguments, arguments.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))))); } public static ObjectCreationExpressionSyntax New(this TypeSyntax type, params ExpressionSyntax[] arguments) { return SyntaxFactory.ObjectCreationExpression(type) .WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(x => SyntaxFactory.Argument(x)), arguments.Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))))); } public static string GetContainingMemberName(this SyntaxNode node) { var current = node; while (current != null) { if (current.Parent is BaseTypeDeclarationSyntax && ((BaseTypeDeclarationSyntax)current.Parent).Identifier.ToString().Contains("$")) { var identifier = ((BaseTypeDeclarationSyntax)current.Parent).Identifier.ToString(); var parts = identifier.Split('$'); return parts[1]; } if (current is MethodDeclarationSyntax && !(current.Parent is PropertyDeclarationSyntax)) { var method = (MethodDeclarationSyntax)current; return method.Identifier.ToString(); } else if (current is PropertyDeclarationSyntax) { var property = (PropertyDeclarationSyntax)current; return property.Identifier.ToString(); } else if (current is ConstructorDeclarationSyntax) { var constructor = (ConstructorDeclarationSyntax)current; if (constructor.Modifiers.Any(x => x.IsKind(SyntaxKind.StaticKeyword))) return ".cctor"; else return ".ctor"; } current = current.Parent; } return null; } public static ParameterListSyntax ToParameterList(this IEnumerable<IParameterSymbol> parameters) { return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Select(x => SyntaxFactory.Parameter(SyntaxFactory.Identifier(x.Name)).WithType(x.Type.ToTypeSyntax()) ))); } public static FieldDeclarationSyntax WithAttributes(this FieldDeclarationSyntax field, params ITypeSymbol[] attributeTypes) { return field.WithAttributeLists(SyntaxFactory.List(new[] { SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributeTypes.Select(x => SyntaxFactory.Attribute(SyntaxFactory.ParseName(x.ToDisplayString()))))) })); } public static IEnumerable<ITypeSymbol> GetContainingTypes(this ITypeSymbol type) { var current = type.ContainingType; while (current != null) { yield return current; current = current.ContainingType; } } public static bool IsAutoProperty(this PropertyDeclarationSyntax property) { if (property.AccessorList == null) return false; var getter = property.AccessorList.Accessors.SingleOrDefault(x => x.Keyword.IsKind(SyntaxKind.GetKeyword)); var setter = property.AccessorList.Accessors.SingleOrDefault(x => x.Keyword.IsKind(SyntaxKind.SetKeyword)); return !property.Modifiers.Any(x => x == SyntaxFactory.Token(SyntaxKind.AbstractKeyword)) && getter != null && getter.Body == null && setter?.Body == null; } public static bool IsAutoProperty(this IPropertySymbol property) { var propertySyntaxNode = property.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).OfType<PropertyDeclarationSyntax>().SingleOrDefault(); return propertySyntaxNode != null && propertySyntaxNode.IsAutoProperty(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; namespace System.ServiceModel.Dispatcher { internal class ErrorBehavior { private IErrorHandler[] _handlers; private bool _debug; private bool _isOnServer; private MessageVersion _messageVersion; internal ErrorBehavior(ChannelDispatcher channelDispatcher) { _handlers = EmptyArray<IErrorHandler>.ToArray(channelDispatcher.ErrorHandlers); _debug = channelDispatcher.IncludeExceptionDetailInFaults; _isOnServer = channelDispatcher.IsOnServer; _messageVersion = channelDispatcher.MessageVersion; } private void InitializeFault(ref MessageRpc rpc) { Exception error = rpc.Error; FaultException fault = error as FaultException; if (fault != null) { string action; MessageFault messageFault = rpc.Operation.FaultFormatter.Serialize(fault, out action); if (action == null) action = rpc.RequestVersion.Addressing.DefaultFaultAction; if (messageFault != null) rpc.FaultInfo.Fault = Message.CreateMessage(rpc.RequestVersion, messageFault, action); } } internal void ProvideMessageFault(ref MessageRpc rpc) { if (rpc.Error != null) { ProvideMessageFaultCore(ref rpc); } } private void ProvideMessageFaultCore(ref MessageRpc rpc) { if (_messageVersion != rpc.RequestVersion) { Fx.Assert("System.ServiceModel.Dispatcher.ErrorBehavior.ProvideMessageFaultCore(): (this.messageVersion != rpc.RequestVersion)"); } this.InitializeFault(ref rpc); this.ProvideFault(rpc.Error, rpc.Channel.GetProperty<FaultConverter>(), ref rpc.FaultInfo); this.ProvideMessageFaultCoreCoda(ref rpc); } private void ProvideMessageFaultCoreCoda(ref MessageRpc rpc) { if (rpc.FaultInfo.Fault.Headers.Action == null) { rpc.FaultInfo.Fault.Headers.Action = rpc.RequestVersion.Addressing.DefaultFaultAction; } rpc.Reply = rpc.FaultInfo.Fault; } internal void ProvideOnlyFaultOfLastResort(ref MessageRpc rpc) { ProvideFaultOfLastResort(rpc.Error, ref rpc.FaultInfo); ProvideMessageFaultCoreCoda(ref rpc); } private void ProvideFaultOfLastResort(Exception error, ref ErrorHandlerFaultInfo faultInfo) { if (faultInfo.Fault == null) { FaultCode code = new FaultCode(FaultCodeConstants.Codes.InternalServiceFault, FaultCodeConstants.Namespaces.NetDispatch); code = FaultCode.CreateReceiverFaultCode(code); string action = FaultCodeConstants.Actions.NetDispatcher; MessageFault fault; if (_debug) { faultInfo.DefaultFaultAction = action; fault = MessageFault.CreateFault(code, new FaultReason(error.Message), new ExceptionDetail(error)); } else { string reason = _isOnServer ? SR.SFxInternalServerError : SR.SFxInternalCallbackError; fault = MessageFault.CreateFault(code, new FaultReason(reason)); } faultInfo.IsConsideredUnhandled = true; faultInfo.Fault = Message.CreateMessage(_messageVersion, fault, action); } //if this is an InternalServiceFault coming from another service dispatcher we should treat it as unhandled so that the channels are cleaned up else if (error != null) { FaultException e = error as FaultException; if (e != null && e.Fault != null && e.Fault.Code != null && e.Fault.Code.SubCode != null && string.Compare(e.Fault.Code.SubCode.Namespace, FaultCodeConstants.Namespaces.NetDispatch, StringComparison.Ordinal) == 0 && string.Compare(e.Fault.Code.SubCode.Name, FaultCodeConstants.Codes.InternalServiceFault, StringComparison.Ordinal) == 0) { faultInfo.IsConsideredUnhandled = true; } } } internal void ProvideFault(Exception e, FaultConverter faultConverter, ref ErrorHandlerFaultInfo faultInfo) { ProvideWellKnownFault(e, faultConverter, ref faultInfo); for (int i = 0; i < _handlers.Length; i++) { Message m = faultInfo.Fault; _handlers[i].ProvideFault(e, _messageVersion, ref m); faultInfo.Fault = m; if (WcfEventSource.Instance.FaultProviderInvokedIsEnabled()) { WcfEventSource.Instance.FaultProviderInvoked(_handlers[i].GetType().FullName, e.Message); } } this.ProvideFaultOfLastResort(e, ref faultInfo); } private void ProvideWellKnownFault(Exception e, FaultConverter faultConverter, ref ErrorHandlerFaultInfo faultInfo) { Message faultMessage; if (faultConverter != null && faultConverter.TryCreateFaultMessage(e, out faultMessage)) { faultInfo.Fault = faultMessage; return; } else if (e is NetDispatcherFaultException) { NetDispatcherFaultException ndfe = e as NetDispatcherFaultException; if (_debug) { ExceptionDetail detail = new ExceptionDetail(ndfe); faultInfo.Fault = Message.CreateMessage(_messageVersion, MessageFault.CreateFault(ndfe.Code, ndfe.Reason, detail), ndfe.Action); } else { faultInfo.Fault = Message.CreateMessage(_messageVersion, ndfe.CreateMessageFault(), ndfe.Action); } } } internal void HandleError(ref MessageRpc rpc) { if (rpc.Error != null) { HandleErrorCore(ref rpc); } } private void HandleErrorCore(ref MessageRpc rpc) { bool handled = HandleErrorCommon(rpc.Error, ref rpc.FaultInfo); if (handled) { rpc.Error = null; } } private bool HandleErrorCommon(Exception error, ref ErrorHandlerFaultInfo faultInfo) { bool handled; if (faultInfo.Fault != null // there is a message && !faultInfo.IsConsideredUnhandled) // and it's not the internal-server-error one { handled = true; } else { handled = false; } try { if (WcfEventSource.Instance.ServiceExceptionIsEnabled()) { WcfEventSource.Instance.ServiceException(error.ToString(), error.GetType().FullName); } for (int i = 0; i < _handlers.Length; i++) { bool handledByThis = _handlers[i].HandleError(error); handled = handledByThis || handled; if (WcfEventSource.Instance.ErrorHandlerInvokedIsEnabled()) { WcfEventSource.Instance.ErrorHandlerInvoked(_handlers[i].GetType().FullName, handledByThis, error.GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } return handled; } internal bool HandleError(Exception error) { ErrorHandlerFaultInfo faultInfo = new ErrorHandlerFaultInfo(_messageVersion.Addressing.DefaultFaultAction); return HandleError(error, ref faultInfo); } internal bool HandleError(Exception error, ref ErrorHandlerFaultInfo faultInfo) { return HandleErrorCommon(error, ref faultInfo); } internal static bool ShouldRethrowClientSideExceptionAsIs(Exception e) { return true; } // This ensures that people debugging first-chance Exceptions see this Exception, // and that the Exception shows up in the trace logs. internal static void ThrowAndCatch(Exception e, Message message) { try { if (System.Diagnostics.Debugger.IsAttached) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e); } else { throw TraceUtility.ThrowHelperError(e, message); } } else { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e); } else { TraceUtility.ThrowHelperError(e, message); } } } catch (Exception e2) { if (!object.ReferenceEquals(e, e2)) { throw; } } } internal static void ThrowAndCatch(Exception e) { ThrowAndCatch(e, null); } } }
using System; using System.Collections.Generic; using System.Text; using gView.Framework.IO; using gView.Framework.Carto; using gView.MapServer; using gView.Framework.Data; using System.Xml; using gView.Framework.UI; using System.Reflection; using gView.Framework.system; namespace gView.Interoperability.ArcXML.Dataset { [gView.Framework.system.RegisterPlugIn("704FCEAF-7BD8-4e50-81AB-8F5581584F9A")] public class Metadata : IMetadataProvider, IPropertyPage { public enum credentialMethod { none = 0, def = 1, net = 2, custom = 3 } private string _modifyOutputFile = String.Empty, _modifyOutputUrl = String.Empty; private credentialMethod _credMethod = credentialMethod.none; private string _credUser = String.Empty, _credPwd = String.Empty, _credDomain = String.Empty; private static object lockThis = new object(); #region IMetadataProvider Member public bool ApplyTo(object Object) { if (Object is IServiceMap) { IServiceMap map = (IServiceMap)Object; IMapServer server = map.MapServer; if (ServiceMapIsSVC(server, map)) { ArcIMSClass cls = ArcIMSServiceClass(map); if (cls != null) { lock (lockThis) { cls.ModifyResponseOuput -= new EventHandler(cls_ModifyResponseOuput); cls.ModifyResponseOuput += new EventHandler(cls_ModifyResponseOuput); } } return true; } } return false; } void cls_ModifyResponseOuput(object sender, EventArgs e) { if (!(e is ModifyOutputEventArgs) || ((ModifyOutputEventArgs)e).OutputNode == null) return; XmlNode output = ((ModifyOutputEventArgs)e).OutputNode; if (_credMethod != credentialMethod.none) { XmlNode credNode = output.OwnerDocument.CreateElement("credentials"); XmlAttribute attr; switch (_credMethod) { case credentialMethod.def: attr = output.OwnerDocument.CreateAttribute("default"); attr.Value = "true"; credNode.Attributes.Append(attr); break; case credentialMethod.net: attr = output.OwnerDocument.CreateAttribute("default"); attr.Value = "net"; credNode.Attributes.Append(attr); break; case credentialMethod.custom: attr = output.OwnerDocument.CreateAttribute("domain"); attr.Value = _credDomain; credNode.Attributes.Append(attr); attr = output.OwnerDocument.CreateAttribute("user"); attr.Value = _credUser; credNode.Attributes.Append(attr); attr = output.OwnerDocument.CreateAttribute("pwd"); attr.Value = _credPwd; credNode.Attributes.Append(attr); break; } output.AppendChild(credNode); } if (output.Attributes["file"] != null && !String.IsNullOrEmpty(_modifyOutputFile)) { output.Attributes["file"].Value = String.Format(_modifyOutputFile, output.Attributes["file"].Value); } if (output.Attributes["url"] != null && !String.IsNullOrEmpty(_modifyOutputUrl)) { output.Attributes["url"].Value = String.Format(_modifyOutputUrl, output.Attributes["url"].Value); } } public string Name { get { return "ArcIMS Service"; } } #endregion #region IPersistable Member public void Load(IPersistStream stream) { _credMethod = (credentialMethod)stream.Load("credMethod", (int)credentialMethod.none); _credUser = (string)stream.Load("credUser", String.Empty); _credPwd = (string)stream.Load("credPwd", String.Empty); if (!String.IsNullOrEmpty(_credPwd)) _credPwd = Crypto.Decrypt(_credPwd, "5A01A23E93664a8e8A3DC8F84C05FAD1"); _credDomain = (string)stream.Load("credDomain", String.Empty); _modifyOutputFile = (string)stream.Load("modOFile", String.Empty); _modifyOutputUrl = (string)stream.Load("modOUrl", String.Empty); } public void Save(IPersistStream stream) { stream.Save("credMethod", (int)_credMethod); stream.Save("credUser", _credUser); stream.Save("credPwd", String.IsNullOrEmpty(_credPwd) ? String.Empty : Crypto.Encrypt(_credPwd, "5A01A23E93664a8e8A3DC8F84C05FAD1") ); stream.Save("credDomain", _credDomain); stream.Save("modOFile", _modifyOutputFile); stream.Save("modOUrl", _modifyOutputUrl); } #endregion #region Properties public credentialMethod CredentialMethod { get { return _credMethod; } set { _credMethod = value; } } public string CredentialUser { get { return _credUser; } set { _credUser = value; } } public string CredentialPwd { get { return _credPwd; } set { _credPwd = value; } } public string CredentialDomain { get { return _credDomain; } set { _credDomain = value; } } public string ModifyOutputFile { get { return _modifyOutputFile; } set { _modifyOutputFile = value; } } public string ModifyOutputUrl { get { return _modifyOutputUrl; } set { _modifyOutputUrl = value; } } #endregion #region Helper private ArcIMSClass ArcIMSServiceClass(IServiceMap map) { if (map.MapElements == null) return null; foreach (IDatasetElement element in map.MapElements) { if (element != null && element.Class is ArcIMSClass) return (ArcIMSClass)element.Class; } return null; } private bool ServiceMapIsSVC(IMapServer server, IServiceMap map) { if (server == null || map == null) return false; foreach (IMapService service in server.Maps) { if (service == null) continue; if (service.Name == map.Name && service.Type == MapServiceType.SVC) return true; } return false; } #endregion #region IPropertyPage Member public object PropertyPage(object initObject) { string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"\gView.Interoperability.ArcXML.UI.dll"); IPlugInParameter p = uiAssembly.CreateInstance("gView.Interoperability.ArcXML.UI.PropertyPage.Metadata") as IPlugInParameter; if (p != null) p.Parameter = this; return p; } public object PropertyPageObject() { return this; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.Linq.Parallel.Tests { public static class UnorderedSources { public const int AdditionalTypeLimit = 1024; // Get a set of ranges, of each count in `counts`. // The start of each range is determined by passing the count into the `start` predicate. private static IEnumerable<object[]> Ranges(Func<int, int> start, IEnumerable<int> counts) { foreach (int count in counts) { int s = start(count); foreach (Labeled<ParallelQuery<int>> query in LabeledRanges(s, count)) { yield return new object[] { query, count, s }; } } } /// <summary> /// Get a set of ranges, starting at `start`, and running for each count in `counts`. /// </summary> /// <param name="start">The starting element of the range.</param> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the start.</returns> public static IEnumerable<object[]> Ranges(int start, IEnumerable<int> counts) { foreach (object[] parms in Ranges(x => start, counts)) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> Ranges(int[] counts) { foreach (object[] parms in Ranges(counts.Cast<int>())) yield return parms; } /// <summary> /// Get a set of ranges, starting at `start`, and running for each count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="start">The starting element of the range.</param> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the start.</returns> public static IEnumerable<object[]> Ranges(int start, int[] counts) { foreach (object[] parms in Ranges(start, counts.Cast<int>())) yield return parms; } /// <summary> /// Return pairs of ranges, both from 0 to each respective count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count, .</returns> public static IEnumerable<object[]> BinaryRanges(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in BinaryRanges(leftCounts.Cast<int>(), rightCounts.Cast<int>())) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> Ranges(IEnumerable<int> counts) { foreach (object[] parms in Ranges(x => 0, counts)) yield return parms.Take(2).ToArray(); } /// <summary> /// Return pairs of ranges, both from 0 to each respective count in `counts`. /// </summary> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count.</returns> public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, IEnumerable<int> rightCounts) { foreach (object[] left in Ranges(leftCounts)) { foreach (object[] right in Ranges(rightCounts)) { yield return left.Concat(right).ToArray(); } } } /// <summary> /// Return pairs of ranges, for each respective count in `counts`. /// </summary> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightStart">A predicate to determine the start of the right range, by passing the left and right range size.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, the fourth element is the right count, /// and the fifth is the right start..</returns> public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, Func<int, int, int> rightStart, IEnumerable<int> rightCounts) { foreach (object[] left in Ranges(leftCounts)) { foreach (object[] right in Ranges(right => rightStart((int)left[1], right), rightCounts)) { yield return left.Concat(right).ToArray(); } } } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks> /// This is useful for things like showing an average (via the use of `x => (double)SumRange(0, x) / x`) /// </remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <param name="modifiers">A set of modifiers to return as additional parameters.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and one additional element for each modifier.</returns> public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, params Func<int, T>[] modifiers) { if (modifiers == null || !modifiers.Any()) { foreach (object[] parms in Ranges(counts)) yield return parms; } else { foreach (object[] parms in Ranges(counts)) { int count = (int)parms[1]; yield return parms.Concat(modifiers.Select(f => f(count)).Cast<object>()).ToArray(); } } } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks> /// This is useful for things like dealing with `Max(predicate)`, /// allowing multiple predicate values for the same source count to be tested. /// The number of variations is equal to the longest modifier enumeration (all others will cycle). /// </remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <param name="modifiers">A set of modifiers to return as additional parameters.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and one additional element for each modifier.</returns> public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, params Func<int, IEnumerable<T>>[] modifiers) { if (modifiers == null || !modifiers.Any()) { foreach (object[] parms in Ranges(counts)) yield return parms; } else { foreach (object[] parms in Ranges(counts)) { IEnumerable<IEnumerable<T>> mod = modifiers.Select(f => f((int)parms[1])); for (int i = 0, count = mod.Max(e => e.Count()); i < count; i++) { yield return parms.Concat(mod.Select(e => e.ElementAt(i % e.Count())).Cast<object>()).ToArray(); } } } } // Return an enumerable which throws on first MoveNext. // Useful for testing promptness of cancellation. public static IEnumerable<object[]> ThrowOnFirstEnumeration() { yield return new object[] { Labeled.Label("ThrowOnFirstEnumeration", Enumerables<int>.ThrowOnEnumeration().AsParallel()), 8 }; } private static IEnumerable<Labeled<ParallelQuery<int>>> LabeledRanges(int start, int count) { yield return Labeled.Label("ParallelEnumerable.Range", ParallelEnumerable.Range(start, count)); yield return Labeled.Label("Enumerable.Range", Enumerable.Range(start, count).AsParallel()); int[] rangeArray = GetRangeArray(start, count); yield return Labeled.Label("Array", rangeArray.AsParallel()); IList<int> rangeList = rangeArray.ToList(); yield return Labeled.Label("List", rangeList.AsParallel()); if (count < AdditionalTypeLimit + 1) { yield return Labeled.Label("Partitioner", Partitioner.Create(rangeArray).AsParallel()); yield return Labeled.Label("ReadOnlyCollection", new ReadOnlyCollection<int>(rangeList).AsParallel()); } } internal static int[] GetRangeArray(int start, int count) { int[] range = new int[count]; for (int i = 0; i < count; i++) range[i] = start + i; return range; } } }
namespace Loon.Core.Graphics.Opengl.Particle { using System.Collections.Generic; using Loon.Utils; using System; public class ParticleSystem { public const int BLEND_ADDITIVE = 1; public const int BLEND_COMBINE = 2; private const int DEFAULT_PARTICLES = 100; private List<ParticleEmitter> removeMe = new List<ParticleEmitter>(); public class ParticlePool { public Particle[] particles; public List<Particle> available; public ParticlePool(ParticleSystem system, int maxParticles) { particles = new Particle[maxParticles]; available = new List<Particle>(); for (int i = 0; i < particles.Length; i++) { particles[i] = CreateParticle(system); } Reset(system); } public void Reset(ParticleSystem system) { available.Clear(); for (int i = 0; i < particles.Length; i++) { available.Add(particles[i]); } } } protected internal Dictionary<ParticleEmitter, ParticlePool> particlesByEmitter = new Dictionary<ParticleEmitter, ParticlePool>(); protected internal int maxParticlesPerEmitter; protected internal List<ParticleEmitter> emitters = new List<ParticleEmitter>(); protected internal Particle dummy; private int blendingMode = BLEND_COMBINE; private int pCount; private bool usePoints; private float x; private float y; private bool removeCompletedEmitters = true; private LTexture sprite; private bool visible = true; private string defaultImageName; private LColor mask; public ParticleSystem(LTexture defaultSprite) : this(defaultSprite, DEFAULT_PARTICLES) { } public ParticleSystem(string defaultSpriteRef) : this(defaultSpriteRef, DEFAULT_PARTICLES) { } public void Reset() { IEnumerator<ParticlePool> pools = particlesByEmitter.Values.GetEnumerator(); while (pools.MoveNext()) { ParticlePool pool = pools.Current; pool.Reset(this); } for (int i = 0; i < emitters.Count; i++) { ParticleEmitter emitter = emitters[i]; emitter.ResetState(); } } public bool IsVisible() { return visible; } public void SetVisible(bool visible) { this.visible = visible; } public void SetRemoveCompletedEmitters(bool remove) { removeCompletedEmitters = remove; } public void SetUsePoints(bool usePoints) { this.usePoints = usePoints; } public bool UsePoints() { return usePoints; } public ParticleSystem(string defaultSpriteRef, int maxParticles) : this(defaultSpriteRef, maxParticles, null) { } public ParticleSystem(string defaultSpriteRef, int maxParticles, LColor mask) { this.maxParticlesPerEmitter = maxParticles; this.mask = mask; SetDefaultImageName(defaultSpriteRef); dummy = CreateParticle(this); } public ParticleSystem(LTexture defaultSprite, int maxParticles) { this.maxParticlesPerEmitter = maxParticles; sprite = defaultSprite; dummy = CreateParticle(this); } public void SetDefaultImageName(string refs) { defaultImageName = refs; sprite = null; } public int GetBlendingMode() { return blendingMode; } protected internal static Particle CreateParticle(ParticleSystem system) { return new Particle(system); } public void SetBlendingMode(int mode) { this.blendingMode = mode; } public int GetEmitterCount() { return emitters.Count; } public ParticleEmitter GetEmitter(int index) { return (ParticleEmitter)emitters[index]; } public void AddEmitter(ParticleEmitter emitter) { emitters.Add(emitter); ParticlePool pool = new ParticlePool(this, maxParticlesPerEmitter); CollectionUtils.Put(particlesByEmitter, emitter, pool); } public void RemoveEmitter(ParticleEmitter emitter) { emitters.Remove(emitter); particlesByEmitter.Remove(emitter); } public void RemoveAllEmitters() { for (int i = 0; i < emitters.Count; i++) { RemoveEmitter(emitters[i]); i--; } } public float GetPositionX() { return x; } public float GetPositionY() { return y; } public void SetPosition(float x, float y) { this.x = x; this.y = y; } public void Render(GLEx g) { Render(g, x, y); } public void Render(GLEx g, float x, float y) { if (!visible) { return; } if ((sprite == null) && (defaultImageName != null)) { LoadSystemParticleImage(); } g.Translate(x, y); if (blendingMode == BLEND_ADDITIVE) { //GLEx.self.setBlendMode(GL.MODE_ALPHA_ONE); } if (UsePoints()) { //GLEx.gl10.glEnable(GL.GL_POINT_SMOOTH); //g.glTex2DDisable(); } for (int emitterIdx = 0; emitterIdx < emitters.Count; emitterIdx++) { ParticleEmitter emitter = emitters[emitterIdx]; if (!emitter.IsEnabled()) { continue; } if (emitter.UseAdditive()) { //g.setBlendMode(GL.MODE_ALPHA_ONE); } ParticlePool pool = particlesByEmitter[emitter]; LTexture image = emitter.GetImage(); if (image == null) { image = this.sprite; } if (!emitter.IsOriented() && !emitter.UsePoints(this)) { image.GLBegin(); } for (int i = 0; i < pool.particles.Length; i++) { if (pool.particles[i].InUse()) { pool.particles[i].Render(); } } if (!emitter.IsOriented() && !emitter.UsePoints(this)) { image.GLEnd(); } if (emitter.UseAdditive()) { //g.setBlendMode(GL.MODE_NORMAL); } } if (UsePoints()) { //GLEx.gl10.glDisable(GL.GL_POINT_SMOOTH); } if (blendingMode == BLEND_ADDITIVE) { //g.setBlendMode(GL.MODE_NORMAL); } g.ResetColor(); g.Translate(-x, -y); } private void LoadSystemParticleImage() { try { if (mask != null) { sprite = TextureUtils.FilterColor(defaultImageName, mask); } else { sprite = new LTexture(defaultImageName); } } catch (Exception e) { Loon.Utils.Debugging.Log.Exception(e); defaultImageName = null; } } public void Update(long delta) { if ((sprite == null) && (defaultImageName != null)) { LoadSystemParticleImage(); } removeMe.Clear(); List<ParticleEmitter> emitters = new List<ParticleEmitter>( this.emitters); for (int i = 0; i < emitters.Count; i++) { ParticleEmitter emitter = emitters[i]; if (emitter.IsEnabled()) { emitter.Update(this, delta); if (removeCompletedEmitters) { if (emitter.Completed()) { removeMe.Add(emitter); particlesByEmitter.Remove(emitter); } } } } CollectionUtils.RemoveAll(emitters, removeMe); pCount = 0; if (particlesByEmitter.Count != 0) { IEnumerator<ParticleEmitter> it = particlesByEmitter.Keys .GetEnumerator(); while (it.MoveNext()) { ParticleEmitter emitter = it.Current; if (emitter.IsEnabled()) { ParticlePool pool = particlesByEmitter[emitter]; for (int i = 0; i < pool.particles.Length; i++) { if (pool.particles[i].life > 0) { pool.particles[i].Update(delta); pCount++; } } } } } } public int GetParticleCount() { return pCount; } public Particle GetNewParticle(ParticleEmitter emitter, float life) { ParticlePool pool = particlesByEmitter[emitter]; List<Particle> available = pool.available; if (available.Count > 0) { Particle p = (Particle)CollectionUtils.RemoveAt(available,available.Count - 1); p.Init(emitter, life); p.SetImage(sprite); return p; } Loon.Utils.Debugging.Log.DebugWrite("Ran out of particles (increase the limit)!"); return dummy; } public void Release(Particle particle) { if (particle != dummy) { ParticlePool pool = (ParticlePool)CollectionUtils.Get(particlesByEmitter, particle .GetEmitter()); pool.available.Add(particle); } } public void ReleaseAll(ParticleEmitter emitter) { if (particlesByEmitter.Count != 0) { IEnumerator<ParticlePool> it = particlesByEmitter.Values.GetEnumerator(); while (it.MoveNext()) { ParticlePool pool = it.Current; for (int i = 0; i < pool.particles.Length; i++) { if (pool.particles[i].InUse()) { if (pool.particles[i].GetEmitter() == emitter) { pool.particles[i].SetLife(-1); Release(pool.particles[i]); } } } } } } public void MoveAll(ParticleEmitter emitter, float x, float y) { ParticlePool pool = particlesByEmitter[emitter]; for (int i = 0; i < pool.particles.Length; i++) { if (pool.particles[i].InUse()) { pool.particles[i].Move(x, y); } } } } }
// 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.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Interpreter { internal abstract class NotEqualInstruction : Instruction { // Perf: EqualityComparer<T> but is 3/2 to 2 times slower. private static Instruction s_reference, s_boolean, s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; private static Instruction s_referenceLiftedToNull, s_booleanLiftedToNull, s_SByteLiftedToNull, s_int16LiftedToNull, s_charLiftedToNull, s_int32LiftedToNull, s_int64LiftedToNull, s_byteLiftedToNull, s_UInt16LiftedToNull, s_UInt32LiftedToNull, s_UInt64LiftedToNull, s_singleLiftedToNull, s_doubleLiftedToNull; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "NotEqual"; } } private NotEqualInstruction() { } internal sealed class NotEqualBoolean : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Boolean)left) != ((Boolean)right))); } return +1; } } internal sealed class NotEqualSByte : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((SByte)left) != ((SByte)right))); } return +1; } } internal sealed class NotEqualInt16 : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int16)left) != ((Int16)right))); } return +1; } } internal sealed class NotEqualChar : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Char)left) != ((Char)right))); } return +1; } } internal sealed class NotEqualInt32 : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int32)left) != ((Int32)right))); } return +1; } } internal sealed class NotEqualInt64 : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int64)left) != ((Int64)right))); } return +1; } } internal sealed class NotEqualByte : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Byte)left) != ((Byte)right))); } return +1; } } internal sealed class NotEqualUInt16 : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt16)left) != ((UInt16)right))); } return +1; } } internal sealed class NotEqualUInt32 : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt32)left) != ((UInt32)right))); } return +1; } } internal sealed class NotEqualUInt64 : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt64)left) != ((UInt64)right))); } return +1; } } internal sealed class NotEqualSingle : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Single)left) != ((Single)right))); } return +1; } } internal sealed class NotEqualDouble : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right != null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.True); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Double)left) != ((Double)right))); } return +1; } } internal sealed class NotEqualReference : NotEqualInstruction { public override int Run(InterpretedFrame frame) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(frame.Pop() != frame.Pop())); return +1; } } internal sealed class NotEqualBooleanLiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Boolean)left) != ((Boolean)right))); } return +1; } } internal sealed class NotEqualSByteLiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((SByte)left) != ((SByte)right))); } return +1; } } internal sealed class NotEqualInt16LiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int16)left) != ((Int16)right))); } return +1; } } internal sealed class NotEqualCharLiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Char)left) != ((Char)right))); } return +1; } } internal sealed class NotEqualInt32LiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int32)left) != ((Int32)right))); } return +1; } } internal sealed class NotEqualInt64LiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int64)left) != ((Int64)right))); } return +1; } } internal sealed class NotEqualByteLiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Byte)left) != ((Byte)right))); } return +1; } } internal sealed class NotEqualUInt16LiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt16)left) != ((UInt16)right))); } return +1; } } internal sealed class NotEqualUInt32LiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt32)left) != ((UInt32)right))); } return +1; } } internal sealed class NotEqualUInt64LiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt64)left) != ((UInt64)right))); } return +1; } } internal sealed class NotEqualSingleLiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Single)left) != ((Single)right))); } return +1; } } internal sealed class NotEqualDoubleLiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Double)left) != ((Double)right))); } return +1; } } internal sealed class NotEqualReferenceLiftedToNull : NotEqualInstruction { public override int Run(InterpretedFrame frame) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(frame.Pop() != frame.Pop())); return +1; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public static Instruction Create(Type type, bool liftedToNull) { if (liftedToNull) { // Boxed enums can be unboxed as their underlying types: switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type.GetTypeInfo().IsEnum ? Enum.GetUnderlyingType(type) : TypeUtils.GetNonNullableType(type))) { case TypeCode.Boolean: return s_booleanLiftedToNull ?? (s_booleanLiftedToNull = new NotEqualBooleanLiftedToNull()); case TypeCode.SByte: return s_SByteLiftedToNull ?? (s_SByteLiftedToNull = new NotEqualSByteLiftedToNull()); case TypeCode.Byte: return s_byteLiftedToNull ?? (s_byteLiftedToNull = new NotEqualByteLiftedToNull()); case TypeCode.Char: return s_charLiftedToNull ?? (s_charLiftedToNull = new NotEqualCharLiftedToNull()); case TypeCode.Int16: return s_int16LiftedToNull ?? (s_int16LiftedToNull = new NotEqualInt16LiftedToNull()); case TypeCode.Int32: return s_int32LiftedToNull ?? (s_int32LiftedToNull = new NotEqualInt32LiftedToNull()); case TypeCode.Int64: return s_int64LiftedToNull ?? (s_int64LiftedToNull = new NotEqualInt64LiftedToNull()); case TypeCode.UInt16: return s_UInt16LiftedToNull ?? (s_UInt16LiftedToNull = new NotEqualUInt16LiftedToNull()); case TypeCode.UInt32: return s_UInt32LiftedToNull ?? (s_UInt32LiftedToNull = new NotEqualUInt32LiftedToNull()); case TypeCode.UInt64: return s_UInt64LiftedToNull ?? (s_UInt64LiftedToNull = new NotEqualUInt64LiftedToNull()); case TypeCode.Single: return s_singleLiftedToNull ?? (s_singleLiftedToNull = new NotEqualSingleLiftedToNull()); case TypeCode.Double: return s_doubleLiftedToNull ?? (s_doubleLiftedToNull = new NotEqualDoubleLiftedToNull()); case TypeCode.String: case TypeCode.Object: if (!type.GetTypeInfo().IsValueType) { return s_referenceLiftedToNull ?? (s_referenceLiftedToNull = new NotEqualReferenceLiftedToNull()); } // TODO: Nullable<T> throw Error.ExpressionNotSupportedForNullableType("NotEqual", type); default: throw Error.ExpressionNotSupportedForType("NotEqual", type); } } else { // Boxed enums can be unboxed as their underlying types: switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type.GetTypeInfo().IsEnum ? Enum.GetUnderlyingType(type) : TypeUtils.GetNonNullableType(type))) { case TypeCode.Boolean: return s_boolean ?? (s_boolean = new NotEqualBoolean()); case TypeCode.SByte: return s_SByte ?? (s_SByte = new NotEqualSByte()); case TypeCode.Byte: return s_byte ?? (s_byte = new NotEqualByte()); case TypeCode.Char: return s_char ?? (s_char = new NotEqualChar()); case TypeCode.Int16: return s_int16 ?? (s_int16 = new NotEqualInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new NotEqualInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new NotEqualInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new NotEqualUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new NotEqualUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new NotEqualUInt64()); case TypeCode.Single: return s_single ?? (s_single = new NotEqualSingle()); case TypeCode.Double: return s_double ?? (s_double = new NotEqualDouble()); case TypeCode.String: case TypeCode.Object: if (!type.GetTypeInfo().IsValueType) { return s_reference ?? (s_reference = new NotEqualReference()); } // TODO: Nullable<T> throw Error.ExpressionNotSupportedForNullableType("NotEqual", type); default: throw Error.ExpressionNotSupportedForType("NotEqual", type); } } } public override string ToString() { return "NotEqual()"; } } }
//--------------------------------------------------------------------------- // // <copyright file=?AnnotationHighlightLayer.cs? company=?Microsoft?> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: HighlightLayer for annotations. It handles highlights // and StickyNote anchors as well. // // History: // 01/27/2005 ssimova - Created // //--------------------------------------------------------------------------- using System; using MS.Internal; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Documents; using MS.Internal.Documents; using System.Windows.Media; using MS.Internal.Text; using System.Windows.Shapes; using MS.Internal.Annotations.Anchoring; using System.Windows.Controls; namespace MS.Internal.Annotations.Component { // Highlight rendering for the Annotation highlight and sticky note anchor. internal class AnnotationHighlightLayer : HighlightLayer { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Creates a new instance of the highlight layer /// </summary> internal AnnotationHighlightLayer() { _segments = new List<HighlightSegment>(); } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// Adds a new text range to the layer /// </summary> /// <remarks> /// If the range does not overlap any of the existing segments it is added on the appropriate position /// in the _segments array - the _segments array contains non overlapping HighlightSegments sorted by ITextPointers. /// If the range overlaps some of the existing segments its IHighlightRange is added to the list of owners /// for those segments. If the input range overlaps partially some of the existing segments they will be split into /// new segments by the corresponding range end points. For the overlapping parts the IHighlightRange of the new /// range will be added. If the new range overlaps parts of existing segments and some nonhighlighted areas, new /// HighlightSegments will be generated for the nonhighlighted areas. Example: /// 1. text "1234567" has 2 HighlightSegments covereing "234" and "67" /// 2. Add a range that covers "3456" /// 3.The result will be 5 HighlightSegments - "2", "34", "5", "6" and "7". "2" and "7" will keep their original owners array. /// "5" will have only one owner - the new IHighlightRange, "34" and "6" will have their previous owners + the new one. /// </remarks> /// <param name="highlightRange">the highlight range owner</param> internal void AddRange(IHighlightRange highlightRange) { Invariant.Assert(highlightRange != null, "the owner is null"); ITextPointer start = highlightRange.Range.Start; ITextPointer end = highlightRange.Range.End; //check input data Debug.Assert(start != null, "start pointer is null"); Debug.Assert(end != null, "end pointer is null"); Debug.Assert(start.CompareTo(end) <= 0, "end pointer before start"); if (start.CompareTo(end) == 0) { //it is a 0 length highlight - do not render it return; } if (_segments.Count == 0) { //set container type object textContainer = start.TextContainer; IsFixedContainer = textContainer is FixedTextContainer || textContainer is DocumentSequenceTextContainer; } ITextPointer invalidateStart; ITextPointer invalidateEnd; ProcessOverlapingSegments(highlightRange, out invalidateStart, out invalidateEnd); //fire event - do it only for fixed to avoid disposing of the page in flow. Needs to be changed in V2. if ((Changed != null) && IsFixedContainer) { Changed(this, new AnnotationHighlightChangedEventArgs(invalidateStart, invalidateEnd)); } } /// <summary> /// RemoveRange from the highlight layer. The corresponding IHighlightRange object will be removed /// from all HighlightSegments that belong to this range. All ranges with no more owners will also be removed. /// The visual properties of ranges that have more owners might change. /// </summary> /// <param name="highlightRange">The highlight range owner</param> /// <returns>true if the range is successfuly removed</returns> internal void RemoveRange(IHighlightRange highlightRange) { Debug.Assert(highlightRange != null, "null range data"); //if range is 0 length do nothing if (highlightRange.Range.Start.CompareTo(highlightRange.Range.End) == 0) return; int startSeg; int endSeg; GetSpannedSegments(highlightRange.Range.Start, highlightRange.Range.End, out startSeg, out endSeg); //get invalidate start and end point ITextPointer invalidateStart = _segments[startSeg].Segment.Start; ITextPointer invalidateEnd = _segments[endSeg].Segment.End; for (int i = startSeg; i <= endSeg; ) { HighlightSegment highlightSegment = _segments[i]; int count = highlightSegment.RemoveOwner(highlightRange); if (count == 0) { _segments.Remove(highlightSegment); endSeg--; } else { i++; } } //TBD:Should do something against fragmentation //fire event - do it only for fixed to avoid disposing of the page in flow. Needs to be changed in V2. if ((Changed != null) && IsFixedContainer) { Changed(this, new AnnotationHighlightChangedEventArgs(invalidateStart, invalidateEnd)); } } /// <summary> /// Notifies segments and listeners that a IHighlightRange colors have been modified /// </summary> /// <param name="highlightRange">the highlight range to be modified</param> /// <returns>true if successfuly modified</returns> internal void ModifiedRange(IHighlightRange highlightRange) { Invariant.Assert(highlightRange != null, "null range data"); //if range is 0 length do nothing if (highlightRange.Range.Start.CompareTo(highlightRange.Range.End) == 0) return; int startSeg; int endSeg; GetSpannedSegments(highlightRange.Range.Start, highlightRange.Range.End, out startSeg, out endSeg); //update colors for (int seg = startSeg; seg < endSeg; seg++) { //the owners have not changed so this will only update the colors _segments[seg].UpdateOwners(); } //get invalidate start and end point ITextPointer invalidateStart = _segments[startSeg].Segment.Start; ITextPointer invalidateEnd = _segments[endSeg].Segment.End; //fire event - do it only for fixed to avoid disposing of the page in flow. Needs to be changed in V2. if ((Changed != null) && IsFixedContainer) { Changed(this, new AnnotationHighlightChangedEventArgs(invalidateStart, invalidateEnd)); } } /// <summary> /// Activate/Deactivate highlight range /// </summary> /// <param name="highlightRange">the text range to be modified</param> /// <param name="activate">true - activate, false - deactivate</param> internal void ActivateRange(IHighlightRange highlightRange, bool activate) { Invariant.Assert(highlightRange != null, "null range data"); //if range is 0 length do nothing if (highlightRange.Range.Start.CompareTo(highlightRange.Range.End) == 0) return; int startSeg; int endSeg; GetSpannedSegments(highlightRange.Range.Start, highlightRange.Range.End, out startSeg, out endSeg); //get invalidate start and end point ITextPointer invalidateStart = _segments[startSeg].Segment.Start; ITextPointer invalidateEnd = _segments[endSeg].Segment.End; //set them as active for (int i = startSeg; i <= endSeg; i++) { if (activate) _segments[i].AddActiveOwner(highlightRange); else _segments[i].RemoveActiveOwner(highlightRange); } //fire event - do it only for fixed to avoid disposing of the page in flow. Needs to be changed in V2. if ((Changed != null) && IsFixedContainer) { Changed(this, new AnnotationHighlightChangedEventArgs(invalidateStart, invalidateEnd)); } } /// <summary> /// Returns the value of a property stored on scoping highlight, if any. /// If no property value is set, returns null. /// </summary> /// <remarks> /// We scan all the segments in a loop end for each segment make two checks: /// 1. Is the textPosition before the beginning of the segment, or at the begining with /// GicalDirection.Backward. If this is true our point is before the current segment. /// We know that if it belongs to any of the previous segments the loop will stop, so that /// means the point is outside any segments - break the loop. /// 2. If the textPosition is not before the current segment, check if it is on the current segment /// or at the end with LogicalDirection.Backward. If this is true the point belongs to the /// current segment - save it and break the loop. /// </remarks> /// <param name="textPosition">position to check for</param> /// <param name="direction">logical direction</param> /// <returns></returns> internal override object GetHighlightValue(StaticTextPointer textPosition, LogicalDirection direction) { object value = DependencyProperty.UnsetValue; HighlightSegment highlightSegment = null; for (int i = 0; i < _segments.Count; i++) { highlightSegment = _segments[i]; if ((highlightSegment.Segment.Start.CompareTo(textPosition) > 0) || ((highlightSegment.Segment.Start.CompareTo(textPosition) == 0) && (direction == LogicalDirection.Backward))) { // the point is outside highlights break; } if ((highlightSegment.Segment.End.CompareTo(textPosition) > 0) || ((highlightSegment.Segment.End.CompareTo(textPosition) == 0) && (direction == LogicalDirection.Backward))) { value = highlightSegment; break; } } return value; } // Returns true if the indicated content has scoping highlights. internal override bool IsContentHighlighted(StaticTextPointer staticTextPosition, LogicalDirection direction) { return GetHighlightValue(staticTextPosition, direction) != DependencyProperty.UnsetValue; } // Returns the position of the next highlight start or end in an // indicated direction, or null if there is no such position. internal override StaticTextPointer GetNextChangePosition(StaticTextPointer textPosition, LogicalDirection direction) { ITextPointer dynamicPosition; if (direction == LogicalDirection.Forward) { dynamicPosition = GetNextForwardPosition(textPosition); } else { dynamicPosition = GetNextBackwardPosition(textPosition); } return dynamicPosition == null ? StaticTextPointer.Null : dynamicPosition.CreateStaticPointer(); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// Type identifying this layer for Highlights.GetHighlightValue calls. /// </summary> internal override Type OwnerType { get { return typeof(HighlightComponent); } } #endregion Internal Properties //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ #region Internal Events // Event raised when a highlight range is inserted, removed, moved, or // has a local property value change. internal override event HighlightChangedEventHandler Changed; #endregion Internal Events //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// Checks if the input range overlaps existing segments and splits them if needed /// </summary> /// <param name="highlightRange">range data</param> /// <param name="invalidateStart">start pointer of the invalid area</param> /// <param name="invalidateEnd">end pointer of the invalid area</param> /// <remarks>This method requires ordered nonoverlaped input segments. Otherwise it will assert.</remarks> private void ProcessOverlapingSegments(IHighlightRange highlightRange, out ITextPointer invalidateStart, out ITextPointer invalidateEnd) { Debug.Assert(highlightRange != null, " null highlight range"); ReadOnlyCollection<TextSegment> rangeSegments = highlightRange.Range.TextSegments; Debug.Assert((rangeSegments != null) && (rangeSegments.Count > 0), "invalid rangeSegments"); invalidateStart = null; invalidateEnd = null; int ind = 0; IEnumerator<TextSegment> rangeEnumerator = rangeSegments.GetEnumerator(); TextSegment rangeSegment = rangeEnumerator.MoveNext() ? rangeEnumerator.Current : TextSegment.Null; while ((ind < _segments.Count) && (!rangeSegment.IsNull)) { HighlightSegment highlightSegment = _segments[ind]; Debug.Assert(highlightSegment != null, "null highlight segment"); if (highlightSegment.Segment.Start.CompareTo(rangeSegment.Start) <= 0) { if (highlightSegment.Segment.End.CompareTo(rangeSegment.Start) > 0) { //split highlightSegment //the split method is smart enough to take care of edge cases - point on start/end of the //segment, points outside the segment etc IList<HighlightSegment> res = highlightSegment.Split(rangeSegment.Start, rangeSegment.End, highlightRange); //if the result does not contain the original segment we need to clear the owners if (!res.Contains(highlightSegment)) highlightSegment.ClearOwners(); _segments.Remove(highlightSegment); _segments.InsertRange(ind, res); ind = ind + res.Count - 1; //check if we need to move to next range segment if (rangeSegment.End.CompareTo(highlightSegment.Segment.End) <= 0) { //get next one bool next = rangeEnumerator.MoveNext(); Debug.Assert(rangeEnumerator.Current.IsNull || !next || (rangeSegment.End.CompareTo(rangeEnumerator.Current.Start) <= 0), "overlapped range segments"); rangeSegment = next ? rangeEnumerator.Current : TextSegment.Null; } else { //get the piece that is left rangeSegment = new TextSegment(highlightSegment.Segment.End, rangeSegment.End); } //set invalidateStart if needed if (invalidateStart == null) invalidateStart = highlightSegment.Segment.Start; } else { //move to next highlightsegment ind++; } } else { //set invalidateStart if needed if (invalidateStart == null) invalidateStart = rangeSegment.Start; if (rangeSegment.End.CompareTo(highlightSegment.Segment.Start) > 0) { //add the piece before the highlight segment HighlightSegment temp = new HighlightSegment(rangeSegment.Start, highlightSegment.Segment.Start, highlightRange); _segments.Insert(ind++, temp); //now our current segment is the rest of the range segment rangeSegment = new TextSegment(highlightSegment.Segment.Start, rangeSegment.End); } else { //just insert this range segment - it does not cover any highlight segnments. Increment ind //so it points to the same highlight segment _segments.Insert(ind++, new HighlightSegment(rangeSegment.Start, rangeSegment.End, highlightRange)); //get next range segment rangeSegment = rangeEnumerator.MoveNext() ? rangeEnumerator.Current : TextSegment.Null; } } } // if (!rangeSegment.IsNull) { if (invalidateStart == null) invalidateStart = rangeSegment.Start; _segments.Insert(ind++, new HighlightSegment(rangeSegment.Start, rangeSegment.End, highlightRange)); } //check if there are more rangeSegments while (rangeEnumerator.MoveNext()) { _segments.Insert(ind++, new HighlightSegment(rangeEnumerator.Current.Start, rangeEnumerator.Current.End, highlightRange)); } //set invalidateEnd if (invalidateStart != null) { if (ind == _segments.Count) ind--; invalidateEnd = _segments[ind].Segment.End; } } /// <summary> /// Gets next change position in the forward direction /// </summary> /// <param name="pos"> start position</param> /// <returns>next position if any</returns> private ITextPointer GetNextForwardPosition(StaticTextPointer pos) { for (int i = 0; i < _segments.Count; i++) { HighlightSegment highlightSegment = _segments[i]; if (pos.CompareTo(highlightSegment.Segment.Start) >= 0) { if (pos.CompareTo(highlightSegment.Segment.End) < 0) return highlightSegment.Segment.End; } else { return highlightSegment.Segment.Start; } } return null; } /// <summary> /// Gets next change position in the backward direction /// </summary> /// <param name="pos"> start position</param> /// <returns>nex position if any</returns> private ITextPointer GetNextBackwardPosition(StaticTextPointer pos) { for (int i = _segments.Count - 1; i >= 0; i--) { HighlightSegment highlightSegment = _segments[i]; if (pos.CompareTo(highlightSegment.Segment.End) <= 0) { if (pos.CompareTo(highlightSegment.Segment.Start) > 0) return highlightSegment.Segment.Start; } else { return highlightSegment.Segment.End; } } return null; } void GetSpannedSegments(ITextPointer start, ITextPointer end, out int startSeg, out int endSeg) { startSeg = -1; endSeg = -1; //add it to Highlight segments for (int i = 0; i < _segments.Count; i++) { HighlightSegment highlightSegment = _segments[i]; if (highlightSegment.Segment.Start.CompareTo(start) == 0) startSeg = i; if (highlightSegment.Segment.End.CompareTo(end) == 0) { endSeg = i; break; } } if ((startSeg < 0) || (endSeg < 0) || (startSeg > endSeg)) Debug.Assert(false, "Mismatched segment data"); } #endregion Private Methods //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ #region Private Properties private bool IsFixedContainer { get { return _isFixedContainer; } set { _isFixedContainer = value; } } #endregion Private Properties //------------------------------------------------------ // // Private Types // //------------------------------------------------------ #region Private Types // Argument for the Changed event, encapsulates a highlight change. private class AnnotationHighlightChangedEventArgs : HighlightChangedEventArgs { // Constructor. internal AnnotationHighlightChangedEventArgs(ITextPointer start, ITextPointer end) { TextSegment[] rangeArray = new TextSegment[] { new TextSegment(start, end) }; _ranges = new ReadOnlyCollection<TextSegment>(rangeArray); } // Collection of changed content ranges. internal override IList Ranges { get { return _ranges; } } // Type identifying the owner of the changed layer. internal override Type OwnerType { get { return typeof(HighlightComponent); } } // Collection of changed content ranges. private readonly ReadOnlyCollection<TextSegment> _ranges; } /// <summary> /// Represent one segment of the highlight that belongs to a particular set of owners. /// In case of overlaping highlights one HighlightSegment will be generated for each part /// that hase same set of owners. /// </summary> internal sealed class HighlightSegment : Shape { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Creates a new HighlightSegment with one owner /// </summary> /// <param name="start">start segment position</param> /// <param name="end">end segment position</param> /// <param name="owner">Owners data. Used to find the right place of this owner in the list</param> internal HighlightSegment(ITextPointer start, ITextPointer end, IHighlightRange owner) : base() { List<IHighlightRange> list = new List<IHighlightRange>(1); list.Add(owner); Init(start, end, list); _owners = list; UpdateOwners(); } /// <summary> /// Creates a new HighlightSegment with a list of owners /// </summary> /// <param name="start">start segment position</param> /// <param name="end">end segment position</param> /// <param name="owners">owners list</param> internal HighlightSegment(ITextPointer start, ITextPointer end, IList<IHighlightRange> owners) { Init(start, end, owners); //make a copy of the owners _owners = new List<IHighlightRange>(owners.Count); _owners.AddRange(owners); UpdateOwners(); } /// <summary> /// Creates a new HighlightSegment with a list of owners /// </summary> /// <param name="start">start segment position</param> /// <param name="end">end segment position</param> /// <param name="owners">owners list</param> private void Init(ITextPointer start, ITextPointer end, IList<IHighlightRange> owners) { Debug.Assert(start != null, "start pointer is null"); Debug.Assert(end != null, "end pointer is null"); Debug.Assert(owners != null, "null owners list"); Debug.Assert(owners.Count > 0, "empty owners list"); for (int i = 0; i < owners.Count; i++) Debug.Assert(owners[i] != null, "null owner"); _segment = new TextSegment(start, end); IsHitTestVisible = false; object textContainer = start.TextContainer; _isFixedContainer = textContainer is FixedTextContainer || textContainer is DocumentSequenceTextContainer; //check for tables, figures and floaters and extract the content GetContent(); } #endregion Constructors //------------------------------------------------------ // // Internal methods // //------------------------------------------------------ #region Internal methods /// <summary> /// Adds one owner to the _owners list /// </summary> /// <param name="owner">owner data</param> /// <returns></returns> internal void AddOwner(IHighlightRange owner) { //Find the right place in the list according to TimeStamp and the priority //Note: - currently we care only about priority for (int i = 0; i < _owners.Count; i++) { if (_owners[i].Priority < owner.Priority) { _owners.Insert(i, owner); UpdateOwners(); return; } } //every body has higher priority - add this at the end _owners.Add(owner); UpdateOwners(); } /// <summary> /// Removes one owner from the _owners list /// </summary> /// <param name="owner">owner data</param> /// <returns>the number of owners left for this HighlightSegment</returns> internal int RemoveOwner(IHighlightRange owner) { if (_owners.Contains(owner)) { if (_activeOwners.Contains(owner)) _activeOwners.Remove(owner); _owners.Remove(owner); UpdateOwners(); } return _owners.Count; } /// <summary> /// Adds an owner to_activeOwners list /// </summary> /// <param name="owner">owner data</param> /// <returns>the number of owners left for this HighlightSegment</returns> internal void AddActiveOwner(IHighlightRange owner) { //this must be a valid owner if (_owners.Contains(owner)) { _activeOwners.Add(owner); UpdateOwners(); } } /// <summary> /// Adds owners range to_activeOwners list /// </summary> /// <param name="owners">owner list</param> /// <returns>the number of owners left for this HighlightSegment</returns> private void AddActiveOwners(List<IHighlightRange> owners) { _activeOwners.AddRange(owners); UpdateOwners(); } /// <summary> /// Removes one owner from the _activeOwners list /// </summary> /// <param name="owner">owner data</param> /// <returns>the number of owners left for this HighlightSegment</returns> internal void RemoveActiveOwner(IHighlightRange owner) { if (_activeOwners.Contains(owner)) { _activeOwners.Remove(owner); UpdateOwners(); } } /// <summary> /// Clear all segment owners - most probably the segment will be removed /// </summary> internal void ClearOwners() { _owners.Clear(); _activeOwners.Clear(); UpdateOwners(); } /// <summary> /// Splits this HighlightSegemnt into two highlights /// </summary> /// <param name="ps">splitting position</param> /// <param name="side">On which side of the splitting point to add new owner</param> /// <returns>A list of resulting highlights. They have new TextSegments and the same set of /// owners as this</returns> internal IList<HighlightSegment> Split(ITextPointer ps, LogicalDirection side) { IList<HighlightSegment> res = null; if ((ps.CompareTo(_segment.Start) == 0) || (ps.CompareTo(_segment.End) == 0)) { if ( ((ps.CompareTo(_segment.Start) == 0) && (side == LogicalDirection.Forward)) || ((ps.CompareTo(_segment.End) == 0) && (side == LogicalDirection.Backward)) ) { res = new List<HighlightSegment>(1); res.Add(this); } } else if (_segment.Contains(ps)) { res = new List<HighlightSegment>(2); res.Add(new HighlightSegment(_segment.Start, ps, _owners)); res.Add(new HighlightSegment(ps, _segment.End, _owners)); res[0].AddActiveOwners(_activeOwners); res[1].AddActiveOwners(_activeOwners); } return res; } /// <summary> /// Splits HighlightSegment in two positions /// </summary> /// <param name="ps1">first splitting position</param> /// <param name="ps2">second splitting position</param> /// <param name="newOwner">Guid of a new owner to be added in the middle. May be null</param> /// <returns>A list of resulting HighlightSegments. They have same list of owners as this</returns> internal IList<HighlightSegment> Split(ITextPointer ps1, ITextPointer ps2, IHighlightRange newOwner) { Debug.Assert((ps1 != null) && (ps2 != null) && (ps1.CompareTo(ps2) <= 0), "invalid splitting points"); IList<HighlightSegment> res = new List<HighlightSegment>(); if (ps1.CompareTo(ps2) == 0) { //special processing for equal splitting points if ((_segment.Start.CompareTo(ps1) > 0) || (_segment.End.CompareTo(ps1) < 0)) return res; if (_segment.Start.CompareTo(ps1) < 0) { res.Add(new HighlightSegment(_segment.Start, ps1, _owners)); } //add 0-length segment res.Add(new HighlightSegment(ps1, ps1, _owners)); if (_segment.End.CompareTo(ps1) > 0) { res.Add(new HighlightSegment(ps1, _segment.End, _owners)); } //add active owners as well foreach (HighlightSegment seg in res) { seg.AddActiveOwners(_activeOwners); } } else if (_segment.Contains(ps1)) { IList<HighlightSegment> r1 = Split(ps1, LogicalDirection.Forward); for (int i = 0; i < r1.Count; i++) { if (r1[i].Segment.Contains(ps2)) { IList<HighlightSegment> r2 = r1[i].Split(ps2, LogicalDirection.Backward); for (int j = 0; j < r2.Count; j++) res.Add(r2[j]); //check if r1[i] needs to be discarded (it can be included in the split result // so we should not discard it in that case) if (!r2.Contains(r1[i])) r1[i].Discard(); } else { res.Add(r1[i]); } } } else { res = Split(ps2, LogicalDirection.Backward); } if ((res != null) && (res.Count > 0) && (newOwner != null)) { //add owner if (res.Count == 3) { //if we have 3 segments the new owner will go to the middle one res[1].AddOwner(newOwner); } else if ((res[0].Segment.Start.CompareTo(ps1) == 0) || (res[0].Segment.End.CompareTo(ps2) == 0)) { //if one of the splitting points is on the corresponding end of the first //segment it will have the new owner res[0].AddOwner(newOwner); } else { //if we have 1 segment we should go through the else above, so they must be 2 Debug.Assert(res.Count == 2, "unexpected resulting segment count after split"); res[1].AddOwner(newOwner); } } return res; } internal void UpdateOwners() { if (_cachedTopOwner != TopOwner) { //remove it from the old owner children if (_cachedTopOwner != null) _cachedTopOwner.RemoveChild(this); _cachedTopOwner = TopOwner; //add it to the new owner children if (_cachedTopOwner != null) _cachedTopOwner.AddChild(this); } Fill = OwnerColor; } /// <summary> /// this is called when this HighlightSegment will be discarded /// It has to remove itself from the TopOwner's children and empty the /// owners lists /// </summary> internal void Discard() { if (TopOwner != null) TopOwner.RemoveChild(this); _activeOwners.Clear(); _owners.Clear(); } #endregion Internal methods //------------------------------------------------------ // // Private methods // //------------------------------------------------------ #region Private methods /// <summary> /// Calculates geometry for ine TextSegment /// </summary> /// <param name="geometry">GeometryGroup to add the geometry</param> /// <param name="segment">TextSegment</param> /// <param name="parentView">TextView to which geometry has to be transformed</param> private void GetSegmentGeometry(GeometryGroup geometry, TextSegment segment, ITextView parentView) { List<ITextView> textViews = TextSelectionHelper.GetDocumentPageTextViews(segment); Debug.Assert(textViews != null, "geometry text view not found"); foreach (ITextView view in textViews) { Geometry viewGeometry = GetPageGeometry(segment, view, parentView); if (viewGeometry != null) geometry.Children.Add(viewGeometry); } } /// <summary> /// Get a geometry for a particular page and transforms it to the parent page /// </summary> /// <param name="segment">the TextSegment for which geometry we are looking</param> /// <param name="view">the page view</param> /// <param name="parentView">the parent page view</param> /// <returns></returns> private Geometry GetPageGeometry(TextSegment segment, ITextView view, ITextView parentView) { Debug.Assert((view != null) && (parentView != null), "null text view"); //in the initial layout update the TextViews might be invalid. This is OK //since there will be a second pass if (!view.IsValid || !parentView.IsValid) return null; //Debug.Assert((view.RenderScope != null) && (parentView.RenderScope != null), "null text view render scope"); if ((view.RenderScope == null) || (parentView.RenderScope == null)) return null; Geometry pageGeometry = null; pageGeometry = view.GetTightBoundingGeometryFromTextPositions(segment.Start, segment.End); if (pageGeometry != null) { if (parentView != null) { Transform additionalTransform = (Transform)view.RenderScope.TransformToVisual(parentView.RenderScope); if (pageGeometry.Transform != null) { //we need to create geometry group in this case TransformGroup group = new TransformGroup(); group.Children.Add(pageGeometry.Transform); group.Children.Add(additionalTransform); pageGeometry.Transform = group; } else { //now set the transformation pageGeometry.Transform = additionalTransform; } } } return pageGeometry; } /// <summary> /// Checks the TextSegment for tables, figures and floaters and gets the content if any /// </summary> private void GetContent() { Debug.Assert(!_segment.IsNull, "null TextSegment"); _contentSegments.Clear(); ITextPointer cursor = _segment.Start.CreatePointer(); ITextPointer segmentStart = null; while (cursor.CompareTo(_segment.End) < 0) { TextPointerContext nextContext = cursor.GetPointerContext(LogicalDirection.Forward); if (nextContext == TextPointerContext.ElementStart) { Type elementType = cursor.GetElementType(LogicalDirection.Forward); if (typeof(Run).IsAssignableFrom(elementType) || typeof(BlockUIContainer).IsAssignableFrom(elementType)) { // Open new segment if it was not opened already OpenSegment(ref segmentStart, cursor); } else if (typeof(Table).IsAssignableFrom(elementType) || typeof(Floater).IsAssignableFrom(elementType) || typeof(Figure).IsAssignableFrom(elementType)) { // Start of table encountered. Add previous segment to the collection CloseSegment(ref segmentStart, cursor, _segment.End); } cursor.MoveToNextContextPosition(LogicalDirection.Forward); if (typeof(Run).IsAssignableFrom(elementType) || typeof(BlockUIContainer).IsAssignableFrom(elementType)) {// Skip the whole element - it dos not contain Tables, Figures or Floaters cursor.MoveToElementEdge(ElementEdge.AfterEnd); } } else if (nextContext == TextPointerContext.ElementEnd) { Type elementType = cursor.ParentType; if (typeof(TableCell).IsAssignableFrom(elementType) || typeof(Floater).IsAssignableFrom(elementType) || typeof(Figure).IsAssignableFrom(elementType)) { // End of cell encountered. Add the previous segment to the collection CloseSegment(ref segmentStart, cursor, _segment.End); } // Skip the closing tag cursor.MoveToNextContextPosition(LogicalDirection.Forward); } else if (nextContext == TextPointerContext.Text || nextContext == TextPointerContext.EmbeddedElement) { // Open new segment if it was not opened already OpenSegment(ref segmentStart, cursor); // Skip the text run cursor.MoveToNextContextPosition(LogicalDirection.Forward); } else { Invariant.Assert(false, "unexpected TextPointerContext"); } } // Close the last segment CloseSegment(ref segmentStart, cursor, _segment.End); } // Opens a segment for the following portion private void OpenSegment(ref ITextPointer segmentStart, ITextPointer cursor) { if (segmentStart == null) { // Create normalized position for the segment start segmentStart = cursor.GetInsertionPosition(LogicalDirection.Forward); } } // Adds individual segment to a collection private void CloseSegment(ref ITextPointer segmentStart, ITextPointer cursor, ITextPointer end) { if (segmentStart != null) { // Check for going beyond the end if (cursor.CompareTo(end) > 0) { cursor = end; } // Create normalized position for the segment end ITextPointer segmentEnd = cursor.GetInsertionPosition(LogicalDirection.Backward); // Add segment to the collection if it is not empty if (segmentStart.CompareTo(segmentEnd) < 0) { _contentSegments.Add(new TextSegment(segmentStart, segmentEnd)); } // Close the previous segment segmentStart = null; } } #endregion Private methods #region Protected Properties /// <summary> /// Get the geometry that defines this shape /// </summary> protected override Geometry DefiningGeometry { get { //on fixed document the highlights are drawn in a different way if (_isFixedContainer) return Geometry.Empty; Debug.Assert(TopOwner != null, "invalid TopOwner"); ITextView parentView = TextSelectionHelper.GetDocumentPageTextView(TopOwner.Range.Start.CreatePointer(LogicalDirection.Forward)); Debug.Assert(parentView != null, "geometry parent text view not found"); GeometryGroup geometry = new GeometryGroup(); if (TopOwner.HighlightContent) { foreach (TextSegment segment in _contentSegments) { GetSegmentGeometry(geometry, segment, parentView); } } else { GetSegmentGeometry(geometry, _segment, parentView); } //reset render transformation of the TopOwner UIElement uie = TopOwner as UIElement; if (uie != null) uie.RenderTransform = Transform.Identity; return geometry; } } #endregion Protected Properties //------------------------------------------------------ // // Internal properties // //------------------------------------------------------ #region Internal Properties internal TextSegment Segment { get { return _segment; } } /// <summary> /// returns the IHighlightRange that is currently drawn on top of this TextSegment /// </summary> internal IHighlightRange TopOwner { get { if (_activeOwners.Count != 0) return _activeOwners[0]; else //TBD implement Z order return _owners.Count > 0 ? _owners[0] : null; } } #endregion Internal Properties //------------------------------------------------------ // // Private properties // //------------------------------------------------------ #region Private Properties /// <summary> /// Creates a background Brush for this segment that reflects the properties /// and Z order of the owners /// </summary> private Brush OwnerColor { get { if (_activeOwners.Count != 0) return new SolidColorBrush(_activeOwners[0].SelectedBackground); else //TBD implement Z order return _owners.Count > 0 ? new SolidColorBrush(_owners[0].Background) : null; } } #endregion Private Properties //------------------------------------------------------ // // Private fields // //------------------------------------------------------ #region Private fields private TextSegment _segment; private List<TextSegment> _contentSegments = new List<TextSegment>(1); private readonly List<IHighlightRange> _owners; private List<IHighlightRange> _activeOwners = new List<IHighlightRange>(); private IHighlightRange _cachedTopOwner = null; private bool _isFixedContainer; #endregion Private fields } #endregion Private Types //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields /// <summary> /// A list of all HiglightSegments ordered by position /// </summary> List<HighlightSegment> _segments; bool _isFixedContainer = false; #endregion Private Fields } }
#region CVS Log /* * Version: * $Id: ID3v2Frame.cs,v 1.10 2004/11/20 23:12:13 cwoodbury Exp $ * * Revisions: * $Log: ID3v2Frame.cs,v $ * Revision 1.10 2004/11/20 23:12:13 cwoodbury * Removed TextEncodingType.ASCII type; replaced with ISO_8859_1 type * or default type for EncodedString. * * Revision 1.9 2004/11/16 07:09:49 cwoodbury * Added wrappers to FrameRegistry's wrappers to simplify usage for clients. * * Revision 1.8 2004/11/11 09:40:06 cwoodbury * Fixed bug in frame-parsing. * * Revision 1.7 2004/11/10 07:32:29 cwoodbury * Factored out ParseFrameData() into ID3v2Frame. * * Revision 1.6 2004/11/10 06:51:55 cwoodbury * Hid CVS log messages away in #region * * Revision 1.5 2004/11/10 06:31:14 cwoodbury * Updated documentation. * * Revision 1.4 2004/11/10 04:44:16 cwoodbury * Updated documentation. * * Revision 1.3 2004/11/03 08:19:33 cwoodbury * Updated documentation. * * Revision 1.2 2004/11/03 06:49:17 cwoodbury * Fixed bug with size * * Revision 1.1 2004/11/03 01:18:07 cwoodbury * Added to ID3Sharp * */ #endregion /* * Author(s): * Chris Woodbury * * Project Location: * http://id3sharp.sourceforge.net * * License: * Licensed under the Open Software License version 2.0 */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using ID3Sharp.Exceptions; using ID3Sharp.Frames; using ID3Sharp.IO; namespace ID3Sharp.Models { /// <summary> /// An abstract ID3v2 frame. /// </summary> public abstract class ID3v2Frame { #region Constants /// <summary>A constant for the length (in bytes) of an ID3v2.2 frame header.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")] protected const int ID3V2_2FrameHeaderLength = 6; /// <summary>A constant for the length (in bytes) of an ID3v2.3 frame header.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_3FrameHeaderLength = 10; /// <summary>A constant for the length (in bytes) of an ID3v2.4 frame header.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_4FrameHeaderLength = 10; /// <summary>A constant for the length (in bytes) of an ID3v2.2 frame ID.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_2FrameIdFieldLength = 3; /// <summary>A constant for the length (in bytes) of an ID3v2.3 frame ID.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_3FrameIdFieldLength = 4; /// <summary>A constant for the length (in bytes) of an ID3v2.4 frame ID.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_4FrameIdFieldLength = 4; /// <summary>A constant for the length (in bytes) of an ID3v2.2 frame size field.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_2FrameSizeFieldLength = 3; /// <summary>A constant for the length (in bytes) of an ID3v2.3 frame size field.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_3FrameSizeFieldLength = 4; /// <summary>A constant for the length (in bytes) of an ID3v2.4 frame size field.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_4FrameSizeFieldLength = 4; /// <summary>A constant for the length (in bytes) of an ID3v2.2 flags field.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_2FrameFlagsField = 0; /// <summary>A constant for the length (in bytes) of an ID3v2.3 flags field.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_3FrameFlagsField = 2; /// <summary>A constant for the length (in bytes) of an ID3v2.4 flags field.</summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] protected const int ID3V2_4FrameFlagsField = 2; #endregion #region Fields /// <summary> /// The type of this frame. /// </summary> private FrameType frameType; /// <summary> /// The header flags for this frame. /// </summary> private FrameHeaderFlagsV2_4 headerFlags; #endregion #region Constructors /// <summary> /// Creates a new ID3v2Frame with unknown frame type. /// </summary> protected ID3v2Frame() { frameType = FrameType.Unknown; } /// <summary> /// Copy constructor. /// </summary> /// <param name="frame">Frame to copy.</param> protected ID3v2Frame( ID3v2Frame frame ) { this.frameType = frame.frameType; this.headerFlags = frame.headerFlags; } #endregion #region Constructor/Initialize helper methods /// <summary> /// Parses the frame header flags. /// </summary> /// <param name="flagBytes">The frame header flags.</param> /// <param name="version">The ID3 version of the tag being parsed.</param> private void ParseFlags( byte[] flagBytes, ID3Versions version ) { int frameStatus; int frameFormat; switch ( version ) { case ID3Versions.V2_2: // do nothing - no flags in v2.2 break; case ID3Versions.V2_3: frameStatus = (int) flagBytes[0]; frameFormat = (int) flagBytes[1]; frameStatus = frameStatus << 8; headerFlags = ConvertFlags( (FrameHeaderFlagsV2_3) frameStatus + frameFormat ); break; case ID3Versions.V2_4: frameStatus = (int) flagBytes[0]; frameFormat = (int) flagBytes[1]; frameStatus = frameStatus << 8; headerFlags = (FrameHeaderFlagsV2_4) frameStatus + frameFormat; break; default: throw new UnsupportedVersionException( version ); } } /// <summary> /// Parses the raw frame data. /// </summary> /// <param name="frameData">The raw frame data.</param> /// <param name="version">The ID3 version of the tag being parsed.</param> protected abstract void ParseFrameData( byte[] frameData, ID3Versions version ); #endregion #region Factory Methods /// <summary> /// Returns the frame ID for the given FrameType and version. /// </summary> /// <param name="frameType">The FrameType to look up.</param> /// <param name="version">The ID3v2 version to use.</param> /// <returns>The frame ID for the given FrameType and version.</returns> public static string GetFrameId( FrameType frameType, ID3Versions version ) { return FrameRegistry.GetFrameId( frameType, version ); } /// <summary> /// Returns the FrameType for the given frame ID and version. /// </summary> /// <param name="frameId">The frame ID string to look up.</param> /// <param name="version">The ID3v2 version to use.</param> /// <returns>The frame ID for the given FrameType and version.</returns> public static FrameType GetFrameType( string frameId, ID3Versions version ) { return FrameRegistry.GetFrameType( frameId, version ); } /// <summary> /// Returns a new frame of the given type. /// </summary> /// <param name="frameType">The type of frame to return.</param> /// <returns>A new frame of the given type.</returns> public static ID3v2Frame GetNewFrame( FrameType frameType ) { return FrameRegistry.GetNewFrame( frameType ); } #endregion #region Properties /// <summary> /// Gets and sets the FrameType of this frame. /// </summary> public FrameType Type { get { return frameType; } set { frameType = value; } } /// <summary> /// Gets the size (in bytes, not including header) of the frame. /// </summary> public abstract int Size { get; } /// <summary> /// The header flags for this frame. /// </summary> public FrameHeaderFlagsV2_4 HeaderFlags { get { return headerFlags; } } #endregion #region Public Methods /// <summary> /// Gets the total size (in bytes, including header) of this frame for the given /// ID3v2 version. /// </summary> /// <param name="version">The format to be used in determing the frame size.</param> /// <returns>The total size (including header) of this frame for the given /// ID3v2 version.</returns> public virtual int GetTotalSize( ID3Versions version ) { int frameHeaderLength = 0; switch ( version ) { case ID3Versions.V2_2: frameHeaderLength = ID3V2_2FrameHeaderLength; break; case ID3Versions.V2_3: frameHeaderLength = ID3V2_3FrameHeaderLength; break; case ID3Versions.V2_4: frameHeaderLength = ID3V2_4FrameHeaderLength; break; } return this.Size + frameHeaderLength; } /// <summary> /// Returns a copy of this frame. Supports the prototype design pattern. /// </summary> /// <returns>A copy of this frame.</returns> public abstract ID3v2Frame Copy(); /// <summary> /// Initializes the frame. Supports the prototype design pattern. /// </summary> /// <param name="flags">The frame header flags for this frame.</param> /// <param name="frameData">The raw data in the frame's data section.</param> /// <param name="version">The ID3v2 version of the tag being parsed.</param> public virtual void Initialize( byte[] flags, byte[] frameData, ID3Versions version) { ParseFlags( flags, version ); ParseFrameData( frameData, version ); } #endregion #region Protected Methods public abstract void Validate( ID3Versions version ); #endregion #region Frame-Writing Methods /// <summary> /// Writes the frame to a stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="version">The ID3v2 version to use in writing the frame.</param> public abstract void WriteToStream( Stream stream, ID3Versions version ); /// <summary> /// Writes the header for this frame to a stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="version">The ID3v2 version to use in writing the frame.</param> protected void WriteHeaderToStream( Stream stream, ID3Versions version ) { if ( stream == null ) { throw new ArgumentNullException( "stream" ); } if ( (version & ID3Versions.V2) == ID3Versions.V2 ) { string frameIDString = FrameRegistry.GetFrameId( this.frameType, version ); if ( frameIDString == null ) { throw new UnsupportedVersionException( version ); } EncodedString frameID = new EncodedString( TextEncodingType.ISO_8859_1, frameIDString ); frameID.IsTerminated = false; frameID.HasEncodingTypePrepended = false; frameID.WriteToStream( stream ); WriteFrameSize( stream, version ); WriteFlags( stream, version ); stream.Flush(); } else { throw new UnsupportedVersionException( version ); } } /// <summary> /// Writes the header flags for this frame to a stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="version">The ID3v2 version to use in writing the frame.</param> protected void WriteFlags( Stream stream, ID3Versions version ) { if ( stream == null ) { throw new ArgumentNullException( "stream" ); } byte formatByte; byte statusByte; switch ( version ) { case ID3Versions.V2_2: break; case ID3Versions.V2_3: FrameHeaderFlagsV2_3 flags2_3 = ConvertFlags( this.HeaderFlags ); formatByte = (byte) flags2_3; statusByte = (byte) ( ((int) flags2_3) >> 8 ); stream.WriteByte( statusByte ); stream.WriteByte( formatByte ); break; case ID3Versions.V2_4: formatByte = (byte) this.HeaderFlags; statusByte = (byte) ( ((int) this.HeaderFlags) >> 8 ); stream.WriteByte( statusByte ); stream.WriteByte( formatByte ); break; default: throw new UnsupportedVersionException( version ); } } /// <summary> /// Writes the size field for this frame to a stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="version">The ID3v2 version to use in writing the frame.</param> protected void WriteFrameSize( Stream stream, ID3Versions version ) { if ( stream == null ) { throw new ArgumentNullException( "stream" ); } switch ( version ) { case ID3Versions.V2_2: stream.Write( EncodedInteger.ToBytes( this.Size, ID3V2_2FrameSizeFieldLength ), 0, ID3V2_2FrameSizeFieldLength ); break; case ID3Versions.V2_3: stream.Write( EncodedInteger.ToBytes( this.Size, ID3V2_3FrameSizeFieldLength ), 0, ID3V2_3FrameSizeFieldLength ); break; case ID3Versions.V2_4: stream.Write( SynchsafeInteger.Synchsafe( this.Size ), 0, ID3V2_4FrameSizeFieldLength ); break; default: throw new UnsupportedVersionException( version ); } } #endregion #region Frame-Reading Methods /// <summary> /// Reads and returns a frame from a stream. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="version">The ID3v2 version of the tag being parsed.</param> /// <returns>The frame read from the stream.</returns> public static ID3v2Frame ReadFrame( Stream stream, ID3Versions version ) { if ( stream == null ) { throw new ArgumentNullException( "stream" ); } ID3v2Frame frame = null; FrameParameters parameters = new FrameParameters( version ); byte[] header = new byte[ parameters.HeaderLength ]; char[] idChars = new char[ parameters.IDLength ]; byte[] sizeBytes = new byte[ parameters.SizeLength ]; byte[] flags = new byte[ parameters.FlagsLength ]; byte[] frameData; string frameID; int size; stream.Read( header, 0, header.Length ); Array.Copy( header, 0, idChars, 0, idChars.Length ); Array.Copy( header, parameters.IDLength, sizeBytes, 0, sizeBytes.Length ); Array.Copy( header, parameters.IDLength + parameters.SizeLength, flags, 0, flags.Length ); if ( idChars[0] != 0x0 ) { frameID = new String( idChars ); if ( parameters.SizeIsSynchSafe ) { size = SynchsafeInteger.UnSynchsafe( sizeBytes ); } else { size = EncodedInteger.ToInt( sizeBytes ); } frameData = new byte[ size ]; stream.Read( frameData, 0, frameData.Length ); FrameType frameType = FrameRegistry.GetFrameType( frameID, version ); frame = FrameRegistry.GetNewFrame( frameType ); frame.Initialize( flags, frameData, version ); } else { frame = null; } return frame; } #endregion #region Reading/Writing Helper Methods /// <summary> /// Converts ID3v2.4 frame header flags to ID3v2.3 frame header flags. /// WARNING: This may cause a loss of data. /// </summary> /// <param name="flags2_4">ID3v2.4 frame header flags to convert.</param> /// <returns>Converted ID3v2.3 frame header flags.</returns> private FrameHeaderFlagsV2_3 ConvertFlags( FrameHeaderFlagsV2_4 flags2_4 ) { FrameHeaderFlagsV2_3 flags2_3 = FrameHeaderFlagsV2_3.None; if ( HasFlag( flags2_4, FrameHeaderFlagsV2_4.TagAlterPreservation ) ) { flags2_3 |= FrameHeaderFlagsV2_3.TagAlterPreservation; } if ( HasFlag( flags2_4, FrameHeaderFlagsV2_4.FileAlterPreservation ) ) { flags2_3 |= FrameHeaderFlagsV2_3.FileAlterPreservation; } if ( HasFlag( flags2_4, FrameHeaderFlagsV2_4.ReadOnly ) ) { flags2_3 |= FrameHeaderFlagsV2_3.ReadOnly; } if ( HasFlag( flags2_4, FrameHeaderFlagsV2_4.Compression ) ) { flags2_3 |= FrameHeaderFlagsV2_3.Compression; } if ( HasFlag( flags2_4, FrameHeaderFlagsV2_4.Encryption ) ) { flags2_3 |= FrameHeaderFlagsV2_3.Encryption; } return flags2_3; } /// <summary> /// Converts ID3v2.3 frame header flags to ID3v2.4 frame header flags. /// </summary> /// <param name="flags2_3">ID3v2.3 frame header flags to convert.</param> /// <returns>Converted ID3v2.4 frame header flags.</returns> private FrameHeaderFlagsV2_4 ConvertFlags( FrameHeaderFlagsV2_3 flags2_3 ) { FrameHeaderFlagsV2_4 flags2_4 = FrameHeaderFlagsV2_4.None; if ( HasFlag( flags2_3, FrameHeaderFlagsV2_3.TagAlterPreservation ) ) { flags2_4 |= FrameHeaderFlagsV2_4.TagAlterPreservation; } if ( HasFlag( flags2_3, FrameHeaderFlagsV2_3.FileAlterPreservation ) ) { flags2_4 |= FrameHeaderFlagsV2_4.FileAlterPreservation; } if ( HasFlag( flags2_3, FrameHeaderFlagsV2_3.ReadOnly ) ) { flags2_4 |= FrameHeaderFlagsV2_4.ReadOnly; } if ( HasFlag( flags2_3, FrameHeaderFlagsV2_3.Compression ) ) { flags2_4 |= FrameHeaderFlagsV2_4.Compression; } if ( HasFlag( flags2_3, FrameHeaderFlagsV2_3.Encryption ) ) { flags2_4 |= FrameHeaderFlagsV2_4.Encryption; } return flags2_4; } /// <summary> /// Returns true if flagSet contains flagToCheck; false otherwise. /// </summary> /// <param name="flagSet">A set of flags.</param> /// <param name="flagToCheck">A flag to be checked for.</param> /// <returns>True if flagSet contains flagToCheck; false otherwise.</returns> private bool HasFlag( FrameHeaderFlagsV2_4 flagSet, FrameHeaderFlagsV2_4 flagToCheck ) { return ( (flagSet & flagToCheck) == flagToCheck ); } /// <summary> /// Returns true if flagSet contains flagToCheck; false otherwise. /// </summary> /// <param name="flagSet">A set of flags.</param> /// <param name="flagToCheck">A flag to be checked for.</param> /// <returns>True if flagSet contains flagToCheck; false otherwise.</returns> private bool HasFlag( FrameHeaderFlagsV2_3 flagSet, FrameHeaderFlagsV2_3 flagToCheck ) { return ( (flagSet & flagToCheck) == flagToCheck ); } #endregion private class FrameParameters { public int HeaderLength; public int IDLength; public int SizeLength; public int FlagsLength; public bool SizeIsSynchSafe; [SuppressMessage( "Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily" )] public FrameParameters( ID3Versions version ) { switch ( version ) { case ID3Versions.V2_2: HeaderLength = ID3V2_2FrameHeaderLength; IDLength = ID3V2_2FrameIdFieldLength; SizeLength = ID3V2_2FrameSizeFieldLength; FlagsLength = ID3V2_2FrameFlagsField; SizeIsSynchSafe = false; break; case ID3Versions.V2_3: HeaderLength = ID3V2_3FrameHeaderLength; IDLength = ID3V2_3FrameIdFieldLength; SizeLength = ID3V2_3FrameSizeFieldLength; FlagsLength = ID3V2_3FrameFlagsField; SizeIsSynchSafe = false; break; case ID3Versions.V2_4: HeaderLength = ID3V2_4FrameHeaderLength; IDLength = ID3V2_4FrameIdFieldLength; SizeLength = ID3V2_4FrameSizeFieldLength; FlagsLength = ID3V2_4FrameFlagsField; SizeIsSynchSafe = true; break; default: throw new UnsupportedVersionException( version ); } } } } #region Frame Header Flag enums /// <summary> /// The set of ID3v2.3 frame header flags. /// </summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] [Flags] public enum FrameHeaderFlagsV2_3 : int { /// <summary>Frame status byte, bit 7</summary> TagAlterPreservation = 32768, /// <summary>Frame status byte, bit 6</summary> FileAlterPreservation = 16384, /// <summary>Frame status byte, bit 5</summary> ReadOnly = 8192, /// <summary>Frame format byte, bit 7</summary> Compression = 128, /// <summary>Frame format byte, bit 6</summary> Encryption = 64, /// <summary>Frame format byte, bit 5</summary> GroupingIdentity = 32, /// <summary>No flags set.</summary> None = 0 }; /// <summary> /// The set of ID3v2.4 frame header flags. /// </summary> [SuppressMessage( "Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores" )] [Flags] public enum FrameHeaderFlagsV2_4 : int { // Frame status flags /// <summary>Frame status byte, bit 6</summary> TagAlterPreservation = 16384, /// <summary>Frame status byte, bit 5</summary> FileAlterPreservation = 8192, /// <summary>Frame status byte, bit 4</summary> ReadOnly = 4096, // Frame format flags /// <summary>Frame format byte, bit 6</summary> GroupingIdentity = 64, /// <summary>Frame format byte, bit 3</summary> Compression = 8, /// <summary>Frame format byte, bit 2</summary> Encryption = 4, /// <summary>Frame format byte, bit 1</summary> Unsynchronization = 2, /// <summary>Frame format byte, bit 0</summary> DataLengthIndicator = 1, /// <summary>No flags set.</summary> None = 0 }; #endregion }
using System; using System.Collections.Generic; using System.Linq; using Qwack.Core.Basic; using Qwack.Dates; using Qwack.Transport.BasicTypes; namespace Qwack.Core.Instruments.Funding { public class GenericSwapLeg { public GenericSwapLeg() { } public GenericSwapLeg(DateTime startDate, DateTime endDate, Calendar calendars, Currency currency, Frequency resetFrequency, DayCountBasis dayBasis) { EffectiveDate = startDate; TerminationDate = new TenorDateAbsolute(endDate); ResetFrequency = resetFrequency; Currency = currency; SetAllCalendars(calendars); AccrualDCB = dayBasis; } public GenericSwapLeg(DateTime startDate, Frequency tenor, Calendar calendars, Currency currency, Frequency resetFrequency, DayCountBasis dayBasis) { EffectiveDate = startDate; TerminationDate = new TenorDateRelative(tenor); ResetFrequency = resetFrequency; Currency = currency; SetAllCalendars(calendars); AccrualDCB = dayBasis; } private void SetAllCalendars(Calendar calendars) { FixingCalendar = calendars; AccrualCalendar = calendars; ResetCalendar = calendars; PaymentCalendar = calendars; } public Currency Currency { get; set; } public DateTime EffectiveDate { get; set; } public ITenorDate TerminationDate { get; set; } public Calendar FixingCalendar { get; set; } public Calendar ResetCalendar { get; set; } public Calendar AccrualCalendar { get; set; } public Calendar PaymentCalendar { get; set; } public RollType ResetRollType { get; set; } = RollType.ModFollowing; public RollType PaymentRollType { get; set; } = RollType.Following; public RollType FixingRollType { get; set; } = RollType.Previous; public string RollDay { get; set; } = "Termination"; public StubType StubType { get; set; } = StubType.ShortFront; public Frequency ResetFrequency { get; set; } public Frequency FixingOffset { get; set; } = new Frequency("2b"); public Frequency ForecastTenor { get; set; } public SwapLegType LegType { get; set; } public Frequency PaymentOffset { get; set; } = 0.Bd(); public OffsetRelativeToType PaymentOffsetRelativeTo { get; set; } = OffsetRelativeToType.PeriodEnd; public decimal FixedRateOrMargin { get; set; } public decimal Nominal { get; set; } = 1e6M; public DayCountBasis AccrualDCB { get; set; } public FraDiscountingType FraDiscounting { get; set; } public AverageType AveragingType { get; set; } public ExchangeType NotionalExchange { get; set; } public SwapPayReceiveType Direction { get; set; } public GenericSwapLeg Clone() => new() { AccrualCalendar = AccrualCalendar, AccrualDCB = AccrualDCB, AveragingType = AveragingType, Currency = Currency, Direction = Direction, EffectiveDate = EffectiveDate, FixedRateOrMargin = FixedRateOrMargin, FixingCalendar = FixingCalendar, FixingOffset = FixingOffset, FixingRollType = FixingRollType, ForecastTenor = ForecastTenor, FraDiscounting = FraDiscounting, LegType = LegType, Nominal = Nominal, NotionalExchange = NotionalExchange, PaymentCalendar = PaymentCalendar, PaymentOffset = PaymentOffset, PaymentOffsetRelativeTo = PaymentOffsetRelativeTo, PaymentRollType = PaymentRollType, ResetCalendar = ResetCalendar, ResetFrequency = ResetFrequency, ResetRollType = ResetRollType, RollDay = RollDay, StubType = StubType, TerminationDate = TerminationDate, }; public CashFlowSchedule GenerateSchedule() { var startDate = EffectiveDate; var endDate = TerminationDate.Date(startDate, ResetRollType, ResetCalendar); var f = new CashFlowSchedule(); var lf = new List<CashFlow>(); if (NotionalExchange == ExchangeType.FrontOnly || NotionalExchange == ExchangeType.Both) { lf.Add(new CashFlow { Notional = (double)Nominal * (Direction == SwapPayReceiveType.Payer ? -1.0 : 1.0), Fv = (double)Nominal * (Direction == SwapPayReceiveType.Payer ? -1.0 : 1.0), SettleDate = startDate, YearFraction = 1.0, Dcf = 1.0, FlowType = FlowType.FixedAmount }); } //need to handle stub types and roll day types switch (StubType) { case StubType.ShortFront: case StubType.LongFront: { var nQ = 0; var currentReset = GetNextResetDate(endDate, false); while (GetNextResetDate(currentReset, false) >= startDate) { var q = new CashFlow() { ResetDateStart = currentReset, AccrualPeriodStart = currentReset, FixingDateStart = currentReset.SubtractPeriod(FixingRollType, FixingCalendar, FixingOffset), AccrualPeriodEnd = currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency) }; q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ? q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) : q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset); q.YearFraction = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ? q.AccrualPeriodStart.CalculateYearFraction(q.AccrualPeriodEnd, AccrualDCB) : 1.0; q.Dcf = q.YearFraction; q.Fv = (LegType == SwapLegType.Fixed) ? (double)Nominal * q.YearFraction * (double)FixedRateOrMargin : 0; q.FixedRateOrMargin = (double)FixedRateOrMargin; q.FlowType = (LegType == SwapLegType.Fixed) ? FlowType.FixedRate : FlowType.FloatRate; q.Notional = (double)Nominal; lf.Add(q); nQ++; currentReset = GetNextResetDate(currentReset, false); } if (lf.Count == 0 || lf.Last().AccrualPeriodStart != startDate) { if (StubType == StubType.LongFront) { var Q = lf.Last(); Q.ResetDateStart = startDate; Q.AccrualPeriodStart = startDate; Q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ? Q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) : Q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset); Q.Dcf = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ? Q.AccrualPeriodStart.CalculateYearFraction(Q.AccrualPeriodEnd, AccrualDCB) : 1.0; } else { var q = new CashFlow() { AccrualPeriodStart = startDate, FixingDateStart = startDate.SubtractPeriod(FixingRollType, FixingCalendar, FixingOffset), AccrualPeriodEnd = (lf.Count > 0 && lf.Last().AccrualPeriodEnd!=DateTime.MinValue )? lf.Last().AccrualPeriodStart : endDate }; q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ? q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) : q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset); //Q.Currency = CCY; q.YearFraction = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ? q.AccrualPeriodStart.CalculateYearFraction(q.AccrualPeriodEnd, AccrualDCB) : 1.0; q.Dcf = q.YearFraction; q.Fv = (LegType == SwapLegType.Fixed) ? (double)Nominal * q.YearFraction * (double)FixedRateOrMargin : 0; q.FixedRateOrMargin = (double)FixedRateOrMargin; q.FlowType = (LegType == SwapLegType.Fixed) ? FlowType.FixedRate : FlowType.FloatRate; q.Notional = (double)Nominal; lf.Add(q); nQ++; } } break; } case StubType.ShortBack: case StubType.LongBack: { var nQ = 0; var currentReset = startDate; while (GetNextResetDate(currentReset, true) <= endDate) { var Q = new CashFlow() { AccrualPeriodStart = currentReset, FixingDateStart = currentReset.SubtractPeriod(FixingRollType, FixingCalendar, FixingOffset), AccrualPeriodEnd = currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency) }; Q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ? Q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) : Q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset); //Q.Currency = CCY; Q.YearFraction = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ? Q.AccrualPeriodStart.CalculateYearFraction(Q.AccrualPeriodEnd, AccrualDCB) : 1.0; Q.Dcf = Q.YearFraction; Q.Notional = (double)Nominal; Q.Fv = (LegType == SwapLegType.Fixed) ? (double)Nominal * Q.YearFraction * (double)FixedRateOrMargin : 0; Q.FixedRateOrMargin = (double)FixedRateOrMargin; Q.FlowType = (LegType == SwapLegType.Fixed) ? FlowType.FixedRate : FlowType.FloatRate; lf.Add(Q); nQ++; currentReset = GetNextResetDate(currentReset, false); } if (lf.Last().AccrualPeriodEnd != endDate) { if (StubType == StubType.LongBack) { var Q = lf.Last(); Q.AccrualPeriodEnd = endDate; Q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ? Q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) : Q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset); Q.Dcf = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ? Q.AccrualPeriodStart.CalculateYearFraction(Q.AccrualPeriodEnd, AccrualDCB) : 1.0; } else { var Q = new CashFlow() { AccrualPeriodStart = lf.Last().AccrualPeriodEnd, FixingDateStart = startDate.SubtractPeriod(FixingRollType, FixingCalendar, FixingOffset), AccrualPeriodEnd = endDate }; Q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ? Q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) : Q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset); //Q.Currency = CCY; Q.YearFraction = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ? Q.AccrualPeriodStart.CalculateYearFraction(Q.AccrualPeriodEnd, AccrualDCB) : 1.0; Q.Notional = (double)Nominal; Q.Dcf = Q.YearFraction; Q.Fv = (LegType == SwapLegType.Fixed) ? (double)Nominal * Q.YearFraction * (double)FixedRateOrMargin : 0; Q.FixedRateOrMargin = (double)FixedRateOrMargin; Q.FlowType = (LegType == SwapLegType.Fixed) ? FlowType.FixedRate : FlowType.FloatRate; Q.Notional = (double)Nominal; lf.Add(Q); nQ++; } } break; } case StubType.LongBoth: case StubType.ShortBoth: throw new NotImplementedException("Schedules with Both type stubs cannot be generated"); } if (NotionalExchange == ExchangeType.BackOnly || NotionalExchange == ExchangeType.Both) { lf.Add(new CashFlow { Notional = (double)Nominal * (Direction == SwapPayReceiveType.Receiver ? -1.0 : 1.0), Fv = (double)Nominal * (Direction == SwapPayReceiveType.Receiver ? -1.0 : 1.0), SettleDate = endDate, YearFraction = 1.0, Dcf = 1.0, FlowType = FlowType.FixedAmount }); } f.Flows = lf.OrderBy(x => x.AccrualPeriodStart).ToList(); return f; } private DateTime GetNextResetDate(DateTime currentReset, bool fwdDirection) { if (RollDay == "IMM") return fwdDirection ? currentReset.GetNextImmDate() : currentReset.GetPrevImmDate(); if (RollDay == "EOM") if (fwdDirection) { var d1 = currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency); return d1.LastDayOfMonth().AddPeriod(RollType.P, ResetCalendar, 0.Bd()); } else { var d1 = currentReset.SubtractPeriod(ResetRollType, ResetCalendar, ResetFrequency); return d1.LastDayOfMonth().AddPeriod(RollType.P, ResetCalendar, 0.Bd()); } if (int.TryParse(RollDay, out var rollOut)) if (fwdDirection) { var d1 = currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency); return new DateTime(d1.Year, d1.Month, rollOut).AddPeriod(ResetRollType, ResetCalendar, 0.Bd()); } else { var d1 = currentReset.SubtractPeriod(ResetRollType, ResetCalendar, ResetFrequency); return new DateTime(d1.Year, d1.Month, rollOut).AddPeriod(ResetRollType, ResetCalendar, 0.Bd()); } return fwdDirection ? currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency) : currentReset.SubtractPeriod(ResetRollType, ResetCalendar, ResetFrequency); } } }
namespace MbUnit.Framework.Tests.Asserts.XmlUnit { using MbUnit.Framework; using MbUnit.Framework.Xml; using MbUnit.Core.Exceptions; using System.IO; [TestFixture] public class XmlAssertionTests { private string _xmlTrueTest; private string _xmlFalseTest; [TestFixtureSetUp] public void StartTest() { _xmlTrueTest = "<assert>true</assert>"; _xmlFalseTest = "<assert>false</assert>"; } #region XmlEquals [Test] public void XmlEqualsWithTextReader() { XmlAssert.XmlEquals(new StringReader(_xmlTrueTest), new StringReader(_xmlTrueTest)); } [Test, ExpectedException(typeof(NotEqualAssertionException))] public void XmlEqualsWithTextReaderFail() { XmlAssert.XmlEquals(new StringReader(_xmlTrueTest), new StringReader(_xmlFalseTest)); } [Test] public void XmlEqualsWithString() { XmlAssert.XmlEquals(_xmlTrueTest, _xmlTrueTest); } [Test, ExpectedException(typeof(NotEqualAssertionException))] public void XmlEqualsWithStringFail() { XmlAssert.XmlEquals(_xmlTrueTest, _xmlFalseTest); } [Test] public void XmlEqualsWithXmlInput() { XmlAssert.XmlEquals(new XmlInput(_xmlTrueTest), new XmlInput(_xmlTrueTest)); } [Test, ExpectedException(typeof(NotEqualAssertionException))] public void XmlEqualsWithXmlInputFail() { XmlAssert.XmlEquals(new XmlInput(_xmlTrueTest), new XmlInput(_xmlFalseTest)); } [Test] public void XmlEqualsWithXmlDiff() { XmlAssert.XmlEquals(new XmlDiff(_xmlTrueTest, _xmlTrueTest)); } [Test, ExpectedException(typeof(NotEqualAssertionException))] public void XmlEqualsWithXmlDiffFail() { XmlAssert.XmlEquals(new XmlDiff(new XmlInput(_xmlTrueTest), new XmlInput(_xmlFalseTest))); } [RowTest] [Row("Optional Description", "Optional Description")] [Row("", "Xml does not match")] [Row("XmlDiff", "Xml does not match")] public void XmlEqualsWithXmlDiffFail_WithDiffConfiguration(string optionalDesciption, string expectedMessage) { try { XmlAssert.XmlEquals(new XmlDiff(new XmlInput(_xmlTrueTest), new XmlInput(_xmlFalseTest), new DiffConfiguration(optionalDesciption))); } catch (AssertionException e) { Assert.AreEqual(true, e.Message.StartsWith(expectedMessage)); } } [Test] public void XmlEqualsWithXmlDiffFail_WithNullOptionalDescription() { try { XmlAssert.XmlEquals(new XmlDiff(new XmlInput(_xmlTrueTest), new XmlInput(_xmlFalseTest), new DiffConfiguration(null))); } catch (AssertionException e) { Assert.AreEqual(true, e.Message.StartsWith("Xml does not match")); } } #endregion [Test] public void AssertStringEqualAndIdenticalToSelf() { string control = _xmlTrueTest; string test = _xmlTrueTest; XmlAssert.XmlIdentical(control, test); XmlAssert.XmlEquals(control, test); } [Test] public void AssertDifferentStringsNotEqualNorIdentical() { string control = "<assert>true</assert>"; string test = "<assert>false</assert>"; XmlDiff xmlDiff = new XmlDiff(control, test); XmlAssert.XmlNotIdentical(xmlDiff); XmlAssert.XmlNotEquals(xmlDiff); } [Test] public void AssertXmlIdenticalUsesOptionalDescription() { string description = "An Optional Description"; try { XmlDiff diff = new XmlDiff(new XmlInput("<a/>"), new XmlInput("<b/>"), new DiffConfiguration(description)); XmlAssert.XmlIdentical(diff); } catch (AssertionException e) { Assert.AreEqual(true, e.Message.StartsWith(description)); } } [Test] public void AssertXmlEqualsUsesOptionalDescription() { string description = "Another Optional Description"; try { XmlDiff diff = new XmlDiff(new XmlInput("<a/>"), new XmlInput("<b/>"), new DiffConfiguration(description)); XmlAssert.XmlEquals(diff); } catch (AssertionException e) { Assert.AreEqual(true, e.Message.StartsWith(description)); } } [Test] public void AssertXmlValidTrueForValidFile() { StreamReader reader = new StreamReader(ValidatorTests.ValidFile); try { XmlAssert.XmlValid(reader); } finally { reader.Close(); } } [Test] public void AssertXmlValidFalseForInvalidFile() { StreamReader reader = new StreamReader(ValidatorTests.InvalidFile); try { XmlAssert.XmlValid(reader); Assert.Fail("Expected assertion failure"); } catch(AssertionException e) { AvoidUnusedVariableCompilerWarning(e); } finally { reader.Close(); } } private static readonly string MY_SOLAR_SYSTEM = "<solar-system><planet name='Earth' position='3' supportsLife='yes'/><planet name='Venus' position='4'/></solar-system>"; [Test] public void AssertXPathExistsWorksForExistentXPath() { XmlAssert.XPathExists("//planet[@name='Earth']", MY_SOLAR_SYSTEM); } [Test] public void AssertXPathExistsFailsForNonExistentXPath() { try { XmlAssert.XPathExists("//star[@name='alpha centauri']", MY_SOLAR_SYSTEM); Assert.Fail("Expected assertion failure"); } catch (AssertionException e) { AvoidUnusedVariableCompilerWarning(e); } } [Test] public void AssertXPathEvaluatesToWorksForMatchingExpression() { XmlAssert.XPathEvaluatesTo("//planet[@position='3']/@supportsLife", MY_SOLAR_SYSTEM, "yes"); } [Test] public void AssertXPathEvaluatesToWorksForNonMatchingExpression() { XmlAssert.XPathEvaluatesTo("//planet[@position='4']/@supportsLife", MY_SOLAR_SYSTEM, ""); } [Test] public void AssertXPathEvaluatesToWorksConstantExpression() { XmlAssert.XPathEvaluatesTo("true()", MY_SOLAR_SYSTEM, "True"); XmlAssert.XPathEvaluatesTo("false()", MY_SOLAR_SYSTEM, "False"); } [Test] public void AssertXslTransformResultsWorksWithStrings() { string xslt = XsltTests.IDENTITY_TRANSFORM; string someXml = "<a><b>c</b><b/></a>"; XmlAssert.XslTransformResults(xslt, someXml, someXml); } [Test] public void AssertXslTransformResultsWorksWithXmlInput() { StreamReader xsl = ValidatorTests.GetTestReader("animal.xsl"); XmlInput xslt = new XmlInput(xsl); StreamReader xml = ValidatorTests.GetTestReader("testAnimal.xml"); XmlInput xmlToTransform = new XmlInput(xml); XmlInput expectedXml = new XmlInput("<dog/>"); XmlAssert.XslTransformResults(xslt, xmlToTransform, expectedXml); } [Test] public void AssertXslTransformResultsCatchesFalsePositive() { StreamReader xsl = ValidatorTests.GetTestReader("animal.xsl"); XmlInput xslt = new XmlInput(xsl); StreamReader xml = ValidatorTests.GetTestReader("testAnimal.xml"); XmlInput xmlToTransform = new XmlInput(xml); XmlInput expectedXml = new XmlInput("<cat/>"); bool exceptionExpected = true; try { XmlAssert.XslTransformResults(xslt, xmlToTransform, expectedXml); exceptionExpected = false; Assert.Fail("Expected dog not cat!"); } catch (AssertionException e) { AvoidUnusedVariableCompilerWarning(e); if (!exceptionExpected) { throw e; } } } private void AvoidUnusedVariableCompilerWarning(AssertionException e) { string msg = e.Message; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.ApplicationModel.Resources.Core; using Windows.Globalization; using Windows.Media.SpeechRecognition; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Documents; using Windows.UI.Xaml.Navigation; using Windows.Foundation; namespace SpeechAndTTS { public sealed partial class PredefinedDictationGrammarScenario : Page { /// <summary> /// This HResult represents the scenario where a user is prompted to allow in-app speech, but /// declines. This should only happen on a Phone device, where speech is enabled for the entire device, /// not per-app. /// </summary> private static uint HResultPrivacyStatementDeclined = 0x80045509; private SpeechRecognizer speechRecognizer; private CoreDispatcher dispatcher; private IAsyncOperation<SpeechRecognitionResult> recognitionOperation; private ResourceContext speechContext; private ResourceMap speechResourceMap; public PredefinedDictationGrammarScenario() { InitializeComponent(); } /// <summary> /// When activating the scenario, ensure we have permission from the user to access their microphone, and /// provide an appropriate path for the user to enable access to the microphone if they haven't /// given explicit permission for it. /// </summary> /// <param name="e">The navigation event details</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { // Save the UI thread dispatcher to allow speech status messages to be shown on the UI. dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission(); if (permissionGained) { // Enable the recognition buttons. btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage; speechContext = ResourceContext.GetForCurrentView(); speechContext.Languages = new string[] { speechLanguage.LanguageTag }; speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources"); PopulateLanguageDropdown(); await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage); } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone."; btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; cbLanguageSelection.IsEnabled = false; } } /// <summary> /// Look up the supported languages for this speech recognition scenario, /// that are installed on this machine, and populate a dropdown with a list. /// </summary> private void PopulateLanguageDropdown() { Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage; IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedTopicLanguages; foreach (Language lang in supportedLanguages) { ComboBoxItem item = new ComboBoxItem(); item.Tag = lang; item.Content = lang.DisplayName; cbLanguageSelection.Items.Add(item); if (lang.LanguageTag == defaultLanguage.LanguageTag) { item.IsSelected = true; cbLanguageSelection.SelectedItem = item; } } } /// <summary> /// When a user changes the speech recognition language, trigger re-initialization of the /// speech engine with that language, and change any speech-specific UI assets. /// </summary> /// <param name="sender">Ignored</param> /// <param name="e">Ignored</param> private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (speechRecognizer != null) { ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem); Language newLanguage = (Language)item.Tag; if (speechRecognizer.CurrentLanguage != newLanguage) { // trigger cleanup and re-initialization of speech. try { speechContext.Languages = new string[] { newLanguage.LanguageTag }; await InitializeRecognizer(newLanguage); } catch (Exception exception) { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } } } /// <summary> /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks. /// </summary> /// <param name="e">Details about the navigation event</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); if (speechRecognizer != null) { if (speechRecognizer.State != SpeechRecognizerState.Idle) { if (recognitionOperation != null) { recognitionOperation.Cancel(); recognitionOperation = null; } } speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } } /// <summary> /// Initialize Speech Recognizer and compile constraints. /// </summary> /// <param name="recognizerLanguage">Language to use for the speech recognizer</param> /// <returns>Awaitable task.</returns> private async Task InitializeRecognizer(Language recognizerLanguage) { if (speechRecognizer != null) { // cleanup prior to re-initializing this scenario. speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } // Create an instance of SpeechRecognizer. speechRecognizer = new SpeechRecognizer(recognizerLanguage); // Provide feedback to the user about the state of the recognizer. speechRecognizer.StateChanged += SpeechRecognizer_StateChanged; // Compile the dictation topic constraint, which optimizes for dictated speech. var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "dictation"); speechRecognizer.Constraints.Add(dictationConstraint); SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync(); // RecognizeWithUIAsync allows developers to customize the prompts. speechRecognizer.UIOptions.AudiblePrompt = "Dictate a phrase or sentence..."; speechRecognizer.UIOptions.ExampleText = speechResourceMap.GetValue("DictationUIOptionsExampleText", speechContext).ValueAsString; // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it. if (compilationResult.Status != SpeechRecognitionResultStatus.Success) { // Disable the recognition buttons. btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; // Let the user know that the grammar didn't compile properly. resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Unable to compile grammar."; } } /// <summary> /// Handle SpeechRecognizer state changed events by updating a UI component. /// </summary> /// <param name="sender">Speech recognizer that generated this status event</param> /// <param name="args">The recognizer's status</param> private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args) { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage); }); } /// <summary> /// Uses the recognizer constructed earlier to listen for speech from the user before displaying /// it back on the screen. Uses the built-in speech recognition UI. /// </summary> /// <param name="sender">Button that triggered this event</param> /// <param name="e">State information about the routed event</param> private async void RecognizeWithUIDictationGrammar_Click(object sender, RoutedEventArgs e) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed; hlOpenPrivacySettings.Visibility = Visibility.Collapsed; // Start recognition. try { recognitionOperation = speechRecognizer.RecognizeWithUIAsync(); SpeechRecognitionResult speechRecognitionResult = await recognitionOperation; // If successful, display the recognition result. if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = speechRecognitionResult.Text; } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString()); } } catch (TaskCanceledException exception) { // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively // processing speech. Since this happens here when we navigate out of the scenario, don't try to // show a message dialog for this exception. System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):"); System.Diagnostics.Debug.WriteLine(exception.ToString()); } catch (Exception exception) { // Handle the speech privacy policy error. if ((uint)exception.HResult == HResultPrivacyStatementDeclined) { hlOpenPrivacySettings.Visibility = Visibility.Visible; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } } /// <summary> /// Uses the recognizer constructed earlier to listen for speech from the user before displaying /// it back on the screen. Uses developer-provided UI for user feedback. /// </summary> /// <param name="sender">Button that triggered this event</param> /// <param name="e">State information about the routed event</param> private async void RecognizeWithoutUIDictationGrammar_Click(object sender, RoutedEventArgs e) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed; // Disable the UI while recognition is occurring, and provide feedback to the user about current state. btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; cbLanguageSelection.IsEnabled = false; hlOpenPrivacySettings.Visibility = Visibility.Collapsed; listenWithoutUIButtonText.Text = " listening for speech..."; // Start recognition. try { recognitionOperation = speechRecognizer.RecognizeAsync(); SpeechRecognitionResult speechRecognitionResult = await recognitionOperation; // If successful, display the recognition result. if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = speechRecognitionResult.Text; } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString()); } } catch (TaskCanceledException exception) { // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively // processing speech. Since this happens here when we navigate out of the scenario, don't try to // show a message dialog for this exception. System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):"); System.Diagnostics.Debug.WriteLine(exception.ToString()); } catch (Exception exception) { // Handle the speech privacy policy error. if ((uint)exception.HResult == HResultPrivacyStatementDeclined) { hlOpenPrivacySettings.Visibility = Visibility.Visible; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } // Reset UI state. listenWithoutUIButtonText.Text = " without UI"; cbLanguageSelection.IsEnabled = true; btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; } /// <summary> /// Open the Speech, Inking and Typing page under Settings -> Privacy, enabling a user to accept the /// Microsoft Privacy Policy, and enable personalization. /// </summary> /// <param name="sender">Ignored</param> /// <param name="args">Ignored</param> private async void openPrivacySettings_Click(Hyperlink sender, HyperlinkClickEventArgs args) { await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-speechtyping")); } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using FSLib = FSharp.Compiler.AbstractIL.Internal.Library; using System; using System.Runtime.InteropServices; using System.Collections; using System.IO; using System.Windows.Forms; using System.Diagnostics; using System.Globalization; using System.Text; using System.Threading; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; using System.Linq; namespace Microsoft.VisualStudio.FSharp.ProjectSystem { [CLSCompliant(false)] [ComVisible(true)] public class FolderNode : HierarchyNode { /// <summary> /// Constructor for the FolderNode /// </summary> /// <param name="root">Root node of the hierarchy</param> /// <param name="relativePath">relative path from root i.e.: "NewFolder1\\NewFolder2\\NewFolder3</param> /// <param name="element">Associated project element</param> internal FolderNode(ProjectNode root, string relativePath, ProjectElement element) : base(root, element) { this.VirtualNodeName = relativePath.TrimEnd('\\'); } /// <summary> /// This relates to the SCC glyph /// </summary> public override VsStateIcon StateIconIndex { get { // The SCC manager does not support being asked for the state icon of a folder (result of the operation is undefined) return VsStateIcon.STATEICON_NOSTATEICON; } } public override NodeProperties CreatePropertiesObject() { return new FolderNodeProperties(this); } public override void DeleteFromStorage(string path) { this.DeleteFolder(path); } /// <summary> /// Get the automation object for the FolderNode /// </summary> /// <returns>An instance of the Automation.OAFolderNode type if succeeded</returns> public override object GetAutomationObject() { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } public override object GetIconHandle(bool open) { return this.ProjectMgr.ImageHandler.GetIconHandle(open ? (int)ProjectNode.ImageName.OpenFolder : (int)ProjectNode.ImageName.Folder); } /// <summary> /// Rename Folder /// </summary> /// <param name="label">new Name of Folder</param> /// <returns>VSConstants.S_OK, if succeeded</returns> public override int SetEditLabel(string label) { if (String.Compare(Path.GetFileName(this.Url.TrimEnd('\\')), label, StringComparison.Ordinal) == 0) { // Label matches current Name return VSConstants.S_OK; } string newPath = Path.Combine(new DirectoryInfo(this.Url).Parent.FullName, label); // Verify that No Directory/file already exists with the new name among siblings for (HierarchyNode n = Parent.FirstChild; n != null; n = n.NextSibling) { if (n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0) { return ShowErrorMessage(SR.FileOrFolderAlreadyExists, newPath); } } try { RenameFolder(label); //Refresh the properties in the properties window IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell; Debug.Assert(shell != null, "Could not get the ui shell from the project"); ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0)); // Notify the listeners that the name of this folder is changed. This will // also force a refresh of the SolutionExplorer's node. this.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.RenameFolder, CultureInfo.CurrentUICulture), e.Message)); } return VSConstants.S_OK; } public override int MenuCommandId { get { return VsMenus.IDM_VS_CTXT_FOLDERNODE; } } public override Guid ItemTypeGuid { get { return VSConstants.GUID_ItemType_PhysicalFolder; } } public override string Url { get { return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(this.ProjectMgr.Url), this.VirtualNodeName)) + "\\"; } } public override string Caption { get { // it might have a backslash at the end... // and it might consist of Grandparent\parent\this\ string caption = this.VirtualNodeName; string[] parts; parts = caption.Split(Path.DirectorySeparatorChar); caption = parts[parts.GetUpperBound(0)]; return caption; } } public override string GetMkDocument() { Debug.Assert(this.Url != null, "No url sepcified for this node"); return this.Url; } /// <summary> /// Enumerate the files associated with this node. /// A folder node is not a file and as such no file to enumerate. /// </summary> /// <param name="files">The list of files to be placed under source control.</param> /// <param name="flags">The flags that are associated to the files.</param> public override void GetSccFiles(System.Collections.Generic.IList<string> files, System.Collections.Generic.IList<tagVsSccFilesFlags> flags) { return; } /// <summary> /// This method should be overridden to provide the list of special files and associated flags for source control. /// </summary> /// <param name="sccFile">One of the file associated to the node.</param> /// <param name="files">The list of files to be placed under source control.</param> /// <param name="flags">The flags that are associated to the files.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "scc")] public override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) { if (this.ExcludeNodeFromScc) { return; } if (files == null) { throw new ArgumentNullException("files"); } if (flags == null) { throw new ArgumentNullException("flags"); } if (string.IsNullOrEmpty(sccFile)) { throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "sccFile"); } } /// <summary> /// Recursevily walks the folder nodes and redraws the state icons /// </summary> public override void UpdateSccStateIcons() { for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) { child.UpdateSccStateIcons(); } } internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet97) { switch ((VsCommands)cmd) { case VsCommands.Copy: case VsCommands.Paste: case VsCommands.Cut: case VsCommands.Rename: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; case VsCommands.NewFolder: case VsCommands.AddNewItem: case VsCommands.AddExistingItem: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } if ((VsCommands2K) cmd == VsMenus.OpenFolderInExplorerCmdId) { result |= QueryStatusResult.SUPPORTED; result |= CanOpenFolderInExplorer()? QueryStatusResult.ENABLED : QueryStatusResult.INVISIBLE; return VSConstants.S_OK; } } else { return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP; } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } public bool CanOpenFolderInExplorer() { return Directory.Exists(this.Url); } public void OpenFolderInExplorer() { if (CanOpenFolderInExplorer()) Process.Start(this.Url); } public override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K) cmd == VsMenus.OpenFolderInExplorerCmdId) { OpenFolderInExplorer(); return VSConstants.S_OK; } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } public override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) { return this.ProjectMgr.CanProjectDeleteItems; } return false; } /// <summary> /// Override if your node is not a file system folder so that /// it does nothing or it deletes it from your storage location. /// </summary> /// <param name="path">Path to the folder to delete</param> public virtual void DeleteFolder(string path) { if (Directory.Exists(path)) Directory.Delete(path, true); } /// <summary> /// creates the physical directory for a folder node /// Override if your node does not use file system folder /// </summary> public virtual void CreateDirectory() { try { if (Directory.Exists(this.Url) == false) { Directory.CreateDirectory(this.Url); } } //TODO - this should not digest all exceptions. catch (System.Exception e) { CCITracing.Trace(e); throw; } } /// <summary> /// Creates a folder nodes physical directory /// Override if your node does not use file system folder /// </summary> /// <param name="newName"></param> /// <returns></returns> public virtual void CreateDirectory(string newName) { if (String.IsNullOrEmpty(newName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newName"); } try { // on a new dir && enter, we get called with the same name (so do nothing if name is the same char[] dummy = new char[1]; dummy[0] = Path.DirectorySeparatorChar; string oldDir = this.Url; oldDir = oldDir.TrimEnd(dummy); string strNewDir = Path.Combine(Path.GetDirectoryName(oldDir), newName); if (String.Compare(strNewDir, oldDir, StringComparison.OrdinalIgnoreCase) != 0) { if (Directory.Exists(strNewDir)) { throw new InvalidOperationException(SR.GetString(SR.DirectoryExistError, CultureInfo.CurrentUICulture)); } Directory.CreateDirectory(strNewDir); } } //TODO - this should not digest all exceptions. catch (System.Exception e) { CCITracing.Trace(e); throw; } } /// <summary> /// Rename the physical directory for a folder node /// Override if your node does not use file system folder /// </summary> /// <returns></returns> public virtual void RenameDirectory(string newPath) { if (Directory.Exists(this.Url)) { if (Directory.Exists(newPath)) { ShowErrorMessage(SR.FileOrFolderAlreadyExists, newPath); return; } Directory.Move(this.Url, newPath); } } private void RenameFolder(string newName) { string newPath = Path.Combine(this.Parent.VirtualNodeName, newName); string newFullPath = Path.Combine(this.ProjectMgr.ProjectFolder, newPath); // Only do the physical rename if the leaf name changed if (String.Compare(Path.GetFileName(VirtualNodeName), newName, StringComparison.Ordinal) != 0) { // Verify that no directory/file already exists with the new name on disk. // If it does, just subsume that name if our directory is empty. if (Directory.Exists(newFullPath) || FSLib.Shim.FileSystem.SafeExists(newFullPath)) { // We can't delete our old directory as it is not empty if (Directory.EnumerateFileSystemEntries(this.Url).Any()) { ShowErrorMessage(SR.FolderCannotBeRenamed, newPath); return; } // Try to delete the old (empty) directory. // Note that we don't want to delete recursively in case a file was added between // when we checked and when we went to delete (potential race condition). Directory.Delete(this.Url, false); } else { this.RenameDirectory(newFullPath); } } this.VirtualNodeName = newPath; this.ItemNode.Rename(VirtualNodeName); // Let all children know of the new path for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) { if (!(child is FolderNode)) { child.SetEditLabel(child.Caption); } else { FolderNode childFolderNode = (FolderNode)child; childFolderNode.RenameFolder(childFolderNode.Caption); } } // Some of the previous operation may have changed the selection so set it back to us IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer); ErrorHandler.ThrowOnFailure(uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, this.ID, EXPANDFLAGS.EXPF_SelectItem)); } /// <summary> /// Show error message if not in automation mode, otherwise throw exception /// </summary> /// <param name="parameter">Parameter for resource string format</param> /// <returns>S_OK</returns> private int ShowErrorMessage(string resourceName, string parameter) { // Most likely the cause of: // A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. // -or- // This folder cannot be renamed to '{0}' as it already exists on disk. string errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetStringWithCR(resourceName), parameter); if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) { string title = null; OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL; OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton); return VSConstants.S_OK; } else { throw new InvalidOperationException(errorMessage); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.UnitTests.LayoutRenderers { using System; using Microsoft.Win32; using Xunit; public class RegistryTests : NLogTestBase, IDisposable { private const string TestKey = @"Software\NLogTest"; public RegistryTests() { var key = Registry.CurrentUser.CreateSubKey(TestKey); key.SetValue("Foo", "FooValue"); key.SetValue(null, "UnnamedValue"); #if !NET3_5 //different keys because in 32bit the 64bits uses the 32 RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).CreateSubKey("Software\\NLogTest").SetValue("view32", "reg32"); RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).CreateSubKey("Software\\NLogTest").SetValue("view64", "reg64"); #endif } public void Dispose() { #if !NET3_5 //different keys because in 32bit the 64bits uses the 32 try { RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).DeleteSubKey("Software\\NLogTest"); } catch (Exception) { } try { RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).DeleteSubKey("Software\\NLogTest"); } catch (Exception) { } #endif try { Registry.CurrentUser.DeleteSubKey(TestKey); } catch (Exception) { } } [Fact] public void RegistryNamedValueTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=Foo}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "FooValue"); } #if !NET3_5 [Fact] public void RegistryNamedValueTest_hive32() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view32:view=Registry32}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "reg32"); } [Fact] public void RegistryNamedValueTest_hive64() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view64:view=Registry64}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "reg64"); } #endif [Fact] public void RegistryNamedValueTest_forward_slash() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest:value=Foo}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "FooValue"); } [Fact] public void RegistryUnnamedValueTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "UnnamedValue"); } [Fact] public void RegistryUnnamedValueTest_forward_slash() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "UnnamedValue"); } [Fact] public void RegistryKeyNotFoundTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NoSuchKey:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "xyz"); } [Fact] public void RegistryKeyNotFoundTest_forward_slash() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NoSuchKey:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "xyz"); } [Fact] public void RegistryValueNotFoundTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=NoSuchValue:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "xyz"); } [Fact] public void RegistryDefaultValueTest() { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=logdefaultvalue}", "logdefaultvalue"); } [Fact] public void RegistryDefaultValueTest_with_colon() { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\:temp}", "C:temp"); } [Fact] public void RegistryDefaultValueTest_with_slash() { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C/temp}", "C/temp"); } [Fact] public void RegistryDefaultValueTest_with_foward_slash() { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\\\temp}", "C\\temp"); } [Fact] public void RegistryDefaultValueTest_with_foward_slash2() { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\temp:requireEscapingSlashesInDefaultValue=false}", "C\\temp"); } [Fact] public void Registry_nosubky() { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:key=HKEY_CURRENT_CONFIG}", ""); } [Fact] public void RegistryDefaultValueNull() { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT}", ""); } [Fact] public void RegistryTestWrongKey_no_ex() { LogManager.ThrowExceptions = false; AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", ""); } [Fact(Skip = "SimpleLayout.GetFormattedMessage catches exception. Will be fixed in the future")] public void RegistryTestWrongKey_ex() { LogManager.ThrowExceptions = true; Assert.Throws<ArgumentException>( () => { AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", ""); }); } } } #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. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDateTime { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Datetime. /// </summary> public static partial class DatetimeExtensions { /// <summary> /// Get null datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetNull(this IDatetime operations) { return operations.GetNullAsync().GetAwaiter().GetResult(); } /// <summary> /// Get null datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetNullAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get invalid datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetInvalid(this IDatetime operations) { return operations.GetInvalidAsync().GetAwaiter().GetResult(); } /// <summary> /// Get invalid datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetInvalidAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get overflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetOverflow(this IDatetime operations) { return operations.GetOverflowAsync().GetAwaiter().GetResult(); } /// <summary> /// Get overflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetOverflowAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOverflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get underflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUnderflow(this IDatetime operations) { return operations.GetUnderflowAsync().GetAwaiter().GetResult(); } /// <summary> /// Get underflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetUnderflowAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUnderflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put max datetime value 9999-12-31T23:59:59.9999999Z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutUtcMaxDateTime(this IDatetime operations, System.DateTime datetimeBody) { operations.PutUtcMaxDateTimeAsync(datetimeBody).GetAwaiter().GetResult(); } /// <summary> /// Put max datetime value 9999-12-31T23:59:59.9999999Z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutUtcMaxDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutUtcMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get max datetime value 9999-12-31t23:59:59.9999999z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUtcLowercaseMaxDateTime(this IDatetime operations) { return operations.GetUtcLowercaseMaxDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value 9999-12-31t23:59:59.9999999z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetUtcLowercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get max datetime value 9999-12-31T23:59:59.9999999Z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUtcUppercaseMaxDateTime(this IDatetime operations) { return operations.GetUtcUppercaseMaxDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value 9999-12-31T23:59:59.9999999Z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetUtcUppercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put max datetime value with positive numoffset /// 9999-12-31t23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutLocalPositiveOffsetMaxDateTime(this IDatetime operations, System.DateTime datetimeBody) { operations.PutLocalPositiveOffsetMaxDateTimeAsync(datetimeBody).GetAwaiter().GetResult(); } /// <summary> /// Put max datetime value with positive numoffset /// 9999-12-31t23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutLocalPositiveOffsetMaxDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutLocalPositiveOffsetMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31t23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetLocalPositiveOffsetLowercaseMaxDateTime(this IDatetime operations) { return operations.GetLocalPositiveOffsetLowercaseMaxDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31t23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetLocalPositiveOffsetLowercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLocalPositiveOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31T23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetLocalPositiveOffsetUppercaseMaxDateTime(this IDatetime operations) { return operations.GetLocalPositiveOffsetUppercaseMaxDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31T23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetLocalPositiveOffsetUppercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLocalPositiveOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put max datetime value with positive numoffset /// 9999-12-31t23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutLocalNegativeOffsetMaxDateTime(this IDatetime operations, System.DateTime datetimeBody) { operations.PutLocalNegativeOffsetMaxDateTimeAsync(datetimeBody).GetAwaiter().GetResult(); } /// <summary> /// Put max datetime value with positive numoffset /// 9999-12-31t23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutLocalNegativeOffsetMaxDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutLocalNegativeOffsetMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31T23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetLocalNegativeOffsetUppercaseMaxDateTime(this IDatetime operations) { return operations.GetLocalNegativeOffsetUppercaseMaxDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31T23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetLocalNegativeOffsetUppercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLocalNegativeOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31t23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetLocalNegativeOffsetLowercaseMaxDateTime(this IDatetime operations) { return operations.GetLocalNegativeOffsetLowercaseMaxDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31t23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetLocalNegativeOffsetLowercaseMaxDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLocalNegativeOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put min datetime value 0001-01-01T00:00:00Z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutUtcMinDateTime(this IDatetime operations, System.DateTime datetimeBody) { operations.PutUtcMinDateTimeAsync(datetimeBody).GetAwaiter().GetResult(); } /// <summary> /// Put min datetime value 0001-01-01T00:00:00Z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutUtcMinDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutUtcMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00Z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetUtcMinDateTime(this IDatetime operations) { return operations.GetUtcMinDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00Z /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetUtcMinDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUtcMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put min datetime value 0001-01-01T00:00:00+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutLocalPositiveOffsetMinDateTime(this IDatetime operations, System.DateTime datetimeBody) { operations.PutLocalPositiveOffsetMinDateTimeAsync(datetimeBody).GetAwaiter().GetResult(); } /// <summary> /// Put min datetime value 0001-01-01T00:00:00+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutLocalPositiveOffsetMinDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetLocalPositiveOffsetMinDateTime(this IDatetime operations) { return operations.GetLocalPositiveOffsetMinDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetLocalPositiveOffsetMinDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put min datetime value 0001-01-01T00:00:00-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutLocalNegativeOffsetMinDateTime(this IDatetime operations, System.DateTime datetimeBody) { operations.PutLocalNegativeOffsetMinDateTimeAsync(datetimeBody).GetAwaiter().GetResult(); } /// <summary> /// Put min datetime value 0001-01-01T00:00:00-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutLocalNegativeOffsetMinDateTimeAsync(this IDatetime operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.DateTime? GetLocalNegativeOffsetMinDateTime(this IDatetime operations) { return operations.GetLocalNegativeOffsetMinDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.DateTime?> GetLocalNegativeOffsetMinDateTimeAsync(this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { // Nop. } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { // Nop. } /// <summary>Stops the associated process immediately.</summary> public void Kill() { EnsureState(State.HaveId); int errno = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL); if (errno != 0) { throw new Win32Exception(errno); // same exception as on Windows } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { // Nop. No additional state to reset. } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { if (_waitStateHolder != null) { _waitStateHolder.Dispose(); _waitStateHolder = null; } } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { bool exited = GetWaitState().WaitForExit(milliseconds); Debug.Assert(exited || milliseconds != Timeout.Infinite); if (exited && milliseconds == Timeout.Infinite) // if we have a hard timeout, we cannot wait for the streams { if (_output != null) { _output.WaitUtilEOF(); } if (_error != null) { _error.WaitUtilEOF(); } } return exited; } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { ProcessModuleCollection pmc = Modules; return pmc.Count > 0 ? pmc[0] : null; } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { int? exitCode; _exited = GetWaitState().GetExited(out exitCode); if (_exited && exitCode != null) { _exitCode = exitCode.Value; } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetWaitState().ExitTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { return false; } //Nop set { } // Nop } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { // This mapping is relatively arbitrary. 0 is normal based on the man page, // and the other values above and below are simply distributed evenly. get { EnsureState(State.HaveId); int pri = 0; int errno = Interop.libc.getpriority(Interop.libc.PriorityWhich.PRIO_PROCESS, _processId, out pri); if (errno != 0) { throw new Win32Exception(errno); // match Windows exception } Debug.Assert(pri >= -20 && pri <= 20); return pri < -15 ? ProcessPriorityClass.RealTime : pri < -10 ? ProcessPriorityClass.High : pri < -5 ? ProcessPriorityClass.AboveNormal : pri == 0 ? ProcessPriorityClass.Normal : pri <= 10 ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Idle; } set { int pri; switch (value) { case ProcessPriorityClass.RealTime: pri = -19; break; case ProcessPriorityClass.High: pri = -11; break; case ProcessPriorityClass.AboveNormal: pri = -6; break; case ProcessPriorityClass.Normal: pri = 0; break; case ProcessPriorityClass.BelowNormal: pri = 10; break; case ProcessPriorityClass.Idle: pri = 19; break; default: throw new Win32Exception(); // match Windows exception } int result = Interop.libc.setpriority(Interop.libc.PriorityWhich.PRIO_PROCESS, _processId, pri); if (result == -1) { throw new Win32Exception(); // match Windows exception } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return Interop.Sys.GetPid(); } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { if (_haveProcessHandle) { if (GetWaitState().HasExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } return _processHandle; } EnsureState(State.HaveId | State.IsLocal); return new SafeProcessHandle(_processId); } /// <summary>Starts the process using the supplied start info.</summary> /// <param name="startInfo">The start info with which to start the process.</param> private bool StartCore(ProcessStartInfo startInfo) { // Resolve the path to the specified file name string filename = ResolvePath(startInfo.FileName); // Parse argv, envp, and cwd out of the ProcessStartInfo string[] argv = CreateArgv(startInfo); string[] envp = CreateEnvp(startInfo); string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null; // Invoke the shim fork/execve routine. It will create pipes for all requested // redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr // descriptors, and execve to execute the requested process. The shim implementation // is used to fork/execve as executing managed code in a forked process is not safe (only // the calling thread will transfer, thread IDs aren't stable across the fork, etc.) int childPid, stdinFd, stdoutFd, stderrFd; if (Interop.Sys.ForkAndExecProcess( filename, argv, envp, cwd, startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError, out childPid, out stdinFd, out stdoutFd, out stderrFd) != 0) { throw new Win32Exception(); } // Store the child's information into this Process object. Debug.Assert(childPid >= 0); SetProcessHandle(new SafeProcessHandle(childPid)); SetProcessId(childPid); // Configure the parent's ends of the redirection streams. if (startInfo.RedirectStandardInput) { Debug.Assert(stdinFd >= 0); _standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write), Encoding.UTF8, StreamBufferSize) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { Debug.Assert(stdoutFd >= 0); _standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read), startInfo.StandardOutputEncoding ?? Encoding.UTF8, true, StreamBufferSize); } if (startInfo.RedirectStandardError) { Debug.Assert(stderrFd >= 0); _standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read), startInfo.StandardErrorEncoding ?? Encoding.UTF8, true, StreamBufferSize); } return true; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Finalizable holder for the underlying shared wait state object.</summary> private ProcessWaitState.Holder _waitStateHolder; /// <summary>Size to use for redirect streams and stream readers/writers.</summary> private const int StreamBufferSize = 4096; /// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <returns>The argv array.</returns> private static string[] CreateArgv(ProcessStartInfo psi) { string argv0 = psi.FileName; // pass filename (instead of resolved path) as argv[0], to match what caller supplied if (string.IsNullOrEmpty(psi.Arguments)) { return new string[] { argv0 }; } else { var argvList = new List<string>(); argvList.Add(argv0); ParseArgumentsIntoList(psi.Arguments, argvList); return argvList.ToArray(); } } /// <summary>Converts the environment variables information from a ProcessStartInfo into an envp array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <returns>The envp array.</returns> private static string[] CreateEnvp(ProcessStartInfo psi) { var envp = new string[psi.Environment.Count]; int index = 0; foreach (var pair in psi.Environment) { envp[index++] = pair.Key + "=" + pair.Value; } return envp; } /// <summary>Resolves a path to the filename passed to ProcessStartInfo.</summary> /// <param name="filename">The filename.</param> /// <returns>The resolved path.</returns> private static string ResolvePath(string filename) { // Follow the same resolution that Windows uses with CreateProcess: // 1. First try the exact path provided // 2. Then try the file relative to the executable directory // 3. Then try the file relative to the current directory // 4. then try the file in each of the directories specified in PATH // Windows does additional Windows-specific steps between 3 and 4, // and we ignore those here. // If the filename is a complete path, use it, regardless of whether it exists. if (Path.IsPathRooted(filename)) { // In this case, it doesn't matter whether the file exists or not; // it's what the caller asked for, so it's what they'll get return filename; } // Then check the executable's directory string path = GetExePath(); if (path != null) { try { path = Path.Combine(Path.GetDirectoryName(path), filename); if (File.Exists(path)) { return path; } } catch (ArgumentException) { } // ignore any errors in data that may come from the exe path } // Then check the current directory path = Path.Combine(Directory.GetCurrentDirectory(), filename); if (File.Exists(path)) { return path; } // Then check each directory listed in the PATH environment variables string pathEnvVar = Environment.GetEnvironmentVariable("PATH"); if (pathEnvVar != null) { var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true); while (pathParser.MoveNext()) { string subPath = pathParser.ExtractCurrent(); path = Path.Combine(subPath, filename); if (File.Exists(path)) { return path; } } } // Could not find the file throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno); } /// <summary>Convert a number of "jiffies", or ticks, to a TimeSpan.</summary> /// <param name="ticks">The number of ticks.</param> /// <returns>The equivalent TimeSpan.</returns> internal static TimeSpan TicksToTimeSpan(double ticks) { // Look up the number of ticks per second in the system's configuration, // then use that to convert to a TimeSpan int ticksPerSecond = Interop.libc.sysconf(Interop.libc.SysConfNames._SC_CLK_TCK); if (ticksPerSecond <= 0) { throw new Win32Exception(); } return TimeSpan.FromSeconds(ticks / (double)ticksPerSecond); } /// <summary>Opens a stream around the specified file descriptor and with the specified access.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="access">The access mode.</param> /// <returns>The opened stream.</returns> private static FileStream OpenStream(int fd, FileAccess access) { Debug.Assert(fd >= 0); return new FileStream( new SafeFileHandle((IntPtr)fd, ownsHandle: true), access, StreamBufferSize, isAsync: false); } /// <summary>Parses a command-line argument string into a list of arguments.</summary> /// <param name="arguments">The argument string.</param> /// <param name="results">The list into which the component arguments should be stored.</param> private static void ParseArgumentsIntoList(string arguments, List<string> results) { var currentArgument = new StringBuilder(); bool inQuotes = false; // Iterate through all of the characters in the argument string for (int i = 0; i < arguments.Length; i++) { char c = arguments[i]; // If this is an escaped double-quote, just add a '"' to the current // argument and then skip past it in the input. if (c == '\\' && i < arguments.Length - 1 && arguments[i + 1] == '"') { currentArgument.Append('"'); i++; continue; } // If this is a double quote, track whether we're inside of quotes or not. // Anything within quotes will be treated as a single argument, even if // it contains spaces. if (c == '"') { inQuotes = !inQuotes; continue; } // If this is a space and we're not in quotes, we're done with the current // argument, and if we've built up any characters in the current argument, // it should be added to the results and then reset for the next one. if (c == ' ' && !inQuotes) { if (currentArgument.Length > 0) { results.Add(currentArgument.ToString()); currentArgument.Clear(); } continue; } // Nothing special; add the character to the current argument. currentArgument.Append(c); } // If we reach the end of the string and we still have anything in our current // argument buffer, treat it as an argument to be added to the results. if (currentArgument.Length > 0) { results.Add(currentArgument.ToString()); } } /// <summary>Gets the wait state for this Process object.</summary> private ProcessWaitState GetWaitState() { if (_waitStateHolder == null) { EnsureState(State.HaveId); _waitStateHolder = new ProcessWaitState.Holder(_processId); } return _waitStateHolder._state; } } }
using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Chess { [TestClass] public class GameTests { [TestMethod] public void TestPositionOfPiecesWhenGameStarts() { var game = new Game(); game.New(); Assert.IsNotNull(game.Board); Assert.IsTrue(game.Board.Square(File.A, Rank._1).Piece is Rook); Assert.AreEqual(Color.White, game.Board.Square(File.A, Rank._1).Piece.Color); Assert.IsTrue(game.Board.Square(File.H, Rank._1).Piece is Rook); Assert.AreEqual(Color.White, game.Board.Square(File.H, Rank._1).Piece.Color); Assert.IsTrue(game.Board.Square(File.B, Rank._1).Piece is Knight); Assert.IsTrue(game.Board.Square(File.G, Rank._1).Piece is Knight); Assert.IsTrue(game.Board.Square(File.C, Rank._1).Piece is Bishop); Assert.IsTrue(game.Board.Square(File.F, Rank._1).Piece is Bishop); Assert.IsTrue(game.Board.Square(File.D, Rank._1).Piece is Queen); Assert.IsTrue(game.Board.Square(File.E, Rank._1).Piece is King); for (int i = 0; i < 8; i++) Assert.IsTrue(game.Board.Squares[i + 1 * 8].Piece is Pawn); Assert.IsTrue(game.Board.Square(File.A, Rank._8).Piece is Rook); Assert.AreEqual(Color.Black, game.Board.Square(File.A, Rank._8).Piece.Color); Assert.IsTrue(game.Board.Square(File.H, Rank._8).Piece is Rook); Assert.AreEqual(Color.Black, game.Board.Square(File.H, Rank._8).Piece.Color); Assert.IsTrue(game.Board.Square(File.B, Rank._8).Piece is Knight); Assert.IsTrue(game.Board.Square(File.G, Rank._8).Piece is Knight); Assert.IsTrue(game.Board.Square(File.C, Rank._8).Piece is Bishop); Assert.IsTrue(game.Board.Square(File.F, Rank._8).Piece is Bishop); Assert.IsTrue(game.Board.Square(File.D, Rank._8).Piece is Queen); Assert.IsTrue(game.Board.Square(File.E, Rank._8).Piece is King); for (int i = 0; i < 8; i++) Assert.IsTrue(game.Board.Squares[i + 6 * 8].Piece is Pawn); } [TestMethod] public void TestPlayersAtStartup() { var game = new Game(); game.New(); Assert.IsNotNull(game.WhitePlayer); Assert.IsNotNull(game.BlackPlayer); Assert.AreEqual(16, game.WhitePlayer.Pieces.Count); Assert.AreEqual(16, game.BlackPlayer.Pieces.Count); Assert.AreSame(game.WhitePlayer.Pieces.First().Square.Piece, game.WhitePlayer.Pieces.First()); Assert.AreSame(game.CurrentPlayer, game.WhitePlayer); foreach (var piece in game.WhitePlayer.Pieces) Assert.IsTrue(piece.ImageChar != 0); foreach (var piece in game.BlackPlayer.Pieces) Assert.IsTrue(piece.ImageChar != 0); } [TestMethod] public void TestKingMoves() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._2, new Pawn(Color.Black)); //Captures on E2 game.AddPiece(File.F, Rank._2, new Pawn(Color.White)); //Blocks own King var moves = game.GetPseudoLegalMoves(); var kingMoves = moves.Where(x => x.Piece is King).ToArray(); Assert.AreEqual(4, kingMoves.Length); Assert.IsNotNull(kingMoves.Single(x => x.Piece.Color == Color.White && x.ToSquare.ToString() == "d1")); Assert.IsNotNull(kingMoves.Single(x => x.Piece.Color == Color.White && x.ToSquare.ToString() == "d2")); Assert.IsNotNull(kingMoves.Single(x => x.Piece.Color == Color.White && x.ToSquare.ToString() == "e2")); Assert.IsNotNull(kingMoves.Single(x => x.Piece.Color == Color.White && x.ToSquare.ToString() == "f1")); } [TestMethod] public void TestRookMoves() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._6, new Pawn(Color.Black)); game.AddPiece(File.E, Rank._2, new Rook(Color.White)); game.SetInitials(); var moves = game.GetPseudoLegalMoves(); var rookMoves = moves.Where(x => x.Piece is Rook && x.Piece.Color == Color.White); var squares = rookMoves.Select(x => x.ToSquare.ToString()).ToArray(); Assert.AreEqual(11, squares.Length); Assert.IsTrue(squares.Contains("e3")); Assert.IsTrue(squares.Contains("e4")); Assert.IsTrue(squares.Contains("e5")); Assert.IsTrue(squares.Contains("e6")); Assert.IsTrue(squares.Contains("a2")); Assert.IsTrue(squares.Contains("b2")); Assert.IsTrue(squares.Contains("c2")); Assert.IsTrue(squares.Contains("d2")); Assert.IsTrue(squares.Contains("f2")); Assert.IsTrue(squares.Contains("g2")); Assert.IsTrue(squares.Contains("h2")); } [TestMethod] public void TestBishopMoves() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._4, new Bishop(Color.White)); game.AddPiece(File.F, Rank._3, new Pawn(Color.White)); game.AddPiece(File.D, Rank._3, new Pawn(Color.Black)); var moves = game.GetPseudoLegalMoves(); var bishopMoves = moves.Where(x => x.Piece is Bishop && x.Piece.Color == Color.White); var squares = bishopMoves.Select(x => x.ToSquare.ToString()).ToArray(); Assert.AreEqual(8, squares.Length); Assert.IsTrue(squares.Contains("d3")); Assert.IsTrue(squares.Contains("d5")); Assert.IsTrue(squares.Contains("c6")); Assert.IsTrue(squares.Contains("b7")); Assert.IsTrue(squares.Contains("a8")); Assert.IsTrue(squares.Contains("f5")); Assert.IsTrue(squares.Contains("g6")); Assert.IsTrue(squares.Contains("h7")); } [TestMethod] public void TestKnightMoves() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._4, new Knight(Color.White)); game.AddPiece(File.D, Rank._6, new Pawn(Color.White)); var moves = game.GetPseudoLegalMoves(); var knightMoves = moves.Where(x => x.Piece is Knight && x.Piece.Color == Color.White); var squares = knightMoves.Select(x => x.ToSquare.ToString()).ToArray(); Assert.AreEqual(7, squares.Length); Assert.IsTrue(squares.Contains("f6")); Assert.IsTrue(squares.Contains("g5")); Assert.IsTrue(squares.Contains("g3")); Assert.IsTrue(squares.Contains("f2")); Assert.IsTrue(squares.Contains("d2")); Assert.IsTrue(squares.Contains("c3")); Assert.IsTrue(squares.Contains("c5")); } [TestMethod] public void TestWhitePawnMoves() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._2, new Pawn(Color.White)); var moves = game.GetPseudoLegalMoves(); var pawnMoves = moves.Where(x => x.Piece is Pawn && x.Piece.Color == Color.White) .Select(x => x.ToSquare.ToString()) .ToArray(); Assert.AreEqual(2, pawnMoves.Length); Assert.IsTrue(pawnMoves.Contains("e3")); Assert.IsTrue(pawnMoves.Contains("e4")); game.AddPiece(File.F, Rank._3, new Pawn(Color.Black)); moves = game.GetPseudoLegalMoves(); pawnMoves = moves.Where(x => x.Piece is Pawn && x.Piece.Color == Color.White) .Select(x => x.ToSquare.ToString()) .ToArray(); Assert.AreEqual(3, pawnMoves.Length); Assert.IsTrue(pawnMoves.Contains("f3")); } [TestMethod] public void TestBlackPawnMoves() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._7, new Pawn(Color.Black)); game.CurrentPlayer = game.BlackPlayer; var moves = game.GetPseudoLegalMoves(); var pawnMoves = moves.Where(x => x.Piece is Pawn && x.Piece.Color == Color.Black) .Select(x => x.ToSquare.ToString()) .ToArray(); Assert.AreEqual(2, pawnMoves.Length); Assert.IsTrue(pawnMoves.Contains("e6")); Assert.IsTrue(pawnMoves.Contains("e5")); game.AddPiece(File.F, Rank._6, new Pawn(Color.White)); moves = game.GetPseudoLegalMoves(); pawnMoves = moves.Where(x => x.Piece is Pawn && x.Piece.Color == Color.Black) .Select(x => x.ToSquare.ToString()) .ToArray(); Assert.AreEqual(3, pawnMoves.Length); Assert.IsTrue(pawnMoves.Contains("f6")); } [TestMethod] public void TestPawnMoveTwoSquares() { var game = new Game(); game.New(); Assert.IsTrue(game.TryStringMove("b1-c3")); Assert.IsTrue(game.TryStringMove("b7-b6")); Assert.IsFalse(game.TryStringMove("c2-c4")); } [TestMethod] public void TestCastling() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.A, Rank._1, new Rook(Color.White)); game.AddPiece(File.H, Rank._1, new Rook(Color.White)); game.SetInitials(); var moves = game.GetPseudoLegalMoves(); var kingMoves = moves.Where(x => x.Piece is King && x.Piece.Color == Color.White).Select(x => x.ToString()).ToArray(); Assert.IsTrue(kingMoves.Contains("0-0")); Assert.IsTrue(kingMoves.Contains("0-0-0")); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._1, File.G, Rank._1))); Assert.IsFalse(game.WhitePlayer.CanCastleKingSide); game.UndoLastMove(); Assert.IsTrue(game.WhitePlayer.CanCastleKingSide); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._1, File.C, Rank._1))); Assert.IsFalse(game.WhitePlayer.CanCastleQueenSide); game.UndoLastMove(); Assert.IsTrue(game.WhitePlayer.CanCastleQueenSide); } [TestMethod] public void TestCastlingHasBeenChecked() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.A, Rank._1, new Rook(Color.White)); game.AddPiece(File.H, Rank._1, new Rook(Color.White)); game.AddPiece(File.G, Rank._4, new Bishop(Color.White)); game.AddPiece(File.A, Rank._3, new Rook(Color.Black)); game.CurrentPlayer = game.BlackPlayer; game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.A, Rank._3, File.E, Rank._3))); Assert.IsTrue(game.WhitePlayer.IsChecked); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.G, Rank._4, File.E, Rank._2))); Assert.IsFalse(game.WhitePlayer.IsChecked); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._3, File.E, Rank._4))); Assert.AreSame(game.CurrentPlayer, game.WhitePlayer); var moves = game.GetPseudoLegalMoves(); var kingMoves = moves.Where(x => x.Piece is King && x.Piece.Color == Color.White).Select(x => x.ToString()).ToArray(); Assert.IsTrue(kingMoves.Contains("0-0")); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._1, File.G, Rank._1))); Assert.IsFalse(game.WhitePlayer.CanCastleKingSide); game.UndoLastMove(); Assert.IsTrue(game.WhitePlayer.CanCastleKingSide); } [TestMethod] public void TestBlockedCastling() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.A, Rank._1, new Rook(Color.White)); game.AddPiece(File.H, Rank._1, new Rook(Color.White)); game.AddPiece(File.G, Rank._5, new Rook(Color.Black)); //should block king side game.AddPiece(File.D, Rank._1, new Knight(Color.White)); //should block queen side game.SetInitials(); var moves = game.GetPseudoLegalMoves(); var kingMoves = moves.Where(x => x.Piece is King && x.Piece.Color == Color.White).Select(x => x.ToString()).ToArray(); Assert.IsFalse(kingMoves.Contains("0-0")); Assert.IsFalse(kingMoves.Contains("0-0-0")); } [TestMethod] public void TestMoveAndUndo() { var game = new Game(); game.New(); var result = game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._2, File.E, Rank._4)); Assert.AreEqual(true, result); Assert.IsNull(game.Board.Square(File.E, Rank._2).Piece); Assert.IsTrue(game.Board.Square(File.E, Rank._4).Piece is Pawn); Assert.IsTrue(game.CurrentPlayer == game.BlackPlayer); Assert.AreEqual(1, game.WhitePlayer.Moves.Count); game.UndoLastMove(); Assert.IsTrue(game.Board.Square(File.E, Rank._2).Piece is Pawn); Assert.IsNull(game.Board.Square(File.E, Rank._4).Piece); Assert.IsTrue(game.CurrentPlayer == game.WhitePlayer); Assert.AreEqual(0, game.WhitePlayer.Moves.Count); } [TestMethod] public void TestManyMovesAndUndo() { var game = new Game(); game.New(); Assert.AreEqual(20, game.GetPseudoLegalMoves().Count); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._2, File.E, Rank._4))); //e4 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._7, File.E, Rank._5))); //e5 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.G, Rank._1, File.F, Rank._3))); //Nf3 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.G, Rank._8, File.F, Rank._6))); //Nf6 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.F, Rank._1, File.C, Rank._4))); //Bc4 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.F, Rank._8, File.C, Rank._5))); //Bc5 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._1, File.G, Rank._1))); //0-0 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._8, File.G, Rank._8))); //0-0 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._2, File.D, Rank._4))); //d4 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.C, Rank._5, File.D, Rank._4))); //Bxd4 Assert.AreEqual(15, game.WhitePlayer.Pieces.Count()); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.F, Rank._3, File.D, Rank._4))); //Nxd4 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._5, File.D, Rank._4))); //Bxd4 Assert.AreEqual(14, game.WhitePlayer.Pieces.Count()); Assert.AreEqual(15, game.BlackPlayer.Pieces.Count()); game.UndoLastMove(); game.UndoLastMove(); game.UndoLastMove(); Assert.AreEqual(16, game.WhitePlayer.Pieces.Count()); Assert.AreEqual(16, game.BlackPlayer.Pieces.Count()); for (int i = 0; i < 9; i++) //from start { game.UndoLastMove(); } Assert.AreEqual(20, game.GetPseudoLegalMoves().Count); } [TestMethod] public void TestUndoCapture() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._2, new Pawn(Color.White)); game.AddPiece(File.D, Rank._7, new Pawn(Color.Black)); Assert.AreEqual(2, game.WhitePlayer.Pieces.Count()); Assert.AreEqual(2, game.BlackPlayer.Pieces.Count()); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._2, File.E, Rank._4))); //e4 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._7, File.D, Rank._5))); //e5 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._4, File.D, Rank._5))); //exd5 Assert.AreEqual(1, game.BlackPlayer.Pieces.Count()); game.UndoLastMove(); Assert.AreEqual(2, game.BlackPlayer.Pieces.Count()); game.UndoLastMove(); game.UndoLastMove(); //now from start //same moves again Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._2, File.E, Rank._4))); //e4 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._7, File.D, Rank._5))); //e5 Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._4, File.D, Rank._5))); //exd5 Assert.AreEqual(1, game.BlackPlayer.Pieces.Count()); } [TestMethod] public void TestEnPassantWhiteRight() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.D, Rank._4, new Pawn(Color.White)); game.AddPiece(File.E, Rank._7, new Pawn(Color.Black)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._4, File.D, Rank._5))); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._7, File.E, Rank._5))); var moves = game.GetPseudoLegalMoves(); var passant = moves.Single(x => x.IsEnpassant); Assert.IsTrue(passant.FromSquare.File == File.D && passant.FromSquare.Rank == Rank._5); Assert.IsTrue(passant.ToSquare.File == File.E && passant.ToSquare.Rank == Rank._6); Assert.IsTrue(passant.Capture is Pawn && passant.Capture.Color == Color.Black); } [TestMethod] public void TestEnPassantWhiteLeft() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.D, Rank._4, new Pawn(Color.White)); game.AddPiece(File.C, Rank._7, new Pawn(Color.Black)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._4, File.D, Rank._5))); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.C, Rank._7, File.C, Rank._5))); var moves = game.GetPseudoLegalMoves(); var passant = moves.Single(x => x.IsEnpassant); Assert.IsTrue(passant.FromSquare.File == File.D && passant.FromSquare.Rank == Rank._5); Assert.IsTrue(passant.ToSquare.File == File.C && passant.ToSquare.Rank == Rank._6); Assert.IsTrue(passant.Capture is Pawn && passant.Capture.Color == Color.Black); } [TestMethod] public void TestEnPassantBlackRight() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._2, new Pawn(Color.White)); game.AddPiece(File.D, Rank._4, new Pawn(Color.Black)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._2, File.E, Rank._4))); var moves = game.GetPseudoLegalMoves(); var passant = moves.Single(x => x.IsEnpassant); Assert.IsTrue(passant.FromSquare.File == File.D && passant.FromSquare.Rank == Rank._4); Assert.IsTrue(passant.ToSquare.File == File.E && passant.ToSquare.Rank == Rank._3); Assert.IsTrue(passant.Capture is Pawn && passant.Capture.Color == Color.White); } [TestMethod] public void TestEnPassantBlackLeft() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.C, Rank._2, new Pawn(Color.White)); game.AddPiece(File.D, Rank._4, new Pawn(Color.Black)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.C, Rank._2, File.C, Rank._4))); var moves = game.GetPseudoLegalMoves(); var passant = moves.Single(x => x.IsEnpassant); Assert.IsTrue(passant.FromSquare.File == File.D && passant.FromSquare.Rank == Rank._4); Assert.IsTrue(passant.ToSquare.File == File.C && passant.ToSquare.Rank == Rank._3); Assert.IsTrue(passant.Capture is Pawn && passant.Capture.Color == Color.White); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._4, File.C, Rank._3))); Assert.IsNull(passant.CapturedFrom.Piece); } [TestMethod] public void TestEnPassantBlackLeft_Negative() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.C, Rank._2, new Pawn(Color.White)); game.AddPiece(File.D, Rank._4, new Pawn(Color.Black)); game.SetInitials(); Assert.IsTrue(game.TryStringMove("c2-c4")); Assert.IsTrue(game.TryStringMove("e8-f8"));//Black King moves between Assert.IsTrue(game.TryStringMove("e1-f1"));//then white queen var moves = game.GetPseudoLegalMoves(); Assert.IsFalse(moves.Any(x => x.IsEnpassant)); } [TestMethod] public void TestInvalidMove() { var game = new Game(); game.New(); Assert.IsFalse(game.TryPossibleMoveCommand(new MoveCommand(File.A, Rank._1, File.F, Rank._1))); } [TestMethod] public void TestMoveToCheck() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.D, Rank._1, new Queen(Color.Black)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._1, File.F, Rank._2))); game.UndoLastMove(); Assert.IsFalse(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._1, File.F, Rank._1))); game.UndoLastMove(); Assert.IsFalse(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._1, File.E, Rank._2))); game.UndoLastMove(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._1, File.D, Rank._1))); } [TestMethod] public void TestCheck() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.F, Rank._2, new Rook(Color.White)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.F, Rank._2, File.E, Rank._2)));//white Assert.IsTrue(game.BlackPlayer.IsChecked); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._8, File.F, Rank._8)));//black Assert.IsFalse(game.BlackPlayer.IsChecked); game.UndoLastMove(); Assert.IsTrue(game.BlackPlayer.IsChecked); game.UndoLastMove(); Assert.IsFalse(game.BlackPlayer.IsChecked); } [TestMethod] public void TestCheckMate() { var game = new Game(); game.New(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.F, Rank._2, File.F, Rank._3))); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.E, Rank._7, File.E, Rank._6))); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.G, Rank._2, File.G, Rank._4))); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.D, Rank._8, File.H, Rank._4))); Assert.IsTrue(game.WhitePlayer.Mated); Assert.IsTrue(game.Ended); Assert.AreSame(game.Winner, game.BlackPlayer); game.UndoLastMove(); Assert.IsFalse(game.WhitePlayer.Mated); Assert.IsTrue(game.Winner == null); } [TestMethod] public void TestStaleMate() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.H, Rank._8, new King(Color.Black)); game.AddPiece(File.A, Rank._1, new King(Color.White)); game.AddPiece(File.G, Rank._2, new Queen(Color.White)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.G, Rank._2, File.G, Rank._6))); Assert.IsTrue(game.Ended); Assert.IsTrue(game.IsStaleMate); game.UndoLastMove(); Assert.IsFalse(game.Ended); Assert.IsFalse(game.IsStaleMate); } [TestMethod] public void TestNegativeStaleMate() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.H, Rank._8, new King(Color.Black)); game.AddPiece(File.A, Rank._1, new King(Color.White)); game.AddPiece(File.G, Rank._2, new Queen(Color.White)); game.AddPiece(File.C, Rank._7, new Pawn(Color.Black)); //preventing stale game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.G, Rank._2, File.G, Rank._6))); Assert.IsFalse(game.Ended); Assert.IsFalse(game.IsStaleMate); } [TestMethod] public void TestPromotion() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.H, Rank._8, new King(Color.Black)); game.AddPiece(File.A, Rank._1, new King(Color.White)); game.AddPiece(File.B, Rank._6, new Pawn(Color.White)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.B, Rank._6, File.B, Rank._7))); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.H, Rank._8, File.H, Rank._7))); Assert.AreEqual(-100, game.Material); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.B, Rank._7, File.B, Rank._8))); Assert.IsTrue(game.Board.Square(File.B, Rank._8).Piece is Queen); Assert.AreEqual(-900, game.Material); game.UndoLastMove(); Assert.AreEqual(-100, game.Material); var square = game.Board.Square(File.B, Rank._7); var pawn = (Pawn)square.Piece; Assert.AreSame(pawn.Square, game.Board.Square(File.B, Rank._7)); Assert.AreSame(square.Piece, pawn); game.UndoLastMove(); game.UndoLastMove(); //undone all moves pawn = game.WhitePlayer.Pieces.OfType<Pawn>().Single(); Assert.AreSame(pawn.Square.Piece, pawn); } [TestMethod] public void TestInsufficientMaterial() { var game = new Game(); game.New(); game.Reset(); game.AddPiece(File.E, Rank._8, new King(Color.Black)); game.AddPiece(File.E, Rank._1, new King(Color.White)); game.AddPiece(File.D, Rank._4, new Queen(Color.Black)); game.AddPiece(File.C, Rank._5, new Bishop(Color.White)); game.SetInitials(); Assert.IsTrue(game.TryPossibleMoveCommand(new MoveCommand(File.C, Rank._5, File.D, Rank._4))); Assert.IsTrue(game.Ended); Assert.AreEqual(0, game.WhitePlayer.Moves.First().ScoreAfterMove.Value); } [TestMethod] public void TestCopyGame() { var game = new Game(); game.New(); var gameFile = GameFile.Load("TestGames\\mated.txt"); foreach (var command in gameFile.MoveCommands) Assert.IsTrue(game.TryPossibleMoveCommand(command)); var copy = game.Copy(); Assert.AreNotSame(game, copy); } [TestMethod] public void TestMaterial() { var game = new Game(); game.New(); Assert.AreEqual(0, game.Material); Assert.IsTrue(game.TryStringMove("e2-e4")); Assert.AreEqual(0, game.Material); Assert.IsTrue(game.TryStringMove("d7-d5")); Assert.AreEqual(0, game.Material); Assert.IsTrue(game.TryStringMove("e4-d5")); Assert.AreEqual(-100, game.Material); game.UndoLastMove(); Assert.AreEqual(0, game.Material); } [TestMethod] public void TestDrawByRepetion() { var game = new Game(); game.New(); //start position Assert.IsTrue(game.TryStringMove("b1-c3")); Assert.IsTrue(game.TryStringMove("b8-c6")); Assert.IsTrue(game.TryStringMove("c3-b1")); Assert.IsTrue(game.TryStringMove("c6-b8")); //start position Assert.IsTrue(game.TryStringMove("b1-c3")); Assert.IsTrue(game.TryStringMove("b8-c6")); Assert.IsTrue(game.TryStringMove("c3-b1")); Assert.IsFalse(game.Ended); Assert.IsTrue(game.TryStringMove("c6-b8")); //start position, three times Assert.IsTrue(game.Ended); Assert.IsNull(game.Winner); } [TestMethod] public void TestGetFEN() { var game = new Game(); game.New(); Assert.AreEqual("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", game.GetFEN()); Assert.IsTrue(game.TryStringMove("e2-e4")); Assert.AreEqual("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1", game.GetFEN()); Assert.IsTrue(game.TryStringMove("c7-c5")); Assert.AreEqual("rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2", game.GetFEN()); Assert.IsTrue(game.TryStringMove("g1-f3")); Assert.AreEqual("rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2", game.GetFEN()); } [TestMethod] public void TestParseFEN() { var game = new Game(); game.New(); var fen = "rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2"; game.LoadFEN(fen); Assert.AreEqual(fen, game.GetFEN()); game = new Game(); game.New(); fen = "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2"; game.LoadFEN(fen); Assert.AreEqual(fen, game.GetFEN()); } [TestMethod] public void TestDrawby50moverule() { var game = new Game(); game.New(); var gameFile = GameFile.Load("TestGames\\drawby50moverule.txt"); game.Load(gameFile); Assert.IsTrue(game.Ended); game.UndoLastMove(); Assert.IsFalse(game.Ended); Assert.IsTrue(game.TryStringMove("h8-g8")); Assert.IsTrue(game.Ended); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.CSharp.RenameTracking; using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Editor.VisualBasic.RenameTracking; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking { internal sealed class RenameTrackingTestState : IDisposable { private readonly ITagger<RenameTrackingTag> _tagger; public readonly TestWorkspace Workspace; private readonly IWpfTextView _view; private readonly ITextUndoHistoryRegistry _historyRegistry; private string _notificationMessage = null; private readonly TestHostDocument _hostDocument; public TestHostDocument HostDocument { get { return _hostDocument; } } private readonly IEditorOperations _editorOperations; public IEditorOperations EditorOperations { get { return _editorOperations; } } private readonly MockRefactorNotifyService _mockRefactorNotifyService; public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } } private readonly CodeFixProvider _codeFixProvider; private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler(); public static async Task<RenameTrackingTestState> CreateAsync( string markup, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { var workspace = await CreateTestWorkspaceAsync(markup, languageName, TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic()); return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue); } public RenameTrackingTestState( TestWorkspace workspace, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { this.Workspace = workspace; _hostDocument = Workspace.Documents.First(); _view = _hostDocument.GetTextView(); _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value)); _editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view); _historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value; _mockRefactorNotifyService = new MockRefactorNotifyService { OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue, OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue }; var optionService = this.Workspace.Services.GetService<IOptionService>(); // Mock the action taken by the workspace INotificationService var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message); notificationService.NotificationCallback = callback; var tracker = new RenameTrackingTaggerProvider( _historyRegistry, Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value, Workspace.ExportProvider.GetExport<IInlineRenameService>().Value, Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value, SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService), Workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>()); _tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer()); if (languageName == LanguageNames.CSharp) { _codeFixProvider = new CSharpRenameTrackingCodeFixProvider( Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value, _historyRegistry, SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService)); } else if (languageName == LanguageNames.VisualBasic) { _codeFixProvider = new VisualBasicRenameTrackingCodeFixProvider( Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value, _historyRegistry, SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService)); } else { throw new ArgumentException("Invalid language name: " + languageName, "languageName"); } } private static Task<TestWorkspace> CreateTestWorkspaceAsync(string code, string languageName, ExportProvider exportProvider = null) { var xml = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document>{1}</Document> </Project> </Workspace>", languageName, code); return TestWorkspaceFactory.CreateWorkspaceAsync(xml, exportProvider: exportProvider); } public void SendEscape() { _commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), () => { }); } public void MoveCaret(int delta) { var position = _view.Caret.Position.BufferPosition.Position; _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta)); } public void Undo(int count = 1) { var history = _historyRegistry.GetHistory(_view.TextBuffer); history.Undo(count); } public void Redo(int count = 1) { var history = _historyRegistry.GetHistory(_view.TextBuffer); history.Redo(count); } public async Task AssertNoTag() { await WaitForAsyncOperationsAsync(); var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); Assert.Equal(0, tags.Count()); } public async Task<IList<Diagnostic>> GetDocumentDiagnosticsAsync(Document document = null) { document = document ?? this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id); var analyzer = new RenameTrackingDiagnosticAnalyzer(); return (await DiagnosticProviderTestUtilities.GetDocumentDiagnosticsAsync(analyzer, document, (await document.GetSyntaxRootAsync()).FullSpan)).ToList(); } public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false) { await WaitForAsyncOperationsAsync(); var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); // There should only ever be one tag Assert.Equal(1, tags.Count()); var tag = tags.Single(); var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id); var diagnostics = await GetDocumentDiagnosticsAsync(document); // There should be a single rename tracking diagnostic Assert.Equal(1, diagnostics.Count); Assert.Equal(RenameTrackingDiagnosticAnalyzer.DiagnosticId, diagnostics[0].Id); var actions = new List<CodeAction>(); var context = new CodeFixContext(document, diagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); await _codeFixProvider.RegisterCodeFixesAsync(context); // There should only be one code action Assert.Equal(1, actions.Count); Assert.Equal(string.Format(EditorFeaturesResources.RenameTo, expectedFromName, expectedToName), actions[0].Title); if (invokeAction) { var operations = (await actions[0].GetOperationsAsync(CancellationToken.None)).ToArray(); Assert.Equal(1, operations.Length); operations[0].Apply(this.Workspace, CancellationToken.None); } } public void AssertNoNotificationMessage() { Assert.Null(_notificationMessage); } public void AssertNotificationMessage() { Assert.NotNull(_notificationMessage); } private async Task WaitForAsyncOperationsAsync() { var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>(); await waiters.WaitAllAsync(); } public void Dispose() { Workspace.Dispose(); } } }
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2001 // // File: TextProperties.cs // // Contents: Properties of text, text line and paragraph // // Created: 2-25-2003 Worachai Chaoweeraprasit (wchao) // //------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Globalization; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Media.TextFormatting; using MS.Internal; using MS.Internal.Shaping; namespace MS.Internal.TextFormatting { /// <summary> /// Internal paragraph properties wrapper /// </summary> internal sealed class ParaProp { /// <summary> /// Constructing paragraph properties /// </summary> /// <param name="formatter">Text formatter</param> /// <param name="paragraphProperties">paragraph properties</param> /// <param name="optimalBreak">produce optimal break</param> internal ParaProp( TextFormatterImp formatter, TextParagraphProperties paragraphProperties, bool optimalBreak ) { _paragraphProperties = paragraphProperties; _emSize = TextFormatterImp.RealToIdeal(paragraphProperties.DefaultTextRunProperties.FontRenderingEmSize); _indent = TextFormatterImp.RealToIdeal(paragraphProperties.Indent); _paragraphIndent = TextFormatterImp.RealToIdeal(paragraphProperties.ParagraphIndent); _height = TextFormatterImp.RealToIdeal(paragraphProperties.LineHeight); if (_paragraphProperties.FlowDirection == FlowDirection.RightToLeft) { _statusFlags |= StatusFlags.Rtl; } if (optimalBreak) { _statusFlags |= StatusFlags.OptimalBreak; } } [Flags] private enum StatusFlags { Rtl = 0x00000001, // right-to-left reading OptimalBreak = 0x00000002, // produce optimal break } internal bool RightToLeft { get { return (_statusFlags & StatusFlags.Rtl) != 0; } } internal bool OptimalBreak { get { return (_statusFlags & StatusFlags.OptimalBreak) != 0; } } internal bool FirstLineInParagraph { get { return _paragraphProperties.FirstLineInParagraph; } } internal bool AlwaysCollapsible { get { return _paragraphProperties.AlwaysCollapsible; } } internal int Indent { get { return _indent; } } internal int ParagraphIndent { get { return _paragraphIndent; } } internal double DefaultIncrementalTab { get { return _paragraphProperties.DefaultIncrementalTab; } } internal IList<TextTabProperties> Tabs { get { return _paragraphProperties.Tabs; } } internal TextAlignment Align { get { return _paragraphProperties.TextAlignment; } } internal bool Justify { get { return _paragraphProperties.TextAlignment == TextAlignment.Justify; } } internal bool EmergencyWrap { get { return _paragraphProperties.TextWrapping == TextWrapping.Wrap; } } internal bool Wrap { get { return _paragraphProperties.TextWrapping == TextWrapping.WrapWithOverflow || EmergencyWrap; } } internal Typeface DefaultTypeface { get { return _paragraphProperties.DefaultTextRunProperties.Typeface; } } internal int EmSize { get { return _emSize; } } internal int LineHeight { get { return _height; } } internal TextMarkerProperties TextMarkerProperties { get { return _paragraphProperties.TextMarkerProperties; } } internal TextLexicalService Hyphenator { get { return _paragraphProperties.Hyphenator; } } internal TextDecorationCollection TextDecorations { get { return _paragraphProperties.TextDecorations; } } internal Brush DefaultTextDecorationsBrush { get { return _paragraphProperties.DefaultTextRunProperties.ForegroundBrush; } } private StatusFlags _statusFlags; private TextParagraphProperties _paragraphProperties; private int _emSize; private int _indent; private int _paragraphIndent; private int _height; } /// <summary> /// State of textrun started when it's fetched /// </summary> internal sealed class TextRunInfo { private CharacterBufferRange _charBufferRange; private int _textRunLength; private int _offsetToFirstCp; private TextRun _textRun; private Plsrun _plsrun; private CultureInfo _digitCulture; private ushort _charFlags; private ushort _runFlags; private TextModifierScope _modifierScope; private TextRunProperties _properties; /// <summary> /// Constructing a textrun info /// </summary> /// <param name="charBufferRange">characte buffer range for the run</param> /// <param name="textRunLength">textrun length</param> /// <param name="offsetToFirstCp">character offset to run first cp</param> /// <param name="textRun">text run</param> /// <param name="lsRunType">the internal LS run type </param> /// <param name="charFlags">character attribute flags</param> /// <param name="digitCulture">digit culture for the run</param> /// <param name="contextualSubstitution">contextual number substitution for the run</param> /// <param name="symbolTypeface">if true, indicates a text run in a symbol (i.e., non-Unicode) font</param> /// <param name="modifierScope">The current TextModifier scope for this TextRunInfo</param> internal TextRunInfo( CharacterBufferRange charBufferRange, int textRunLength, int offsetToFirstCp, TextRun textRun, Plsrun lsRunType, ushort charFlags, CultureInfo digitCulture, bool contextualSubstitution, bool symbolTypeface, TextModifierScope modifierScope ) { _charBufferRange = charBufferRange; _textRunLength = textRunLength; _offsetToFirstCp = offsetToFirstCp; _textRun = textRun; _plsrun = lsRunType; _charFlags = charFlags; _digitCulture = digitCulture; _runFlags = 0; _modifierScope = modifierScope; if (contextualSubstitution) { _runFlags |= (ushort)RunFlags.ContextualSubstitution; } if (symbolTypeface) { _runFlags |= (ushort)RunFlags.IsSymbol; } } /// <summary> /// Text run /// </summary> internal TextRun TextRun { get { return _textRun; } } /// <summary> /// The final TextRunProperties of the TextRun /// </summary> internal TextRunProperties Properties { get { // The non-null value is cached if (_properties == null) { if (_modifierScope != null) { _properties = _modifierScope.ModifyProperties(_textRun.Properties); } else { _properties = _textRun.Properties; } } return _properties; } } /// <summary> /// character buffer /// </summary> internal CharacterBuffer CharacterBuffer { get { return _charBufferRange.CharacterBuffer; } } /// <summary> /// Character offset to run first character in the buffer /// </summary> internal int OffsetToFirstChar { get { return _charBufferRange.OffsetToFirstChar; } } /// <summary> /// Character offset to run first cp from line start /// </summary> internal int OffsetToFirstCp { get { return _offsetToFirstCp; } } /// <summary> /// String length /// </summary> internal int StringLength { get { return _charBufferRange.Length; } set { _charBufferRange = new CharacterBufferRange(_charBufferRange.CharacterBufferReference, value); } } /// <summary> /// Run length /// </summary> internal int Length { get { return _textRunLength; } set { _textRunLength = value; } } /// <summary> /// State of character in the run /// </summary> internal ushort CharacterAttributeFlags { get { return _charFlags; } set { _charFlags = value; } } /// <summary> /// Digit culture for the run. /// </summary> internal CultureInfo DigitCulture { get { return _digitCulture; } } /// <summary> /// Specifies whether the run requires contextual number substitution. /// </summary> internal bool ContextualSubstitution { get { return (_runFlags & (ushort)RunFlags.ContextualSubstitution) != 0; } } /// <summary> /// Specifies whether the run is in a non-Unicode font, such as Symbol or Wingdings. /// </summary> /// <remarks> /// Non-Unicode runs require special handling because code points do not have their /// standard Unicode meanings. /// </remarks> internal bool IsSymbol { get { return (_runFlags & (ushort)RunFlags.IsSymbol) != 0; } } /// <summary> /// Plsrun type /// </summary> internal Plsrun Plsrun { get { return _plsrun; } } /// <summary> /// Is run an end of line? /// </summary> internal bool IsEndOfLine { get { return _textRun is TextEndOfLine; } } /// <summary> /// The modification scope of this run /// </summary> internal TextModifierScope TextModifierScope { get { return _modifierScope; } } /// <summary> /// Get rough width of the run /// </summary> internal int GetRoughWidth(double realToIdeal) { TextRunProperties properties = _textRun.Properties; if (properties != null) { // estimate rough width of each character in a run being 75% of Em. return (int)Math.Round(properties.FontRenderingEmSize * 0.75 * _textRunLength * realToIdeal); } return 0; } /// <summary> /// Map TextRun type to known plsrun type /// </summary> internal static Plsrun GetRunType(TextRun textRun) { if (textRun is ITextSymbols || textRun is TextShapeableSymbols) return Plsrun.Text; if (textRun is TextEmbeddedObject) return Plsrun.InlineObject; if (textRun is TextEndOfParagraph) return Plsrun.ParaBreak; if (textRun is TextEndOfLine) return Plsrun.LineBreak; // Other text run type are all considered hidden by LS return Plsrun.Hidden; } [Flags] private enum RunFlags { ContextualSubstitution = 0x0001, IsSymbol = 0x0002, } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Android.Bluetooth; using Android.Bluetooth.LE; using Android.OS; using Java.Util; using Plugin.BLE.Abstractions; using Plugin.BLE.Abstractions.Contracts; using Plugin.BLE.Extensions; using Object = Java.Lang.Object; using Trace = Plugin.BLE.Abstractions.Trace; using Android.App; namespace Plugin.BLE.Android { public class Adapter : AdapterBase { private readonly BluetoothManager _bluetoothManager; private readonly BluetoothAdapter _bluetoothAdapter; private readonly Api18BleScanCallback _api18ScanCallback; private readonly Api21BleScanCallback _api21ScanCallback; public override IList<IDevice> ConnectedDevices => ConnectedDeviceRegistry.Values.ToList(); /// <summary> /// Used to store all connected devices /// </summary> public Dictionary<string, IDevice> ConnectedDeviceRegistry { get; } public Adapter(BluetoothManager bluetoothManager) { _bluetoothManager = bluetoothManager; _bluetoothAdapter = bluetoothManager.Adapter; ConnectedDeviceRegistry = new Dictionary<string, IDevice>(); // TODO: bonding //var bondStatusBroadcastReceiver = new BondStatusBroadcastReceiver(); //Application.Context.RegisterReceiver(bondStatusBroadcastReceiver, // new IntentFilter(BluetoothDevice.ActionBondStateChanged)); ////forward events from broadcast receiver //bondStatusBroadcastReceiver.BondStateChanged += (s, args) => //{ // //DeviceBondStateChanged(this, args); //}; if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) { _api21ScanCallback = new Api21BleScanCallback(this); } else { _api18ScanCallback = new Api18BleScanCallback(this); } } protected override Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken) { // clear out the list DiscoveredDevices.Clear(); if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { StartScanningOld(serviceUuids); } else { StartScanningNew(serviceUuids); } return Task.FromResult(true); } private void StartScanningOld(Guid[] serviceUuids) { var hasFilter = serviceUuids?.Any() ?? false; UUID[] uuids = null; if (hasFilter) { uuids = serviceUuids.Select(u => UUID.FromString(u.ToString())).ToArray(); } Trace.Message("Adapter < 21: Starting a scan for devices."); #pragma warning disable 618 _bluetoothAdapter.StartLeScan(uuids, _api18ScanCallback); #pragma warning restore 618 } private void StartScanningNew(Guid[] serviceUuids) { var hasFilter = serviceUuids?.Any() ?? false; List<ScanFilter> scanFilters = null; if (hasFilter) { scanFilters = new List<ScanFilter>(); foreach (var serviceUuid in serviceUuids) { var sfb = new ScanFilter.Builder(); sfb.SetServiceUuid(ParcelUuid.FromString(serviceUuid.ToString())); scanFilters.Add(sfb.Build()); } } var ssb = new ScanSettings.Builder(); ssb.SetScanMode(ScanMode.ToNative()); //ssb.SetCallbackType(ScanCallbackType.AllMatches); if (_bluetoothAdapter.BluetoothLeScanner != null) { Trace.Message($"Adapter >=21: Starting a scan for devices. ScanMode: {ScanMode}"); if (hasFilter) { Trace.Message($"ScanFilters: {string.Join(", ", serviceUuids)}"); } _bluetoothAdapter.BluetoothLeScanner.StartScan(scanFilters, ssb.Build(), _api21ScanCallback); } else { Trace.Message("Adapter >= 21: Scan failed. Bluetooth is probably off"); } } protected override void StopScanNative() { if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { Trace.Message("Adapter < 21: Stopping the scan for devices."); #pragma warning disable 618 _bluetoothAdapter.StopLeScan(_api18ScanCallback); #pragma warning restore 618 } else { Trace.Message("Adapter >= 21: Stopping the scan for devices."); _bluetoothAdapter.BluetoothLeScanner?.StopScan(_api21ScanCallback); } } protected override Task ConnectToDeviceNativeAsync(IDevice device, ConnectParameters connectParameters, CancellationToken cancellationToken) { ((Device)device).Connect(connectParameters, cancellationToken); return Task.CompletedTask; } protected override void DisconnectDeviceNative(IDevice device) { //make sure everything is disconnected ((Device)device).Disconnect(); } public override async Task<IDevice> ConnectToKnownDeviceAsync(Guid deviceGuid, ConnectParameters connectParameters = default(ConnectParameters), CancellationToken cancellationToken = default(CancellationToken)) { var macBytes = deviceGuid.ToByteArray().Skip(10).Take(6).ToArray(); var nativeDevice = _bluetoothAdapter.GetRemoteDevice(macBytes); var device = new Device(this, nativeDevice, null, 0, new byte[] { }); await ConnectToDeviceAsync(device, connectParameters, cancellationToken); return device; } public override List<IDevice> GetSystemConnectedOrPairedDevices(Guid[] services = null) { if (services != null) { Trace.Message("Caution: GetSystemConnectedDevices does not take into account the 'services' parameter on Android."); } //add dualMode type too as they are BLE too ;) var connectedDevices = _bluetoothManager.GetConnectedDevices(ProfileType.Gatt).Where(d => d.Type == BluetoothDeviceType.Le || d.Type == BluetoothDeviceType.Dual); var bondedDevices = _bluetoothAdapter.BondedDevices.Where(d => d.Type == BluetoothDeviceType.Le || d.Type == BluetoothDeviceType.Dual); return connectedDevices.Union(bondedDevices, new DeviceComparer()).Select(d => new Device(this, d, null, 0)).Cast<IDevice>().ToList(); } private class DeviceComparer : IEqualityComparer<BluetoothDevice> { public bool Equals(BluetoothDevice x, BluetoothDevice y) { return x.Address == y.Address; } public int GetHashCode(BluetoothDevice obj) { return obj.GetHashCode(); } } public class Api18BleScanCallback : Object, BluetoothAdapter.ILeScanCallback { private readonly Adapter _adapter; public Api18BleScanCallback(Adapter adapter) { _adapter = adapter; } public void OnLeScan(BluetoothDevice bleDevice, int rssi, byte[] scanRecord) { Trace.Message("Adapter.LeScanCallback: " + bleDevice.Name); _adapter.HandleDiscoveredDevice(new Device(_adapter, bleDevice, null, rssi, scanRecord)); } } public class Api21BleScanCallback : ScanCallback { private readonly Adapter _adapter; public Api21BleScanCallback(Adapter adapter) { _adapter = adapter; } public override void OnScanFailed(ScanFailure errorCode) { Trace.Message("Adapter: Scan failed with code {0}", errorCode); base.OnScanFailed(errorCode); } public override void OnScanResult(ScanCallbackType callbackType, ScanResult result) { base.OnScanResult(callbackType, result); /* Might want to transition to parsing the API21+ ScanResult, but sort of a pain for now List<AdvertisementRecord> records = new List<AdvertisementRecord>(); records.Add(new AdvertisementRecord(AdvertisementRecordType.Flags, BitConverter.GetBytes(result.ScanRecord.AdvertiseFlags))); if (!string.IsNullOrEmpty(result.ScanRecord.DeviceName)) { records.Add(new AdvertisementRecord(AdvertisementRecordType.CompleteLocalName, Encoding.UTF8.GetBytes(result.ScanRecord.DeviceName))); } for (int i = 0; i < result.ScanRecord.ManufacturerSpecificData.Size(); i++) { int key = result.ScanRecord.ManufacturerSpecificData.KeyAt(i); var arr = result.ScanRecord.GetManufacturerSpecificData(key); byte[] data = new byte[arr.Length + 2]; BitConverter.GetBytes((ushort)key).CopyTo(data,0); arr.CopyTo(data, 2); records.Add(new AdvertisementRecord(AdvertisementRecordType.ManufacturerSpecificData, data)); } foreach(var uuid in result.ScanRecord.ServiceUuids) { records.Add(new AdvertisementRecord(AdvertisementRecordType.UuidsIncomplete128Bit, uuid.Uuid.)); } foreach(var key in result.ScanRecord.ServiceData.Keys) { records.Add(new AdvertisementRecord(AdvertisementRecordType.ServiceData, result.ScanRecord.ServiceData)); }*/ var device = new Device(_adapter, result.Device, null, result.Rssi, result.ScanRecord.GetBytes()); //Device device; //if (result.ScanRecord.ManufacturerSpecificData.Size() > 0) //{ // int key = result.ScanRecord.ManufacturerSpecificData.KeyAt(0); // byte[] mdata = result.ScanRecord.GetManufacturerSpecificData(key); // byte[] mdataWithKey = new byte[mdata.Length + 2]; // BitConverter.GetBytes((ushort)key).CopyTo(mdataWithKey, 0); // mdata.CopyTo(mdataWithKey, 2); // device = new Device(result.Device, null, null, result.Rssi, mdataWithKey); //} //else //{ // device = new Device(result.Device, null, null, result.Rssi, new byte[0]); //} _adapter.HandleDiscoveredDevice(device); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using FunWithSqlServer.Models; using FunWithSqlServer.Models.ManageViewModels; using FunWithSqlServer.Services; namespace FunWithSqlServer.Controllers { [Authorize] public class ManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly string _externalCookieScheme; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IOptions<IdentityCookieOptions> identityCookieOptions, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<ManageController>(); } // // GET: /Manage/Index [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } // // GET: /Manage/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // GET: /Manage/VerifyPhoneNumber [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } // // POST: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } //GET: /Manage/ManageLogins [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LinkLogin(string provider) { // Clear the existing external cookie to ensure a clean login process await HttpContext.Authentication.SignOutAsync(_externalCookieScheme); // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action(nameof(LinkLoginCallback), "Manage"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return Challenge(properties, provider); } // // GET: /Manage/LinkLoginCallback [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); } var result = await _userManager.AddLoginAsync(user, info); var message = ManageMessageId.Error; if (result.Succeeded) { message = ManageMessageId.AddLoginSuccess; // Clear the existing external cookie to ensure a clean login process await HttpContext.Authentication.SignOutAsync(_externalCookieScheme); } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } #endregion } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class Supplement : IEquatable<Supplement> { /// <summary> /// Initializes a new instance of the <see cref="Supplement" /> class. /// Initializes a new instance of the <see cref="Supplement" />class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="CreateDate">CreateDate.</param> /// <param name="ModifyDate">ModifyDate.</param> /// <param name="OriginalSKUId">OriginalSKUId (required).</param> /// <param name="SupplementSKUId">SupplementSKUId (required).</param> /// <param name="Type">Type (required).</param> /// <param name="SupplementQuantity">SupplementQuantity (required).</param> /// <param name="CustomFields">CustomFields.</param> public Supplement(int? LobId = null, DateTime? CreateDate = null, DateTime? ModifyDate = null, int? OriginalSKUId = null, int? SupplementSKUId = null, string Type = null, double? SupplementQuantity = null, Dictionary<string, Object> CustomFields = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for Supplement and cannot be null"); } else { this.LobId = LobId; } // to ensure "OriginalSKUId" is required (not null) if (OriginalSKUId == null) { throw new InvalidDataException("OriginalSKUId is a required property for Supplement and cannot be null"); } else { this.OriginalSKUId = OriginalSKUId; } // to ensure "SupplementSKUId" is required (not null) if (SupplementSKUId == null) { throw new InvalidDataException("SupplementSKUId is a required property for Supplement and cannot be null"); } else { this.SupplementSKUId = SupplementSKUId; } // to ensure "Type" is required (not null) if (Type == null) { throw new InvalidDataException("Type is a required property for Supplement and cannot be null"); } else { this.Type = Type; } // to ensure "SupplementQuantity" is required (not null) if (SupplementQuantity == null) { throw new InvalidDataException("SupplementQuantity is a required property for Supplement and cannot be null"); } else { this.SupplementQuantity = SupplementQuantity; } this.CreateDate = CreateDate; this.ModifyDate = ModifyDate; this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; set; } /// <summary> /// Gets or Sets OriginalSKUId /// </summary> [DataMember(Name="originalSKUId", EmitDefaultValue=false)] public int? OriginalSKUId { get; set; } /// <summary> /// Gets or Sets SupplementSKUId /// </summary> [DataMember(Name="supplementSKUId", EmitDefaultValue=false)] public int? SupplementSKUId { get; set; } /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name="type", EmitDefaultValue=false)] public string Type { get; set; } /// <summary> /// Gets or Sets SupplementQuantity /// </summary> [DataMember(Name="supplementQuantity", EmitDefaultValue=false)] public double? SupplementQuantity { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Supplement {\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" OriginalSKUId: ").Append(OriginalSKUId).Append("\n"); sb.Append(" SupplementSKUId: ").Append(SupplementSKUId).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" SupplementQuantity: ").Append(SupplementQuantity).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Supplement); } /// <summary> /// Returns true if Supplement instances are equal /// </summary> /// <param name="other">Instance of Supplement to be compared</param> /// <returns>Boolean</returns> public bool Equals(Supplement other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.OriginalSKUId == other.OriginalSKUId || this.OriginalSKUId != null && this.OriginalSKUId.Equals(other.OriginalSKUId) ) && ( this.SupplementSKUId == other.SupplementSKUId || this.SupplementSKUId != null && this.SupplementSKUId.Equals(other.SupplementSKUId) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ) && ( this.SupplementQuantity == other.SupplementQuantity || this.SupplementQuantity != null && this.SupplementQuantity.Equals(other.SupplementQuantity) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.OriginalSKUId != null) hash = hash * 59 + this.OriginalSKUId.GetHashCode(); if (this.SupplementSKUId != null) hash = hash * 59 + this.SupplementSKUId.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); if (this.SupplementQuantity != null) hash = hash * 59 + this.SupplementQuantity.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
// // rootcontext.cs: keeps track of our tree representation, and assemblies loaded. // // Author: Miguel de Icaza (miguel@ximian.com) // Ravi Pratap (ravi@ximian.com) // Marek Safar (marek.safar@gmail.com) // // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001 Ximian, Inc (http://www.ximian.com) // Copyright 2004-2008 Novell, Inc using System.Collections.Generic; using System.IO; using System.Text; using System.Globalization; using System; namespace Mono.CSharp { public enum LanguageVersion { ISO_1 = 1, ISO_2 = 2, V_3 = 3, V_4 = 4, Future = 100, Default = LanguageVersion.V_4, } public enum RuntimeVersion { v1, v2, v4 } public enum Target { Library, Exe, Module, WinExe } public enum Platform { AnyCPU, X86, X64, IA64 } public class CompilerSettings { public Target Target; public Platform Platform; public string TargetExt; public bool VerifyClsCompliance; public bool Optimize; public LanguageVersion Version; public bool EnhancedWarnings; public bool LoadDefaultReferences; public string SdkVersion; public string StrongNameKeyFile; public string StrongNameKeyContainer; public bool StrongNameDelaySign; // // Assemblies references to be loaded // public List<string> AssemblyReferences; // // External aliases for assemblies // public List<Tuple<string, string>> AssemblyReferencesAliases; // // Modules to be embedded // public List<string> Modules; // // Lookup paths for referenced assemblies // public List<string> ReferencesLookupPaths; // // Encoding. // public Encoding Encoding; // // If set, enable XML documentation generation // public /*Documentation*/object Documentation; public string MainClass; // // Output file // public string OutputFile; // // The default compiler checked state // public bool Checked; // // If true, the compiler is operating in statement mode, // this currently turns local variable declaration into // static variables of a class // public bool StatementMode; // TODO: SUPER UGLY // // Whether to allow Unsafe code // public bool Unsafe; public string Win32ResourceFile; public string Win32IconFile; // // A list of resource files for embedding // public List<AssemblyResource> Resources; public bool GenerateDebugInfo; // Compiler debug flags only public bool ParseOnly, TokenizeOnly, Timestamps; // // Whether we are being linked against the standard libraries. // This is only used to tell whether `System.Object' should // have a base class or not. // public bool StdLib; public RuntimeVersion StdLibRuntimeVersion; public CompilerSettings () { StdLib = true; Target = Target.Exe; TargetExt = ".exe"; Platform = Platform.AnyCPU; Version = LanguageVersion.Default; VerifyClsCompliance = true; Optimize = true; Encoding = Encoding.UTF8; LoadDefaultReferences = true; StdLibRuntimeVersion = RuntimeVersion.v4; AssemblyReferences = new List<string> (); AssemblyReferencesAliases = new List<Tuple<string, string>> (); Modules = new List<string> (); ReferencesLookupPaths = new List<string> (); } public bool HasKeyFileOrContainer { get { return StrongNameKeyFile != null || StrongNameKeyContainer != null; } } public bool NeedsEntryPoint { get { return Target == Target.Exe || Target == Target.WinExe; } } } public class CommandLineParser { enum ParseResult { Success, Error, Stop, UnknownOption } static readonly char[] argument_value_separator = new char[] { ';', ',' }; static readonly char[] numeric_value_separator = new char[] { ';', ',', ' ' }; readonly Report report; readonly TextWriter output; bool stop_argument; public event Func<string[], int, int> UnknownOptionHandler; public CommandLineParser (Report report) : this (report, Console.Out) { } public CommandLineParser (Report report, TextWriter messagesOutput) { this.report = report; this.output = messagesOutput; } public bool HasBeenStopped { get { return stop_argument; } } void About () { output.WriteLine ( "The Mono C# compiler is Copyright 2001-2011, Novell, Inc.\n\n" + "The compiler source code is released under the terms of the \n" + "MIT X11 or GNU GPL licenses\n\n" + "For more information on Mono, visit the project Web site\n" + " http://www.mono-project.com\n\n" + "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto"); } public CompilerSettings ParseArguments (string[] args) { CompilerSettings settings = new CompilerSettings (); List<string> response_file_list = null; bool parsing_options = true; stop_argument = false; for (int i = 0; i < args.Length; i++) { string arg = args[i]; if (arg.Length == 0) continue; if (arg[0] == '@') { string[] extra_args; string response_file = arg.Substring (1); if (response_file_list == null) response_file_list = new List<string> (); if (response_file_list.Contains (response_file)) { report.Error (1515, "Response file `{0}' specified multiple times", response_file); return null; } response_file_list.Add (response_file); extra_args = LoadArgs (response_file); if (extra_args == null) { report.Error (2011, "Unable to open response file: " + response_file); return null; } args = AddArgs (args, extra_args); continue; } if (parsing_options) { if (arg == "--") { parsing_options = false; continue; } bool dash_opt = arg[0] == '-'; bool slash_opt = arg[0] == '/'; if (dash_opt) { switch (ParseOptionUnix (arg, ref args, ref i, settings)) { case ParseResult.Error: case ParseResult.Success: continue; case ParseResult.Stop: stop_argument = true; return settings; case ParseResult.UnknownOption: if (UnknownOptionHandler != null) { var ret = UnknownOptionHandler (args, i); if (ret != -1) { i = ret; continue; } } break; } } if (dash_opt || slash_opt) { // Try a -CSCOPTION string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg; switch (ParseOption (csc_opt, ref args, settings)) { case ParseResult.Error: case ParseResult.Success: continue; case ParseResult.UnknownOption: // Need to skip `/home/test.cs' however /test.cs is considered as error if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0)) break; if (UnknownOptionHandler != null) { var ret = UnknownOptionHandler (args, i); if (ret != -1) { i = ret; continue; } } Error_WrongOption (arg); return null; case ParseResult.Stop: stop_argument = true; return settings; } } } ProcessSourceFiles (arg, false); } return settings; } void ProcessSourceFiles (string spec, bool recurse) { string path, pattern; SplitPathAndPattern (spec, out path, out pattern); if (pattern.IndexOf ('*') == -1) { AddSourceFile (spec); return; } string[] files = null; try { throw new NotSupportedException("Directory.GetFiles"); //files = Directory.GetFiles (path, pattern); } catch (System.IO.DirectoryNotFoundException) { report.Error (2001, "Source file `" + spec + "' could not be found"); return; } catch (System.IO.IOException) { report.Error (2001, "Source file `" + spec + "' could not be found"); return; } foreach (string f in files) { AddSourceFile (f); } if (!recurse) return; string[] dirs = new string[0]; //try { // dirs = Directory.GetDirectories (path); //} catch { //} foreach (string d in dirs) { // Don't include path in this string, as each // directory entry already does ProcessSourceFiles (d + "/" + pattern, true); } } static string[] AddArgs (string[] args, string[] extra_args) { string[] new_args; new_args = new string[extra_args.Length + args.Length]; // if args contains '--' we have to take that into account // split args into first half and second half based on '--' // and add the extra_args before -- int split_position = Array.IndexOf (args, "--"); if (split_position != -1) { Array.Copy (args, new_args, split_position); extra_args.CopyTo (new_args, split_position); Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position); } else { args.CopyTo (new_args, 0); extra_args.CopyTo (new_args, args.Length); } return new_args; } void AddAssemblyReference (string alias, string assembly, CompilerSettings settings) { if (assembly.Length == 0) { report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias); return; } if (!IsExternAliasValid (alias)) { report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias); return; } settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly)); } void AddResource (AssemblyResource res, CompilerSettings settings) { if (settings.Resources == null) { settings.Resources = new List<AssemblyResource> (); settings.Resources.Add (res); return; } if (settings.Resources.Contains (res)) { report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name); return; } settings.Resources.Add (res); } void AddSourceFile (string f) { Location.AddFile (report, f); } void Error_RequiresArgument (string option) { report.Error (2006, "Missing argument for `{0}' option", option); } void Error_RequiresFileName (string option) { report.Error (2005, "Missing file specification for `{0}' option", option); } void Error_WrongOption (string option) { report.Error (2007, "Unrecognized command-line option: `{0}'", option); } static bool IsExternAliasValid (string identifier) { if (identifier.Length == 0) return false; if (identifier[0] != '_' && !char.IsLetter (identifier[0])) return false; for (int i = 1; i < identifier.Length; i++) { char c = identifier[i]; if (char.IsLetter (c) || char.IsDigit (c)) continue; UnicodeCategory category = char.GetUnicodeCategory (c); if (category != UnicodeCategory.Format || category != UnicodeCategory.NonSpacingMark || category != UnicodeCategory.SpacingCombiningMark || category != UnicodeCategory.ConnectorPunctuation) return false; } return true; } static string[] LoadArgs (string file) { StreamReader f; var args = new List<string> (); string line; try { f = new StreamReader (file); } catch { return null; } StringBuilder sb = new StringBuilder (); while ((line = f.ReadLine ()) != null) { int t = line.Length; for (int i = 0; i < t; i++) { char c = line[i]; if (c == '"' || c == '\'') { char end = c; for (i++; i < t; i++) { c = line[i]; if (c == end) break; sb.Append (c); } } else if (c == ' ') { if (sb.Length > 0) { args.Add (sb.ToString ()); sb.Length = 0; } } else sb.Append (c); } if (sb.Length > 0) { args.Add (sb.ToString ()); sb.Length = 0; } } return args.ToArray (); } void OtherFlags () { output.WriteLine ( "Other flags in the compiler\n" + " --fatal[=COUNT] Makes errors after COUNT fatal\n" + " --lint Enhanced warnings\n" + " --parse Only parses the source file\n" + " --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" + " --stacktrace Shows stack trace at error location\n" + " --timestamp Displays time stamps of various compiler events\n" + " -v Verbose parsing (for debugging the parser)\n" + " --mcs-debug X Sets MCS debugging level to X\n"); } // // This parses the -arg and /arg options to the compiler, even if the strings // in the following text use "/arg" on the strings. // ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings) { int idx = option.IndexOf (':'); string arg, value; if (idx == -1) { arg = option; value = ""; } else { arg = option.Substring (0, idx); value = option.Substring (idx + 1); } switch (arg.ToLowerInvariant ()) { case "/nologo": return ParseResult.Success; case "/t": case "/target": switch (value) { case "exe": settings.Target = Target.Exe; break; case "winexe": settings.Target = Target.WinExe; break; case "library": settings.Target = Target.Library; settings.TargetExt = ".dll"; break; case "module": settings.Target = Target.Module; settings.TargetExt = ".netmodule"; break; default: report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'"); return ParseResult.Error; } return ParseResult.Success; case "/out": if (value.Length == 0) { Error_RequiresFileName (option); return ParseResult.Error; } settings.OutputFile = value; return ParseResult.Success; case "/o": case "/o+": case "/optimize": case "/optimize+": settings.Optimize = true; return ParseResult.Success; case "/o-": case "/optimize-": settings.Optimize = false; return ParseResult.Success; // TODO: Not supported by csc 3.5+ case "/incremental": case "/incremental+": case "/incremental-": // nothing. return ParseResult.Success; case "/d": case "/define": { if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } foreach (string d in value.Split (argument_value_separator)) { string conditional = d.Trim (); if (!Tokenizer.IsValidIdentifier (conditional)) { report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional); continue; } RootContext.AddConditional (conditional); } return ParseResult.Success; } case "/bugreport": // // We should collect data, runtime, etc and store in the file specified // output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs"); return ParseResult.Success; case "/pkg": { string packages; if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' })); string pkgout = null;// Driver.GetPackageFlags(packages, report); if (pkgout == null) return ParseResult.Error; string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' }); args = AddArgs (args, xargs); return ParseResult.Success; } case "/linkres": case "/linkresource": case "/res": case "/resource": AssemblyResource res = null; string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries); switch (s.Length) { case 1: if (s[0].Length == 0) goto default; res = new AssemblyResource (s[0], Path.GetFileName (s[0])); break; case 2: res = new AssemblyResource (s[0], s[1]); break; case 3: if (s[2] != "public" && s[2] != "private") { report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]); return ParseResult.Error; } res = new AssemblyResource (s[0], s[1], s[2] == "private"); break; default: report.Error (-2005, "Wrong number of arguments for option `{0}'", option); return ParseResult.Error; } if (res != null) { res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R'; AddResource (res, settings); } return ParseResult.Success; case "/recurse": if (value.Length == 0) { Error_RequiresFileName (option); return ParseResult.Error; } ProcessSourceFiles (value, true); return ParseResult.Success; case "/r": case "/reference": { if (value.Length == 0) { Error_RequiresFileName (option); return ParseResult.Error; } string[] refs = value.Split (argument_value_separator); foreach (string r in refs) { if (r.Length == 0) continue; string val = r; int index = val.IndexOf ('='); if (index > -1) { string alias = r.Substring (0, index); string assembly = r.Substring (index + 1); AddAssemblyReference (alias, assembly, settings); if (refs.Length != 1) { report.Error (2034, "Cannot specify multiple aliases using single /reference option"); return ParseResult.Error; } } else { settings.AssemblyReferences.Add (val); } } return ParseResult.Success; } case "/addmodule": { if (value.Length == 0) { Error_RequiresFileName (option); return ParseResult.Error; } string[] refs = value.Split (argument_value_separator); foreach (string r in refs) { settings.Modules.Add (r); } return ParseResult.Success; } case "/win32res": { if (value.Length == 0) { Error_RequiresFileName (option); return ParseResult.Error; } if (settings.Win32IconFile != null) report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time"); settings.Win32ResourceFile = value; return ParseResult.Success; } case "/win32icon": { if (value.Length == 0) { Error_RequiresFileName (option); return ParseResult.Error; } if (settings.Win32ResourceFile != null) report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time"); settings.Win32IconFile = value; return ParseResult.Success; } case "/doc": { if (value.Length == 0) { Error_RequiresFileName (option); return ParseResult.Error; } //settings.Documentation = new Documentation (value); return ParseResult.Error; } case "/lib": { string[] libdirs; if (value.Length == 0) { return ParseResult.Error; } libdirs = value.Split (argument_value_separator); foreach (string dir in libdirs) settings.ReferencesLookupPaths.Add (dir); return ParseResult.Success; } case "/debug-": settings.GenerateDebugInfo = false; return ParseResult.Success; case "/debug": if (value == "full" || value == "") settings.GenerateDebugInfo = true; return ParseResult.Success; case "/debug+": settings.GenerateDebugInfo = true; return ParseResult.Success; case "/checked": case "/checked+": settings.Checked = true; return ParseResult.Success; case "/checked-": settings.Checked = false; return ParseResult.Success; case "/clscheck": case "/clscheck+": settings.VerifyClsCompliance = true; return ParseResult.Success; case "/clscheck-": settings.VerifyClsCompliance = false; return ParseResult.Success; case "/unsafe": case "/unsafe+": settings.Unsafe = true; return ParseResult.Success; case "/unsafe-": settings.Unsafe = false; return ParseResult.Success; case "/warnaserror": case "/warnaserror+": if (value.Length == 0) { report.WarningsAreErrors = true; } else { foreach (string wid in value.Split (numeric_value_separator)) report.AddWarningAsError (wid); } return ParseResult.Success; case "/warnaserror-": if (value.Length == 0) { report.WarningsAreErrors = false; } else { foreach (string wid in value.Split (numeric_value_separator)) report.RemoveWarningAsError (wid); } return ParseResult.Success; case "/warn": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } SetWarningLevel (value); return ParseResult.Success; case "/nowarn": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } var warns = value.Split (numeric_value_separator); foreach (string wc in warns) { try { if (wc.Trim ().Length == 0) continue; int warn = Int32.Parse (wc); if (warn < 1) { throw new ArgumentOutOfRangeException ("warn"); } report.SetIgnoreWarning (warn); } catch { report.Error (1904, "`{0}' is not a valid warning number", wc); return ParseResult.Error; } } return ParseResult.Success; case "/noconfig": settings.LoadDefaultReferences = false; return ParseResult.Success; case "/platform": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } switch (value.ToLower (CultureInfo.InvariantCulture)) { case "anycpu": settings.Platform = Platform.AnyCPU; break; case "x86": settings.Platform = Platform.X86; break; case "x64": settings.Platform = Platform.X64; break; case "itanium": settings.Platform = Platform.IA64; break; default: report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'"); return ParseResult.Error; } return ParseResult.Success; case "/sdk": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } settings.SdkVersion = value; return ParseResult.Success; // We just ignore this. case "/errorreport": case "/filealign": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } return ParseResult.Success; case "/helpinternal": OtherFlags (); return ParseResult.Stop; case "/help": case "/?": Usage (); return ParseResult.Stop; case "/main": case "/m": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } settings.MainClass = value; return ParseResult.Success; case "/nostdlib": case "/nostdlib+": settings.StdLib = false; return ParseResult.Success; case "/nostdlib-": settings.StdLib = true; return ParseResult.Success; case "/fullpaths": report.Printer.ShowFullPaths = true; return ParseResult.Success; case "/keyfile": if (value.Length == 0) { Error_RequiresFileName (option); return ParseResult.Error; } settings.StrongNameKeyFile = value; return ParseResult.Success; case "/keycontainer": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } settings.StrongNameKeyContainer = value; return ParseResult.Success; case "/delaysign+": case "/delaysign": settings.StrongNameDelaySign = true; return ParseResult.Success; case "/delaysign-": settings.StrongNameDelaySign = false; return ParseResult.Success; case "/langversion": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } switch (value.ToLowerInvariant ()) { case "iso-1": settings.Version = LanguageVersion.ISO_1; return ParseResult.Success; case "default": settings.Version = LanguageVersion.Default; RootContext.AddConditional ("__V2__"); return ParseResult.Success; case "iso-2": settings.Version = LanguageVersion.ISO_2; return ParseResult.Success; case "3": settings.Version = LanguageVersion.V_3; return ParseResult.Success; case "future": settings.Version = LanguageVersion.Future; return ParseResult.Success; } report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value); return ParseResult.Error; case "/codepage": if (value.Length == 0) { Error_RequiresArgument (option); return ParseResult.Error; } switch (value) { case "utf8": settings.Encoding = new UTF8Encoding (); break; case "reset": settings.Encoding = new UTF8Encoding ();//Encoding.Default; break; default: try { settings.Encoding = new UTF8Encoding(); //Encoding.GetEncoding(int.Parse(value)); } catch { report.Error (2016, "Code page `{0}' is invalid or not installed", value); } return ParseResult.Error; } return ParseResult.Success; default: return ParseResult.UnknownOption; } } // // Currently handles the Unix-like command line options, but will be // deprecated in favor of the CSCParseOption, which will also handle the // options that start with a dash in the future. // ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings) { switch (arg){ case "-v": CSharpParser.yacc_verbose_flag++; return ParseResult.Success; case "--version": Version (); return ParseResult.Stop; case "--parse": settings.ParseOnly = true; return ParseResult.Success; case "--main": case "-m": report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } settings.MainClass = args[++i]; return ParseResult.Success; case "--unsafe": report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe"); settings.Unsafe = true; return ParseResult.Success; case "/?": case "/h": case "/help": case "--help": Usage (); return ParseResult.Stop; case "--define": report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } RootContext.AddConditional (args [++i]); return ParseResult.Success; case "--tokenize": settings.TokenizeOnly = true; return ParseResult.Success; case "-o": case "--output": report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } settings.OutputFile = args[++i]; return ParseResult.Success; case "--checked": report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked"); settings.Checked = true; return ParseResult.Success; case "--stacktrace": report.Printer.Stacktrace = true; return ParseResult.Success; case "--linkresource": case "--linkres": report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } AddResource (new AssemblyResource (args[++i], args[i]), settings); return ParseResult.Success; case "--resource": case "--res": report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } AddResource (new AssemblyResource (args[++i], args[i], true), settings); return ParseResult.Success; case "--target": report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } string type = args [++i]; switch (type){ case "library": settings.Target = Target.Library; settings.TargetExt = ".dll"; break; case "exe": settings.Target = Target.Exe; break; case "winexe": settings.Target = Target.WinExe; break; case "module": settings.Target = Target.Module; settings.TargetExt = ".dll"; break; default: report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'"); break; } return ParseResult.Success; case "-r": report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } string val = args [++i]; int idx = val.IndexOf ('='); if (idx > -1) { string alias = val.Substring (0, idx); string assembly = val.Substring (idx + 1); AddAssemblyReference (alias, assembly, settings); return ParseResult.Success; } settings.AssemblyReferences.Add (val); return ParseResult.Success; case "-L": report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } settings.ReferencesLookupPaths.Add (args [++i]); return ParseResult.Success; case "--lint": settings.EnhancedWarnings = true; return ParseResult.Success; case "--nostdlib": report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib"); settings.StdLib = false; return ParseResult.Success; case "--nowarn": report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } int warn = 0; try { warn = int.Parse (args [++i]); } catch { Usage (); //Environment.Exit (1); } report.SetIgnoreWarning (warn); return ParseResult.Success; case "--wlevel": report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } SetWarningLevel (args [++i]); return ParseResult.Success; case "--mcs-debug": if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } try { Report.DebugFlags = int.Parse (args [++i]); } catch { Error_RequiresArgument (arg); return ParseResult.Error; } return ParseResult.Success; case "--about": About (); return ParseResult.Stop; case "--recurse": report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN"); if ((i + 1) >= args.Length){ Error_RequiresArgument (arg); return ParseResult.Error; } ProcessSourceFiles (args [++i], true); return ParseResult.Success; case "--timestamp": settings.Timestamps = true; return ParseResult.Success; case "--debug": case "-g": report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug"); settings.GenerateDebugInfo = true; return ParseResult.Success; case "--noconfig": report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig"); settings.LoadDefaultReferences = false; return ParseResult.Success; default: if (arg.StartsWith ("--fatal")){ int fatal = 1; if (arg.StartsWith ("--fatal=")) int.TryParse (arg.Substring (8), out fatal); report.Printer.FatalCounter = fatal; return ParseResult.Success; } if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) { string version = arg.Substring (10); switch (version) { case "v1": case "V1": settings.StdLibRuntimeVersion = RuntimeVersion.v1; break; case "v2": case "V2": settings.StdLibRuntimeVersion = RuntimeVersion.v2; break; case "v4": case "V4": settings.StdLibRuntimeVersion = RuntimeVersion.v4; break; } return ParseResult.Success; } return ParseResult.UnknownOption; } } void SetWarningLevel (string s) { int level = -1; try { level = int.Parse (s); } catch { } if (level < 0 || level > 4) { report.Error (1900, "Warning level must be in the range 0-4"); return; } report.WarningLevel = level; } // // Given a path specification, splits the path from the file/pattern // static void SplitPathAndPattern (string spec, out string path, out string pattern) { int p = spec.LastIndexOf ('/'); if (p != -1) { // // Windows does not like /file.cs, switch that to: // "\", "file.cs" // if (p == 0) { path = "\\"; pattern = spec.Substring (1); } else { path = spec.Substring (0, p); pattern = spec.Substring (p + 1); } return; } p = spec.LastIndexOf ('\\'); if (p != -1) { path = spec.Substring (0, p); pattern = spec.Substring (p + 1); return; } path = "."; pattern = spec; } void Usage () { output.WriteLine ( "Mono C# compiler, Copyright 2001 - 2011 Novell, Inc.\n" + "mcs [options] source-files\n" + " --about About the Mono C# compiler\n" + " -addmodule:M1[,Mn] Adds the module to the generated assembly\n" + " -checked[+|-] Sets default aritmetic overflow context\n" + " -clscheck[+|-] Disables CLS Compliance verifications\n" + " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" + " -define:S1[;S2] Defines one or more conditional symbols (short: -d)\n" + " -debug[+|-], -g Generate debugging information\n" + " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" + " -doc:FILE Process documentation comments to XML file\n" + " -fullpaths Any issued error or warning uses absolute file path\n" + " -help Lists all compiler options (short: -?)\n" + " -keycontainer:NAME The key pair container used to sign the output assembly\n" + " -keyfile:FILE The key file used to strongname the ouput assembly\n" + " -langversion:TEXT Specifies language version: ISO-1, ISO-2, 3, Default or Future\n" + " -lib:PATH1[,PATHn] Specifies the location of referenced assemblies\n" + " -main:CLASS Specifies the class with the Main method (short: -m)\n" + " -noconfig Disables implicitly referenced assemblies\n" + " -nostdlib[+|-] Does not reference mscorlib.dll library\n" + " -nowarn:W1[,Wn] Suppress one or more compiler warnings\n" + " -optimize[+|-] Enables advanced compiler optimizations (short: -o)\n" + " -out:FILE Specifies output assembly name\n" + " -pkg:P1[,Pn] References packages P1..Pn\n" + " -platform:ARCH Specifies the target platform of the output assembly\n" + " ARCH can be one of: anycpu, x86, x64 or itanium\n" + " -recurse:SPEC Recursively compiles files according to SPEC pattern\n" + " -reference:A1[,An] Imports metadata from the specified assembly (short: -r)\n" + " -reference:ALIAS=A Imports metadata using specified extern alias (short: -r)\n" + " -sdk:VERSION Specifies SDK version of referenced assemblies\n" + " VERSION can be one of: 2, 4 (default) or custom value\n" + " -target:KIND Specifies the format of the output assembly (short: -t)\n" + " KIND can be one of: exe, winexe, library, module\n" + " -unsafe[+|-] Allows to compile code which uses unsafe keyword\n" + " -warnaserror[+|-] Treats all warnings as errors\n" + " -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" + " -warn:0-4 Sets warning level, the default is 4 (short -w:)\n" + " -helpinternal Shows internal and advanced compiler options\n" + "\n" + "Resources:\n" + " -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" + " -resource:FILE[,ID] Embed FILE as a resource (short: -res)\n" + " -win32res:FILE Specifies Win32 resource file (.res)\n" + " -win32icon:FILE Use this icon for the output\n" + " @file Read response file for more options\n\n" + "Options can be of the form -option or /option"); } void Version () { string version = System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType.Assembly.GetName ().Version.ToString (); output.WriteLine ("Mono C# compiler version {0}", version); } } public class RootContext { // // Contains the parsed tree // static ModuleContainer root; // // This hashtable contains all of the #definitions across the source code // it is used by the ConditionalAttribute handler. // static List<string> AllDefines; // // Constructor // static RootContext () { Reset (true); } public static void PartialReset () { Reset (false); } public static void Reset (bool full) { if (!full) return; // // Setup default defines // AllDefines = new List<string> (); AddConditional ("__MonoCS__"); } public static void AddConditional (string p) { if (AllDefines.Contains (p)) return; AllDefines.Add (p); } public static bool IsConditionalDefined (string value) { return AllDefines.Contains (value); } static public ModuleContainer ToplevelTypes { get { return root; } set { root = value; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Batches; using osu.Framework.Graphics.OpenGL.Vertices; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Shaders; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps.Timing; using osu.Game.Graphics; using osu.Game.Graphics.OpenGL.Vertices; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Mods { public abstract class ModFlashlight : Mod { public override string Name => "Flashlight"; public override string Acronym => "FL"; public override IconUsage Icon => OsuIcon.ModFlashlight; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Restricted view area."; public override bool Ranked => true; internal ModFlashlight() { } } public abstract class ModFlashlight<T> : ModFlashlight, IApplicableToDrawableRuleset<T>, IApplicableToScoreProcessor where T : HitObject { public const double FLASHLIGHT_FADE_DURATION = 800; protected readonly BindableInt Combo = new BindableInt(); public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { Combo.BindTo(scoreProcessor.Combo); } public ScoreRank AdjustRank(ScoreRank rank, double accuracy) => rank; public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset) { var flashlight = CreateFlashlight(); flashlight.Combo = Combo; flashlight.RelativeSizeAxes = Axes.Both; flashlight.Colour = Color4.Black; drawableRuleset.KeyBindingInputManager.Add(flashlight); flashlight.Breaks = drawableRuleset.Beatmap.Breaks; } public abstract Flashlight CreateFlashlight(); public abstract class Flashlight : Drawable { internal BindableInt Combo; private IShader shader; protected override DrawNode CreateDrawNode() => new FlashlightDrawNode(this); public override bool RemoveCompletedTransforms => false; public List<BreakPeriod> Breaks; [BackgroundDependencyLoader] private void load(ShaderManager shaderManager) { shader = shaderManager.Load("PositionAndColour", FragmentShader); } protected override void LoadComplete() { base.LoadComplete(); Combo.ValueChanged += OnComboChange; using (BeginAbsoluteSequence(0)) { foreach (var breakPeriod in Breaks) { if (breakPeriod.Duration < FLASHLIGHT_FADE_DURATION * 2) continue; this.Delay(breakPeriod.StartTime + FLASHLIGHT_FADE_DURATION).FadeOutFromOne(FLASHLIGHT_FADE_DURATION); this.Delay(breakPeriod.EndTime - FLASHLIGHT_FADE_DURATION).FadeInFromZero(FLASHLIGHT_FADE_DURATION); } } } protected abstract void OnComboChange(ValueChangedEvent<int> e); protected abstract string FragmentShader { get; } private Vector2 flashlightPosition; protected Vector2 FlashlightPosition { get => flashlightPosition; set { if (flashlightPosition == value) return; flashlightPosition = value; Invalidate(Invalidation.DrawNode); } } private Vector2 flashlightSize; protected Vector2 FlashlightSize { get => flashlightSize; set { if (flashlightSize == value) return; flashlightSize = value; Invalidate(Invalidation.DrawNode); } } private float flashlightDim; public float FlashlightDim { get => flashlightDim; set { if (flashlightDim == value) return; flashlightDim = value; Invalidate(Invalidation.DrawNode); } } private class FlashlightDrawNode : DrawNode { protected new Flashlight Source => (Flashlight)base.Source; private IShader shader; private Quad screenSpaceDrawQuad; private Vector2 flashlightPosition; private Vector2 flashlightSize; private float flashlightDim; private readonly VertexBatch<PositionAndColourVertex> quadBatch = new QuadBatch<PositionAndColourVertex>(1, 1); private readonly Action<TexturedVertex2D> addAction; public FlashlightDrawNode(Flashlight source) : base(source) { addAction = v => quadBatch.Add(new PositionAndColourVertex { Position = v.Position, Colour = v.Colour }); } public override void ApplyState() { base.ApplyState(); shader = Source.shader; screenSpaceDrawQuad = Source.ScreenSpaceDrawQuad; flashlightPosition = Vector2Extensions.Transform(Source.FlashlightPosition, DrawInfo.Matrix); flashlightSize = Source.FlashlightSize * DrawInfo.Matrix.ExtractScale().Xy; flashlightDim = Source.FlashlightDim; } public override void Draw(Action<TexturedVertex2D> vertexAction) { base.Draw(vertexAction); shader.Bind(); shader.GetUniform<Vector2>("flashlightPos").UpdateValue(ref flashlightPosition); shader.GetUniform<Vector2>("flashlightSize").UpdateValue(ref flashlightSize); shader.GetUniform<float>("flashlightDim").UpdateValue(ref flashlightDim); DrawQuad(Texture.WhitePixel, screenSpaceDrawQuad, DrawColourInfo.Colour, vertexAction: addAction); shader.Unbind(); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); quadBatch?.Dispose(); } } } } }
using DataGg.Database; using Microsoft.Extensions.Configuration; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; namespace DataGg.Test { [TestClass] public class GuernseyDbTest { private GuernseyDb _guernseyDb; [TestInitialize] public void Init() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.development.json") .Build(); _guernseyDb = new GuernseyDb(config); } [TestMethod] public async Task BusUsage() { var busUsage = await _guernseyDb.GetBusUsage(); Assert.IsNotNull(busUsage); Assert.IsTrue(busUsage.Length > 0); } /* [TestMethod] public async Task HermTrident() { var hermTrident = await _guernseyDb.GetHermTrident(); Assert.IsNotNull(hermTrident); Assert.IsTrue(hermTrident.Length > 0); }*/ [TestMethod] public async Task Crime() { var crime = await _guernseyDb.GetCrime(); Assert.IsNotNull(crime); Assert.IsTrue(crime.Length > 0); } [TestMethod] public async Task CrimePrisonPopulation() { var crimePrisonPopulation = await _guernseyDb.GetCrimePrisonPopulation(); Assert.IsNotNull(crimePrisonPopulation); Assert.IsTrue(crimePrisonPopulation.Length > 0); } [TestMethod] public async Task CrimeWorried() { var crimeWorried = await _guernseyDb.GetCrimeWorried(); Assert.IsNotNull(crimeWorried); Assert.IsTrue(crimeWorried.Length > 0); } [TestMethod] public async Task EarningsAgeGroup() { var earningsAgeGroup = await _guernseyDb.GetEarningsAgeGroup(); Assert.IsNotNull(earningsAgeGroup); Assert.IsTrue(earningsAgeGroup.Length > 0); } [TestMethod] public async Task EducationEarningsSector() { var educationEarningsSector = await _guernseyDb.GetEducationEarningsSector(); Assert.IsNotNull(educationEarningsSector); Assert.IsTrue(educationEarningsSector.Length > 0); } [TestMethod] public async Task EducationEarningsSex() { var educationEarningsSex = await _guernseyDb.GetEducationEarningsSex(); Assert.IsNotNull(educationEarningsSex); Assert.IsTrue(educationEarningsSex.Length > 0); } [TestMethod] public async Task EducationGcseOverall() { var educationGcseOverall = await _guernseyDb.GetEducationGcseOverall(); Assert.IsNotNull(educationGcseOverall); Assert.IsTrue(educationGcseOverall.Length > 0); } [TestMethod] public async Task EducationGcseSchool() { var educationGcseSchool = await _guernseyDb.GetEducationGcseSchool(); Assert.IsNotNull(educationGcseSchool); Assert.IsTrue(educationGcseSchool.Length > 0); } [TestMethod] public async Task EducationPost16Results() { var educationPost16Results = await _guernseyDb.GetEducationPost16Results(); Assert.IsNotNull(educationPost16Results); Assert.IsTrue(educationPost16Results.Length > 0); } [TestMethod] public async Task EducationStudentsInUk() { var educationStudentsInUk = await _guernseyDb.GetEducationStudentsInUk(); Assert.IsNotNull(educationStudentsInUk); Assert.IsTrue(educationStudentsInUk.Length > 0); } [TestMethod] public async Task EmissionSource() { var emissionSource = await _guernseyDb.GetEmissionSource(); Assert.IsNotNull(emissionSource); Assert.IsTrue(emissionSource.Length > 0); } [TestMethod] public async Task EmissionType() { var emissionType = await _guernseyDb.GetEmissionType(); Assert.IsNotNull(emissionType); Assert.IsTrue(emissionType.Length > 0); } [TestMethod] public async Task EmploymentSector() { var employmentSector = await _guernseyDb.GetEmploymentSector(); Assert.IsNotNull(employmentSector); Assert.IsTrue(employmentSector.Length > 0); } [TestMethod] public async Task EmploymentTotals() { var employmentTotals = await _guernseyDb.GetEmploymentTotals(); Assert.IsNotNull(employmentTotals); Assert.IsTrue(employmentTotals.Length > 0); } [TestMethod] public async Task EnergyElectricityConsumption() { var energyElectricityConsumption = await _guernseyDb.GetEnergyElectricityConsumption(); Assert.IsNotNull(energyElectricityConsumption); Assert.IsTrue(energyElectricityConsumption.Length > 0); } [TestMethod] public async Task EnergyElectricityImportVsGenerated() { var energyElectricityImportVsGenerated = await _guernseyDb.GetEnergyElectricityImportVsGenerated(); Assert.IsNotNull(energyElectricityImportVsGenerated); Assert.IsTrue(energyElectricityImportVsGenerated.Length > 0); } [TestMethod] public async Task EnergyGas() { var energyGas = await _guernseyDb.GetEnergyGas(); Assert.IsNotNull(energyGas); Assert.IsTrue(energyGas.Length > 0); } [TestMethod] public async Task EnergyOilImports() { var energyOilImports = await _guernseyDb.GetEnergyOilImports(); Assert.IsNotNull(energyOilImports); Assert.IsTrue(energyOilImports.Length > 0); } [TestMethod] public async Task EnergyRenewable() { var energyRenewable = await _guernseyDb.GetEnergyRenewable(); Assert.IsNotNull(energyRenewable); Assert.IsTrue(energyRenewable.Length > 0); } [TestMethod] public async Task FinanceBanking() { var financeBanking = await _guernseyDb.GetFinanceBanking(); Assert.IsNotNull(financeBanking); Assert.IsTrue(financeBanking.Length > 0); } [TestMethod] public async Task FinanceFundsUnderManagement() { var financeFundsUnderManagement = await _guernseyDb.GetFinanceFundsUnderManagement(); Assert.IsNotNull(financeFundsUnderManagement); Assert.IsTrue(financeFundsUnderManagement.Length > 0); } [TestMethod] public async Task FireAndRescueAttendances() { var fireAndRescueAttendances = await _guernseyDb.GetFireAndRescueAttendances(); Assert.IsNotNull(fireAndRescueAttendances); Assert.IsTrue(fireAndRescueAttendances.Length > 0); } [TestMethod] public async Task GovSpendingBreakdown() { var govSpendingBreakdown = await _guernseyDb.GetGovSpendingBreakdown(); Assert.IsNotNull(govSpendingBreakdown); Assert.IsTrue(govSpendingBreakdown.Length > 0); } [TestMethod] public async Task HealthChestAndHeartConcerns() { var healthChestAndHeartConcerns = await _guernseyDb.GetHealthChestAndHeartConcerns(); Assert.IsNotNull(healthChestAndHeartConcerns); Assert.IsTrue(healthChestAndHeartConcerns.Length > 0); } [TestMethod] public async Task HealthChestAndHeartTotals() { var healthChestAndHeartTotals = await _guernseyDb.GetHealthChestAndHeartTotals(); Assert.IsNotNull(healthChestAndHeartTotals); Assert.IsTrue(healthChestAndHeartTotals.Length > 0); } [TestMethod] public async Task HealthMedUnitBedDaysFiveYrAvg() { var healthMedUnitBedDaysFiveYrAvg = await _guernseyDb.GetHealthMedUnitBedDaysFiveYrAvg(); Assert.IsNotNull(healthMedUnitBedDaysFiveYrAvg); Assert.IsTrue(healthMedUnitBedDaysFiveYrAvg.Length > 0); } [TestMethod] public async Task HouseBedrooms() { var houseBedrooms = await _guernseyDb.GetHouseBedrooms(); Assert.IsNotNull(houseBedrooms); Assert.IsTrue(houseBedrooms.Length > 0); } [TestMethod] public async Task HouseLocalPrices() { var houseLocalPrices = await _guernseyDb.GetHouseLocalPrices(); Assert.IsNotNull(houseLocalPrices); Assert.IsTrue(houseLocalPrices.Length > 0); } [TestMethod] public async Task HouseOpenPrices() { var houseOpenPrices = await _guernseyDb.GetHouseOpenPrices(); Assert.IsNotNull(houseOpenPrices); Assert.IsTrue(houseOpenPrices.Length > 0); } [TestMethod] public async Task HouseTypes() { var houseTypes = await _guernseyDb.GetHouseTypes(); Assert.IsNotNull(houseTypes); Assert.IsTrue(houseTypes.Length > 0); } [TestMethod] public async Task HouseUnits() { var houseUnits = await _guernseyDb.GetHouseUnits(); Assert.IsNotNull(houseUnits); Assert.IsTrue(houseUnits.Length > 0); } [TestMethod] public async Task InflationChanges() { var inflationChanges = await _guernseyDb.GetInflationChanges(); Assert.IsNotNull(inflationChanges); Assert.IsTrue(inflationChanges.Length > 0); } [TestMethod] public async Task InflationRpixGroupChanges() { var inflationRpixGroupChanges = await _guernseyDb.GetInflationRpixGroupChanges(); Assert.IsNotNull(inflationRpixGroupChanges); Assert.IsTrue(inflationRpixGroupChanges.Length > 0); } [TestMethod] public async Task InflationRpiGroupChanges() { var inflationRpiGroupChanges = await _guernseyDb.GetInflationRpiGroupChanges(); Assert.IsNotNull(inflationRpiGroupChanges); Assert.IsTrue(inflationRpiGroupChanges.Length > 0); } [TestMethod] public async Task OverseasContributions() { var overseasContributions = await _guernseyDb.GetOverseasContributions(); Assert.IsNotNull(overseasContributions); Assert.IsTrue(overseasContributions.Length > 0); } [TestMethod] public async Task PopulationAge() { var populationAge = await _guernseyDb.GetPopulationAge(); Assert.IsNotNull(populationAge); Assert.IsTrue(populationAge.Length > 0); } [TestMethod] public async Task PopulationAgeFemale() { var populationAgeFemale = await _guernseyDb.GetPopulationAgeFemale(); Assert.IsNotNull(populationAgeFemale); Assert.IsTrue(populationAgeFemale.Length > 0); } [TestMethod] public async Task PopulationAgeMale() { var populationAgeMale = await _guernseyDb.GetPopulationAgeMale(); Assert.IsNotNull(populationAgeMale); Assert.IsTrue(populationAgeMale.Length > 0); } [TestMethod] public async Task PopulationBirthplace() { var populationBirthplace = await _guernseyDb.GetPopulationBirthplace(); Assert.IsNotNull(populationBirthplace); Assert.IsTrue(populationBirthplace.Length > 0); } [TestMethod] public async Task GetPopulationChanges() { var popChanges = await _guernseyDb.GetPopulationChanges(); Assert.IsNotNull(popChanges); Assert.IsTrue(popChanges.Length > 0); } [TestMethod] public async Task PopulationDistrict() { var populationDistrict = await _guernseyDb.GetPopulationDistrict(); Assert.IsNotNull(populationDistrict); Assert.IsTrue(populationDistrict.Length > 0); } [TestMethod] public async Task PopulationParish() { var populationParish = await _guernseyDb.GetPopulationParish(); Assert.IsNotNull(populationParish); Assert.IsTrue(populationParish.Length > 0); } [TestMethod] public async Task Population() { var population = await _guernseyDb.GetPopulation(); Assert.IsNotNull(population); Assert.IsTrue(population.Length > 0); } [TestMethod] public async Task SailingsCondorPunctuality() { var sailingsCondorPunctuality = await _guernseyDb.GetSailingsCondorPunctuality(); Assert.IsNotNull(sailingsCondorPunctuality); Assert.IsTrue(sailingsCondorPunctuality.Length > 0); } [TestMethod] public async Task SailingsCruises() { var sailingsCruises = await _guernseyDb.GetSailingsCruises(); Assert.IsNotNull(sailingsCruises); Assert.IsTrue(sailingsCruises.Length > 0); } [TestMethod] public async Task TourismAirByMonth() { var tourismAirByMonth = await _guernseyDb.GetTourismAirByMonth(); Assert.IsNotNull(tourismAirByMonth); Assert.IsTrue(tourismAirByMonth.Length > 0); } [TestMethod] public async Task GetTourismCruises() { var cruises = await _guernseyDb.GetTourismCruises(); Assert.IsNotNull(cruises); Assert.IsTrue(cruises.Length > 0); } [TestMethod] public async Task TourismSeaByMonth() { var tourismSeaByMonth = await _guernseyDb.GetTourismSeaByMonth(); Assert.IsNotNull(tourismSeaByMonth); Assert.IsTrue(tourismSeaByMonth.Length > 0); } [TestMethod] public async Task Traffic() { var traffic = await _guernseyDb.GetTraffic(); Assert.IsNotNull(traffic); Assert.IsTrue(traffic.Length > 0); } [TestMethod] public async Task TrafficClassifications() { var trafficClassifications = await _guernseyDb.GetTrafficClassifications(); Assert.IsNotNull(trafficClassifications); Assert.IsTrue(trafficClassifications.Length > 0); } [TestMethod] public async Task TrafficCollisions() { var trafficCollisions = await _guernseyDb.GetTrafficCollisions(); Assert.IsNotNull(trafficCollisions); Assert.IsTrue(trafficCollisions.Length > 0); } [TestMethod] public async Task TrafficInjuries() { var trafficInjuries = await _guernseyDb.GetTrafficInjuries(); Assert.IsNotNull(trafficInjuries); Assert.IsTrue(trafficInjuries.Length > 0); } [TestMethod] public async Task TransportRegisteredVehicles() { var transportRegisteredVehicles = await _guernseyDb.GetTransportRegisteredVehicles(); Assert.IsNotNull(transportRegisteredVehicles); Assert.IsTrue(transportRegisteredVehicles.Length > 0); } [TestMethod] public async Task WasteCommercialAndIndustrialWaste() { var wasteCommercialAndIndustrialWaste = await _guernseyDb.GetWasteCommercialAndIndustrialWaste(); Assert.IsNotNull(wasteCommercialAndIndustrialWaste); Assert.IsTrue(wasteCommercialAndIndustrialWaste.Length > 0); } [TestMethod] public async Task WasteConstructionAndDemolition() { var wasteConstructionAndDemolition = await _guernseyDb.GetWasteConstructionAndDemolition(); Assert.IsNotNull(wasteConstructionAndDemolition); Assert.IsTrue(wasteConstructionAndDemolition.Length > 0); } [TestMethod] public async Task WasteHousehold() { var wasteHousehold = await _guernseyDb.GetWasteHousehold(); Assert.IsNotNull(wasteHousehold); Assert.IsTrue(wasteHousehold.Length > 0); } [TestMethod] public async Task WaterDomesticConsumption() { var waterDomesticConsumption = await _guernseyDb.GetWaterDomesticConsumption(); Assert.IsNotNull(waterDomesticConsumption); Assert.IsTrue(waterDomesticConsumption.Length > 0); } [TestMethod] public async Task WaterNitrateConcentration() { var waterNitrateConcentration = await _guernseyDb.GetWaterNitrateConcentration(); Assert.IsNotNull(waterNitrateConcentration); Assert.IsTrue(waterNitrateConcentration.Length > 0); } [TestMethod] public async Task WaterPollutionIncidents() { var waterPollutionIncidents = await _guernseyDb.GetWaterPollutionIncidents(); Assert.IsNotNull(waterPollutionIncidents); Assert.IsTrue(waterPollutionIncidents.Length > 0); } [TestMethod] public async Task WaterUnaccounted() { var waterUnaccounted = await _guernseyDb.GetWaterUnaccounted(); Assert.IsNotNull(waterUnaccounted); Assert.IsTrue(waterUnaccounted.Length > 0); } [TestMethod] public async Task WaterConsumption() { var waterConsumption = await _guernseyDb.GetWaterConsumption(); Assert.IsNotNull(waterConsumption); Assert.IsTrue(waterConsumption.Length > 0); } [TestMethod] public async Task WaterQualityCompliance() { var waterQualityCompliance = await _guernseyDb.GetWaterQualityCompliance(); Assert.IsNotNull(waterQualityCompliance); Assert.IsTrue(waterQualityCompliance.Length > 0); } [TestMethod] public async Task WaterStorage() { var waterStorage = await _guernseyDb.GetWaterStorage(); Assert.IsNotNull(waterStorage); Assert.IsTrue(waterStorage.Length > 0); } [TestMethod] public async Task WeatherFrostDays() { var weatherFrostDays = await _guernseyDb.GetWeatherFrostDays(); Assert.IsNotNull(weatherFrostDays); Assert.IsTrue(weatherFrostDays.Length > 0); } [TestMethod] public async Task WeatherMetOfficeAnnual() { var weatherMetOfficeAnnual = await _guernseyDb.GetWeatherMetOfficeAnnual(); Assert.IsNotNull(weatherMetOfficeAnnual); Assert.IsTrue(weatherMetOfficeAnnual.Length > 0); } [TestMethod] public async Task WeatherMetOfficeMonthly() { var weatherMetOfficeMonthly = await _guernseyDb.GetWeatherMetOfficeMonthly(); Assert.IsNotNull(weatherMetOfficeMonthly); Assert.IsTrue(weatherMetOfficeMonthly.Length > 0); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace SharePoint.Utilities { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class Attribute : Node, INodeWithArguments { protected string _name; protected ExpressionCollection _arguments; protected ExpressionPairCollection _namedArguments; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Attribute CloneNode() { return (Attribute)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Attribute CleanClone() { return (Attribute)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.Attribute; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnAttribute(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( Attribute)node; if (_name != other._name) return NoMatch("Attribute._name"); if (!Node.AllMatch(_arguments, other._arguments)) return NoMatch("Attribute._arguments"); if (!Node.AllMatch(_namedArguments, other._namedArguments)) return NoMatch("Attribute._namedArguments"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_arguments != null) { Expression item = existing as Expression; if (null != item) { Expression newItem = (Expression)newNode; if (_arguments.Replace(item, newItem)) { return true; } } } if (_namedArguments != null) { ExpressionPair item = existing as ExpressionPair; if (null != item) { ExpressionPair newItem = (ExpressionPair)newNode; if (_namedArguments.Replace(item, newItem)) { return true; } } } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { Attribute clone = new Attribute(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._name = _name; if (null != _arguments) { clone._arguments = _arguments.Clone() as ExpressionCollection; clone._arguments.InitializeParent(clone); } if (null != _namedArguments) { clone._namedArguments = _namedArguments.Clone() as ExpressionPairCollection; clone._namedArguments.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _arguments) { _arguments.ClearTypeSystemBindings(); } if (null != _namedArguments) { _namedArguments.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlAttribute] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public string Name { get { return _name; } set { _name = value; } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(Expression))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public ExpressionCollection Arguments { get { return _arguments ?? (_arguments = new ExpressionCollection(this)); } set { if (_arguments != value) { _arguments = value; if (null != _arguments) { _arguments.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(ExpressionPair))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public ExpressionPairCollection NamedArguments { get { return _namedArguments ?? (_namedArguments = new ExpressionPairCollection(this)); } set { if (_namedArguments != value) { _namedArguments = value; if (null != _namedArguments) { _namedArguments.InitializeParent(this); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; namespace System { public partial class String { [Pure] public bool Contains(string value) { return (IndexOf(value, StringComparison.Ordinal) >= 0); } // Returns the index of the first occurrence of a specified character in the current instance. // The search starts at startIndex and runs thorough the next count characters. // [Pure] public int IndexOf(char value) { return IndexOf(value, 0, this.Length); } [Pure] public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } [Pure] public unsafe int IndexOf(char value, int startIndex, int count) { if (startIndex < 0 || startIndex > Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count > Length - startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); fixed (char* pChars = &m_firstChar) { char* pCh = pChars + startIndex; while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh + 1) == value) goto ReturnIndex1; if (*(pCh + 2) == value) goto ReturnIndex2; if (*(pCh + 3) == value) goto ReturnIndex3; count -= 4; pCh += 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh++; } return -1; ReturnIndex3: pCh++; ReturnIndex2: pCh++; ReturnIndex1: pCh++; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the first occurrence of any specified character in the current instance. // The search starts at startIndex and runs to startIndex + count -1. // [Pure] public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, this.Length); } [Pure] public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, this.Length - startIndex); } [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOfAny(char[] anyOf, int startIndex, int count); // Determines the position within this string of the first occurrence of the specified // string, according to the specified search criteria. The search begins at // the first character of this string, it is case-sensitive and the current culture // comparison is used. // [Pure] public int IndexOf(String value) { return IndexOf(value, StringComparison.CurrentCulture); } // Determines the position within this string of the first occurrence of the specified // string, according to the specified search criteria. The search begins at // startIndex, it is case-sensitive and the current culture comparison is used. // [Pure] public int IndexOf(String value, int startIndex) { return IndexOf(value, startIndex, StringComparison.CurrentCulture); } // Determines the position within this string of the first occurrence of the specified // string, according to the specified search criteria. The search begins at // startIndex, ends at endIndex and the current culture comparison is used. // [Pure] public int IndexOf(String value, int startIndex, int count) { if (startIndex < 0 || startIndex > this.Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if (count < 0 || count > this.Length - startIndex) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } Contract.EndContractBlock(); return IndexOf(value, startIndex, count, StringComparison.CurrentCulture); } [Pure] public int IndexOf(String value, StringComparison comparisonType) { return IndexOf(value, 0, this.Length, comparisonType); } [Pure] public int IndexOf(String value, int startIndex, StringComparison comparisonType) { return IndexOf(value, startIndex, this.Length - startIndex, comparisonType); } [Pure] public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { // Validate inputs if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > this.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); Contract.EndContractBlock(); switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.Ordinal); case StringComparison.OrdinalIgnoreCase: if (value.IsAscii() && this.IsAscii()) return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); else return TextInfo.IndexOfStringOrdinalIgnoreCase(this, value, startIndex, count); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } // Returns the index of the last occurrence of a specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // [Pure] public int LastIndexOf(char value) { return LastIndexOf(value, this.Length - 1, this.Length); } [Pure] public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } [Pure] public unsafe int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) return -1; if (startIndex < 0 || startIndex >= Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count - 1 > startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); fixed (char* pChars = &m_firstChar) { char* pCh = pChars + startIndex; //We search [startIndex..EndIndex] while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh - 1) == value) goto ReturnIndex1; if (*(pCh - 2) == value) goto ReturnIndex2; if (*(pCh - 3) == value) goto ReturnIndex3; count -= 4; pCh -= 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh--; } return -1; ReturnIndex3: pCh--; ReturnIndex2: pCh--; ReturnIndex1: pCh--; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the last occurrence of any specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // //ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff" [Pure] public int LastIndexOfAny(char[] anyOf) { return LastIndexOfAny(anyOf, this.Length - 1, this.Length); } [Pure] public int LastIndexOfAny(char[] anyOf, int startIndex) { return LastIndexOfAny(anyOf, startIndex, startIndex + 1); } [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOfAny(char[] anyOf, int startIndex, int count); // Returns the index of the last occurrence of any character in value in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // [Pure] public int LastIndexOf(String value) { return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture); } [Pure] public int LastIndexOf(String value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture); } [Pure] public int LastIndexOf(String value, int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } Contract.EndContractBlock(); return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture); } [Pure] public int LastIndexOf(String value, StringComparison comparisonType) { return LastIndexOf(value, this.Length - 1, this.Length, comparisonType); } [Pure] public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { return LastIndexOf(value, startIndex, startIndex + 1, comparisonType); } [Pure] public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Special case for 0 length input strings if (this.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Now after handling empty strings, make sure we're not out of range if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == this.Length if (startIndex == this.Length) { startIndex--; if (count > 0) count--; // If we are looking for nothing, just return 0 if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) return startIndex; } // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.Ordinal); case StringComparison.OrdinalIgnoreCase: if (value.IsAscii() && this.IsAscii()) return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase); else return TextInfo.LastIndexOfStringOrdinalIgnoreCase(this, value, startIndex, count); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } } }
//Copyright (c) 2007 Josip Medved <jmedved@jmedved.com> //2007-12-29: New version. //2008-01-03: Added Resources. //2008-01-06: System.Environment.Exit returns E_ABORT (0x80004004). //2008-01-08: Main method is now called Attach. //2008-01-26: AutoExit parameter changed to NoAutoExit //2008-04-10: NewInstanceEventArgs is not nested class anymore. //2008-04-11: Cleaned code to match FxCop 1.36 beta 2 (SpecifyMarshalingForPInvokeStringArguments, NestedTypesShouldNotBeVisible). //2008-11-14: Reworked code to use SafeHandle. //2010-10-07: Added IsOtherInstanceRunning method. //2012-11-24: Suppressing bogus CA5122 warning (http://connect.microsoft.com/VisualStudio/feedback/details/729254/bogus-ca5122-warning-about-p-invoke-declarations-should-not-be-safe-critical). using System; using System.Runtime.InteropServices; using System.Threading; namespace Medo.Application { /// <summary> /// Handles detection and communication of programs multiple instances. /// This class is thread safe. /// </summary> public static class SingleInstance { private static Mutex _mtxFirstInstance; private static Thread _thread; private static readonly object _syncRoot = new object(); /// <summary> /// Returns true if this application is not already started. /// Another instance is contacted via named pipe. /// </summary> /// <exception cref="System.InvalidOperationException">API call failed.</exception> public static bool Attach() { return Attach(false); } /// <summary> /// Returns true if this application is not already started. /// Another instance is contacted via named pipe. /// </summary> /// <param name="noAutoExit">If true, application will exit after informing another instance.</param> /// <exception cref="System.InvalidOperationException">API call failed.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Needs to be cought all in order not to break in any case.")] public static bool Attach(bool noAutoExit) { lock (_syncRoot) { NativeMethods.FileSafeHandle handle = null; bool isFirstInstance = false; try { _mtxFirstInstance = new Mutex(true, MutexName, out isFirstInstance); if (isFirstInstance == false) { //we need to contact previous instance. _mtxFirstInstance = null; byte[] buffer; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(ms, new NewInstanceEventArgs(System.Environment.CommandLine, System.Environment.GetCommandLineArgs())); ms.Flush(); buffer = ms.GetBuffer(); } //open pipe if (!NativeMethods.WaitNamedPipe(NamedPipeName, NativeMethods.NMPWAIT_USE_DEFAULT_WAIT)) { throw new System.InvalidOperationException(Resources.ExceptionWaitNamedPipeFailed); } handle = NativeMethods.CreateFile(NamedPipeName, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 0, System.IntPtr.Zero, NativeMethods.OPEN_EXISTING, NativeMethods.FILE_ATTRIBUTE_NORMAL, System.IntPtr.Zero); if (handle.IsInvalid) { throw new System.InvalidOperationException(Resources.ExceptionCreateFileFailed); } //send bytes uint written = 0; NativeOverlapped overlapped = new NativeOverlapped(); if (!NativeMethods.WriteFile(handle, buffer, (uint)buffer.Length, ref written, ref overlapped)) { throw new System.InvalidOperationException(Resources.ExceptionWriteFileFailed); } if (written != buffer.Length) { throw new System.InvalidOperationException(Resources.ExceptionWriteFileWroteUnexpectedNumberOfBytes); } } else { //there is no application already running. _thread = new Thread(Run); _thread.Name = "Medo.Application.SingleInstance.0"; _thread.IsBackground = true; _thread.Start(); } } catch (System.Exception ex) { System.Diagnostics.Trace.TraceWarning(ex.Message + " {Medo.Application.SingleInstance}"); } finally { //if (handle != null && (!(handle.IsClosed || handle.IsInvalid))) { // handle.Close(); //} if (handle != null) { handle.Dispose(); } } if ((isFirstInstance == false) && (noAutoExit == false)) { System.Diagnostics.Trace.TraceInformation("Exit(E_ABORT): Another instance is running. {Medo.Application.SingleInstance}"); System.Environment.Exit(unchecked((int)0x80004004)); //E_ABORT(0x80004004) } return isFirstInstance; } } private static string _mutexName; private static string MutexName { get { lock (_syncRoot) { if (_mutexName == null) { System.Text.StringBuilder sbComponents = new System.Text.StringBuilder(); sbComponents.AppendLine(System.Environment.MachineName); sbComponents.AppendLine(System.Environment.UserName); sbComponents.AppendLine(System.Reflection.Assembly.GetEntryAssembly().FullName); sbComponents.AppendLine(System.Reflection.Assembly.GetEntryAssembly().CodeBase); byte[] hash; using (var sha1 =System.Security.Cryptography.SHA1Managed.Create()){ hash = sha1.ComputeHash(System.Text.Encoding.Unicode.GetBytes(sbComponents.ToString())); } System.Text.StringBuilder sbFinal = new System.Text.StringBuilder(); string assName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; sbFinal.Append(assName, 0, System.Math.Min(assName.Length, 64)); sbFinal.Append('.'); for (int i = 0; i < hash.Length; ++i) { sbFinal.AppendFormat("{0:X2}", hash[i]); } _mutexName = sbFinal.ToString(); } return _mutexName; } } } private static string NamedPipeName = @"\\.\pipe\" + MutexName; /// <summary> /// Gets whether there is another instance running. /// It temporary creates mutex. /// </summary> public static bool IsOtherInstanceRunning { get { lock (_syncRoot) { if (_mtxFirstInstance != null) { return false; //no other instance is running } else { bool isFirstInstance = false; var tempInstance = new Mutex(true, MutexName, out isFirstInstance); tempInstance.Close(); return (isFirstInstance == false); } } } } /// <summary> /// Occurs in first instance when new instance is detected. /// </summary> public static event System.EventHandler<NewInstanceEventArgs> NewInstanceDetected; /// <summary> /// Thread function. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Needs to be cought all in order not to break in any case.")] private static void Run() { while (_mtxFirstInstance != null) { IntPtr handle = IntPtr.Zero; try { handle = NativeMethods.CreateNamedPipe(NamedPipeName, NativeMethods.PIPE_ACCESS_DUPLEX, NativeMethods.PIPE_TYPE_BYTE | NativeMethods.PIPE_READMODE_BYTE | NativeMethods.PIPE_WAIT, NativeMethods.PIPE_UNLIMITED_INSTANCES, 4096, 4096, NativeMethods.NMPWAIT_USE_DEFAULT_WAIT, System.IntPtr.Zero); if (handle.Equals(IntPtr.Zero)) { throw new System.InvalidOperationException(Resources.ExceptionCreateNamedPipeFailed); } bool connected = NativeMethods.ConnectNamedPipe(handle, System.IntPtr.Zero); if (!connected) { throw new System.InvalidOperationException(Resources.ExceptionConnectNamedPipeFailed); } uint available = 0; while (available == 0) { uint bytesRead = 0, thismsg = 0; if (!NativeMethods.PeekNamedPipe(handle, null, 0, ref bytesRead, ref available, ref thismsg)) { Thread.Sleep(100); available = 0; } } byte[] buffer = new byte[available]; uint read = 0; NativeOverlapped overlapped = new NativeOverlapped(); if (!NativeMethods.ReadFile(handle, buffer, (uint)buffer.Length, ref read, ref overlapped)) { throw new System.InvalidOperationException(Resources.ExceptionReadFileFailed); } if (read != available) { throw new System.InvalidOperationException(Resources.ExceptionReadFileReturnedUnexpectedNumberOfBytes); } using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); if (NewInstanceDetected != null) { NewInstanceDetected(null, (NewInstanceEventArgs)bf.Deserialize(ms)); } } } catch (System.Exception ex) { System.Diagnostics.Trace.TraceWarning(ex.Message + " {Medo.Application.SingleInstance"); Thread.Sleep(1000); } finally { //closing native resources. if (!handle.Equals(System.IntPtr.Zero)) { NativeMethods.CloseHandle(handle); } }//try }//while } private static class Resources { internal static string ExceptionWaitNamedPipeFailed { get { return "WaitNamedPipe failed."; } } internal static string ExceptionCreateFileFailed { get { return "CreateFile failed."; } } internal static string ExceptionWriteFileFailed { get { return "WriteFile failed."; } } internal static string ExceptionWriteFileWroteUnexpectedNumberOfBytes { get { return "WriteFile wrote unexpected number of bytes."; } } internal static string ExceptionCreateNamedPipeFailed { get { return "CreateNamedPipe failed."; } } internal static string ExceptionConnectNamedPipeFailed { get { return "ConnectNamedPipe failed."; } } internal static string ExceptionReadFileFailed { get { return "ReadFile failed."; } } internal static string ExceptionReadFileReturnedUnexpectedNumberOfBytes { get { return "ReadFile returned unexpected number of bytes."; } } } private static class NativeMethods { public const uint FILE_ATTRIBUTE_NORMAL = 0; public const uint GENERIC_READ = 0x80000000; public const uint GENERIC_WRITE = 0x40000000; public const int INVALID_HANDLE_VALUE = -1; public const uint NMPWAIT_USE_DEFAULT_WAIT = 0x00000000; public const uint OPEN_EXISTING = 3; public const uint PIPE_ACCESS_DUPLEX = 0x00000003; public const uint PIPE_READMODE_BYTE = 0x00000000; public const uint PIPE_TYPE_BYTE = 0x00000000; public const uint PIPE_UNLIMITED_INSTANCES = 255; public const uint PIPE_WAIT = 0x00000000; public class FileSafeHandle : SafeHandle { private static IntPtr minusOne = new IntPtr(-1); public FileSafeHandle() : base(minusOne, true) { } public override bool IsInvalid { get { return (this.IsClosed) || (base.handle == minusOne); } } protected override bool ReleaseHandle() { return CloseHandle(this.handle); } public override string ToString() { return this.handle.ToString(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(System.IntPtr hObject); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ConnectNamedPipe(System.IntPtr hNamedPipe, System.IntPtr lpOverlapped); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern FileSafeHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, System.IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, System.IntPtr hTemplateFile); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern System.IntPtr CreateNamedPipe(string lpName, uint dwOpenMode, uint dwPipeMode, uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut, System.IntPtr lpSecurityAttributes); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PeekNamedPipe(System.IntPtr hNamedPipe, byte[] lpBuffer, uint nBufferSize, ref uint lpBytesRead, ref uint lpTotalBytesAvail, ref uint lpBytesLeftThisMessage); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ReadFile(System.IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToRead, ref uint lpNumberOfBytesRead, ref NativeOverlapped lpOverlapped); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WriteFile(FileSafeHandle hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, ref uint lpNumberOfBytesWritten, ref NativeOverlapped lpOverlapped); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WaitNamedPipe(string lpNamedPipeName, uint nTimeOut); } } } namespace Medo.Application { /// <summary> /// Arguments for newly detected application instance. /// </summary> [System.Serializable()] public class NewInstanceEventArgs : System.EventArgs { /// <summary> /// Creates new instance. /// </summary> /// <param name="commandLine">Command line.</param> /// <param name="commandLineArgs">String array containing the command line arguments.</param> public NewInstanceEventArgs(string commandLine, string[] commandLineArgs) { this._commandLine = commandLine; this._commandLineArgs = commandLineArgs; } private string _commandLine; /// <summary> /// Gets the command line. /// </summary> public string CommandLine { get { return this._commandLine; } } private string[] _commandLineArgs; /// <summary> /// Returns a string array containing the command line arguments. /// </summary> public string[] GetCommandLineArgs() { return this._commandLineArgs; } } }
using System; using System.Text; using Wintellect.PowerCollections; class Event : IComparable { public DateTime date; public String title; public String location; public Event(DateTime date, String title, String location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int byDate = this.date.CompareTo(other.date); int byTitle = this.title.CompareTo(other.title); int byLocation = this.location.CompareTo(other.location); if (byDate == 0) { if (byTitle == 0) { return byLocation; } else { return byTitle; } } else { return byDate; } } public override string ToString() { StringBuilder toString = new StringBuilder(); toString.Append(date.ToString("yyyy-MM-ddTHH:mm:ss")); toString.Append(" | " + title); if (location != null && location != "") { toString.Append(" | " + location); } return toString.ToString(); } } class Program { static StringBuilder output = new StringBuilder(); static EventHolder events = new EventHolder(); static void Main(string[] args) { while (ExecuteNextCommand()) { } Console.WriteLine(output); } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); if (command[0] == 'A') { AddEvent(command); return true; } if (command[0] == 'D') { DeleteEvents(command); return true; } if (command[0] == 'L') { ListEvents(command); return true; } if (command[0] == 'E') { return false; } return false; } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate(command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters(string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim(); eventLocation = ""; } else { eventTitle = commandForExecution.Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1).Trim(); eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } static class Messages { public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } class EventHolder { MultiDictionary<string, Event> byTitle = new MultiDictionary<string, Event>(true); OrderedBag<Event> byDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); byTitle.Add(title.ToLower(), newEvent); byDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { string title = titleToDelete.ToLower(); int removed = 0; foreach (var eventToRemove in byTitle[title]) { removed++; byDate.Remove(eventToRemove); } byTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { OrderedBag<Event>.View eventsToShow = byDate.RangeFrom(new Event(date, "", ""), true); int showed = 0; foreach (var eventToShow in eventsToShow) { if (showed == count) { break; } Messages.PrintEvent(eventToShow); showed += 1; } if (showed == 0) { Messages.NoEventsFound(); } } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.Services { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class ContentTypeServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void Deleting_PropertyType_Removes_The_Property_From_Content() { IContentType contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); IContent contentItem = MockedContent.CreateTextpageContent(contentType1, "Testing", -1); ServiceContext.ContentService.SaveAndPublish(contentItem); var initProps = contentItem.Properties.Count; var initPropTypes = contentItem.PropertyTypes.Count(); //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); //re-load it from the db contentItem = ServiceContext.ContentService.GetById(contentItem.Id); Assert.AreEqual(initPropTypes - 1, contentItem.PropertyTypes.Count()); Assert.AreEqual(initProps -1, contentItem.Properties.Count); } [Test] public void Rebuild_Content_Xml_On_Alias_Change() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); var contentType2 = MockedContentTypes.CreateTextpageContentType("test2", "Test2"); ServiceContext.ContentTypeService.Save(contentType1); ServiceContext.ContentTypeService.Save(contentType2); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublish(x)); var contentItems2 = MockedContent.CreateTextpageContent(contentType2, -1, 5).ToArray(); contentItems2.ForEach(x => ServiceContext.ContentService.SaveAndPublish(x)); //only update the contentType1 alias which will force an xml rebuild for all content of that type contentType1.Alias = "newAlias"; ServiceContext.ContentTypeService.Save(contentType1); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<newAlias")); } foreach (var c in contentItems2) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<test2")); //should remain the same } } [Test] public void Rebuild_Content_Xml_On_Property_Removal() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublish(x)); var alias = contentType1.PropertyTypes.First().Alias; var elementToMatch = "<" + alias + ">"; foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.Contains(elementToMatch)); //verify that it is there before we remove the property } //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); var reQueried = ServiceContext.ContentTypeService.GetContentType(contentType1.Id); var reContent = ServiceContext.ContentService.GetById(contentItems1.First().Id); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsFalse(xml.Xml.Contains(elementToMatch)); //verify that it is no longer there } } [Test] public void Get_Descendants() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.Descendants(); //Assert Assert.AreEqual(10, descendants.Count()); } [Test] public void Get_Descendants_And_Self() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.DescendantsAndSelf(); //Assert Assert.AreEqual(11, descendants.Count()); } [Test] public void Can_Bulk_Save_New_Hierarchy_Content_Types() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); // Act contentTypeService.Save(hierarchy, 0); Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); for (var i = 0; i < hierarchy.Count(); i++) { if (i == 0) continue; Assert.AreEqual(hierarchy.ElementAt(i).ParentId, hierarchy.ElementAt(i - 1).Id); } } [Test] public void Can_Save_ContentType_Structure_And_Create_Content_Based_On_It() { // Arrange var cs = ServiceContext.ContentService; var cts = ServiceContext.ContentTypeService; var dtdYesNo = ServiceContext.DataTypeService.GetDataTypeDefinitionById(-49); var ctBase = new ContentType(-1) {Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png"}; ctBase.AddPropertyType(new PropertyType(dtdYesNo) { Name = "Hide From Navigation", Alias = Constants.Conventions.Content.NaviHide } /*,"Navigation"*/); cts.Save(ctBase); var ctHomePage = new ContentType(ctBase) { Name = "Home Page", Alias = "HomePage", Icon = "settingDomain.gif", Thumbnail = "folder.png", AllowedAsRoot = true }; ctHomePage.AddPropertyType(new PropertyType(dtdYesNo) {Name = "Some property", Alias = "someProperty"} /*,"Navigation"*/); cts.Save(ctHomePage); // Act var homeDoc = cs.CreateContent("Home Page", -1, "HomePage"); cs.SaveAndPublish(homeDoc); // Assert Assert.That(ctBase.HasIdentity, Is.True); Assert.That(ctHomePage.HasIdentity, Is.True); Assert.That(homeDoc.HasIdentity, Is.True); Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id)); } [Test] public void Can_Create_And_Save_ContentType_Composition() { /* * Global * - Components * - Category */ var service = ServiceContext.ContentTypeService; var global = MockedContentTypes.CreateSimpleContentType("global", "Global"); service.Save(global); var components = MockedContentTypes.CreateSimpleContentType("components", "Components", global); service.Save(components); var component = MockedContentTypes.CreateSimpleContentType("component", "Component", components); service.Save(component); var category = MockedContentTypes.CreateSimpleContentType("category", "Category", global); service.Save(category); var success = category.AddContentType(component); Assert.That(success, Is.False); } [Test] public void Can_Remove_ContentType_Composition_From_ContentType() { //Test for U4-2234 var cts = ServiceContext.ContentTypeService; //Arrange var component = CreateComponent(); cts.Save(component); var banner = CreateBannerComponent(component); cts.Save(banner); var site = CreateSite(); cts.Save(site); var homepage = CreateHomepage(site); cts.Save(homepage); //Add banner to homepage var added = homepage.AddContentType(banner); cts.Save(homepage); //Assert composition var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(added, Is.True); Assert.That(bannerExists, Is.True); Assert.That(bannerPropertyExists, Is.True); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); //Remove banner from homepage var removed = homepage.RemoveContentType(banner.Alias); cts.Save(homepage); //Assert composition var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(removed, Is.True); Assert.That(bannerStillExists, Is.False); Assert.That(bannerPropertyStillExists, Is.False); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4)); } [Test] public void Can_Copy_ContentType_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var sut = simpleContentType.Clone("newcategory"); service.Save(sut); // Assert Assert.That(sut.HasIdentity, Is.True); var contentType = service.GetContentType(sut.Id); var category = service.GetContentType(categoryId); Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); Assert.AreEqual(contentType.ParentId, category.ParentId); Assert.AreEqual(contentType.Level, category.Level); Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count()); Assert.AreNotEqual(contentType.Id, category.Id); Assert.AreNotEqual(contentType.Key, category.Key); Assert.AreNotEqual(contentType.Path, category.Path); Assert.AreNotEqual(contentType.SortOrder, category.SortOrder); Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_To_New_Parent_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var parentContentType1 = MockedContentTypes.CreateSimpleContentType("parent1", "Parent1"); service.Save(parentContentType1); var parentContentType2 = MockedContentTypes.CreateSimpleContentType("parent2", "Parent2"); service.Save(parentContentType2); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", parentContentType1); service.Save(simpleContentType); // Act var clone = simpleContentType.Clone("newcategory"); clone.RemoveContentType("parent1"); clone.AddContentType(parentContentType2); clone.ParentId = parentContentType2.Id; service.Save(clone); // Assert Assert.That(clone.HasIdentity, Is.True); var clonedContentType = service.GetContentType(clone.Id); var originalContentType = service.GetContentType(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedContentType.Path, "-1," + parentContentType2.Id + "," + clonedContentType.Id); Assert.AreEqual(clonedContentType.PropertyTypes.Count(), originalContentType.PropertyTypes.Count()); Assert.AreNotEqual(clonedContentType.ParentId, originalContentType.ParentId); Assert.AreEqual(clonedContentType.ParentId, parentContentType2.Id); Assert.AreNotEqual(clonedContentType.Id, originalContentType.Id); Assert.AreNotEqual(clonedContentType.Key, originalContentType.Key); Assert.AreNotEqual(clonedContentType.Path, originalContentType.Path); Assert.AreNotEqual(clonedContentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, originalContentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(clonedContentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, originalContentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_With_Service_To_Root() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var clone = service.Copy(simpleContentType, "newcategory", "new category"); // Assert Assert.That(clone.HasIdentity, Is.True); var cloned = service.GetContentType(clone.Id); var original = service.GetContentType(categoryId); Assert.That(cloned.CompositionAliases().Any(x => x.Equals("meta")), Is.False); //it's been copied to root Assert.AreEqual(cloned.ParentId, -1); Assert.AreEqual(cloned.Level, 1); Assert.AreEqual(cloned.PropertyTypes.Count(), original.PropertyTypes.Count()); Assert.AreEqual(cloned.PropertyGroups.Count(), original.PropertyGroups.Count()); for (int i = 0; i < cloned.PropertyGroups.Count; i++) { Assert.AreEqual(cloned.PropertyGroups[i].PropertyTypes.Count, original.PropertyGroups[i].PropertyTypes.Count); foreach (var propertyType in cloned.PropertyGroups[i].PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } } foreach (var propertyType in cloned.PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } Assert.AreNotEqual(cloned.Id, original.Id); Assert.AreNotEqual(cloned.Key, original.Key); Assert.AreNotEqual(cloned.Path, original.Path); Assert.AreNotEqual(cloned.SortOrder, original.SortOrder); Assert.AreNotEqual(cloned.PropertyTypes.First(x => x.Alias.Equals("title")).Id, original.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(cloned.PropertyGroups.First(x => x.Name.Equals("Content")).Id, original.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_To_New_Parent_With_Service() { // Arrange var service = ServiceContext.ContentTypeService; var parentContentType1 = MockedContentTypes.CreateSimpleContentType("parent1", "Parent1"); service.Save(parentContentType1); var parentContentType2 = MockedContentTypes.CreateSimpleContentType("parent2", "Parent2"); service.Save(parentContentType2); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", parentContentType1); service.Save(simpleContentType); // Act var clone = service.Copy(simpleContentType, "newAlias", "new alias", parentContentType2); // Assert Assert.That(clone.HasIdentity, Is.True); var clonedContentType = service.GetContentType(clone.Id); var originalContentType = service.GetContentType(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedContentType.Path, "-1," + parentContentType2.Id + "," + clonedContentType.Id); Assert.AreEqual(clonedContentType.PropertyTypes.Count(), originalContentType.PropertyTypes.Count()); Assert.AreNotEqual(clonedContentType.ParentId, originalContentType.ParentId); Assert.AreEqual(clonedContentType.ParentId, parentContentType2.Id); Assert.AreNotEqual(clonedContentType.Id, originalContentType.Id); Assert.AreNotEqual(clonedContentType.Key, originalContentType.Key); Assert.AreNotEqual(clonedContentType.Path, originalContentType.Path); Assert.AreNotEqual(clonedContentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, originalContentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(clonedContentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, originalContentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } private ContentType CreateComponent() { var component = new ContentType(-1) { Alias = "component", Name = "Component", Description = "ContentType used for Component grouping", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "componentGroup", Name = "Component Group", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); return component; } private ContentType CreateBannerComponent(ContentType parent) { var banner = new ContentType(parent) { Alias = "banner", Name = "Banner Component", Description = "ContentType used for Banner Component", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var propertyType = new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "bannerName", Name = "Banner Name", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -88 }; banner.AddPropertyType(propertyType, "Component"); return banner; } private ContentType CreateSite() { var site = new ContentType(-1) { Alias = "site", Name = "Site", Description = "ContentType used for Site inheritence", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 2, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "hostname", Name = "Hostname", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); return site; } private ContentType CreateHomepage(ContentType parent) { var contentType = new ContentType(parent) { Alias = "homepage", Name = "Homepage", Description = "ContentType used for the Homepage", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "title", Name = "Title", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "bodyText", Name = "Body Text", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "author", Name = "Author", Description = "Name of the author", HelpText = "", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 }); contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); return contentType; } private IContentType[] CreateContentTypeHierarchy() { //create the master type var masterContentType = MockedContentTypes.CreateSimpleContentType("masterContentType", "MasterContentType"); masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); ServiceContext.ContentTypeService.Save(masterContentType); //add the one we just created var list = new List<IContentType> {masterContentType}; for (var i = 0; i < 10; i++) { var contentType = MockedContentTypes.CreateSimpleContentType("childType" + i, "ChildType" + i, //make the last entry in the list, this one's parent list.Last()); list.Add(contentType); } return list.ToArray(); } } }